code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
/**
* 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.gora.cassandra.store;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import me.prettyprint.cassandra.model.ConfigurableConsistencyLevel;
import me.prettyprint.cassandra.serializers.ByteBufferSerializer;
import me.prettyprint.cassandra.serializers.IntegerSerializer;
import me.prettyprint.cassandra.serializers.StringSerializer;
import me.prettyprint.cassandra.service.CassandraHostConfigurator;
import me.prettyprint.hector.api.Cluster;
import me.prettyprint.hector.api.Keyspace;
import me.prettyprint.hector.api.beans.OrderedRows;
import me.prettyprint.hector.api.beans.OrderedSuperRows;
import me.prettyprint.hector.api.beans.Row;
import me.prettyprint.hector.api.beans.SuperRow;
import me.prettyprint.hector.api.ddl.ColumnFamilyDefinition;
import me.prettyprint.hector.api.ddl.ComparatorType;
import me.prettyprint.hector.api.ddl.KeyspaceDefinition;
import me.prettyprint.hector.api.factory.HFactory;
import me.prettyprint.hector.api.mutation.Mutator;
import me.prettyprint.hector.api.query.QueryResult;
import me.prettyprint.hector.api.query.RangeSlicesQuery;
import me.prettyprint.hector.api.query.RangeSuperSlicesQuery;
import me.prettyprint.hector.api.HConsistencyLevel;
import me.prettyprint.hector.api.Serializer;
import org.apache.avro.Schema;
import org.apache.avro.Schema.Type;
import org.apache.avro.generic.GenericArray;
import org.apache.avro.util.Utf8;
import org.apache.gora.cassandra.query.CassandraQuery;
import org.apache.gora.cassandra.serializers.GenericArraySerializer;
import org.apache.gora.cassandra.serializers.GoraSerializerTypeInferer;
import org.apache.gora.cassandra.serializers.TypeUtils;
import org.apache.gora.mapreduce.GoraRecordReader;
import org.apache.gora.persistency.Persistent;
import org.apache.gora.persistency.impl.PersistentBase;
import org.apache.gora.persistency.State;
import org.apache.gora.persistency.StatefulHashMap;
import org.apache.gora.query.Query;
import org.apache.gora.util.ByteUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CassandraClient<K, T extends PersistentBase> {
public static final Logger LOG = LoggerFactory.getLogger(CassandraClient.class);
private Cluster cluster;
private Keyspace keyspace;
private Mutator<K> mutator;
private Class<K> keyClass;
private Class<T> persistentClass;
private CassandraMapping cassandraMapping = null;
private Serializer<K> keySerializer;
public void initialize(Class<K> keyClass, Class<T> persistentClass) throws Exception {
this.keyClass = keyClass;
// get cassandra mapping with persistent class
this.persistentClass = persistentClass;
this.cassandraMapping = CassandraMappingManager.getManager().get(persistentClass);
// LOG.info("persistentClass=" + persistentClass.getName() + " -> cassandraMapping=" + cassandraMapping);
this.cluster = HFactory.getOrCreateCluster(this.cassandraMapping.getClusterName(), new CassandraHostConfigurator(this.cassandraMapping.getHostName()));
// add keyspace to cluster
checkKeyspace();
// Just create a Keyspace object on the client side, corresponding to an already existing keyspace with already created column families.
this.keyspace = HFactory.createKeyspace(this.cassandraMapping.getKeyspaceName(), this.cluster);
this.keySerializer = GoraSerializerTypeInferer.getSerializer(keyClass);
this.mutator = HFactory.createMutator(this.keyspace, this.keySerializer);
}
/**
* Check if keyspace already exists.
*/
public boolean keyspaceExists() {
KeyspaceDefinition keyspaceDefinition = this.cluster.describeKeyspace(this.cassandraMapping.getKeyspaceName());
return (keyspaceDefinition != null);
}
/**
* Check if keyspace already exists. If not, create it.
* In this method, we also utilise Hector's {@ConfigurableConsistencyLevel}
* logic. It is set by passing a ConfigurableConsistencyLevel object right
* when the Keyspace is created. Currently consistency level is .ONE which
* permits consistency to wait until one replica has responded.
*/
public void checkKeyspace() {
// "describe keyspace <keyspaceName>;" query
KeyspaceDefinition keyspaceDefinition = this.cluster.describeKeyspace(this.cassandraMapping.getKeyspaceName());
if (keyspaceDefinition == null) {
List<ColumnFamilyDefinition> columnFamilyDefinitions = this.cassandraMapping.getColumnFamilyDefinitions();
// GORA-197
for (ColumnFamilyDefinition cfDef : columnFamilyDefinitions) {
cfDef.setComparatorType(ComparatorType.BYTESTYPE);
}
keyspaceDefinition = HFactory.createKeyspaceDefinition(this.cassandraMapping.getKeyspaceName(), "org.apache.cassandra.locator.SimpleStrategy", 1, columnFamilyDefinitions);
this.cluster.addKeyspace(keyspaceDefinition, true);
// LOG.info("Keyspace '" + this.cassandraMapping.getKeyspaceName() + "' in cluster '" + this.cassandraMapping.getClusterName() + "' was created on host '" + this.cassandraMapping.getHostName() + "'");
// Create a customized Consistency Level
ConfigurableConsistencyLevel configurableConsistencyLevel = new ConfigurableConsistencyLevel();
Map<String, HConsistencyLevel> clmap = new HashMap<String, HConsistencyLevel>();
// Define CL.ONE for ColumnFamily "ColumnFamily"
clmap.put("ColumnFamily", HConsistencyLevel.ONE);
// In this we use CL.ONE for read and writes. But you can use different CLs if needed.
configurableConsistencyLevel.setReadCfConsistencyLevels(clmap);
configurableConsistencyLevel.setWriteCfConsistencyLevels(clmap);
// Then let the keyspace know
HFactory.createKeyspace("Keyspace", this.cluster, configurableConsistencyLevel);
keyspaceDefinition = null;
}
else {
List<ColumnFamilyDefinition> cfDefs = keyspaceDefinition.getCfDefs();
if (cfDefs == null || cfDefs.size() == 0) {
LOG.warn(keyspaceDefinition.getName() + " does not have any column family.");
}
else {
for (ColumnFamilyDefinition cfDef : cfDefs) {
ComparatorType comparatorType = cfDef.getComparatorType();
if (! comparatorType.equals(ComparatorType.BYTESTYPE)) {
// GORA-197
LOG.warn("The comparator type of " + cfDef.getName() + " column family is " + comparatorType.getTypeName()
+ ", not BytesType. It may cause a fatal error on column validation later.");
}
else {
// LOG.info("The comparator type of " + cfDef.getName() + " column family is " + comparatorType.getTypeName() + ".");
}
}
}
}
}
/**
* Drop keyspace.
*/
public void dropKeyspace() {
// "drop keyspace <keyspaceName>;" query
this.cluster.dropKeyspace(this.cassandraMapping.getKeyspaceName());
}
/**
* Insert a field in a column.
* @param key the row key
* @param fieldName the field name
* @param value the field value.
*/
public void addColumn(K key, String fieldName, Object value) {
if (value == null) {
return;
}
ByteBuffer byteBuffer = toByteBuffer(value);
String columnFamily = this.cassandraMapping.getFamily(fieldName);
String columnName = this.cassandraMapping.getColumn(fieldName);
if (columnName == null) {
LOG.warn("Column name is null for field=" + fieldName + " with value=" + value.toString());
return;
}
synchronized(mutator) {
HectorUtils.insertColumn(mutator, key, columnFamily, columnName, byteBuffer);
}
}
/**
* Insert a member in a super column. This is used for map and record Avro types.
* @param key the row key
* @param fieldName the field name
* @param columnName the column name (the member name, or the index of array)
* @param value the member value
*/
@SuppressWarnings("unchecked")
public void addSubColumn(K key, String fieldName, ByteBuffer columnName, Object value) {
if (value == null) {
return;
}
ByteBuffer byteBuffer = toByteBuffer(value);
String columnFamily = this.cassandraMapping.getFamily(fieldName);
String superColumnName = this.cassandraMapping.getColumn(fieldName);
synchronized(mutator) {
HectorUtils.insertSubColumn(mutator, key, columnFamily, superColumnName, columnName, byteBuffer);
}
}
public void addSubColumn(K key, String fieldName, String columnName, Object value) {
addSubColumn(key, fieldName, StringSerializer.get().toByteBuffer(columnName), value);
}
public void addSubColumn(K key, String fieldName, Integer columnName, Object value) {
addSubColumn(key, fieldName, IntegerSerializer.get().toByteBuffer(columnName), value);
}
/**
* Delete a member in a super column. This is used for map and record Avro types.
* @param key the row key
* @param fieldName the field name
* @param columnName the column name (the member name, or the index of array)
*/
@SuppressWarnings("unchecked")
public void deleteSubColumn(K key, String fieldName, ByteBuffer columnName) {
String columnFamily = this.cassandraMapping.getFamily(fieldName);
String superColumnName = this.cassandraMapping.getColumn(fieldName);
synchronized(mutator) {
HectorUtils.deleteSubColumn(mutator, key, columnFamily, superColumnName, columnName);
}
}
public void deleteSubColumn(K key, String fieldName, String columnName) {
deleteSubColumn(key, fieldName, StringSerializer.get().toByteBuffer(columnName));
}
@SuppressWarnings("unchecked")
public void addGenericArray(K key, String fieldName, GenericArray array) {
if (isSuper( cassandraMapping.getFamily(fieldName) )) {
int i= 0;
for (Object itemValue: array) {
// TODO: hack, do not store empty arrays
if (itemValue instanceof GenericArray<?>) {
if (((GenericArray)itemValue).size() == 0) {
continue;
}
} else if (itemValue instanceof StatefulHashMap<?,?>) {
if (((StatefulHashMap)itemValue).size() == 0) {
continue;
}
}
addSubColumn(key, fieldName, i++, itemValue);
}
}
else {
addColumn(key, fieldName, array);
}
}
@SuppressWarnings("unchecked")
public void addStatefulHashMap(K key, String fieldName, StatefulHashMap<Utf8,Object> map) {
if (isSuper( cassandraMapping.getFamily(fieldName) )) {
int i= 0;
for (Utf8 mapKey: map.keySet()) {
if (map.getState(mapKey) == State.DELETED) {
deleteSubColumn(key, fieldName, mapKey.toString());
continue;
}
// TODO: hack, do not store empty arrays
Object mapValue = map.get(mapKey);
if (mapValue instanceof GenericArray<?>) {
if (((GenericArray)mapValue).size() == 0) {
continue;
}
} else if (mapValue instanceof StatefulHashMap<?,?>) {
if (((StatefulHashMap)mapValue).size() == 0) {
continue;
}
}
addSubColumn(key, fieldName, mapKey.toString(), mapValue);
}
}
else {
addColumn(key, fieldName, map);
}
}
/**
* Serialize value to ByteBuffer.
* @param value the member value
* @return ByteBuffer object
*/
@SuppressWarnings("unchecked")
public ByteBuffer toByteBuffer(Object value) {
ByteBuffer byteBuffer = null;
Serializer serializer = GoraSerializerTypeInferer.getSerializer(value);
if (serializer == null) {
LOG.info("Serializer not found for: " + value.toString());
}
else {
byteBuffer = serializer.toByteBuffer(value);
}
if (byteBuffer == null) {
LOG.info("value class=" + value.getClass().getName() + " value=" + value + " -> null");
}
return byteBuffer;
}
/**
* Select a family column in the keyspace.
* @param cassandraQuery a wrapper of the query
* @param family the family name to be queried
* @return a list of family rows
*/
public List<Row<K, ByteBuffer, ByteBuffer>> execute(CassandraQuery<K, T> cassandraQuery, String family) {
String[] columnNames = cassandraQuery.getColumns(family);
ByteBuffer[] columnNameByteBuffers = new ByteBuffer[columnNames.length];
for (int i = 0; i < columnNames.length; i++) {
columnNameByteBuffers[i] = StringSerializer.get().toByteBuffer(columnNames[i]);
}
Query<K, T> query = cassandraQuery.getQuery();
int limit = (int) query.getLimit();
if (limit < 1) {
limit = Integer.MAX_VALUE;
}
K startKey = query.getStartKey();
K endKey = query.getEndKey();
RangeSlicesQuery<K, ByteBuffer, ByteBuffer> rangeSlicesQuery = HFactory.createRangeSlicesQuery(this.keyspace, this.keySerializer, ByteBufferSerializer.get(), ByteBufferSerializer.get());
rangeSlicesQuery.setColumnFamily(family);
rangeSlicesQuery.setKeys(startKey, endKey);
rangeSlicesQuery.setRange(ByteBuffer.wrap(new byte[0]), ByteBuffer.wrap(new byte[0]), false, GoraRecordReader.BUFFER_LIMIT_READ_VALUE);
rangeSlicesQuery.setRowCount(limit);
rangeSlicesQuery.setColumnNames(columnNameByteBuffers);
QueryResult<OrderedRows<K, ByteBuffer, ByteBuffer>> queryResult = rangeSlicesQuery.execute();
OrderedRows<K, ByteBuffer, ByteBuffer> orderedRows = queryResult.get();
return orderedRows.getList();
}
/**
* Select the families that contain at least one column mapped to a query field.
* @param query indicates the columns to select
* @return a map which keys are the family names and values the corresponding column names required to get all the query fields.
*/
public Map<String, List<String>> getFamilyMap(Query<K, T> query) {
Map<String, List<String>> map = new HashMap<String, List<String>>();
for (String field: query.getFields()) {
String family = this.cassandraMapping.getFamily(field);
String column = this.cassandraMapping.getColumn(field);
// check if the family value was already initialized
List<String> list = map.get(family);
if (list == null) {
list = new ArrayList<String>();
map.put(family, list);
}
if (column != null) {
list.add(column);
}
}
return map;
}
/**
* Select the field names according to the column names, which format if fully qualified: "family:column"
* @param query
* @return a map which keys are the fully qualified column names and values the query fields
*/
public Map<String, String> getReverseMap(Query<K, T> query) {
Map<String, String> map = new HashMap<String, String>();
for (String field: query.getFields()) {
String family = this.cassandraMapping.getFamily(field);
String column = this.cassandraMapping.getColumn(field);
map.put(family + ":" + column, field);
}
return map;
}
public boolean isSuper(String family) {
return this.cassandraMapping.isSuper(family);
}
public List<SuperRow<K, String, ByteBuffer, ByteBuffer>> executeSuper(CassandraQuery<K, T> cassandraQuery, String family) {
String[] columnNames = cassandraQuery.getColumns(family);
Query<K, T> query = cassandraQuery.getQuery();
int limit = (int) query.getLimit();
if (limit < 1) {
limit = Integer.MAX_VALUE;
}
K startKey = query.getStartKey();
K endKey = query.getEndKey();
RangeSuperSlicesQuery<K, String, ByteBuffer, ByteBuffer> rangeSuperSlicesQuery = HFactory.createRangeSuperSlicesQuery(this.keyspace, this.keySerializer, StringSerializer.get(), ByteBufferSerializer.get(), ByteBufferSerializer.get());
rangeSuperSlicesQuery.setColumnFamily(family);
rangeSuperSlicesQuery.setKeys(startKey, endKey);
rangeSuperSlicesQuery.setRange("", "", false, GoraRecordReader.BUFFER_LIMIT_READ_VALUE);
rangeSuperSlicesQuery.setRowCount(limit);
rangeSuperSlicesQuery.setColumnNames(columnNames);
QueryResult<OrderedSuperRows<K, String, ByteBuffer, ByteBuffer>> queryResult = rangeSuperSlicesQuery.execute();
OrderedSuperRows<K, String, ByteBuffer, ByteBuffer> orderedRows = queryResult.get();
return orderedRows.getList();
}
/**
* Obtain Schema/Keyspace name
* @return Keyspace
*/
public String getKeyspaceName() {
return this.cassandraMapping.getKeyspaceName();
}
}
| prateekbansal/apache-gora-0.4 | gora-cassandra/src/main/java/org/apache/gora/cassandra/store/CassandraClient.java | Java | apache-2.0 | 17,283 |
/*
* 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.io.sstable;
import java.io.IOException;
import java.util.Iterator;
import com.google.common.util.concurrent.RateLimiter;
import com.google.common.collect.AbstractIterator;
import org.apache.cassandra.db.DataRange;
import org.apache.cassandra.db.DecoratedKey;
import org.apache.cassandra.db.RowIndexEntry;
import org.apache.cassandra.db.RowPosition;
import org.apache.cassandra.db.columniterator.IColumnIteratorFactory;
import org.apache.cassandra.db.columniterator.LazyColumnIterator;
import org.apache.cassandra.db.columniterator.OnDiskAtomIterator;
import org.apache.cassandra.db.compaction.ICompactionScanner;
import org.apache.cassandra.db.filter.QueryFilter;
import org.apache.cassandra.dht.AbstractBounds;
import org.apache.cassandra.dht.Range;
import org.apache.cassandra.dht.Token;
import org.apache.cassandra.io.util.FileUtils;
import org.apache.cassandra.io.util.RandomAccessReader;
import org.apache.cassandra.utils.ByteBufferUtil;
public class SSTableScanner implements ICompactionScanner
{
protected final RandomAccessReader dfile;
protected final RandomAccessReader ifile;
public final SSTableReader sstable;
private final DataRange dataRange;
private final long stopAt;
protected Iterator<OnDiskAtomIterator> iterator;
/**
* @param sstable SSTable to scan; must not be null
* @param filter range of data to fetch; must not be null
* @param limiter background i/o RateLimiter; may be null
*/
SSTableScanner(SSTableReader sstable, DataRange dataRange, RateLimiter limiter)
{
assert sstable != null;
this.dfile = limiter == null ? sstable.openDataReader() : sstable.openDataReader(limiter);
this.ifile = sstable.openIndexReader();
this.sstable = sstable;
this.dataRange = dataRange;
this.stopAt = computeStopAt();
seekToStart();
}
private void seekToStart()
{
if (dataRange.startKey().isMinimum(sstable.partitioner))
return;
long indexPosition = sstable.getIndexScanPosition(dataRange.startKey());
// -1 means the key is before everything in the sstable. So just start from the beginning.
if (indexPosition == -1)
return;
ifile.seek(indexPosition);
try
{
while (!ifile.isEOF())
{
indexPosition = ifile.getFilePointer();
DecoratedKey indexDecoratedKey = sstable.partitioner.decorateKey(ByteBufferUtil.readWithShortLength(ifile));
int comparison = indexDecoratedKey.compareTo(dataRange.startKey());
if (comparison >= 0)
{
// Found, just read the dataPosition and seek into index and data files
long dataPosition = ifile.readLong();
ifile.seek(indexPosition);
dfile.seek(dataPosition);
break;
}
else
{
RowIndexEntry.serializer.skip(ifile);
}
}
}
catch (IOException e)
{
sstable.markSuspect();
throw new CorruptSSTableException(e, sstable.getFilename());
}
}
private long computeStopAt()
{
AbstractBounds<RowPosition> keyRange = dataRange.keyRange();
if (dataRange.stopKey().isMinimum(sstable.partitioner) || (keyRange instanceof Range && ((Range)keyRange).isWrapAround()))
return dfile.length();
RowIndexEntry position = sstable.getPosition(keyRange.toRowBounds().right, SSTableReader.Operator.GT);
return position == null ? dfile.length() : position.position;
}
public void close() throws IOException
{
FileUtils.close(dfile, ifile);
}
public long getLengthInBytes()
{
return dfile.length();
}
public long getCurrentPosition()
{
return dfile.getFilePointer();
}
public String getBackingFiles()
{
return sstable.toString();
}
public boolean hasNext()
{
if (iterator == null)
iterator = createIterator();
return iterator.hasNext();
}
public OnDiskAtomIterator next()
{
if (iterator == null)
iterator = createIterator();
return iterator.next();
}
public void remove()
{
throw new UnsupportedOperationException();
}
private Iterator<OnDiskAtomIterator> createIterator()
{
return new KeyScanningIterator();
}
protected class KeyScanningIterator extends AbstractIterator<OnDiskAtomIterator>
{
private DecoratedKey nextKey;
private RowIndexEntry nextEntry;
private DecoratedKey currentKey;
private RowIndexEntry currentEntry;
protected OnDiskAtomIterator computeNext()
{
try
{
if (ifile.isEOF() && nextKey == null)
return endOfData();
if (currentKey == null)
{
currentKey = sstable.partitioner.decorateKey(ByteBufferUtil.readWithShortLength(ifile));
currentEntry = RowIndexEntry.serializer.deserialize(ifile, sstable.descriptor.version);
}
else
{
currentKey = nextKey;
currentEntry = nextEntry;
}
assert currentEntry.position <= stopAt;
if (currentEntry.position == stopAt)
return endOfData();
if (ifile.isEOF())
{
nextKey = null;
nextEntry = null;
}
else
{
nextKey = sstable.partitioner.decorateKey(ByteBufferUtil.readWithShortLength(ifile));
nextEntry = RowIndexEntry.serializer.deserialize(ifile, sstable.descriptor.version);
}
assert !dfile.isEOF();
if (dataRange.selectsFullRowFor(currentKey.key))
{
dfile.seek(currentEntry.position);
ByteBufferUtil.readWithShortLength(dfile); // key
if (sstable.descriptor.version.hasRowSizeAndColumnCount)
dfile.readLong();
long dataSize = (nextEntry == null ? dfile.length() : nextEntry.position) - dfile.getFilePointer();
return new SSTableIdentityIterator(sstable, dfile, currentKey, dataSize);
}
return new LazyColumnIterator(currentKey, new IColumnIteratorFactory()
{
public OnDiskAtomIterator create()
{
return dataRange.columnFilter(currentKey.key).getSSTableColumnIterator(sstable, dfile, currentKey, currentEntry);
}
});
}
catch (IOException e)
{
sstable.markSuspect();
throw new CorruptSSTableException(e, sstable.getFilename());
}
}
}
@Override
public String toString()
{
return getClass().getSimpleName() + "(" +
"dfile=" + dfile +
" ifile=" + ifile +
" sstable=" + sstable +
")";
}
}
| DavidHerzogTU-Berlin/cassandraToRun | src/java/org/apache/cassandra/io/sstable/SSTableScanner.java | Java | apache-2.0 | 8,241 |
/*
* Copyright 2012-2017 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.glacier.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.glacier.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* PartListElement JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class PartListElementJsonUnmarshaller implements Unmarshaller<PartListElement, JsonUnmarshallerContext> {
public PartListElement unmarshall(JsonUnmarshallerContext context) throws Exception {
PartListElement partListElement = new PartListElement();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return null;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("RangeInBytes", targetDepth)) {
context.nextToken();
partListElement.setRangeInBytes(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("SHA256TreeHash", targetDepth)) {
context.nextToken();
partListElement.setSHA256TreeHash(context.getUnmarshaller(String.class).unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return partListElement;
}
private static PartListElementJsonUnmarshaller instance;
public static PartListElementJsonUnmarshaller getInstance() {
if (instance == null)
instance = new PartListElementJsonUnmarshaller();
return instance;
}
}
| dagnir/aws-sdk-java | aws-java-sdk-glacier/src/main/java/com/amazonaws/services/glacier/model/transform/PartListElementJsonUnmarshaller.java | Java | apache-2.0 | 2,994 |
package seborama.demo2.kafka.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonIgnoreProperties(ignoreUnknown = true)
public class Order {
private String id;
private boolean fulfilled;
private boolean dispatched;
private boolean completed;
public void setId(String id) {
this.id = id;
}
public void setFulfilled(Boolean fulfilled) {
this.fulfilled = fulfilled;
}
public void setDispatched(Boolean dispatched) {
this.dispatched = dispatched;
}
public void setCompleted(Boolean completed) {
this.completed = completed;
}
public String getId() {
return id;
}
public Boolean getFulfilled() {
return fulfilled;
}
public Boolean getDispatched() {
return dispatched;
}
public Boolean getCompleted() {
return completed;
}
@Override
public String toString() {
return "Order{" +
"id='" + id + '\'' +
", fulfilled=" + fulfilled +
", dispatched=" + dispatched +
", completed=" + completed +
'}';
}
}
| seborama/demo1-kafka | src/main/java/seborama/demo2/kafka/model/Order.java | Java | apache-2.0 | 1,265 |
# Salix goepperti Andersson SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Malpighiales/Salicaceae/Salix/Salix goepperti/README.md | Markdown | apache-2.0 | 175 |
# Cortinarius olidissimus Ripart SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Cortinarius olidissimus Ripart
### Remarks
null | mdoering/backbone | life/Fungi/Basidiomycota/Agaricomycetes/Agaricales/Cortinariaceae/Cortinarius/Cortinarius olidissimus/README.md | Markdown | apache-2.0 | 189 |
# Polystictoides leucomelas Lázaro Ibiza, 1916 SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Revta R. Acad. Cienc. exact. fis. nat. Madr. 14: 833 (1916)
#### Original name
Polystictoides leucomelas Lázaro Ibiza, 1916
### Remarks
null | mdoering/backbone | life/Fungi/Basidiomycota/Agaricomycetes/Polyporales/Polyporaceae/Perenniporia/Perenniporia fraxinea/ Syn. Polystictoides leucomelas/README.md | Markdown | apache-2.0 | 298 |
public class ChickenBurger extends Burger {
@Override
public float price() {
return 50.5f;
}
@Override
public String name() {
return "Chicken Burger";
}
}
| Iamasoldier6/DesignPattern | BuilderPatternDemo/src/ChickenBurger.java | Java | apache-2.0 | 168 |
/*
* Copyright (c) 2017 Otávio Santana and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Apache License v2.0 is available at http://www.opensource.org/licenses/apache2.0.php.
*
* You may elect to redistribute this code under either of these licenses.
*
* Contributors:
*
* Otavio Santana
*/
package org.jnosql.artemis.column.query;
import org.jnosql.artemis.CDIExtension;
import org.jnosql.artemis.model.Person;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import javax.inject.Inject;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
@ExtendWith(CDIExtension.class)
public class DefaultColumnQueryMapperBuilderTest {
@Inject
private ColumnQueryMapperBuilder mapperBuilder;
@Test
public void shouldReturnErrorWhenEntityClassIsNull() {
assertThrows(NullPointerException.class, () -> mapperBuilder.selectFrom(null));
}
@Test
public void shouldReturnSelectFrom() {
ColumnMapperFrom columnFrom = mapperBuilder.selectFrom(Person.class);
assertNotNull(columnFrom);
}
@Test
public void shouldReturnErrorWhenDeleteEntityClassIsNull() {
assertThrows(NullPointerException.class, () -> mapperBuilder.deleteFrom(null));
}
@Test
public void shouldReturnDeleteFrom() {
ColumnMapperDeleteFrom columnDeleteFrom = mapperBuilder.deleteFrom(Person.class);
assertNotNull(columnDeleteFrom);
}
} | JNOSQL/artemis | artemis-column/src/test/java/org/jnosql/artemis/column/query/DefaultColumnQueryMapperBuilderTest.java | Java | apache-2.0 | 1,793 |
/* tslint:disable:max-classes-per-file */
import { forEach } from 'ramda';
import Interactor from '../CourseInteractor';
import InteractorLoader from '../CourseInteractorLoader';
import { ICourseStorage } from '../ICourseStorage';
import { IProgressStorage } from '../IProgressStorage';
import { ISerializedCourse } from '../ISerializedCourse';
import { ISerializedProgress, Progress } from '../ISerializedProgress';
const courses: { [propName: string]: ISerializedCourse } = {
'09438926-b170-4005-a6e8-5dd8fba83cde': {
id: '09438926-b170-4005-a6e8-5dd8fba83cde',
title: 'Foo bar',
children: [
{
id: '01f23c2a-b681-43db-9d27-5d8d59f62aed',
children: [
{
id: '23e20d5b-ad8e-41be-9891-5ca7b12675c4',
type: 'foo'
}
]
},
{
id: 'e194f80b-7312-43a2-995e-060f64631782',
children: [
{
id: '84fdc1a1-e3bf-4a87-8360-0c3b7beec179',
foo: 'bar',
type: 'foo'
}
]
}
]
}
};
const progresses: ISerializedProgress = {};
class MockCourseStorage implements ICourseStorage {
public getCourse(id: string) {
return new Promise<ISerializedCourse>((resolve, reject) => {
if (courses[id]) {
resolve(courses[id]);
}
reject(new Error(`There exists no course with id ${id}`));
});
}
}
class MockProgressStorage implements IProgressStorage {
public getProgress(id: string) {
return Promise.resolve(progresses);
}
public setProgress(id: string, progress: ISerializedProgress): Promise<void> {
return Promise.resolve();
}
public resetProgress() {
return Promise.resolve();
}
}
let interactorLoader: InteractorLoader;
let interactor: Interactor;
beforeEach(() => {
const storage = new MockCourseStorage();
const progress = new MockProgressStorage();
interactorLoader = new InteractorLoader(storage, progress);
});
it('loadCourse loads the course from storage if it exists', () =>
interactorLoader.loadCourse('09438926-b170-4005-a6e8-5dd8fba83cde'));
it('loadCourse fails if the course does not exist', () => {
return interactorLoader
.loadCourse('c990eacb-12af-4085-8b50-25d95d114984')
.catch(err => {
expect(err).toBeInstanceOf(Error);
});
});
describe('getStructure', () => {
beforeEach(() =>
interactorLoader
.loadCourse('09438926-b170-4005-a6e8-5dd8fba83cde')
.then(i => {
interactor = i;
})
);
it('returns the whole tree by default', () => {
expect(interactor.getStructure()).toMatchSnapshot();
});
it('returns only the first levels if a level is passed', () => {
expect(interactor.getStructure(1)).toMatchSnapshot();
});
});
describe('reset children progress', () => {
beforeEach(() =>
interactorLoader
.loadCourse('09438926-b170-4005-a6e8-5dd8fba83cde')
.then(i => {
interactor = i;
})
);
it('resets progress correctly', () => {
const root = '09438926-b170-4005-a6e8-5dd8fba83cde';
const children = [
'01f23c2a-b681-43db-9d27-5d8d59f62aed',
'23e20d5b-ad8e-41be-9891-5ca7b12675c4',
'e194f80b-7312-43a2-995e-060f64631782',
'84fdc1a1-e3bf-4a87-8360-0c3b7beec179'
];
forEach(
id => {
interactor.markAsCorrect(id);
},
[root, ...children]
);
interactor.resetChildrenProgress(root);
expect(interactor.getProgress(root).progress).toBe(Progress.Correct);
forEach(id => {
expect(interactor.getProgress(id).progress).toBe(Progress.Unseen);
}, children);
});
});
| serlo-org/serlo-abc | packages/entities-interactor/__tests__/CourseInteractor.ts | TypeScript | apache-2.0 | 3,604 |
import React from 'react';
import { action } from '@storybook/addon-actions';
import { Action } from '../Actions';
import ActionBar from './ActionBar.component';
const primary = {
label: 'Primary',
icon: 'talend-cog',
bsStyle: 'primary',
'data-feature': 'actionbar.primary',
onClick: action('You clicked me'),
};
const actions = {
left: [
primary,
{
label: 'Secondary1',
icon: 'talend-cog',
'data-feature': 'actionbar.secondary',
onClick: action('You clicked me'),
},
{
displayMode: ActionBar.DISPLAY_MODES.SPLIT_DROPDOWN,
label: 'Secondary3',
icon: 'talend-cog',
'data-feature': 'actionbar.splitdropdown',
onClick: action('on split button click'),
items: [
{
label: 'From Local',
'data-feature': 'actionbar.splitdropdown.items',
onClick: action('From Local click'),
},
{
label: 'From Remote',
'data-feature': 'actionbar.splitdropdown.items',
onClick: action('From Remote click'),
},
],
emptyDropdownLabel: 'No option',
},
{
id: 'dropdown',
displayMode: ActionBar.DISPLAY_MODES.DROPDOWN,
label: 'Dropdown',
icon: 'talend-cog',
items: [
{
label: 'From Local',
onClick: action('From Local click'),
},
{
label: 'From Remote',
onClick: action('From Remote click'),
},
],
},
],
right: [
{
label: 'Secondary4',
icon: 'talend-upload',
displayMode: 'file',
onChange: action('You changed me'),
},
{
label: 'Secondary5',
icon: 'talend-cog',
onClick: action('You clicked me'),
},
],
};
const multi3 = {
label: 'multi3',
icon: 'talend-cog',
onClick: action('You clicked me'),
};
const multiSelectActions = {
left: [
{
label: 'multi1',
icon: 'talend-cog',
onClick: action('You clicked me'),
},
{
label: 'multi2',
icon: 'talend-cog',
onClick: action('You clicked me'),
},
],
center: [
{
label: 'multi5',
icon: 'talend-cog',
onClick: action('You clicked me'),
},
],
right: [
multi3,
{
label: 'multi4',
icon: 'talend-cog',
onClick: action('You clicked me'),
},
],
};
const btnGroupActions = {
left: [
{
displayMode: ActionBar.DISPLAY_MODES.BTN_GROUP,
actions: [
{
label: 'hidden mean tooltips',
icon: 'talend-cog',
hideLabel: true,
onClick: action('cog'),
},
{
label: 'you are a super star',
icon: 'talend-badge',
hideLabel: true,
onClick: action('badge'),
},
{
label: 'but don t click this',
icon: 'talend-cross',
hideLabel: true,
onClick: action('boom'),
},
{
label: 'edit me',
icon: 'talend-pencil',
hideLabel: true,
onClick: action('oh yes'),
},
],
},
{
displayMode: ActionBar.DISPLAY_MODES.BTN_GROUP,
actions: [
{
label: 'you can also add',
icon: 'talend-plus-circle',
hideLabel: true,
onClick: action('add !'),
},
{
label: 'search',
icon: 'talend-search',
hideLabel: true,
onClick: action('search'),
},
{
label: 'star',
icon: 'talend-star',
hideLabel: true,
onClick: action('star'),
},
],
},
],
center: [
{
displayMode: ActionBar.DISPLAY_MODES.BTN_GROUP,
actions: [
{
label: 'go to dataprep',
icon: 'talend-dataprep',
hideLabel: true,
onClick: action('dataprep'),
},
{
label: 'go to elastic',
icon: 'talend-elastic',
hideLabel: true,
onClick: action('elastic'),
},
{
label: 'go to cloud engine',
icon: 'talend-cloud-engine',
hideLabel: true,
onClick: action('cloud-engine'),
},
],
},
],
right: [
{
displayMode: ActionBar.DISPLAY_MODES.BTN_GROUP,
actions: [
{
label: 'table',
icon: 'talend-table',
hideLabel: true,
onClick: action('table'),
},
{
label: 'trash',
icon: 'talend-trash',
hideLabel: true,
onClick: action('trash'),
},
],
},
],
};
const basicProps = {
actions,
multiSelectActions,
};
const multiDelete = {
label: 'Delete',
icon: 'talend-trash',
onClick: action('multiple delete'),
className: 'btn-icon-text',
};
const multiDuplicate = {
label: 'Duplicate',
icon: 'talend-files-o',
onClick: action('multiple duplicate'),
className: 'btn-icon-text',
};
const multiUpdate = {
label: 'Update',
icon: 'talend-file-move',
onClick: action('multiple update'),
className: 'btn-icon-text',
};
const multiFavorite = {
label: 'Favorite',
icon: 'talend-star',
onClick: action('multiple favorite'),
className: 'btn-icon-text',
};
const multiCertify = {
label: 'Certify',
icon: 'talend-badge',
onClick: action('multiple certify'),
className: 'btn-icon-text',
};
const massActions = {
left: [multiDelete, multiDuplicate, multiUpdate],
};
const appMassActions = {
left: [multiFavorite, multiCertify],
};
export default {
title: 'Form/Controls/ActionBar',
};
export const Default = () => (
<nav>
<p>No Selected, Layout: Left Space Right</p>
<div id="default">
<ActionBar {...basicProps} selected={0} />
</div>
<p>1 Selected, Layout: Left Center Right</p>
<div id="selected">
<ActionBar {...basicProps} selected={1} />
</div>
<p>1 Selected, Layout: Right</p>
<div id="right">
<ActionBar
selected={1}
actions={{ left: [primary] }}
multiSelectActions={{ right: [multi3] }}
/>
</div>
<p>Toolbar with btn-group and only icons/ Layout: left, center, right</p>
<div id="btn-group">
<ActionBar actions={btnGroupActions} />
</div>
<p>3 items selected, with mass/bulk Actions</p>
<div id="mass-actions">
<ActionBar
selected={3}
multiSelectActions={massActions}
appMultiSelectActions={appMassActions}
/>
</div>
</nav>
);
export const Custom = () => (
<nav>
<div id="default">
<ActionBar>
<ActionBar.Content tag="a" left href="#/foo/bar">
Hello anchor
</ActionBar.Content>
<ActionBar.Content tag="button" className="btn btn-default" left>
Hello button
</ActionBar.Content>
<ActionBar.Content left>
<Action label="hello Action" icon="talend-trash" onClick={action('onClick')} />
</ActionBar.Content>
<ActionBar.Content tag="form" role="search" center>
<div className="form-group">
<input type="text" className="form-control" placeholder="Search" />
</div>
<button type="submit" className="btn btn-default">
Submit
</button>
</ActionBar.Content>
<ActionBar.Content tag="p" right>
Hello paragraph
</ActionBar.Content>
</ActionBar>
</div>
</nav>
);
| Talend/ui | packages/components/src/ActionBar/ActionBar.stories.js | JavaScript | apache-2.0 | 6,576 |
import hashlib
from core.analytics import InlineAnalytics
from core.observables import Hash
HASH_TYPES_DICT = {
"md5": hashlib.md5,
"sha1": hashlib.sha1,
"sha256": hashlib.sha256,
"sha512": hashlib.sha512,
}
class HashFile(InlineAnalytics):
default_values = {
"name": "HashFile",
"description": "Extracts MD5, SHA1, SHA256, SHA512 hashes from file",
}
ACTS_ON = ["File", "Certificate"]
@staticmethod
def each(f):
if f.body:
f.hashes = []
for hash_type, h in HashFile.extract_hashes(f.body.contents):
hash_object = Hash.get_or_create(value=h.hexdigest())
hash_object.add_source("analytics")
hash_object.save()
f.active_link_to(
hash_object,
"{} hash".format(hash_type.upper()),
"HashFile",
clean_old=False,
)
f.hashes.append({"hash": hash_type, "value": h.hexdigest()})
f.save()
@staticmethod
def extract_hashes(body_contents):
hashers = {k: HASH_TYPES_DICT[k]() for k in HASH_TYPES_DICT}
while True:
chunk = body_contents.read(512 * 16)
if not chunk:
break
for h in hashers.values():
h.update(chunk)
return hashers.items()
| yeti-platform/yeti | plugins/analytics/public/hash_file.py | Python | apache-2.0 | 1,405 |
/**
* Copyright 2011-2021 Asakusa Framework Team.
*
* 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.asakusafw.dmdl.directio.text;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Predicate;
import org.apache.hadoop.io.compress.CompressionCodec;
import com.asakusafw.dmdl.directio.util.CharsetUtil;
import com.asakusafw.dmdl.directio.util.ClassName;
import com.asakusafw.dmdl.directio.util.Value;
import com.asakusafw.dmdl.java.emitter.EmitContext;
import com.asakusafw.dmdl.java.util.JavaName;
import com.asakusafw.dmdl.model.BasicTypeKind;
import com.asakusafw.dmdl.semantics.ModelDeclaration;
import com.asakusafw.dmdl.semantics.PropertyDeclaration;
import com.asakusafw.dmdl.semantics.type.BasicType;
import com.asakusafw.dmdl.util.AttributeUtil;
import com.asakusafw.runtime.io.text.TextFormat;
import com.asakusafw.runtime.io.text.TextInput;
import com.asakusafw.runtime.io.text.directio.AbstractTextStreamFormat;
import com.asakusafw.runtime.io.text.driver.FieldDefinition;
import com.asakusafw.runtime.io.text.driver.RecordDefinition;
import com.asakusafw.runtime.io.text.value.BooleanOptionFieldAdapter;
import com.asakusafw.runtime.io.text.value.ByteOptionFieldAdapter;
import com.asakusafw.runtime.io.text.value.DateOptionFieldAdapter;
import com.asakusafw.runtime.io.text.value.DateTimeOptionFieldAdapter;
import com.asakusafw.runtime.io.text.value.DecimalOptionFieldAdapter;
import com.asakusafw.runtime.io.text.value.DoubleOptionFieldAdapter;
import com.asakusafw.runtime.io.text.value.FloatOptionFieldAdapter;
import com.asakusafw.runtime.io.text.value.IntOptionFieldAdapter;
import com.asakusafw.runtime.io.text.value.LongOptionFieldAdapter;
import com.asakusafw.runtime.io.text.value.ShortOptionFieldAdapter;
import com.asakusafw.runtime.io.text.value.StringOptionFieldAdapter;
import com.asakusafw.runtime.io.text.value.ValueOptionFieldAdapter;
import com.asakusafw.runtime.io.util.InputSplitter;
import com.asakusafw.runtime.io.util.InputSplitters;
import com.asakusafw.runtime.value.StringOption;
import com.asakusafw.utils.java.model.syntax.ClassDeclaration;
import com.asakusafw.utils.java.model.syntax.Expression;
import com.asakusafw.utils.java.model.syntax.InfixOperator;
import com.asakusafw.utils.java.model.syntax.MethodDeclaration;
import com.asakusafw.utils.java.model.syntax.ModelFactory;
import com.asakusafw.utils.java.model.syntax.SimpleName;
import com.asakusafw.utils.java.model.syntax.Statement;
import com.asakusafw.utils.java.model.syntax.Type;
import com.asakusafw.utils.java.model.syntax.TypeBodyDeclaration;
import com.asakusafw.utils.java.model.util.AttributeBuilder;
import com.asakusafw.utils.java.model.util.ExpressionBuilder;
import com.asakusafw.utils.java.model.util.JavadocBuilder;
import com.asakusafw.utils.java.model.util.Models;
import com.asakusafw.utils.java.model.util.TypeBuilder;
/**
* Generates {@link AbstractTextStreamFormat}.
* @since 0.9.1
*/
public abstract class AbstractTextStreamFormatGenerator {
private static final Map<BasicTypeKind, Class<? extends ValueOptionFieldAdapter<?>>> ADAPTER_TYPES;
static {
Map<BasicTypeKind, Class<? extends ValueOptionFieldAdapter<?>>> map = new EnumMap<>(BasicTypeKind.class);
map.put(BasicTypeKind.BYTE, ByteOptionFieldAdapter.class);
map.put(BasicTypeKind.SHORT, ShortOptionFieldAdapter.class);
map.put(BasicTypeKind.INT, IntOptionFieldAdapter.class);
map.put(BasicTypeKind.LONG, LongOptionFieldAdapter.class);
map.put(BasicTypeKind.FLOAT, FloatOptionFieldAdapter.class);
map.put(BasicTypeKind.DOUBLE, DoubleOptionFieldAdapter.class);
map.put(BasicTypeKind.DECIMAL, DecimalOptionFieldAdapter.class);
map.put(BasicTypeKind.TEXT, StringOptionFieldAdapter.class);
map.put(BasicTypeKind.BOOLEAN, BooleanOptionFieldAdapter.class);
map.put(BasicTypeKind.DATE, DateOptionFieldAdapter.class);
map.put(BasicTypeKind.DATETIME, DateTimeOptionFieldAdapter.class);
ADAPTER_TYPES = map;
}
/**
* The current context.
*/
protected final EmitContext context;
/**
* The target model.
*/
protected final ModelDeclaration model;
private final ModelFactory f;
private final TextFormatSettings formatSettings;
private final TextFieldSettings fieldDefaultSettings;
/**
* Creates a new instance.
* @param context the current context
* @param model the target model
* @param formatSettings the text format settings
* @param fieldDefaultSettings the field default settings
*/
public AbstractTextStreamFormatGenerator(
EmitContext context, ModelDeclaration model,
TextFormatSettings formatSettings, TextFieldSettings fieldDefaultSettings) {
this.context = context;
this.model = model;
this.formatSettings = formatSettings;
this.fieldDefaultSettings = fieldDefaultSettings;
this.f = context.getModelFactory();
}
/**
* Emits an implementation of {@link AbstractTextStreamFormat} class as a Java compilation unit.
* @param description the format description
* @throws IOException if I/O error was occurred while emitting the compilation unit
*/
protected void emit(String description) throws IOException {
ClassDeclaration decl = f.newClassDeclaration(
new JavadocBuilder(f)
.inline(Messages.getString("AbstractTextStreamFormatGenerator.javadocClassOverview"), //$NON-NLS-1$
d -> d.text(description),
d -> d.linkType(context.resolve(model.getSymbol())))
.toJavadoc(),
new AttributeBuilder(f)
.Public()
.toAttributes(),
context.getTypeName(),
f.newParameterizedType(
context.resolve(AbstractTextStreamFormat.class),
context.resolve(model.getSymbol())),
Collections.emptyList(),
createMembers());
context.emit(decl);
}
private List<? extends TypeBodyDeclaration> createMembers() {
List<TypeBodyDeclaration> results = new ArrayList<>();
results.add(createGetSupportedType());
results.add(createCreateTextFormat());
results.addAll(createCreateRecordDefinition());
createGetInputSplitter().ifPresent(results::add);
createGetCompressionCodecClass().ifPresent(results::add);
createAfterInput().ifPresent(results::add);
createBeforeOutput().ifPresent(results::add);
return results;
}
private MethodDeclaration createGetSupportedType() {
return f.newMethodDeclaration(
null,
new AttributeBuilder(f)
.annotation(context.resolve(Override.class))
.Public()
.toAttributes(),
f.newParameterizedType(
context.resolve(Class.class),
context.resolve(model.getSymbol())),
f.newSimpleName("getSupportedType"), //$NON-NLS-1$
Collections.emptyList(),
Arrays.asList(new TypeBuilder(f, context.resolve(model.getSymbol()))
.dotClass()
.toReturnStatement()));
}
private MethodDeclaration createCreateTextFormat() {
return f.newMethodDeclaration(
null,
new AttributeBuilder(f)
.annotation(context.resolve(Override.class))
.Public()
.toAttributes(),
context.resolve(TextFormat.class),
f.newSimpleName("createTextFormat"), //$NON-NLS-1$
Collections.emptyList(),
createGetTextFormatInternal());
}
/**
* Returns a body of {@link AbstractTextStreamFormat#getTextFormat()}.
* @return the body statements
*/
protected abstract List<Statement> createGetTextFormatInternal();
private List<MethodDeclaration> createCreateRecordDefinition() {
SimpleName builder = f.newSimpleName("builder"); //$NON-NLS-1$
List<Statement> statements = new ArrayList<>();
statements.add(new TypeBuilder(f, context.resolve(RecordDefinition.class))
.method("builder", f.newClassLiteral(context.resolve(model.getSymbol()))) //$NON-NLS-1$
.toLocalVariableDeclaration(
f.newParameterizedType(
context.resolve(RecordDefinition.Builder.class),
context.resolve(model.getSymbol())),
builder));
List<MethodDeclaration> fields = buildRecordDefinition(statements, builder);
statements.add(new ExpressionBuilder(f, builder)
.method("build") //$NON-NLS-1$
.toReturnStatement());
List<MethodDeclaration> results = new ArrayList<>();
results.add(f.newMethodDeclaration(
null,
new AttributeBuilder(f)
.annotation(context.resolve(Override.class))
.Protected()
.toAttributes(),
f.newParameterizedType(
context.resolve(RecordDefinition.class),
context.resolve(model.getSymbol())),
f.newSimpleName("createRecordDefinition"), //$NON-NLS-1$
Collections.emptyList(),
statements));
results.addAll(fields);
return results;
}
private List<MethodDeclaration> buildRecordDefinition(List<Statement> statements, SimpleName builder) {
formatSettings.getHeaderType().ifPresent(v -> statements.add(new ExpressionBuilder(f, builder)
.method("withHeaderType", resolve(v)) //$NON-NLS-1$
.toStatement()));
formatSettings.getLessInputAction().ifPresent(v -> statements.add(new ExpressionBuilder(f, builder)
.method("withOnLessInput", resolve(v)) //$NON-NLS-1$
.toStatement()));
formatSettings.getMoreInputAction().ifPresent(v -> statements.add(new ExpressionBuilder(f, builder)
.method("withOnMoreInput", resolve(v)) //$NON-NLS-1$
.toStatement()));
fieldDefaultSettings.getTrimInputWhitespaces().ifPresent(v -> statements.add(new ExpressionBuilder(f, builder)
.method("withTrimInput", resolve(v)) //$NON-NLS-1$
.toStatement()));
fieldDefaultSettings.getSkipEmptyInput().ifPresent(v -> statements.add(new ExpressionBuilder(f, builder)
.method("withSkipEmptyInput", resolve(v)) //$NON-NLS-1$
.toStatement()));
fieldDefaultSettings.getMalformedInputAction().ifPresent(v -> statements.add(new ExpressionBuilder(f, builder)
.method("withOnMalformedInput", resolve(v)) //$NON-NLS-1$
.toStatement()));
fieldDefaultSettings.getUnmappableOutputAction().ifPresent(v -> statements.add(
new ExpressionBuilder(f, builder)
.method("withOnUnmappableOutput", resolve(v)) //$NON-NLS-1$
.toStatement()));
List<MethodDeclaration> fields = new ArrayList<>();
for (PropertyDeclaration property : model.getDeclaredProperties()) {
if (TextFieldTrait.getKind(property) != TextFieldTrait.Kind.VALUE) {
continue;
}
MethodDeclaration method = createGetFieldDefinition(property);
fields.add(method);
statements.add(new ExpressionBuilder(f, builder)
.method("withField", //$NON-NLS-1$
new TypeBuilder(f, context.resolve(model.getSymbol()))
.methodReference(context.getOptionGetterName(property))
.toExpression(),
new ExpressionBuilder(f, f.newThis())
.method(method.getName())
.toExpression())
.toStatement());
}
return fields;
}
private MethodDeclaration createGetFieldDefinition(PropertyDeclaration property) {
SimpleName builder = f.newSimpleName("builder"); //$NON-NLS-1$
List<Statement> statements = new ArrayList<>();
statements.add(new TypeBuilder(f, context.resolve(FieldDefinition.class))
.method("builder", //$NON-NLS-1$
resolve(TextFieldTrait.getName(property)),
buildFieldAdapter(property))
.toLocalVariableDeclaration(
f.newParameterizedType(
context.resolve(FieldDefinition.Builder.class),
context.getFieldType(property)),
builder));
TextFieldSettings settings = TextFieldTrait.getSettings(property);
settings.getTrimInputWhitespaces().ifPresent(v -> statements.add(new ExpressionBuilder(f, builder)
.method("withTrimInput", resolve(v)) //$NON-NLS-1$
.toStatement()));
settings.getSkipEmptyInput().ifPresent(v -> statements.add(new ExpressionBuilder(f, builder)
.method("withSkipEmptyInput", resolve(v)) //$NON-NLS-1$
.toStatement()));
settings.getMalformedInputAction().ifPresent(v -> statements.add(new ExpressionBuilder(f, builder)
.method("withOnMalformedInput", resolve(v)) //$NON-NLS-1$
.toStatement()));
settings.getUnmappableOutputAction().ifPresent(v -> statements.add(new ExpressionBuilder(f, builder)
.method("withOnUnmappableOutput", resolve(v)) //$NON-NLS-1$
.toStatement()));
settings.getQuoteStyle().ifPresent(v -> statements.add(new ExpressionBuilder(f, builder)
.method("withOutputOption", resolve(v)) //$NON-NLS-1$
.toStatement()));
statements.add(new ExpressionBuilder(f, builder)
.method("build") //$NON-NLS-1$
.toReturnStatement());
JavaName name = JavaName.of(property.getName());
name.addFirst("get"); //$NON-NLS-1$
name.addLast("field"); //$NON-NLS-1$
name.addLast("definition"); //$NON-NLS-1$
return f.newMethodDeclaration(
new JavadocBuilder(f)
.inline(Messages.getString("AbstractTextStreamFormatGenerator.javafocGetFieldDefinitionOverview"), //$NON-NLS-1$
d -> d.linkMethod(
context.resolve(model.getSymbol()),
context.getOptionGetterName(property)))
.returns()
.text(Messages.getString("AbstractTextStreamFormatGenerator.javadocGetFieldDefinitionReturn")) //$NON-NLS-1$
.toJavadoc(),
new AttributeBuilder(f)
.Protected()
.toAttributes(),
f.newParameterizedType(
context.resolve(FieldDefinition.class),
context.getFieldType(property)),
f.newSimpleName(name.toMemberName()),
Collections.emptyList(),
statements);
}
private Expression buildFieldAdapter(PropertyDeclaration property) {
TextFieldSettings settings = TextFieldTrait.getSettings(property);
Value<ClassName> adapterClass = setting(settings, TextFieldSettings::getAdapterClass);
if (adapterClass.isPresent()) {
return new TypeBuilder(f, resolve(adapterClass.getEntity()))
.constructorReference()
.toExpression();
}
BasicTypeKind kind = ((BasicType) property.getType()).getKind();
Class<? extends ValueOptionFieldAdapter<?>> basicAdapterClass = ADAPTER_TYPES.get(kind);
assert basicAdapterClass != null;
ExpressionBuilder builder = new TypeBuilder(f, context.resolve(basicAdapterClass)).method("builder"); //$NON-NLS-1$
setting(settings, TextFieldSettings::getNullFormat).ifPresent(v -> builder
.method("withNullFormat", resolve(v))); //$NON-NLS-1$
switch (kind) {
case BOOLEAN:
setting(settings, TextFieldSettings::getTrueFormat).ifPresent(v -> builder
.method("withTrueFormat", resolve(v))); //$NON-NLS-1$
setting(settings, TextFieldSettings::getFalseFormat).ifPresent(v -> builder
.method("withFalseFormat", resolve(v))); //$NON-NLS-1$
break;
case DATE:
setting(settings, TextFieldSettings::getDateFormat).ifPresent(v -> builder
.method("withDateFormat", resolve(v.toString()))); //$NON-NLS-1$
break;
case DATETIME:
setting(settings, TextFieldSettings::getDateTimeFormat).ifPresent(v -> builder
.method("withDateTimeFormat", resolve(v.toString()))); //$NON-NLS-1$
setting(settings, TextFieldSettings::getTimeZone).ifPresent(v -> builder
.method("withTimeZone", resolve(v.getId()))); //$NON-NLS-1$
break;
case DECIMAL:
setting(settings, TextFieldSettings::getNumberFormat).ifPresent(v -> builder
.method("withNumberFormat", resolve(v.toString()))); //$NON-NLS-1$
setting(settings, TextFieldSettings::getDecimalOutputStyle).ifPresent(v -> builder
.method("withOutputStyle", resolve(v))); //$NON-NLS-1$
break;
case BYTE:
case INT:
case SHORT:
case LONG:
case FLOAT:
case DOUBLE:
setting(settings, TextFieldSettings::getNumberFormat).ifPresent(v -> builder
.method("withNumberFormat", resolve(v.toString()))); //$NON-NLS-1$
break;
case TEXT:
// no special members
break;
default:
throw new AssertionError(kind);
}
return builder.method("lazy").toExpression(); //$NON-NLS-1$
}
private <T> Value<T> setting(TextFieldSettings settings, Function<TextFieldSettings, Value<T>> getter) {
return getter.apply(settings).orDefault(getter.apply(fieldDefaultSettings));
}
private Optional<MethodDeclaration> createGetInputSplitter() {
if (isSplittable()) {
return Optional.of(f.newMethodDeclaration(
null,
new AttributeBuilder(f)
.annotation(context.resolve(Override.class))
.Protected()
.toAttributes(),
context.resolve(InputSplitter.class),
f.newSimpleName("getInputSplitter"), //$NON-NLS-1$
Collections.emptyList(),
Arrays.asList(new TypeBuilder(f, context.resolve(InputSplitters.class))
.method("byLineFeed") //$NON-NLS-1$
.toReturnStatement())));
} else {
return Optional.empty();
}
}
private boolean isSplittable() {
if (formatSettings.getCharset().isPresent()) {
if (!CharsetUtil.isAsciiCompatible(formatSettings.getCharset().getEntity())) {
return false;
}
}
if (formatSettings.getCompressionType().isPresent()) {
return false;
}
if (model.getDeclaredProperties().stream()
.map(TextFieldTrait::getKind)
.anyMatch(Predicate.isEqual(TextFieldTrait.Kind.LINE_NUMBER)
.or(Predicate.isEqual(TextFieldTrait.Kind.RECORD_NUMBER)))) {
return false;
}
return isSplittableInternal();
}
/**
* Returns whether or not the input is splittable.
* @return {@code true} if it is splittable, otherwise {@code false}
*/
protected abstract boolean isSplittableInternal();
private Optional<MethodDeclaration> createGetCompressionCodecClass() {
if (formatSettings.getCompressionType().isPresent()) {
ClassName codec = formatSettings.getCompressionType().getEntity();
return Optional.of(f.newMethodDeclaration(
null,
new AttributeBuilder(f)
.annotation(context.resolve(Override.class))
.Protected()
.toAttributes(),
new TypeBuilder(f, context.resolve(Class.class))
.parameterize(f.newWildcardExtends(context.resolve(CompressionCodec.class)))
.toType(),
f.newSimpleName("getCompressionCodecClass"), //$NON-NLS-1$
Collections.emptyList(),
Arrays.asList(new TypeBuilder(f, resolve(codec))
.dotClass()
.toReturnStatement())));
} else {
return Optional.empty();
}
}
private Optional<MethodDeclaration> createAfterInput() {
SimpleName object = f.newSimpleName("object"); //$NON-NLS-1$
SimpleName path = f.newSimpleName("path"); //$NON-NLS-1$
SimpleName input = f.newSimpleName("input"); //$NON-NLS-1$
List<Statement> statements = new ArrayList<>();
for (PropertyDeclaration property : model.getDeclaredProperties()) {
switch (TextFieldTrait.getKind(property)) {
case VALUE:
break; // does nothing
case IGNORE:
statements.add(new ExpressionBuilder(f, object)
.method(context.getOptionSetterName(property), Models.toNullLiteral(f))
.toStatement());
break;
case FILE_NAME:
statements.add(new ExpressionBuilder(f, object)
.method(context.getOptionSetterName(property), path)
.toStatement());
break;
case LINE_NUMBER:
statements.add(new ExpressionBuilder(f, object)
.method(context.getValueSetterName(property),
adjustLong(property, new ExpressionBuilder(f, input)
.method("getLineNumber") //$NON-NLS-1$
.apply(InfixOperator.PLUS, Models.toLiteral(f, 1L))))
.toStatement());
break;
case RECORD_NUMBER:
statements.add(new ExpressionBuilder(f, object)
.method(context.getValueSetterName(property),
adjustLong(property, new ExpressionBuilder(f, input)
.method("getRecordIndex") //$NON-NLS-1$
.apply(InfixOperator.PLUS, Models.toLiteral(f, 1L))))
.toStatement());
break;
default:
throw new AssertionError(TextFieldTrait.getKind(property));
}
}
if (statements.isEmpty()) {
return Optional.empty();
} else {
return Optional.of(f.newMethodDeclaration(
null,
new AttributeBuilder(f)
.annotation(context.resolve(Override.class))
.Protected()
.toAttributes(),
context.resolve(void.class),
f.newSimpleName("afterInput"), //$NON-NLS-1$
Arrays.asList(
f.newFormalParameterDeclaration(context.resolve(model.getSymbol()), object),
f.newFormalParameterDeclaration(context.resolve(StringOption.class), path),
f.newFormalParameterDeclaration(
f.newParameterizedType(
context.resolve(TextInput.class),
context.resolve(model.getSymbol())),
input)),
statements));
}
}
private Expression adjustLong(PropertyDeclaration property, ExpressionBuilder builder) {
if (AttributeUtil.hasFieldType(property, BasicTypeKind.LONG)) {
return builder.toExpression();
} else if (AttributeUtil.hasFieldType(property, BasicTypeKind.INT)) {
return builder.castTo(context.resolve(int.class)).toExpression();
} else {
throw new AssertionError(property);
}
}
private Optional<MethodDeclaration> createBeforeOutput() {
return Optional.empty();
}
/**
* Resolves a value.
* @param value the value
* @return the resolved expression
*/
protected Expression resolve(boolean value) {
return Models.toLiteral(f, value);
}
/**
* Resolves a value.
* @param value the value
* @return the resolved expression
*/
protected Expression resolve(char value) {
return Models.toLiteral(f, value);
}
/**
* Resolves a value.
* @param value the value
* @return the resolved expression
*/
protected Expression resolve(String value) {
return Models.toLiteral(f, value);
}
/**
* Resolves a value.
* @param value the value
* @return the resolved expression
*/
protected Expression resolve(Enum<?> value) {
return new TypeBuilder(f, context.resolve(value.getDeclaringClass()))
.field(value.name())
.toExpression();
}
/**
* Resolves a value.
* @param type the value
* @return the resolved expression
*/
protected Type resolve(ClassName type) {
return context.resolve(Models.toName(f, type.toString()));
}
}
| asakusafw/asakusafw | directio-project/asakusa-directio-dmdl/src/main/java/com/asakusafw/dmdl/directio/text/AbstractTextStreamFormatGenerator.java | Java | apache-2.0 | 26,894 |
/*
* Copyright 2007 Sascha Weinreuter
*
* 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.intellij.plugins.relaxNG.references;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import com.intellij.codeInsight.daemon.EmptyResolveMessageProvider;
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.LocalQuickFixProvider;
import com.intellij.codeInspection.XmlQuickFixFactory;
import com.intellij.lang.xml.XMLLanguage;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiReference;
import com.intellij.psi.PsiReferenceProvider;
import com.intellij.psi.XmlElementFactory;
import com.intellij.psi.impl.source.resolve.reference.impl.providers.BasicAttributeValueReference;
import com.intellij.psi.impl.source.xml.SchemaPrefix;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.xml.XmlAttribute;
import com.intellij.psi.xml.XmlAttributeValue;
import com.intellij.psi.xml.XmlTag;
import com.intellij.util.ArrayUtil;
import com.intellij.util.ProcessingContext;
/*
* Created by IntelliJ IDEA.
* User: sweinreuter
* Date: 24.07.2007
*/
public class PrefixReferenceProvider extends PsiReferenceProvider
{
private static final Logger LOG = Logger.getInstance("#org.intellij.plugins.relaxNG.references.PrefixReferenceProvider");
@Override
@NotNull
public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull ProcessingContext context)
{
final XmlAttributeValue value = (XmlAttributeValue) element;
final String s = value.getValue();
final int i = s.indexOf(':');
if(i <= 0 || s.startsWith("xml:"))
{
return PsiReference.EMPTY_ARRAY;
}
return new PsiReference[]{
new PrefixReference(value, i)
};
}
private static class PrefixReference extends BasicAttributeValueReference implements EmptyResolveMessageProvider, LocalQuickFixProvider
{
public PrefixReference(XmlAttributeValue value, int length)
{
super(value, TextRange.from(1, length));
}
@Override
@Nullable
public PsiElement resolve()
{
final String prefix = getCanonicalText();
XmlTag tag = PsiTreeUtil.getParentOfType(getElement(), XmlTag.class);
while(tag != null)
{
if(tag.getLocalNamespaceDeclarations().containsKey(prefix))
{
final XmlAttribute attribute = tag.getAttribute("xmlns:" + prefix, "");
final TextRange textRange = TextRange.from("xmlns:".length(), prefix.length());
return new SchemaPrefix(attribute, textRange, prefix);
}
tag = tag.getParentTag();
}
return null;
}
@Override
public boolean isReferenceTo(PsiElement element)
{
if(element instanceof SchemaPrefix && element.getContainingFile() == myElement.getContainingFile())
{
final PsiElement e = resolve();
if(e instanceof SchemaPrefix)
{
final String s = ((SchemaPrefix) e).getName();
return s != null && s.equals(((SchemaPrefix) element).getName());
}
}
return super.isReferenceTo(element);
}
@Nullable
@Override
public LocalQuickFix[] getQuickFixes()
{
final PsiElement element = getElement();
final XmlElementFactory factory = XmlElementFactory.getInstance(element.getProject());
final String value = ((XmlAttributeValue) element).getValue();
final String[] name = value.split(":");
final XmlTag tag = factory.createTagFromText("<" + (name.length > 1 ? name[1] : value) + " />", XMLLanguage.INSTANCE);
return new LocalQuickFix[]{XmlQuickFixFactory.getInstance().createNSDeclarationIntentionFix(tag, getCanonicalText(), null)};
}
@Override
@NotNull
public Object[] getVariants()
{
return ArrayUtil.EMPTY_OBJECT_ARRAY;
}
@Override
public boolean isSoft()
{
return false;
}
@Override
@NotNull
public String getUnresolvedMessagePattern()
{
return "Undefined namespace prefix ''{0}''";
}
}
} | consulo/consulo-relaxng | src/org/intellij/plugins/relaxNG/references/PrefixReferenceProvider.java | Java | apache-2.0 | 4,459 |
/**
* Copyright 2017 Hortonworks.
*
* 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.hortonworks.streamline.streams.service;
import com.codahale.metrics.annotation.Timed;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hortonworks.streamline.common.exception.service.exception.request.BadRequestException;
import com.hortonworks.streamline.common.exception.service.exception.request.EntityNotFoundException;
import com.hortonworks.streamline.common.exception.service.exception.server.UnhandledServerException;
import com.hortonworks.streamline.common.util.WSUtils;
import com.hortonworks.streamline.streams.actions.topology.service.TopologyActionsService;
import com.hortonworks.streamline.streams.catalog.Topology;
import com.hortonworks.streamline.streams.catalog.TopologySink;
import com.hortonworks.streamline.streams.catalog.TopologySource;
import com.hortonworks.streamline.streams.catalog.TopologyTestRunCase;
import com.hortonworks.streamline.streams.catalog.TopologyTestRunCaseSink;
import com.hortonworks.streamline.streams.catalog.TopologyTestRunCaseSource;
import com.hortonworks.streamline.streams.catalog.TopologyTestRunHistory;
import com.hortonworks.streamline.streams.catalog.service.StreamCatalogService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.BooleanUtils;
import org.datanucleus.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import static java.util.stream.Collectors.toList;
import static javax.ws.rs.core.Response.Status.CREATED;
import static javax.ws.rs.core.Response.Status.OK;
@Path("/v1/catalog")
@Produces(MediaType.APPLICATION_JSON)
public class TopologyTestRunResource {
private static final Logger LOG = LoggerFactory.getLogger(TopologyTestRunResource.class);
private static final Integer DEFAULT_LIST_ENTITIES_COUNT = 5;
public static final Charset ENCODING_UTF_8 = Charset.forName("UTF-8");
private final StreamCatalogService catalogService;
private final TopologyActionsService actionsService;
private final ObjectMapper objectMapper;
public TopologyTestRunResource(StreamCatalogService catalogService, TopologyActionsService actionsService) {
this.catalogService = catalogService;
this.actionsService = actionsService;
this.objectMapper = new ObjectMapper();
}
@POST
@Path("/topologies/{topologyId}/actions/testrun")
@Timed
public Response testRunTopology (@Context UriInfo urlInfo,
@PathParam("topologyId") Long topologyId,
String testRunInputJson) throws Exception {
Topology result = catalogService.getTopology(topologyId);
if (result != null) {
TopologyTestRunHistory history = actionsService.testRunTopology(result, testRunInputJson);
return WSUtils.respondEntity(history, OK);
}
throw EntityNotFoundException.byId(topologyId.toString());
}
@GET
@Path("/topologies/{topologyId}/testhistories")
@Timed
public Response getHistoriesOfTestRunTopology (@Context UriInfo urlInfo,
@PathParam("topologyId") Long topologyId,
@QueryParam("limit") Integer limit) throws Exception {
Collection<TopologyTestRunHistory> histories = catalogService.listTopologyTestRunHistory(topologyId);
if (histories == null) {
throw EntityNotFoundException.byFilter("topology id " + topologyId);
}
List<TopologyTestRunHistory> filteredHistories = filterHistories(limit, histories);
return WSUtils.respondEntities(filteredHistories, OK);
}
@GET
@Path("/topologies/{topologyId}/versions/{versionId}/testhistories")
@Timed
public Response getHistoriesOfTestRunTopology (@Context UriInfo urlInfo,
@PathParam("topologyId") Long topologyId,
@PathParam("versionId") Long versionId,
@QueryParam("limit") Integer limit) throws Exception {
Collection<TopologyTestRunHistory> histories = catalogService.listTopologyTestRunHistory(topologyId, versionId);
if (histories == null) {
throw EntityNotFoundException.byFilter("topology id " + topologyId);
}
List<TopologyTestRunHistory> filteredHistories = filterHistories(limit, histories);
return WSUtils.respondEntities(filteredHistories, OK);
}
@GET
@Path("/topologies/{topologyId}/testhistories/{historyId}")
@Timed
public Response getHistoryOfTestRunTopology (@Context UriInfo urlInfo,
@PathParam("topologyId") Long topologyId,
@PathParam("historyId") Long historyId,
@QueryParam("simplify") Boolean simplify) throws Exception {
TopologyTestRunHistory history = catalogService.getTopologyTestRunHistory(historyId);
if (history == null) {
throw EntityNotFoundException.byId(String.valueOf(historyId));
}
if (!history.getTopologyId().equals(topologyId)) {
throw BadRequestException.message("Test history " + historyId + " is not belong to topology " + topologyId);
}
if (BooleanUtils.isTrue(simplify)) {
return WSUtils.respondEntity(new SimplifiedTopologyTestRunHistory(history), OK);
} else {
return WSUtils.respondEntity(history, OK);
}
}
@GET
@Path("/topologies/{topologyId}/testhistories/{historyId}/events")
public Response getEventsOfTestRunTopologyHistory(@Context UriInfo urlInfo,
@PathParam("topologyId") Long topologyId,
@PathParam("historyId") Long historyId) throws Exception {
return getEventsOfTestRunTopologyHistory(topologyId, historyId, null);
}
@GET
@Path("/topologies/{topologyId}/testhistories/{historyId}/events/{componentName}")
public Response getEventsOfTestRunTopologyHistory(@Context UriInfo urlInfo,
@PathParam("topologyId") Long topologyId,
@PathParam("historyId") Long historyId,
@PathParam("componentName") String componentName) throws Exception {
return getEventsOfTestRunTopologyHistory(topologyId, historyId, componentName);
}
@GET
@Path("/topologies/{topologyId}/testhistories/{historyId}/events/download")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response downloadEventsOfTestRunTopologyHistory(@Context UriInfo urlInfo,
@PathParam("topologyId") Long topologyId,
@PathParam("historyId") Long historyId) throws Exception {
File eventLogFile = getEventLogFile(topologyId, historyId);
String content = FileUtils.readFileToString(eventLogFile, ENCODING_UTF_8);
InputStream is = new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8));
String fileName = String.format("events-topology-%d-history-%d.log", topologyId, historyId);
return Response.status(OK)
.entity(is)
.header("Content-Disposition", "attachment; filename=\"" + fileName + "\"")
.build();
}
private Response getEventsOfTestRunTopologyHistory(Long topologyId, Long historyId, String componentName) throws IOException {
File eventLogFile = getEventLogFile(topologyId, historyId);
List<String> lines = FileUtils.readLines(eventLogFile, ENCODING_UTF_8);
Stream<Map<String, Object>> eventsStream = lines.stream().map(line -> {
try {
return objectMapper.readValue(line, new TypeReference<Map<String, Object>>() {});
} catch (IOException e) {
throw new RuntimeException(e);
}
});
if (!StringUtils.isEmpty(componentName)) {
eventsStream = eventsStream.filter(event -> {
String eventComponentName = (String) event.get("componentName");
return eventComponentName != null && eventComponentName.equals(componentName);
});
}
return WSUtils.respondEntities(eventsStream.collect(toList()), OK);
}
private File getEventLogFile(Long topologyId, Long historyId) {
TopologyTestRunHistory history = catalogService.getTopologyTestRunHistory(historyId);
if (history == null) {
throw EntityNotFoundException.byId(String.valueOf(historyId));
}
if (!history.getTopologyId().equals(topologyId)) {
throw BadRequestException.message("Test history " + historyId + " is not belong to topology " + topologyId);
}
String eventLogFilePath = history.getEventLogFilePath();
File eventLogFile = new File(eventLogFilePath);
if (!eventLogFile.exists() || eventLogFile.isDirectory() || !eventLogFile.canRead()) {
throw BadRequestException.message("Event log file of history " + historyId + " does not exist or is not readable.");
}
return eventLogFile;
}
private List<TopologyTestRunHistory> filterHistories(Integer limit, Collection<TopologyTestRunHistory> histories) {
if (limit == null) {
limit = DEFAULT_LIST_ENTITIES_COUNT;
}
return histories.stream()
// reverse order
.sorted((h1, h2) -> (int) (h2.getId() - h1.getId()))
.limit(limit)
.collect(toList());
}
@POST
@Path("/topologies/{topologyId}/testcases")
public Response addTestRunCase(@PathParam("topologyId") Long topologyId,
TopologyTestRunCase testRunCase) {
testRunCase.setTopologyId(topologyId);
Long currentVersionId = catalogService.getCurrentVersionId(topologyId);
testRunCase.setVersionId(currentVersionId);
TopologyTestRunCase addedCase = catalogService.addTopologyTestRunCase(testRunCase);
return WSUtils.respondEntity(addedCase, CREATED);
}
@POST
@Path("/topologies/{topologyId}/versions/{versionId}/testcases")
public Response addTestRunCase(@PathParam("topologyId") Long topologyId,
@PathParam("versionId") Long versionId,
TopologyTestRunCase testRunCase) {
testRunCase.setTopologyId(topologyId);
testRunCase.setVersionId(versionId);
TopologyTestRunCase addedCase = catalogService.addTopologyTestRunCase(testRunCase);
return WSUtils.respondEntity(addedCase, CREATED);
}
@PUT
@Path("/topologies/{topologyId}/testcases/{testCaseId}")
public Response addOrUpdateTestRunCase(@PathParam("topologyId") Long topologyId,
@PathParam("testCaseId") Long testCaseId,
TopologyTestRunCase testRunCase) {
testRunCase.setTopologyId(topologyId);
testRunCase.setId(testCaseId);
TopologyTestRunCase updatedCase = catalogService.addOrUpdateTopologyTestRunCase(topologyId, testRunCase);
return WSUtils.respondEntity(updatedCase, OK);
}
@GET
@Path("/topologies/{topologyId}/testcases/{testCaseId}")
public Response getTestRunCase(@PathParam("topologyId") Long topologyId,
@PathParam("testCaseId") Long testCaseId) {
TopologyTestRunCase testcase = catalogService.getTopologyTestRunCase(topologyId, testCaseId);
if (testcase == null) {
throw EntityNotFoundException.byId(Long.toString(testCaseId));
}
return WSUtils.respondEntity(testcase, OK);
}
@GET
@Path("/topologies/{topologyId}/testcases")
@Timed
public Response listTestRunCases(@Context UriInfo urlInfo,
@PathParam("topologyId") Long topologyId,
@QueryParam("limit") Integer limit) throws Exception {
Long currentVersionId = catalogService.getCurrentVersionId(topologyId);
Collection<TopologyTestRunCase> cases = catalogService.listTopologyTestRunCase(topologyId, currentVersionId);
if (cases == null) {
throw EntityNotFoundException.byFilter("topology id " + topologyId);
}
List<TopologyTestRunCase> filteredCases = filterTestRunCases(limit, cases);
return WSUtils.respondEntities(filteredCases, OK);
}
@GET
@Path("/topologies/{topologyId}/versions/{versionId}/testcases")
@Timed
public Response listTestRunCases(@Context UriInfo urlInfo,
@PathParam("topologyId") Long topologyId,
@PathParam("versionId") Long versionId,
@QueryParam("limit") Integer limit) throws Exception {
Collection<TopologyTestRunCase> cases = catalogService.listTopologyTestRunCase(topologyId, versionId);
if (cases == null) {
throw EntityNotFoundException.byFilter("topology id " + topologyId);
}
List<TopologyTestRunCase> filteredCases = filterTestRunCases(limit, cases);
return WSUtils.respondEntities(filteredCases, OK);
}
@DELETE
@Path("/topologies/{topologyId}/testcases/{testCaseId}")
public Response removeTestRunCase(@PathParam("topologyId") Long topologyId,
@PathParam("testCaseId") Long testCaseId) {
TopologyTestRunCase testRunCase = catalogService.removeTestRunCase(topologyId, testCaseId);
if (testRunCase != null) {
return WSUtils.respondEntity(testRunCase, OK);
}
throw EntityNotFoundException.byId(testCaseId.toString());
}
private List<TopologyTestRunCase> filterTestRunCases(Integer limit, Collection<TopologyTestRunCase> cases) {
if (limit == null) {
limit = DEFAULT_LIST_ENTITIES_COUNT;
}
return cases.stream()
// reverse order
.sorted((h1, h2) -> (int) (h2.getId() - h1.getId()))
.limit(limit)
.collect(toList());
}
@POST
@Path("/topologies/{topologyId}/testcases/{testCaseId}/sources")
public Response addTestRunCaseSource(@PathParam("topologyId") Long topologyId,
@PathParam("testCaseId") Long testCaseId,
TopologyTestRunCaseSource testRunCaseSource) {
TopologySource topologySource = getAssociatedTopologySource(topologyId, testCaseId, testRunCaseSource.getSourceId());
testRunCaseSource.setVersionId(topologySource.getVersionId());
TopologyTestRunCaseSource addedCaseSource = catalogService.addTopologyTestRunCaseSource(testRunCaseSource);
return WSUtils.respondEntity(addedCaseSource, CREATED);
}
@PUT
@Path("/topologies/{topologyId}/testcases/{testCaseId}/sources/{id}")
public Response addOrUpdateTestRunCaseSource(@PathParam("topologyId") Long topologyId,
@PathParam("testCaseId") Long testCaseId,
@PathParam("id") Long id,
TopologyTestRunCaseSource testRunCaseSource) {
testRunCaseSource.setId(id);
testRunCaseSource.setTestCaseId(testCaseId);
TopologySource topologySource = getAssociatedTopologySource(topologyId, testCaseId, testRunCaseSource.getSourceId());
testRunCaseSource.setVersionId(topologySource.getVersionId());
TopologyTestRunCaseSource updatedCase = catalogService.addOrUpdateTopologyTestRunCaseSource(testRunCaseSource.getId(), testRunCaseSource);
return WSUtils.respondEntity(updatedCase, OK);
}
private TopologySource getAssociatedTopologySource(Long topologyId, Long testCaseId, Long topologySourceId) {
TopologyTestRunCase testCase = catalogService.getTopologyTestRunCase(topologyId, testCaseId);
if (testCase == null) {
throw EntityNotFoundException.byId("Topology test case with topology id " + topologyId +
" and test case id " + testCaseId);
}
TopologySource topologySource = catalogService.getTopologySource(topologyId, topologySourceId,
testCase.getVersionId());
if (topologySource == null) {
throw EntityNotFoundException.byId("Topology source with topology id " + topologyId +
" and version id " + testCase.getVersionId());
} else if (!testCase.getVersionId().equals(topologySource.getVersionId())) {
throw new IllegalStateException("Test case and topology source point to the different version id: "
+ "version id of test case: " + testCase.getVersionId() + " / "
+ "version id of topology source: " + topologySource.getVersionId());
}
return topologySource;
}
@GET
@Path("/topologies/{topologyId}/testcases/{testcaseId}/sources/{id}")
public Response getTestRunCaseSource(@PathParam("topologyId") Long topologyId,
@PathParam("testcaseId") Long testcaseId,
@PathParam("id") Long id) {
TopologyTestRunCaseSource testCaseSource = catalogService.getTopologyTestRunCaseSource(testcaseId, id);
if (testCaseSource == null) {
throw EntityNotFoundException.byId(Long.toString(id));
}
return WSUtils.respondEntity(testCaseSource, OK);
}
@GET
@Path("/topologies/{topologyId}/testcases/{testCaseId}/sources/topologysource/{sourceId}")
public Response getTestRunCaseSourceByTopologySource(@PathParam("topologyId") Long topologyId,
@PathParam("testCaseId") Long testCaseId,
@PathParam("sourceId") Long sourceId) {
TopologyTestRunCaseSource testCaseSource = catalogService.getTopologyTestRunCaseSourceBySourceId(testCaseId, sourceId);
if (testCaseSource == null) {
throw EntityNotFoundException.byId("test case id: " + testCaseId + " , topology source id: " + sourceId);
}
return WSUtils.respondEntity(testCaseSource, OK);
}
@GET
@Path("/topologies/{topologyId}/testcases/{testCaseId}/sources")
public Response listTestRunCaseSource(@PathParam("topologyId") Long topologyId,
@PathParam("testCaseId") Long testCaseId) {
Collection<TopologyTestRunCaseSource> sources = catalogService.listTopologyTestRunCaseSource(topologyId, testCaseId);
if (sources == null) {
throw EntityNotFoundException.byFilter("topologyId: " + topologyId + " / testCaseId: " + testCaseId);
}
return WSUtils.respondEntities(sources, OK);
}
@POST
@Path("/topologies/{topologyId}/testcases/{testCaseId}/sinks")
public Response addTestRunCaseSink(@PathParam("topologyId") Long topologyId,
@PathParam("testCaseId") Long testCaseId,
TopologyTestRunCaseSink testRunCaseSink) {
TopologySink topologySink = getAssociatedTopologySink(topologyId, testCaseId, testRunCaseSink.getSinkId());
testRunCaseSink.setVersionId(topologySink.getVersionId());
TopologyTestRunCaseSink addedCaseSink = catalogService.addTopologyTestRunCaseSink(testRunCaseSink);
return WSUtils.respondEntity(addedCaseSink, CREATED);
}
@PUT
@Path("/topologies/{topologyId}/testcases/{testCaseId}/sinks/{id}")
public Response addOrUpdateTestRunCaseSink(@PathParam("topologyId") Long topologyId,
@PathParam("testCaseId") Long testCaseId,
@PathParam("id") Long id,
TopologyTestRunCaseSink testRunCaseSink) {
testRunCaseSink.setId(id);
testRunCaseSink.setTestCaseId(testCaseId);
TopologySink topologySink = getAssociatedTopologySink(topologyId, testCaseId, testRunCaseSink.getSinkId());
testRunCaseSink.setVersionId(topologySink.getVersionId());
TopologyTestRunCaseSink updatedCase = catalogService.addOrUpdateTopologyTestRunCaseSink(testRunCaseSink.getId(), testRunCaseSink);
return WSUtils.respondEntity(updatedCase, OK);
}
private TopologySink getAssociatedTopologySink(Long topologyId, Long testCaseId, Long topologySinkId) {
TopologyTestRunCase testCase = catalogService.getTopologyTestRunCase(topologyId, testCaseId);
if (testCase == null) {
throw EntityNotFoundException.byId("Topology test case with topology id " + topologyId +
" and test case id " + testCaseId);
}
TopologySink topologySink = catalogService.getTopologySink(topologyId, topologySinkId,
testCase.getVersionId());
if (topologySink == null) {
throw EntityNotFoundException.byId("Topology sink with topology id " + topologyId +
" and version id " + testCase.getVersionId());
} else if (!testCase.getVersionId().equals(topologySink.getVersionId())) {
throw new IllegalStateException("Test case and topology sink point to the different version id: "
+ "version id of test case: " + testCase.getVersionId() + " / "
+ "version id of topology sink: " + topologySink.getVersionId());
}
return topologySink;
}
@GET
@Path("/topologies/{topologyId}/testcases/{testcaseId}/sinks/{id}")
public Response getTestRunCaseSink(@PathParam("topologyId") Long topologyId,
@PathParam("testcaseId") Long testcaseId,
@PathParam("id") Long id) {
TopologyTestRunCaseSink testCaseSink = catalogService.getTopologyTestRunCaseSink(testcaseId, id);
if (testCaseSink == null) {
throw EntityNotFoundException.byId(Long.toString(id));
}
return WSUtils.respondEntity(testCaseSink, OK);
}
@GET
@Path("/topologies/{topologyId}/testcases/{testCaseId}/sinks/topologysink/{sinkId}")
public Response getTestRunCaseSinkByTopologySink(@PathParam("topologyId") Long topologyId,
@PathParam("testCaseId") Long testCaseId,
@PathParam("sinkId") Long sinkId) {
TopologyTestRunCaseSink testCaseSink = catalogService.getTopologyTestRunCaseSinkBySinkId(testCaseId, sinkId);
if (testCaseSink == null) {
throw EntityNotFoundException.byId("test case id: " + testCaseId + " , topology source id: " + sinkId);
}
return WSUtils.respondEntity(testCaseSink, OK);
}
@GET
@Path("/topologies/{topologyId}/testcases/{testCaseId}/sinks")
public Response listTestRunCaseSink(@PathParam("topologyId") Long topologyId,
@PathParam("testCaseId") Long testCaseId) {
Collection<TopologyTestRunCaseSink> sources = catalogService.listTopologyTestRunCaseSink(topologyId, testCaseId);
if (sources == null) {
throw EntityNotFoundException.byFilter("topologyId: " + topologyId + " / testCaseId: " + testCaseId);
}
return WSUtils.respondEntities(sources, OK);
}
private static class SimplifiedTopologyTestRunHistory {
private Long id;
private Long topologyId;
private Long versionId;
private Boolean finished = false;
private Boolean success = false;
private Boolean matched = false;
private Long startTime;
private Long finishTime;
private Long timestamp;
SimplifiedTopologyTestRunHistory(TopologyTestRunHistory history) {
id = history.getId();
topologyId = history.getTopologyId();
versionId = history.getVersionId();
finished = history.getFinished();
success = history.getSuccess();
matched = history.getMatched();
startTime = history.getStartTime();
finishTime = history.getFinishTime();
timestamp = history.getTimestamp();
}
public Long getId() {
return id;
}
public Long getTopologyId() {
return topologyId;
}
public Long getVersionId() {
return versionId;
}
public Boolean getFinished() {
return finished;
}
public Boolean getSuccess() {
return success;
}
public Boolean getMatched() {
return matched;
}
public Long getStartTime() {
return startTime;
}
public Long getFinishTime() {
return finishTime;
}
public Long getTimestamp() {
return timestamp;
}
}
}
| hmcl/Streams | streams/service/src/main/java/com/hortonworks/streamline/streams/service/TopologyTestRunResource.java | Java | apache-2.0 | 26,797 |
package org.jruby.ext.ffi.jna;
import java.util.ArrayList;
import org.jruby.runtime.ThreadContext;
/**
* An invocation session.
* This provides post-invoke cleanup.
*/
final class Invocation {
private final ThreadContext context;
private ArrayList<Runnable> postInvokeList;
Invocation(ThreadContext context) {
this.context = context;
}
void finish() {
if (postInvokeList != null) {
for (Runnable r : postInvokeList) {
r.run();
}
}
}
void addPostInvoke(Runnable postInvoke) {
if (postInvokeList == null) {
postInvokeList = new ArrayList<Runnable>();
}
postInvokeList.add(postInvoke);
}
ThreadContext getThreadContext() {
return context;
}
}
| google-code/android-scripting | jruby/src/src/org/jruby/ext/ffi/jna/Invocation.java | Java | apache-2.0 | 796 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_75) on Tue May 19 17:12:39 PDT 2015 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>org.apache.hadoop.registry.client.impl.zk (Apache Hadoop Main 2.6.0-cdh5.4.2 API)</title>
<meta name="date" content="2015-05-19">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
</head>
<body>
<h1 class="bar"><a href="../../../../../../../org/apache/hadoop/registry/client/impl/zk/package-summary.html" target="classFrame">org.apache.hadoop.registry.client.impl.zk</a></h1>
<div class="indexContainer">
<h2 title="Interfaces">Interfaces</h2>
<ul title="Interfaces">
<li><a href="RegistryBindingSource.html" title="interface in org.apache.hadoop.registry.client.impl.zk" target="classFrame"><i>RegistryBindingSource</i></a></li>
</ul>
<h2 title="Classes">Classes</h2>
<ul title="Classes">
<li><a href="BindingInformation.html" title="class in org.apache.hadoop.registry.client.impl.zk" target="classFrame">BindingInformation</a></li>
<li><a href="RegistryOperationsService.html" title="class in org.apache.hadoop.registry.client.impl.zk" target="classFrame">RegistryOperationsService</a></li>
</ul>
</div>
</body>
</html>
| ZhangXFeng/hadoop | share/doc/api/org/apache/hadoop/registry/client/impl/zk/package-frame.html | HTML | apache-2.0 | 1,371 |
# Zigara tenuis (Salisb.) Raf. SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Apiales/Apiaceae/Zigara/Zigara tenuis/README.md | Markdown | apache-2.0 | 186 |
package lists
class OrderedTest(val value: String) extends Ordered[OrderedTest] {
override def compare(that: OrderedTest): Int = {
value.compareToIgnoreCase(that.value)
}
override def toString = value
}
object Test extends App {
val test1 = List(0, 1, 2, 3, 4, 5, 6, 7)
val test1concat = List(8, 9, 10)
val test2 = List("Foo", "Bar")
val test2concat = List("Baz")
val test3 = List(new OrderedTest("a"), new OrderedTest("C"), new OrderedTest("B"))
println(length(test1))
println(concat(test1, test1concat))
println(length(test2))
println(concat(test2, test2concat))
println(last(test1))
println(init(test1))
println(tail(test2concat))
println(head(test1))
println(reverse(concat(test1, test1concat)))
println(reverse(reverse(test1)) == test1)
println(take(test1, 3))
println(drop(test1, 3))
println(apply(test1, 3))
println(splitAt(test1, length(test1) / 2))
println(flatten(List(test1, test1concat)))
println(flatten(List(test2, test2concat)))
val normalOrderMerge = mergeSort[Int](_ < _)_
val normalOrderInsert = insertSort[Int](_ < _)_
val reverseOrderMerge = mergeSort[Int](_ > _)_
val reverseOrderInsert = insertSort[Int](_ > _)_
val stringSortMerge = mergeSort[String](_ < _)_
val stringSortInsert = insertSort[String](_ < _)_
println(stringSortMerge(concat(test2concat, test2)))
println(stringSortInsert(concat(test2concat, test2)))
println(normalOrderMerge(concat(reverse(test1), test1concat)))
println(normalOrderInsert(concat(reverse(test1), test1concat)))
println(reverseOrderMerge(test1))
println(reverseOrderInsert(test1))
println(normalOrderMerge(reverseOrderMerge(test1)))
println(normalOrderInsert(reverseOrderInsert(test1)))
println(orderedMergeSort(test3))
}
| mhotchen/programming-in-scala | src/lists/Test.scala | Scala | apache-2.0 | 1,763 |
package org.onetwo.ext.security.utils;
import java.util.Collection;
import org.onetwo.common.web.userdetails.UserDetail;
import org.onetwo.common.web.userdetails.UserRoot;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
@SuppressWarnings("serial")
public class LoginUserDetails extends User implements UserDetail, /*SsoTokenable,*/ UserRoot {
final private long userId;
// private String token;
private String nickname;
private String avatar;
public LoginUserDetails(long userId, String username, String password,
Collection<? extends GrantedAuthority> authorities) {
super(username, password, authorities);
this.userId = userId;
}
public long getUserId() {
return userId;
}
@Override
public String getUserName() {
return getUsername();
}
@Override
public boolean isSystemRootUser() {
return userId==ROOT_USER_ID;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
/*public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}*/
}
| wayshall/onetwo | core/modules/security/src/main/java/org/onetwo/ext/security/utils/LoginUserDetails.java | Java | apache-2.0 | 1,289 |
/*
<samplecode>
<abstract>
A DSPKernel subclass implementing the realtime signal processing portion of the FilterDemo audio unit.
</abstract>
</samplecode>
*/
#ifndef FilterDSPKernel_hpp
#define FilterDSPKernel_hpp
#import "DSPKernel.hpp"
#import "ParameterRamper.hpp"
#import <vector>
static inline float convertBadValuesToZero(float x) {
/*
Eliminate denormals, not-a-numbers, and infinities.
Denormals will fail the first test (absx > 1e-15), infinities will fail
the second test (absx < 1e15), and NaNs will fail both tests. Zero will
also fail both tests, but since it will get set to zero that is OK.
*/
float absx = fabs(x);
if (absx > 1e-15 && absx < 1e15) {
return x;
}
return 0.0;
}
enum {
FilterParamCutoff = 0,
FilterParamResonance = 1
};
static inline double squared(double x) {
return x * x;
}
/*
FilterDSPKernel
Performs our filter signal processing.
As a non-ObjC class, this is safe to use from render thread.
*/
class FilterDSPKernel : public DSPKernel {
public:
// MARK: Types
struct FilterState {
float x1 = 0.0;
float x2 = 0.0;
float y1 = 0.0;
float y2 = 0.0;
void clear() {
x1 = 0.0;
x2 = 0.0;
y1 = 0.0;
y2 = 0.0;
}
void convertBadStateValuesToZero() {
/*
These filters work by feedback. If an infinity or NaN should come
into the filter input, the feedback variables can become infinity
or NaN which will cause the filter to stop operating. This function
clears out any bad numbers in the feedback variables.
*/
x1 = convertBadValuesToZero(x1);
x2 = convertBadValuesToZero(x2);
y1 = convertBadValuesToZero(y1);
y2 = convertBadValuesToZero(y2);
}
};
struct BiquadCoefficients {
float a1 = 0.0;
float a2 = 0.0;
float b0 = 0.0;
float b1 = 0.0;
float b2 = 0.0;
void calculateLopassParams(double frequency, double resonance) {
/*
The transcendental function calls here could be replaced with
interpolated table lookups or other approximations.
*/
// Convert from decibels to linear.
double r = pow(10.0, 0.05 * -resonance);
double k = 0.5 * r * sin(M_PI * frequency);
double c1 = (1.0 - k) / (1.0 + k);
double c2 = (1.0 + c1) * cos(M_PI * frequency);
double c3 = (1.0 + c1 - c2) * 0.25;
b0 = float(c3);
b1 = float(2.0 * c3);
b2 = float(c3);
a1 = float(-c2);
a2 = float(c1);
}
// Arguments in Hertz.
double magnitudeForFrequency( double inFreq) {
// Cast to Double.
double _b0 = double(b0);
double _b1 = double(b1);
double _b2 = double(b2);
double _a1 = double(a1);
double _a2 = double(a2);
// Frequency on unit circle in z-plane.
double zReal = cos(M_PI * inFreq);
double zImaginary = sin(M_PI * inFreq);
// Zeros response.
double numeratorReal = (_b0 * (squared(zReal) - squared(zImaginary))) + (_b1 * zReal) + _b2;
double numeratorImaginary = (2.0 * _b0 * zReal * zImaginary) + (_b1 * zImaginary);
double numeratorMagnitude = sqrt(squared(numeratorReal) + squared(numeratorImaginary));
// Poles response.
double denominatorReal = squared(zReal) - squared(zImaginary) + (_a1 * zReal) + _a2;
double denominatorImaginary = (2.0 * zReal * zImaginary) + (_a1 * zImaginary);
double denominatorMagnitude = sqrt(squared(denominatorReal) + squared(denominatorImaginary));
// Total response.
double response = numeratorMagnitude / denominatorMagnitude;
return response;
}
};
// MARK: Member Functions
FilterDSPKernel() {}
void init(int channelCount, double inSampleRate) {
channelStates.resize(channelCount);
sampleRate = float(inSampleRate);
nyquist = 0.5 * sampleRate;
inverseNyquist = 1.0 / nyquist;
dezipperRampDuration = (AUAudioFrameCount)floor(0.02 * sampleRate);
cutoffRamper.init();
resonanceRamper.init();
}
void reset() {
cutoffRamper.reset();
resonanceRamper.reset();
for (FilterState& state : channelStates) {
state.clear();
}
}
void setParameter(AUParameterAddress address, AUValue value) {
switch (address) {
case FilterParamCutoff:
//cutoffRamper.setUIValue(clamp(value * inverseNyquist, 0.0f, 0.99f));
cutoffRamper.setUIValue(clamp(value * inverseNyquist, 0.0005444f, 0.9070295f));
break;
case FilterParamResonance:
resonanceRamper.setUIValue(clamp(value, -20.0f, 20.0f));
break;
}
}
AUValue getParameter(AUParameterAddress address) {
switch (address) {
case FilterParamCutoff:
// Return the goal. It is not thread safe to return the ramping value.
//return (cutoffRamper.getUIValue() * nyquist);
return roundf((cutoffRamper.getUIValue() * nyquist) * 100) / 100;
case FilterParamResonance:
return resonanceRamper.getUIValue();
default: return 12.0f * inverseNyquist;
}
}
void startRamp(AUParameterAddress address, AUValue value, AUAudioFrameCount duration) override {
switch (address) {
case FilterParamCutoff:
cutoffRamper.startRamp(clamp(value * inverseNyquist, 12.0f * inverseNyquist, 0.99f), duration);
break;
case FilterParamResonance:
resonanceRamper.startRamp(clamp(value, -20.0f, 20.0f), duration);
break;
}
}
void setBuffers(AudioBufferList* inBufferList, AudioBufferList* outBufferList) {
inBufferListPtr = inBufferList;
outBufferListPtr = outBufferList;
}
void process(AUAudioFrameCount frameCount, AUAudioFrameCount bufferOffset) override {
int channelCount = int(channelStates.size());
cutoffRamper.dezipperCheck(dezipperRampDuration);
resonanceRamper.dezipperCheck(dezipperRampDuration);
// For each sample.
for (int frameIndex = 0; frameIndex < frameCount; ++frameIndex) {
/*
The filter coefficients are updated every sample! This is very
expensive. You probably want to do things differently.
*/
double cutoff = double(cutoffRamper.getAndStep());
double resonance = double(resonanceRamper.getAndStep());
coeffs.calculateLopassParams(cutoff, resonance);
int frameOffset = int(frameIndex + bufferOffset);
for (int channel = 0; channel < channelCount; ++channel) {
FilterState& state = channelStates[channel];
float* in = (float*)inBufferListPtr->mBuffers[channel].mData + frameOffset;
float* out = (float*)outBufferListPtr->mBuffers[channel].mData + frameOffset;
float x0 = *in;
float y0 = (coeffs.b0 * x0) + (coeffs.b1 * state.x1) + (coeffs.b2 * state.x2) - (coeffs.a1 * state.y1) - (coeffs.a2 * state.y2);
*out = y0;
state.x2 = state.x1;
state.x1 = x0;
state.y2 = state.y1;
state.y1 = y0;
}
}
// Squelch any blowups once per cycle.
for (int channel = 0; channel < channelCount; ++channel) {
channelStates[channel].convertBadStateValuesToZero();
}
}
// MARK: Member Variables
private:
std::vector<FilterState> channelStates;
BiquadCoefficients coeffs;
float sampleRate = 44100.0;
float nyquist = 0.5 * sampleRate;
float inverseNyquist = 1.0 / nyquist;
AUAudioFrameCount dezipperRampDuration;
AudioBufferList* inBufferListPtr = nullptr;
AudioBufferList* outBufferListPtr = nullptr;
public:
// Parameters.
ParameterRamper cutoffRamper = 400.0 / 44100.0;
ParameterRamper resonanceRamper = 20.0;
};
#endif /* FilterDSPKernel_hpp */
| eviathan/Salt | Pepper/Code Examples/Apple/AudioUnitV3ExampleABasicAudioUnitExtensionandHostImplementation/Filter/Shared/FilterDSPKernel.hpp | C++ | apache-2.0 | 7,597 |
// import { Domain } from '../Domain';
// import { GetDomain } from './GetDomain';
//
// /**
// * Find domain from object or type
// */
// export function FindDomain(target: Function | object): Domain | undefined {
// let prototype;
// if (typeof target === 'function') {
// prototype = target.prototype;
// } else {
// prototype = target;
// }
//
// while (prototype) {
// const domain = GetDomain(prototype);
// if (domain) {
// // console.log('FOUND');
// return domain;
// }
// // console.log('NOT FOUND!!!');
// prototype = Reflect.getPrototypeOf(prototype);
// }
// return;
// }
| agentframework/agentframework | src/domain/Domain/Helpers/FindDomain.ts | TypeScript | apache-2.0 | 641 |
/*
* Copyright (C) 2015 P100 OG, 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.shiftconnects.android.auth.example.util;
import com.google.gson.Gson;
import com.google.gson.JsonParseException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import retrofit.converter.ConversionException;
import retrofit.converter.Converter;
import retrofit.mime.MimeUtil;
import retrofit.mime.TypedInput;
import retrofit.mime.TypedOutput;
/**
* A {@link Converter} which uses GSON for serialization and deserialization of entities.
*
* @author Jake Wharton ([email protected])
*/
public class GsonConverter implements Converter {
private final Gson gson;
private String charset;
/**
* Create an instance using the supplied {@link Gson} object for conversion. Encoding to JSON and
* decoding from JSON (when no charset is specified by a header) will use UTF-8.
*/
public GsonConverter(Gson gson) {
this(gson, "UTF-8");
}
/**
* Create an instance using the supplied {@link Gson} object for conversion. Encoding to JSON and
* decoding from JSON (when no charset is specified by a header) will use the specified charset.
*/
public GsonConverter(Gson gson, String charset) {
this.gson = gson;
this.charset = charset;
}
@Override public Object fromBody(TypedInput body, Type type) throws ConversionException {
String charset = this.charset;
if (body.mimeType() != null) {
charset = MimeUtil.parseCharset(body.mimeType(), charset);
}
InputStreamReader isr = null;
try {
isr = new InputStreamReader(body.in(), charset);
return gson.fromJson(isr, type);
} catch (IOException e) {
throw new ConversionException(e);
} catch (JsonParseException e) {
throw new ConversionException(e);
} finally {
if (isr != null) {
try {
isr.close();
} catch (IOException ignored) {
}
}
}
}
@Override public TypedOutput toBody(Object object) {
try {
return new JsonTypedOutput(gson.toJson(object).getBytes(charset), charset);
} catch (UnsupportedEncodingException e) {
throw new AssertionError(e);
}
}
private static class JsonTypedOutput implements TypedOutput {
private final byte[] jsonBytes;
private final String mimeType;
JsonTypedOutput(byte[] jsonBytes, String encode) {
this.jsonBytes = jsonBytes;
this.mimeType = "application/json; charset=" + encode;
}
@Override public String fileName() {
return null;
}
@Override public String mimeType() {
return mimeType;
}
@Override public long length() {
return jsonBytes.length;
}
@Override public void writeTo(OutputStream out) throws IOException {
out.write(jsonBytes);
}
}
}
| shiftconnects/android-auth-manager | sample/src/main/java/com/shiftconnects/android/auth/example/util/GsonConverter.java | Java | apache-2.0 | 3,430 |
package acceptance;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import utils.CommandStatus;
import utils.TemporaryDigdagServer;
import java.nio.file.Path;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static utils.TestUtils.copyResource;
import static utils.TestUtils.main;
//
// This file doesn't contain normal case.
// It defined in another test.
//
public class ValidateProjectIT
{
@Rule
public TemporaryFolder folder = new TemporaryFolder();
@Rule
public TemporaryDigdagServer server = TemporaryDigdagServer.builder()
.build();
private Path config;
private Path projectDir;
@Before
public void setUp()
throws Exception
{
projectDir = folder.getRoot().toPath().resolve("foobar");
config = folder.newFile().toPath();
}
@Test
public void uploadInvalidTaskProject()
throws Exception
{
// Create new project
CommandStatus initStatus = main("init",
"-c", config.toString(),
projectDir.toString());
assertThat(initStatus.code(), is(0));
copyResource("acceptance/error_task/invalid_at_group.dig", projectDir.resolve("invalid_at_group.dig"));
// Push the project
CommandStatus pushStatus = main(
"push",
"--project", projectDir.toString(),
"foobar",
"-c", config.toString(),
"-e", server.endpoint());
assertThat(pushStatus.code(), is(1));
assertThat(pushStatus.errUtf8(), containsString("A task can't have more than one operator"));
}
@Test
public void uploadInvalidScheduleProject()
throws Exception
{
// Create new project
CommandStatus initStatus = main("init",
"-c", config.toString(),
projectDir.toString());
assertThat(initStatus.code(), is(0));
copyResource("acceptance/schedule/invalid_schedule.dig", projectDir.resolve("invalid_schedule.dig"));
// Push the project
CommandStatus pushStatus = main(
"push",
"--project", projectDir.toString(),
"foobar",
"-c", config.toString(),
"-e", server.endpoint());
assertThat(pushStatus.code(), is(1));
assertThat(pushStatus.errUtf8(), containsString("scheduler requires mm:ss format"));
}
}
| treasure-data/digdag | digdag-tests/src/test/java/acceptance/ValidateProjectIT.java | Java | apache-2.0 | 2,609 |
/*
* Copyright Strimzi authors.
* License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html).
*/
package io.strimzi.api.kafka.model.connect.build;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import io.strimzi.api.kafka.model.UnknownPropertyPreserving;
import io.strimzi.crdgenerator.annotations.Description;
import lombok.EqualsAndHashCode;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* Abstract baseclass for different representations of connect build outputs, discriminated by {@link #getType() type}.
*/
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.EXISTING_PROPERTY,
property = "type"
)
@JsonSubTypes(
{
@JsonSubTypes.Type(value = DockerOutput.class, name = Output.TYPE_DOCKER),
@JsonSubTypes.Type(value = ImageStreamOutput.class, name = Output.TYPE_IMAGESTREAM)
}
)
@JsonInclude(JsonInclude.Include.NON_NULL)
@EqualsAndHashCode
public abstract class Output implements UnknownPropertyPreserving, Serializable {
private static final long serialVersionUID = 1L;
public static final String TYPE_DOCKER = "docker";
public static final String TYPE_IMAGESTREAM = "imagestream";
private String image;
private Map<String, Object> additionalProperties = new HashMap<>(0);
@Description("Output type. " +
"Must be either `docker` for pushing the newly build image to Docker compatible registry or `imagestream` for pushing the image to OpenShift ImageStream. " +
"Required.")
public abstract String getType();
@Description("The name of the image which will be built. " +
"Required")
@JsonProperty(required = true)
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
@Override
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@Override
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
| scholzj/barnabas | api/src/main/java/io/strimzi/api/kafka/model/connect/build/Output.java | Java | apache-2.0 | 2,326 |
/**
*
*/
package com.transcend.rds.worker;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.springframework.transaction.annotation.Transactional;
import com.msi.tough.cf.json.DatabagParameter;
import com.msi.tough.core.Appctx;
import com.msi.tough.core.HibernateUtil;
import com.msi.tough.core.JsonUtil;
import com.msi.tough.model.AccountBean;
import com.msi.tough.model.rds.RdsDbinstance;
import com.msi.tough.model.rds.RdsDbparameterGroup;
import com.msi.tough.model.rds.RdsParameter;
import com.msi.tough.query.ErrorResponse;
import com.msi.tough.query.QueryFaults;
import com.msi.tough.query.ServiceRequestContext;
import com.msi.tough.rds.ValidationManager;
import com.msi.tough.rds.json.RDSConfigDatabagItem;
import com.msi.tough.rds.json.RDSDatabag;
import com.msi.tough.rds.json.RDSParameterGroupDatabagItem;
import com.msi.tough.utils.AccountUtil;
import com.msi.tough.utils.ChefUtil;
import com.msi.tough.utils.ConfigurationUtil;
import com.msi.tough.utils.Constants;
import com.msi.tough.utils.RDSQueryFaults;
import com.msi.tough.utils.rds.InstanceEntity;
import com.msi.tough.utils.rds.ParameterGroupEntity;
import com.msi.tough.utils.rds.RDSUtilities;
import com.msi.tough.workflow.core.AbstractWorker;
import com.transcend.rds.message.ModifyDBParameterGroupActionMessage.ModifyDBParameterGroupActionRequestMessage;
import com.transcend.rds.message.ModifyDBParameterGroupActionMessage.ModifyDBParameterGroupActionResultMessage;
import com.transcend.rds.message.RDSMessage.Parameter;
/**
* @author tdhite
*/
public class ModifyDBParameterGroupActionWorker extends
AbstractWorker<ModifyDBParameterGroupActionRequestMessage, ModifyDBParameterGroupActionResultMessage> {
private final static Logger logger = Appctx
.getLogger(ModifyDBParameterGroupActionWorker.class.getName());
/**
* We need a local copy of this doWork to provide the transactional
* annotation. Transaction management is handled by the annotation, which
* can only be on a concrete class.
* @param req
* @return
* @throws Exception
*/
@Transactional
public ModifyDBParameterGroupActionResultMessage doWork(
ModifyDBParameterGroupActionRequestMessage req) throws Exception {
logger.debug("Performing work for ModifyDBParameterGroupAction.");
return super.doWork(req, getSession());
}
/**
* modifyDBParameterGroup ************************************************
* This Operation modifies the parameters associated with the named
* DBParameterGroup. It essentially adds/updates parameters associated with
* a DBParameterGroup If parameter exists then update if parameter doesn't
* exist then insert Request: DBParameterGroupName(R) List of Parameter
* records(R) Parameters: List of up to 20 parameter records Response:
* DBParameterGroup Exceptions: DBParameterGroupNotFound
* InvalidDBParameterGroupState Processing 1. Confirm that ParamaterGroup
* exists and is in the appropriate state 2. Update the Parameter records by
* inserting or updating new parameter 3. Return response
*/
@Override
protected ModifyDBParameterGroupActionResultMessage doWork0(ModifyDBParameterGroupActionRequestMessage req,
ServiceRequestContext context) throws Exception {
logger.debug("ModifyDBParameterGroup action is called.");
final Session sess = HibernateUtil.newSession();
final AccountBean ac = context.getAccountBean();
final ModifyDBParameterGroupActionResultMessage.Builder resp = ModifyDBParameterGroupActionResultMessage.newBuilder();
try {
sess.beginTransaction();
final long userId = ac.getId();
final String grpName = ValidationManager.validateIdentifier(
req.getDbParameterGroupName(), 255, true);
final List<Parameter> pList = req.getParametersList();
final int pListLen = pList.size();
logger.info("ModifyDBParameterGroup: " + " UserID = " + userId
+ " ParameterGroupName = " + grpName
+ " Total Number of Listed Parameters = " + pListLen);
if (grpName.equals("default.mysql5.5")) {
throw RDSQueryFaults
.InvalidClientTokenId("You do not have privilege to modify default DBParameterGroup.");
}
// check that DBParameterGroup exists
final RdsDbparameterGroup pGrpRec = ParameterGroupEntity
.getParameterGroup(sess, grpName, ac.getId());
if (pGrpRec == null) {
throw RDSQueryFaults.DBParameterGroupNotFound();
}
final Collection<RdsDbinstance> dbInstances = InstanceEntity
.selectDBInstancesByParameterGroup(sess, grpName, -1, ac);
// make sure that all DBInstances using this DBParameterGroup are in
// available state
for (final RdsDbinstance dbinstance : dbInstances) {
if (!dbinstance.getDbinstanceStatus().equals(
RDSUtilities.STATUS_AVAILABLE)) {
throw RDSQueryFaults
.InvalidDBParameterGroupState("Currently there are DBInstance(s) that use this DBParameterGroup and it"
+ " is not in available state.");
}
}
// reset the parameters in the DB
List<RdsParameter> forRebootPending = new LinkedList<RdsParameter>();
final String paramGrpFamily = pGrpRec.getDbparameterGroupFamily();
final AccountBean sac = AccountUtil.readAccount(sess, 1L);
for (final Parameter p : pList) {
final RdsParameter target = ParameterGroupEntity.getParameter(
sess, grpName, p.getParameterName(), userId);
if (target == null) {
throw RDSQueryFaults.InvalidParameterValue(p
.getParameterName() + " parameter does not exist.");
}
logger.debug("Current target parameter: " + target.toString());
if (!target.getIsModifiable()) {
throw RDSQueryFaults.InvalidParameterValue(p
.getParameterName()
+ " is not modifiable parameter.");
}
// TODO validate p.getParameterValue along with
// p.getParameterName to ensure the value is allowed
else if (p.getApplyMethod().equals(
RDSUtilities.PARM_APPMETHOD_IMMEDIATE)) {
if (target.getApplyType().equals(
RDSUtilities.PARM_APPTYPE_STATIC)) {
throw QueryFaults
.InvalidParameterCombination(target
.getParameterName()
+ " is not dynamic. You can only"
+ " use \"pending-reboot\" as valid ApplyMethod for this parameter.");
}
target.setParameterValue(p.getParameterValue());
target.setSource(Constants.USER);
sess.save(target);
} else if (p.getApplyMethod().equals(
RDSUtilities.PARM_APPMETHOD_PENDING)) {
final RdsParameter temp = new RdsParameter();
temp.setParameterName(p.getParameterName());
temp.setApplyMethod(p.getApplyMethod());
temp.setParameterValue(p.getParameterValue());
forRebootPending.add(temp);
}
}
// Delete and regenerate the Databag
logger.debug("There are " + dbInstances.size()
+ " databags to modify.");
for (final RdsDbinstance instance : dbInstances) {
logger.debug("Currently updating the databag for DBInstance "
+ instance.getDbinstanceId());
final String databagName = "rds-" + ac.getId() + "-"
+ instance.getDbinstanceId();
logger.debug("Deleting the databag " + databagName);
ChefUtil.deleteDatabagItem(databagName, "config");
final String postWaitUrl = (String) ConfigurationUtil
.getConfiguration(Arrays.asList(new String[] {
"TRANSCEND_URL", instance.getAvailabilityZone() }));
final String servletUrl = (String) ConfigurationUtil
.getConfiguration(Arrays.asList(new String[] {
"SERVLET_URL", instance.getAvailabilityZone() }));
final RDSConfigDatabagItem configDataBagItem = new RDSConfigDatabagItem(
"config", instance.getAllocatedStorage().toString(),
instance.getMasterUsername(),
instance.getMasterUserPassword(),
instance.getAutoMinorVersionUpgrade(),
instance.getEngine(), instance.getEngineVersion(),
instance.getDbName(), instance
.getBackupRetentionPeriod().toString(),
instance.getPreferredBackupWindow(),
instance.getPreferredMaintenanceWindow(), instance
.getPort().toString(), postWaitUrl, servletUrl,
instance.getDbinstanceId(), "rds." + ac.getId() + "."
+ instance.getDbinstanceId(), ac.getId(), instance.getDbinstanceClass(), "false");
final RDSParameterGroupDatabagItem parameterGroupDatabagItem = new RDSParameterGroupDatabagItem(
"parameters", pGrpRec);
parameterGroupDatabagItem.getParameters().remove("read_only");
parameterGroupDatabagItem.getParameters().put(
"read_only",
DatabagParameter.factory("boolean",
"" + instance.getRead_only(), true, "dynamic"));
parameterGroupDatabagItem.getParameters().remove("port");
parameterGroupDatabagItem.getParameters().put(
"port",
DatabagParameter.factory("integer",
"" + instance.getPort(), false, "static"));
final RDSDatabag bag = new RDSDatabag(configDataBagItem,
parameterGroupDatabagItem);
logger.debug("Databag: "
+ JsonUtil.toJsonPrettyPrintString(bag));
logger.debug("Regenerating the databag " + databagName);
ChefUtil.createDatabagItem(databagName, "config", bag.toJson());
}
if (forRebootPending != null && forRebootPending.size() > 0) {
// forRebootPending is now a list of static parameters and
// dynamic parameters with pending-reboot ApplyMethod
forRebootPending = ParameterGroupEntity
.modifyParamGroupWithPartialList(sess, pGrpRec,
forRebootPending, userId);
// code below may need to be rewritten for better performance;
// Hibernate may be useful to improve the snippet below
for (final RdsDbinstance instance : dbInstances) {
final List<RdsParameter> alreadyPending = instance
.getPendingRebootParameters();
if (alreadyPending == null || alreadyPending.size() == 0) {
instance.setPendingRebootParameters(forRebootPending);
// instance.setDbinstanceStatus(RDSUtilities.STATUS_MODIFYING);
sess.save(instance);
} else {
for (final RdsParameter newParam : forRebootPending) {
boolean found = false;
int i = 0;
while (!found && i < alreadyPending.size()) {
if (alreadyPending.get(i).getParameterName()
.equals(newParam.getParameterName())) {
alreadyPending.get(i).setParameterValue(
newParam.getParameterValue());
found = true;
}
++i;
}
if (!found) {
alreadyPending.add(newParam);
}
}
}
}
}
// build response document - returns DBParameterGroupName
resp.setDbParameterGroupName(grpName);
logger.debug("Committing all the changes...");
sess.getTransaction().commit();
} catch (final ErrorResponse rde) {
sess.getTransaction().rollback();
throw rde;
} catch (final Exception e) {
e.printStackTrace();
sess.getTransaction().rollback();
final String msg = "CreateInstance: Class: " + e.getClass()
+ "Msg:" + e.getMessage();
logger.error(msg);
throw RDSQueryFaults.InternalFailure();
} finally {
sess.close();
}
return resp.buildPartial();
}
}
| TranscendComputing/TopStackRDS | src/com/transcend/rds/worker/ModifyDBParameterGroupActionWorker.java | Java | apache-2.0 | 11,169 |
/*
* Copyright (C) 2014 Johannes Donath <[email protected]>
*
* 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.evilco.emulator.extension.chip8;
import org.evilco.emulator.ui_old.extension.AbstractEmulatorExtension;
import org.evilco.emulator.ui_old.extension.InterfaceExtensionManager;
/**
* @author Johannes Donath <[email protected]>
* @copyright Copyright (C) 2014 Evil-Co <http://www.evil-co.com>
*/
public class Chip8Extension extends AbstractEmulatorExtension {
/**
* {@inheritDoc}
*/
@Override
public String getIdentifier () {
return "org.evilco.emulator.extension.chip8";
}
/**
* {@inheritDoc}
*/
@Override
public void onEnable (InterfaceExtensionManager extensionManager) {
super.onEnable (extensionManager);
extensionManager.registerExtension (this, "c8", Chip8Emulator.class);
}
} | Evil-Co-Legacy/CyborgEmulator | extension/chip8/src/main/java/org/evilco/emulator/extension/chip8/Chip8Extension.java | Java | apache-2.0 | 1,398 |
class PagosController < ApplicationController
before_action :set_pago, only: [:show, :edit, :update, :destroy]
# GET /pagos
# GET /pagos.json
def index
@pagos = Pago.all
end
# GET /pagos/1
# GET /pagos/1.json
def show
end
# GET /pagos/new
def new
@pago = Pago.new
end
# GET /pagos/1/edit
def edit
end
# POST /pagos
# POST /pagos.json
def create
@pago = Pago.new(pago_params)
respond_to do |format|
if @pago.save
format.html { redirect_to @pago, notice: 'Pago añadido' }
format.json { render :show, status: :created, location: @pago }
else
format.html { render :new }
format.json { render json: @pago.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /pagos/1
# PATCH/PUT /pagos/1.json
def update
respond_to do |format|
if @pago.update(pago_params)
format.html { redirect_to @pago, notice: 'Pago actualizado' }
format.json { render :show, status: :ok, location: @pago }
else
format.html { render :edit }
format.json { render json: @pago.errors, status: :unprocessable_entity }
end
end
end
# DELETE /pagos/1
# DELETE /pagos/1.json
def destroy
@pago.destroy
respond_to do |format|
format.html { redirect_to pagos_url, notice: 'Pago eliminado' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_pago
@pago = Pago.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def pago_params
params.require(:pago).permit(:cliente_id,:dominio_fecha_expiracion, :pagado, :fecha_pago, :ano,:dominio_nombre ,:dominio_anual ,:hosting_mes ,:hosting_anual, :total, :comentarios)
end
end
| felixparra/Gestzam | gestzam/app/controllers/pagos_controller.rb | Ruby | apache-2.0 | 1,867 |
/** Automatically generated file. DO NOT MODIFY */
package com.example.android_servicetest;
public final class BuildConfig {
public final static boolean DEBUG = true;
} | firefoxmmx2/Android_ServiceTest | gen/com/example/android_servicetest/BuildConfig.java | Java | apache-2.0 | 173 |
To set your browser's language preferences,
follow the instructions in
[Setting language preferences in a browser](https://www.w3.org/International/questions/qa-lang-priorities).
| edom/web | planner/README.md | Markdown | apache-2.0 | 179 |
/*
* Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
*/
#include "inter_vn_stats.h"
#include <oper/interface.h>
#include <oper/mirror_table.h>
using namespace std;
InterVnStatsCollector::VnStatsSet *InterVnStatsCollector::Find(string vn) {
VnStatsMap::iterator it = inter_vn_stats_.find(vn);
if (it != inter_vn_stats_.end()) {
return it->second;
}
return NULL;
}
void InterVnStatsCollector::PrintAll() {
VnStatsMap::iterator it = inter_vn_stats_.begin();
while(it != inter_vn_stats_.end()) {
PrintVn(it->first);
it++;
}
}
void InterVnStatsCollector::PrintVn(string vn) {
VnStatsSet *stats_set;
VnStats *stats;
LOG(DEBUG, "...........Stats for Vn " << vn);
VnStatsMap::iterator it = inter_vn_stats_.find(vn);
if (it != inter_vn_stats_.end()) {
stats_set = it->second;
/* Remove all the elements of map entry value which is a set */
VnStatsSet::iterator stats_it = stats_set->begin();
while(stats_it != stats_set->end()) {
stats = *stats_it;
stats_it++;
LOG(DEBUG, " Other-VN " << stats->dst_vn);
LOG(DEBUG, " in_pkts " << stats->in_pkts << " in_bytes " << stats->in_bytes);
LOG(DEBUG, " out_pkts " << stats->out_pkts << " out_bytes " << stats->out_bytes);
}
}
}
void InterVnStatsCollector::Remove(string vn) {
VnStatsSet *stats_set;
VnStats *stats;
VnStatsMap::iterator it = inter_vn_stats_.find(vn);
if (it != inter_vn_stats_.end()) {
stats_set = it->second;
/* Remove the entry from the inter_vn_stats_ map */
inter_vn_stats_.erase(it);
/* Remove all the elements of map entry value which is a set */
VnStatsSet::iterator stats_it = stats_set->begin();
VnStatsSet::iterator del_it;
while(stats_it != stats_set->end()) {
stats = *stats_it;
delete stats;
del_it = stats_it;
stats_it++;
stats_set->erase(del_it);
}
delete stats_set;
}
}
void InterVnStatsCollector::UpdateVnStats(FlowEntry *fe, uint64_t bytes,
uint64_t pkts) {
string src_vn = fe->data.source_vn, dst_vn = fe->data.dest_vn;
if (!fe->data.source_vn.length())
src_vn = *FlowHandler::UnknownVn();
if (!fe->data.dest_vn.length())
dst_vn = *FlowHandler::UnknownVn();
if (fe->local_flow) {
VnStatsUpdateInternal(src_vn, dst_vn, bytes, pkts, true);
VnStatsUpdateInternal(dst_vn, src_vn, bytes, pkts, false);
} else {
if (fe->data.ingress) {
VnStatsUpdateInternal(src_vn, dst_vn, bytes, pkts, true);
} else {
VnStatsUpdateInternal(dst_vn, src_vn, bytes, pkts, false);
}
}
//PrintAll();
}
void InterVnStatsCollector::VnStatsUpdateInternal(string src_vn, string dst_vn,
uint64_t bytes, uint64_t pkts,
bool outgoing) {
VnStatsSet *stats_set;
VnStats *stats;
VnStatsMap::iterator it = inter_vn_stats_.find(src_vn);
if (it == inter_vn_stats_.end()) {
stats = new VnStats(dst_vn, bytes, pkts, outgoing);
stats_set = new VnStatsSet;
stats_set->insert(stats);
inter_vn_stats_.insert(make_pair(src_vn, stats_set));
} else {
stats_set = it->second;
VnStats key(dst_vn, 0, 0, false);
VnStatsSet::iterator stats_it = stats_set->find(&key);
if (stats_it == stats_set->end()) {
stats = new VnStats(dst_vn, bytes, pkts, outgoing);
stats_set->insert(stats);
} else {
stats = *stats_it;
if (outgoing) {
stats->out_bytes += bytes;
stats->out_pkts += pkts;
} else {
stats->in_bytes += bytes;
stats->in_pkts += pkts;
}
}
}
}
| sysbot/contrail-controller | src/vnsw/agent/uve/inter_vn_stats.cc | C++ | apache-2.0 | 4,028 |
package com.fordprog.matrix.interpreter.type;
public enum Type {
RATIONAL,
MATRIX,
FUNCTION,
VOID
}
| daergoth/MatrixC | src/main/java/com/fordprog/matrix/interpreter/type/Type.java | Java | apache-2.0 | 115 |
/*
* Copyright 2016 peter.
*
* 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 onl.area51.filesystem.io;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Map;
import org.kohsuke.MetaInfServices;
/**
* A flat FileSystem which locally matches it's structure
*/
@MetaInfServices(FileSystemIO.class)
public class Flat
extends LocalFileSystemIO
{
public Flat( Path basePath,
Map<String, ?> env )
{
super( basePath, env );
}
@Override
protected String getPath( char[] path )
throws IOException
{
return String.valueOf( path );
}
}
| peter-mount/filesystem | filesystem-core/src/main/java/onl/area51/filesystem/io/Flat.java | Java | apache-2.0 | 1,156 |
/*
* @author Flavio Keller
*
* Copyright 2014 University of Zurich
*
* 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.signalcollect.sna.constants;
/**
* Enumeration for the different classes that can occur
* when running a SNA method algorithm
*/
public enum SNAClassNames {
DEGREE("Degree"), PAGERANK("PageRank"), CLOSENESS("Closeness"), BETWEENNESS("Betweenness"), PATH("Path"), LOCALCLUSTERCOEFFICIENT(
"LocalClusterCoefficient"), TRIADCENSUS("Triad Census"), LABELPROPAGATION(
"Label Propagation") ;
private final String className;
SNAClassNames(String name) {
this.className = name;
}
}
| fkzrh/signal-collect-sna | src/main/java/com/signalcollect/sna/constants/SNAClassNames.java | Java | apache-2.0 | 1,155 |
/***************************************************************************
* Copyright 2015 Kieker Project (http://kieker-monitoring.net)
*
* 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 kieker.test.common.junit.record.flow.trace.concurrency.monitor;
import java.nio.ByteBuffer;
import org.junit.Assert;
import org.junit.Test;
import kieker.common.record.flow.trace.concurrency.monitor.MonitorNotifyEvent;
import kieker.common.util.registry.IRegistry;
import kieker.common.util.registry.Registry;
import kieker.test.common.junit.AbstractKiekerTest;
/**
* @author Jan Waller
*
* @since 1.8
*/
public class TestMonitorNotifyEvent extends AbstractKiekerTest {
private static final long TSTAMP = 987998L;
private static final long TRACE_ID = 23444L;
private static final int ORDER_INDEX = 234;
private static final int LOCK_ID = 13;
/**
* Default constructor.
*/
public TestMonitorNotifyEvent() {
// empty default constructor
}
/**
* Tests the constructor and toArray(..) methods of {@link MonitorNotifyEvent}.
*
* Assert that a record instance event1 equals an instance event2 created by serializing event1 to an array event1Array
* and using event1Array to construct event2. This ignores a set loggingTimestamp!
*/
@Test
public void testSerializeDeserializeEquals() {
final MonitorNotifyEvent event1 = new MonitorNotifyEvent(TSTAMP, TRACE_ID, ORDER_INDEX, LOCK_ID);
Assert.assertEquals("Unexpected timestamp", TSTAMP, event1.getTimestamp());
Assert.assertEquals("Unexpected trace ID", TRACE_ID, event1.getTraceId());
Assert.assertEquals("Unexpected order index", ORDER_INDEX, event1.getOrderIndex());
Assert.assertEquals("Unexpected lock id", LOCK_ID, event1.getLockId());
final Object[] event1Array = event1.toArray();
final MonitorNotifyEvent event2 = new MonitorNotifyEvent(event1Array);
Assert.assertEquals(event1, event2);
Assert.assertEquals(0, event1.compareTo(event2));
}
/**
* Tests the constructor and writeBytes(..) methods of {@link MonitorNotifyEvent}.
*/
@Test
public void testSerializeDeserializeBinaryEquals() {
final MonitorNotifyEvent event1 = new MonitorNotifyEvent(TSTAMP, TRACE_ID, ORDER_INDEX, LOCK_ID);
Assert.assertEquals("Unexpected timestamp", TSTAMP, event1.getTimestamp());
Assert.assertEquals("Unexpected trace ID", TRACE_ID, event1.getTraceId());
Assert.assertEquals("Unexpected order index", ORDER_INDEX, event1.getOrderIndex());
Assert.assertEquals("Unexpected lock id", LOCK_ID, event1.getLockId());
final IRegistry<String> stringRegistry = new Registry<String>();
final ByteBuffer buffer = ByteBuffer.allocate(event1.getSize());
event1.writeBytes(buffer, stringRegistry);
buffer.flip();
final MonitorNotifyEvent event2 = new MonitorNotifyEvent(buffer, stringRegistry);
Assert.assertEquals(event1, event2);
Assert.assertEquals(0, event1.compareTo(event2));
}
}
| HaStr/kieker | kieker-common/test/kieker/test/common/junit/record/flow/trace/concurrency/monitor/TestMonitorNotifyEvent.java | Java | apache-2.0 | 3,493 |
import zerorpc
import gevent.queue
import logging
import sys
logging.basicConfig()
# root logger
logger = logging.getLogger()
# set the mimimum level for root logger so it will be possible for a client
# to subscribe and receive logs for any log level
logger.setLevel(0)
class QueueingLogHandler(logging.Handler):
""" A simple logging handler which puts all emitted logs into a
gevent queue.
"""
def __init__(self, queue, level, formatter):
super(QueueingLogHandler, self).__init__()
self._queue = queue
self.setLevel(level)
self.setFormatter(formatter)
def emit(self, record):
msg = self.format(record)
self._queue.put_nowait(msg)
def close(self):
super(QueueingLogHandler, self).close()
self._queue.put_nowait(None)
@property
def emitted(self):
return self._queue
class TestService(object):
_HANDLER_CLASS = QueueingLogHandler
_DEFAULT_FORMAT = '%(name)s - %(levelname)s - %(asctime)s - %(message)s'
logger = logging.getLogger("service")
def __init__(self):
self._logging_handlers = set()
def test(self, logger_name, logger_level, message):
logger = logging.getLogger(logger_name)
getattr(logger, logger_level.lower())(message)
def available_loggers(self):
""" List of initalized loggers """
return logging.getLogger().manager.loggerDict.keys()
def close_log_streams(self):
""" Closes all log_stream streams. """
while self._logging_handlers:
self._logging_handlers.pop().close()
@zerorpc.stream
def log_stream(self, logger_name, level_name, format_str):
""" Attaches a log handler to the specified logger and sends emitted logs
back as stream.
"""
if logger_name != "" and logger_name not in self.available_loggers():
raise ValueError("logger {0} is not available".format(logger_name))
level_name_upper = level_name.upper() if level_name else "NOTSET"
try:
level = getattr(logging, level_name_upper)
except AttributeError, e:
raise AttributeError("log level {0} is not available".format(level_name_upper))
q = gevent.queue.Queue()
fmt = format_str if format_str.strip() else self._DEFAULT_FORMAT
logger = logging.getLogger(logger_name)
formatter = logging.Formatter(fmt)
handler = self._HANDLER_CLASS(q, level, formatter)
logger.addHandler(handler)
self._logging_handlers.add(handler)
self.logger.debug("new subscriber for {0}/{1}".format(logger_name or "root", level_name_upper))
try:
for msg in handler.emitted:
if msg is None:
return
yield msg
finally:
self._logging_handlers.discard(handler)
handler.close()
self.logger.debug("subscription finished for {0}/{1}".format(logger_name or "root", level_name_upper))
if __name__ == "__main__":
service = TestService()
server = zerorpc.Server(service)
server.bind(sys.argv[1])
logger.warning("starting service")
try:
server.run()
except BaseException, e:
logger.error(str(e))
finally:
logger.warning("shutting down")
| benctamas/zerorpc-logging | logstream_test.py | Python | apache-2.0 | 3,399 |
package com.twitter.finagle.postgres.values
/*
* Enumeration of value types that can be included in query results.
*/
object Types {
val BOOL = 16
val BYTE_A = 17
val CHAR = 18
val NAME = 19
val INT_8 = 20
val INT_2 = 21
val INT_4 = 23
val REG_PROC = 24
val TEXT = 25
val OID = 26
val TID = 27
val XID = 28
val CID = 29
val JSON = 114
val XML = 142
val POINT = 600
val L_SEG = 601
val PATH = 602
val BOX = 603
val POLYGON = 604
val LINE = 628
val CIDR = 650
val FLOAT_4 = 700
val FLOAT_8 = 701
val ABS_TIME = 702
val REL_TIME = 703
val T_INTERVAL = 704
val UNKNOWN = 705
val CIRCLE = 718
val MONEY = 790
val MAC_ADDR = 829
val INET = 869
val BP_CHAR = 1042
val VAR_CHAR = 1043
val DATE = 1082
val TIME = 1083
val TIMESTAMP = 1114
val TIMESTAMP_TZ = 1184
val INTERVAL = 1186
val TIME_TZ = 1266
val BIT = 1560
val VAR_BIT = 1562
val NUMERIC = 1700
val REF_CURSOR = 1790
val RECORD = 2249
val VOID = 2278
val UUID = 2950
}
| finagle/finagle-postgres | src/main/scala/com/twitter/finagle/postgres/values/Types.scala | Scala | apache-2.0 | 1,017 |
# Leptopodia murina var. alpestris (Boud.) R. Heim & L. Remy VARIETY
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Leptopodia alpestris Boud.
### Remarks
null | mdoering/backbone | life/Fungi/Ascomycota/Pezizomycetes/Pezizales/Helvellaceae/Helvella/Helvella ephippium/Leptopodia murina alpestris/README.md | Markdown | apache-2.0 | 213 |
/**
* Copyright © 2013 enioka. 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.enioka.jqm.api.test;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.junit.Assert;
import org.junit.Test;
import com.enioka.jqm.api.JqmClientFactory;
import com.enioka.jqm.api.Query;
import com.enioka.jqm.api.Query.Sort;
import com.enioka.jqm.api.State;
import com.enioka.jqm.jdbc.Db;
import com.enioka.jqm.jdbc.DbConn;
import com.enioka.jqm.model.Instruction;
import com.enioka.jqm.model.JobDef;
import com.enioka.jqm.model.JobDef.PathType;
import com.enioka.jqm.model.JobInstance;
import com.enioka.jqm.model.Queue;
/**
* Simple tests for checking query syntax (no data)
*/
public class BasicTest
{
private static Logger jqmlogger = Logger.getLogger(BasicTest.class);
@Test
public void testChain()
{
// No exception allowed!
JqmClientFactory.getClient().getQueues();
jqmlogger.info("q1");
JqmClientFactory.getClient().getQueues();
jqmlogger.info("q2");
}
@Test
public void testQuery()
{
Query q = new Query("toto", null);
q.setInstanceApplication("marsu");
q.setInstanceKeyword2("pouet");
q.setInstanceModule("module");
q.setParentId(12);
q.setJobInstanceId(132);
q.setQueryLiveInstances(true);
q.setJobDefKeyword2("pouet2");
JqmClientFactory.getClient().getJobs(q);
}
@Test
public void testQueryDate()
{
Query q = new Query("toto", null);
q.setInstanceApplication("marsu");
q.setInstanceKeyword2("pouet");
q.setInstanceModule("module");
q.setParentId(12);
q.setJobInstanceId(132);
q.setQueryLiveInstances(true);
q.setEnqueuedBefore(Calendar.getInstance());
q.setEndedAfter(Calendar.getInstance());
q.setBeganRunningAfter(Calendar.getInstance());
q.setBeganRunningBefore(Calendar.getInstance());
q.setEnqueuedAfter(Calendar.getInstance());
q.setEnqueuedBefore(Calendar.getInstance());
q.setJobDefKeyword2("pouet2");
JqmClientFactory.getClient().getJobs(q);
}
@Test
public void testQueryStatusOne()
{
Query q = new Query("toto", null);
q.setQueryLiveInstances(true);
q.setInstanceApplication("marsu");
q.addStatusFilter(State.CRASHED);
JqmClientFactory.getClient().getJobs(q);
}
@Test
public void testQueryStatusTwo()
{
Query q = new Query("toto", null);
q.setQueryLiveInstances(true);
q.setInstanceApplication("marsu");
q.addStatusFilter(State.CRASHED);
q.addStatusFilter(State.HOLDED);
JqmClientFactory.getClient().getJobs(q);
}
@Test
public void testFluentQuery()
{
Query q = new Query("toto", null);
q.setQueryLiveInstances(true);
q.setInstanceApplication("marsu");
q.addStatusFilter(State.CRASHED);
q.addStatusFilter(State.HOLDED);
JqmClientFactory.getClient().getJobs(Query.create().addStatusFilter(State.RUNNING).setApplicationName("MARSU"));
}
@Test
public void testQueryPercent()
{
JqmClientFactory.getClient().getJobs(Query.create().setApplicationName("%TEST"));
}
@Test
public void testQueryNull()
{
JqmClientFactory.getClient().getJobs(new Query("", null));
}
@Test
public void testQueueNameId()
{
Query.create().setQueueName("test").run();
Query.create().setQueueId(12).run();
}
@Test
public void testPaginationWithFilter()
{
Query.create().setQueueName("test").setPageSize(10).run();
Query.create().setQueueId(12).setPageSize(10).run();
}
@Test
public void testUsername()
{
Query.create().setUser("test").setPageSize(10).run();
}
@Test
public void testSortHistory()
{
Query.create().setUser("test").setPageSize(10).addSortAsc(Sort.APPLICATIONNAME).addSortDesc(Sort.DATEATTRIBUTION)
.addSortAsc(Sort.DATEEND).addSortDesc(Sort.DATEENQUEUE).addSortAsc(Sort.ID).addSortDesc(Sort.QUEUENAME)
.addSortAsc(Sort.STATUS).addSortDesc(Sort.USERNAME).addSortAsc(Sort.PARENTID).run();
}
@Test
public void testSortJi()
{
Query.create().setQueryHistoryInstances(false).setQueryLiveInstances(true).setUser("test").addSortAsc(Sort.APPLICATIONNAME)
.addSortDesc(Sort.DATEATTRIBUTION).addSortDesc(Sort.DATEENQUEUE).addSortAsc(Sort.ID).addSortDesc(Sort.QUEUENAME)
.addSortAsc(Sort.STATUS).addSortDesc(Sort.USERNAME).addSortAsc(Sort.PARENTID).run();
}
@Test
public void testOnlyQueue()
{
Query.create().setQueryLiveInstances(true).setQueryHistoryInstances(false).setUser("test").run();
}
@Test
public void testBug159()
{
Query.create().setJobInstanceId(1234).setQueryLiveInstances(true).setQueryHistoryInstances(false).setPageSize(15).setFirstRow(0)
.run();
}
@Test
public void testBug292()
{
Query.create().addSortDesc(Query.Sort.ID).setQueueName("QBATCH").setQueryHistoryInstances(true).setQueryLiveInstances(true).run();
}
@Test
public void testBug305()
{
Properties p = new Properties();
p.putAll(Db.loadProperties());
Db db = new Db(p);
DbConn cnx = null;
try
{
cnx = db.getConn();
int qId = Queue.create(cnx, "q1", "q1 description", true);
int jobDefdId = JobDef.create(cnx, "test description", "class", null, "jar", qId, 1, "appName", null, null, null, null, null,
false, null, PathType.FS);
JobInstance.enqueue(cnx, com.enioka.jqm.model.State.RUNNING, qId, jobDefdId, null, null, null, null, null, null, null, null,
null, false, false, null, 1, Instruction.RUN, new HashMap<String, String>());
JobInstance.enqueue(cnx, com.enioka.jqm.model.State.RUNNING, qId, jobDefdId, null, null, null, null, null, null, null, null,
null, false, false, null, 1, Instruction.RUN, new HashMap<String, String>());
cnx.commit();
Properties p2 = new Properties();
p2.put("com.enioka.jqm.jdbc.contextobject", db);
List<com.enioka.jqm.api.JobInstance> res = JqmClientFactory.getClient("test", p2, false)
.getJobs(Query.create().setQueryHistoryInstances(false).setQueryLiveInstances(true).addSortDesc(Query.Sort.ID)
.setPageSize(1).setApplicationName("appName"));
Assert.assertEquals(1, res.size());
}
finally
{
if (cnx != null)
{
cnx.closeQuietly(cnx);
}
}
}
}
| enioka/jqm | jqm-all/jqm-client/jqm-api-client-jdbc/src/test/java/com/enioka/jqm/api/test/BasicTest.java | Java | apache-2.0 | 7,479 |
<?php
declare(strict_types=1);
namespace DaPigGuy\PiggyCustomEnchants\enchants\armor\chestplate;
use DaPigGuy\PiggyCustomEnchants\enchants\CustomEnchant;
use DaPigGuy\PiggyCustomEnchants\enchants\ToggleableEnchantment;
use DaPigGuy\PiggyCustomEnchants\enchants\traits\TickingTrait;
use pocketmine\entity\effect\EffectInstance;
use pocketmine\entity\effect\VanillaEffects;
use pocketmine\inventory\Inventory;
use pocketmine\item\Item;
use pocketmine\player\Player;
class ProwlEnchant extends ToggleableEnchantment
{
use TickingTrait;
public string $name = "Prowl";
public int $maxLevel = 1;
public int $usageType = CustomEnchant::TYPE_CHESTPLATE;
public int $itemType = CustomEnchant::ITEM_TYPE_CHESTPLATE;
/** @var bool[] */
public array $prowled;
public function toggle(Player $player, Item $item, Inventory $inventory, int $slot, int $level, bool $toggle): void
{
if (!$toggle && isset($this->prowled[$player->getName()])) {
foreach ($player->getServer()->getOnlinePlayers() as $p) {
$p->showPlayer($player);
}
$player->getEffects()->remove(VanillaEffects::SLOWNESS());
if (!$player->getEffects()->has(VanillaEffects::INVISIBILITY())) {
$player->setInvisible(false);
}
unset($this->prowled[$player->getName()]);
}
}
public function tick(Player $player, Item $item, Inventory $inventory, int $slot, int $level): void
{
if ($player->isSneaking()) {
foreach ($player->getServer()->getOnlinePlayers() as $p) {
$p->hidePlayer($player);
}
$effect = new EffectInstance(VanillaEffects::SLOWNESS(), 2147483647, 0, false);
$player->setInvisible();
$player->getEffects()->add($effect);
$this->prowled[$player->getName()] = true;
} else {
if (isset($this->prowled[$player->getName()])) {
foreach ($player->getServer()->getOnlinePlayers() as $p) {
$p->showPlayer($player);
}
$player->getEffects()->remove(VanillaEffects::SLOWNESS());
if (!$player->getEffects()->has(VanillaEffects::INVISIBILITY())) {
$player->setInvisible(false);
}
unset($this->prowled[$player->getName()]);
}
}
}
} | DaPigGuy/PiggyCustomEnchants | src/DaPigGuy/PiggyCustomEnchants/enchants/armor/chestplate/ProwlEnchant.php | PHP | apache-2.0 | 2,425 |
# -*- coding: utf-8 -*-
# Copyright 2022 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
#
# 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.
#
import proto # type: ignore
from google.protobuf import duration_pb2 # type: ignore
from google.protobuf import timestamp_pb2 # type: ignore
__protobuf__ = proto.module(
package="google.cloud.gaming.v1",
manifest={
"OperationMetadata",
"OperationStatus",
"LabelSelector",
"RealmSelector",
"Schedule",
"SpecSource",
"TargetDetails",
"TargetState",
"DeployedFleetDetails",
},
)
class OperationMetadata(proto.Message):
r"""Represents the metadata of the long-running operation.
Attributes:
create_time (google.protobuf.timestamp_pb2.Timestamp):
Output only. The time the operation was
created.
end_time (google.protobuf.timestamp_pb2.Timestamp):
Output only. The time the operation finished
running.
target (str):
Output only. Server-defined resource path for
the target of the operation.
verb (str):
Output only. Name of the verb executed by the
operation.
status_message (str):
Output only. Human-readable status of the
operation, if any.
requested_cancellation (bool):
Output only. Identifies whether the user has requested
cancellation of the operation. Operations that have
successfully been cancelled have [Operation.error][] value
with a [google.rpc.Status.code][google.rpc.Status.code] of
1, corresponding to ``Code.CANCELLED``.
api_version (str):
Output only. API version used to start the
operation.
unreachable (Sequence[str]):
Output only. List of Locations that could not
be reached.
operation_status (Sequence[google.cloud.gaming_v1.types.OperationMetadata.OperationStatusEntry]):
Output only. Operation status for Game
Services API operations. Operation status is in
the form of key-value pairs where keys are
resource IDs and the values show the status of
the operation. In case of failures, the value
includes an error code and error message.
"""
create_time = proto.Field(proto.MESSAGE, number=1, message=timestamp_pb2.Timestamp,)
end_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,)
target = proto.Field(proto.STRING, number=3,)
verb = proto.Field(proto.STRING, number=4,)
status_message = proto.Field(proto.STRING, number=5,)
requested_cancellation = proto.Field(proto.BOOL, number=6,)
api_version = proto.Field(proto.STRING, number=7,)
unreachable = proto.RepeatedField(proto.STRING, number=8,)
operation_status = proto.MapField(
proto.STRING, proto.MESSAGE, number=9, message="OperationStatus",
)
class OperationStatus(proto.Message):
r"""
Attributes:
done (bool):
Output only. Whether the operation is done or
still in progress.
error_code (google.cloud.gaming_v1.types.OperationStatus.ErrorCode):
The error code in case of failures.
error_message (str):
The human-readable error message.
"""
class ErrorCode(proto.Enum):
r""""""
ERROR_CODE_UNSPECIFIED = 0
INTERNAL_ERROR = 1
PERMISSION_DENIED = 2
CLUSTER_CONNECTION = 3
done = proto.Field(proto.BOOL, number=1,)
error_code = proto.Field(proto.ENUM, number=2, enum=ErrorCode,)
error_message = proto.Field(proto.STRING, number=3,)
class LabelSelector(proto.Message):
r"""The label selector, used to group labels on the resources.
Attributes:
labels (Sequence[google.cloud.gaming_v1.types.LabelSelector.LabelsEntry]):
Resource labels for this selector.
"""
labels = proto.MapField(proto.STRING, proto.STRING, number=1,)
class RealmSelector(proto.Message):
r"""The realm selector, used to match realm resources.
Attributes:
realms (Sequence[str]):
List of realms to match.
"""
realms = proto.RepeatedField(proto.STRING, number=1,)
class Schedule(proto.Message):
r"""The schedule of a recurring or one time event. The event's time span
is specified by start_time and end_time. If the scheduled event's
timespan is larger than the cron_spec + cron_job_duration, the event
will be recurring. If only cron_spec + cron_job_duration are
specified, the event is effective starting at the local time
specified by cron_spec, and is recurring.
::
start_time|-------[cron job]-------[cron job]-------[cron job]---|end_time
cron job: cron spec start time + duration
Attributes:
start_time (google.protobuf.timestamp_pb2.Timestamp):
The start time of the event.
end_time (google.protobuf.timestamp_pb2.Timestamp):
The end time of the event.
cron_job_duration (google.protobuf.duration_pb2.Duration):
The duration for the cron job event. The
duration of the event is effective after the
cron job's start time.
cron_spec (str):
The cron definition of the scheduled event.
See https://en.wikipedia.org/wiki/Cron. Cron
spec specifies the local time as defined by the
realm.
"""
start_time = proto.Field(proto.MESSAGE, number=1, message=timestamp_pb2.Timestamp,)
end_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,)
cron_job_duration = proto.Field(
proto.MESSAGE, number=3, message=duration_pb2.Duration,
)
cron_spec = proto.Field(proto.STRING, number=4,)
class SpecSource(proto.Message):
r"""Encapsulates Agones fleet spec and Agones autoscaler spec
sources.
Attributes:
game_server_config_name (str):
The game server config resource. Uses the form:
``projects/{project}/locations/{location}/gameServerDeployments/{deployment_id}/configs/{config_id}``.
name (str):
The name of the Agones leet config or Agones
scaling config used to derive the Agones fleet
or Agones autoscaler spec.
"""
game_server_config_name = proto.Field(proto.STRING, number=1,)
name = proto.Field(proto.STRING, number=2,)
class TargetDetails(proto.Message):
r"""Details about the Agones resources.
Attributes:
game_server_cluster_name (str):
The game server cluster name. Uses the form:
``projects/{project}/locations/{location}/realms/{realm}/gameServerClusters/{cluster}``.
game_server_deployment_name (str):
The game server deployment name. Uses the form:
``projects/{project}/locations/{location}/gameServerDeployments/{deployment_id}``.
fleet_details (Sequence[google.cloud.gaming_v1.types.TargetDetails.TargetFleetDetails]):
Agones fleet details for game server clusters
and game server deployments.
"""
class TargetFleetDetails(proto.Message):
r"""Details of the target Agones fleet.
Attributes:
fleet (google.cloud.gaming_v1.types.TargetDetails.TargetFleetDetails.TargetFleet):
Reference to target Agones fleet.
autoscaler (google.cloud.gaming_v1.types.TargetDetails.TargetFleetDetails.TargetFleetAutoscaler):
Reference to target Agones fleet autoscaling
policy.
"""
class TargetFleet(proto.Message):
r"""Target Agones fleet specification.
Attributes:
name (str):
The name of the Agones fleet.
spec_source (google.cloud.gaming_v1.types.SpecSource):
Encapsulates the source of the Agones fleet
spec. The Agones fleet spec source.
"""
name = proto.Field(proto.STRING, number=1,)
spec_source = proto.Field(proto.MESSAGE, number=2, message="SpecSource",)
class TargetFleetAutoscaler(proto.Message):
r"""Target Agones autoscaler policy reference.
Attributes:
name (str):
The name of the Agones autoscaler.
spec_source (google.cloud.gaming_v1.types.SpecSource):
Encapsulates the source of the Agones fleet
spec. Details about the Agones autoscaler spec.
"""
name = proto.Field(proto.STRING, number=1,)
spec_source = proto.Field(proto.MESSAGE, number=2, message="SpecSource",)
fleet = proto.Field(
proto.MESSAGE,
number=1,
message="TargetDetails.TargetFleetDetails.TargetFleet",
)
autoscaler = proto.Field(
proto.MESSAGE,
number=2,
message="TargetDetails.TargetFleetDetails.TargetFleetAutoscaler",
)
game_server_cluster_name = proto.Field(proto.STRING, number=1,)
game_server_deployment_name = proto.Field(proto.STRING, number=2,)
fleet_details = proto.RepeatedField(
proto.MESSAGE, number=3, message=TargetFleetDetails,
)
class TargetState(proto.Message):
r"""Encapsulates the Target state.
Attributes:
details (Sequence[google.cloud.gaming_v1.types.TargetDetails]):
Details about Agones fleets.
"""
details = proto.RepeatedField(proto.MESSAGE, number=1, message="TargetDetails",)
class DeployedFleetDetails(proto.Message):
r"""Details of the deployed Agones fleet.
Attributes:
deployed_fleet (google.cloud.gaming_v1.types.DeployedFleetDetails.DeployedFleet):
Information about the Agones fleet.
deployed_autoscaler (google.cloud.gaming_v1.types.DeployedFleetDetails.DeployedFleetAutoscaler):
Information about the Agones autoscaler for
that fleet.
"""
class DeployedFleet(proto.Message):
r"""Agones fleet specification and details.
Attributes:
fleet (str):
The name of the Agones fleet.
fleet_spec (str):
The fleet spec retrieved from the Agones
fleet.
spec_source (google.cloud.gaming_v1.types.SpecSource):
The source spec that is used to create the
Agones fleet. The GameServerConfig resource may
no longer exist in the system.
status (google.cloud.gaming_v1.types.DeployedFleetDetails.DeployedFleet.DeployedFleetStatus):
The current status of the Agones fleet.
Includes count of game servers in various
states.
"""
class DeployedFleetStatus(proto.Message):
r"""DeployedFleetStatus has details about the Agones fleets such
as how many are running, how many allocated, and so on.
Attributes:
ready_replicas (int):
The number of GameServer replicas in the
READY state in this fleet.
allocated_replicas (int):
The number of GameServer replicas in the
ALLOCATED state in this fleet.
reserved_replicas (int):
The number of GameServer replicas in the
RESERVED state in this fleet. Reserved instances
won't be deleted on scale down, but won't cause
an autoscaler to scale up.
replicas (int):
The total number of current GameServer
replicas in this fleet.
"""
ready_replicas = proto.Field(proto.INT64, number=1,)
allocated_replicas = proto.Field(proto.INT64, number=2,)
reserved_replicas = proto.Field(proto.INT64, number=3,)
replicas = proto.Field(proto.INT64, number=4,)
fleet = proto.Field(proto.STRING, number=1,)
fleet_spec = proto.Field(proto.STRING, number=2,)
spec_source = proto.Field(proto.MESSAGE, number=3, message="SpecSource",)
status = proto.Field(
proto.MESSAGE,
number=5,
message="DeployedFleetDetails.DeployedFleet.DeployedFleetStatus",
)
class DeployedFleetAutoscaler(proto.Message):
r"""Details about the Agones autoscaler.
Attributes:
autoscaler (str):
The name of the Agones autoscaler.
spec_source (google.cloud.gaming_v1.types.SpecSource):
The source spec that is used to create the
autoscaler. The GameServerConfig resource may no
longer exist in the system.
fleet_autoscaler_spec (str):
The autoscaler spec retrieved from Agones.
"""
autoscaler = proto.Field(proto.STRING, number=1,)
spec_source = proto.Field(proto.MESSAGE, number=4, message="SpecSource",)
fleet_autoscaler_spec = proto.Field(proto.STRING, number=3,)
deployed_fleet = proto.Field(proto.MESSAGE, number=1, message=DeployedFleet,)
deployed_autoscaler = proto.Field(
proto.MESSAGE, number=2, message=DeployedFleetAutoscaler,
)
__all__ = tuple(sorted(__protobuf__.manifest))
| googleapis/python-game-servers | google/cloud/gaming_v1/types/common.py | Python | apache-2.0 | 13,962 |
# AUTOGENERATED FILE
FROM balenalib/edge-ubuntu:xenial-build
# remove several traces of debian python
RUN apt-get purge -y python.*
# http://bugs.python.org/issue19846
# > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK.
ENV LANG C.UTF-8
# key 63C7CC90: public key "Simon McVittie <[email protected]>" imported
# key 3372DCFA: public key "Donald Stufft (dstufft) <[email protected]>" imported
RUN gpg --keyserver keyring.debian.org --recv-keys 4DE8FF2A63C7CC90 \
&& gpg --keyserver keyserver.ubuntu.com --recv-key 6E3CBCE93372DCFA \
&& gpg --keyserver keyserver.ubuntu.com --recv-keys 0x52a43a1e4b77b059
ENV PYTHON_VERSION 3.6.15
# if this is called "PIP_VERSION", pip explodes with "ValueError: invalid truth value '<VERSION>'"
ENV PYTHON_PIP_VERSION 21.3.1
ENV SETUPTOOLS_VERSION 60.5.4
RUN set -x \
&& curl -SLO "http://resin-packages.s3.amazonaws.com/python/v$PYTHON_VERSION/Python-$PYTHON_VERSION.linux-amd64-libffi3.2.tar.gz" \
&& echo "363447510565fe95ceb59ab3b11473c5ddc27b8b646ba02f7892c37174be1696 Python-$PYTHON_VERSION.linux-amd64-libffi3.2.tar.gz" | sha256sum -c - \
&& tar -xzf "Python-$PYTHON_VERSION.linux-amd64-libffi3.2.tar.gz" --strip-components=1 \
&& rm -rf "Python-$PYTHON_VERSION.linux-amd64-libffi3.2.tar.gz" \
&& ldconfig \
&& if [ ! -e /usr/local/bin/pip3 ]; then : \
&& curl -SLO "https://raw.githubusercontent.com/pypa/get-pip/430ba37776ae2ad89f794c7a43b90dc23bac334c/get-pip.py" \
&& echo "19dae841a150c86e2a09d475b5eb0602861f2a5b7761ec268049a662dbd2bd0c get-pip.py" | sha256sum -c - \
&& python3 get-pip.py \
&& rm get-pip.py \
; fi \
&& pip3 install --no-cache-dir --upgrade --force-reinstall pip=="$PYTHON_PIP_VERSION" setuptools=="$SETUPTOOLS_VERSION" \
&& find /usr/local \
\( -type d -a -name test -o -name tests \) \
-o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \
-exec rm -rf '{}' + \
&& cd / \
&& rm -rf /usr/src/python ~/.cache
# install "virtualenv", since the vast majority of users of this image will want it
RUN pip3 install --no-cache-dir virtualenv
ENV PYTHON_DBUS_VERSION 1.2.18
# install dbus-python dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
libdbus-1-dev \
libdbus-glib-1-dev \
&& rm -rf /var/lib/apt/lists/* \
&& apt-get -y autoremove
# install dbus-python
RUN set -x \
&& mkdir -p /usr/src/dbus-python \
&& curl -SL "http://dbus.freedesktop.org/releases/dbus-python/dbus-python-$PYTHON_DBUS_VERSION.tar.gz" -o dbus-python.tar.gz \
&& curl -SL "http://dbus.freedesktop.org/releases/dbus-python/dbus-python-$PYTHON_DBUS_VERSION.tar.gz.asc" -o dbus-python.tar.gz.asc \
&& gpg --verify dbus-python.tar.gz.asc \
&& tar -xzC /usr/src/dbus-python --strip-components=1 -f dbus-python.tar.gz \
&& rm dbus-python.tar.gz* \
&& cd /usr/src/dbus-python \
&& PYTHON_VERSION=$(expr match "$PYTHON_VERSION" '\([0-9]*\.[0-9]*\)') ./configure \
&& make -j$(nproc) \
&& make install -j$(nproc) \
&& cd / \
&& rm -rf /usr/src/dbus-python
# make some useful symlinks that are expected to exist
RUN cd /usr/local/bin \
&& ln -sf pip3 pip \
&& { [ -e easy_install ] || ln -s easy_install-* easy_install; } \
&& ln -sf idle3 idle \
&& ln -sf pydoc3 pydoc \
&& ln -sf python3 python \
&& ln -sf python3-config python-config
# set PYTHONPATH to point to dist-packages
ENV PYTHONPATH /usr/lib/python3/dist-packages:$PYTHONPATH
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/[email protected]" \
&& echo "Running test-stack@python" \
&& chmod +x [email protected] \
&& bash [email protected] \
&& rm -rf [email protected]
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: Intel 64-bit (x86-64) \nOS: Ubuntu xenial \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v3.6.15, Pip v21.3.1, Setuptools v60.5.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh | resin-io-library/base-images | balena-base-images/python/edge/ubuntu/xenial/3.6.15/build/Dockerfile | Dockerfile | apache-2.0 | 4,831 |
/**
* Copyright (c) 2013-2020 Nikita Koksharov
*
* 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.redisson.iterator;
import java.util.AbstractMap;
import java.util.Map;
import java.util.Map.Entry;
/**
*
* @author Nikita Koksharov
*
* @param <V> value type
*/
public abstract class RedissonBaseMapIterator<V> extends BaseIterator<V, Entry<Object, Object>> {
@SuppressWarnings("unchecked")
protected V getValue(Map.Entry<Object, Object> entry) {
return (V) new AbstractMap.SimpleEntry(entry.getKey(), entry.getValue()) {
@Override
public Object setValue(Object value) {
return put(entry, value);
}
};
}
protected abstract Object put(Entry<Object, Object> entry, Object value);
}
| mrniko/redisson | redisson/src/main/java/org/redisson/iterator/RedissonBaseMapIterator.java | Java | apache-2.0 | 1,297 |
package org.artifactory.ui.rest.resource.home;
import org.artifactory.api.security.AuthorizationService;
import org.artifactory.ui.rest.resource.BaseResource;
import org.artifactory.ui.rest.service.general.GeneralServiceFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
* @author Chen keinan
*/
@Path("home")
@RolesAllowed({AuthorizationService.ROLE_ADMIN, AuthorizationService.ROLE_USER})
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class HomeResource extends BaseResource {
@Autowired
GeneralServiceFactory generalFactory;
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getHomeData()
throws Exception {
return runService(generalFactory.getHomePage());
}
}
| alancnet/artifactory | web/rest-ui/src/main/java/org/artifactory/ui/rest/resource/home/HomeResource.java | Java | apache-2.0 | 1,122 |
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
namespace Castleroid.NPCs
{
public class ai8 : ModNPC
{
public override void SetDefaults()
{
npc.name = "ai8";
npc.displayName = "ai8";
npc.width = 28;
npc.height = 20;
npc.damage = 2;
npc.defense = 0;
npc.lifeMax = 2;
npc.soundHit = 1;
npc.soundKilled = 16;
npc.value = 60f;
npc.knockBackResist = 0.0f;
npc.aiStyle = 8;
Main.npcFrameCount[npc.type] = Main.npcFrameCount[NPCID.CyanBeetle];
aiType = NPCID.CyanBeetle;
animationType = NPCID.CyanBeetle;
npc.noGravity = false;
npc.noTileCollide = true;
}
public override void HitEffect(int hitDirection, double damage)
{
for (int i = 0; i < 10; i++)
{
int dustType = Main.rand.Next(139, 143);
int dustIndex = Dust.NewDust(npc.position, npc.width, npc.height, dustType);
Dust dust = Main.dust[dustIndex];
dust.velocity.X = dust.velocity.X + Main.rand.Next(-50, 51) * 0.01f;
dust.velocity.Y = dust.velocity.Y + Main.rand.Next(-50, 51) * 0.01f;
dust.scale *= 1f + Main.rand.Next(-30, 31) * 0.01f;
}
}
}
}
| lukanpeixe/projetocastleroid | Castleroid - tmodloader - 1.0.7/NPCs/ai8.cs | C# | apache-2.0 | 1,113 |
/*
* Licensed to Cloudkick, Inc ('Cloudkick') under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* Cloudkick 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 com.cloudkick;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;
public class LoginActivity extends Activity {
private static final int SETTINGS_ACTIVITY_ID = 0;
RelativeLayout loginView = null;
private String user = null;
private String pass = null;
private ProgressDialog progress = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
setTitle("Cloudkick for Android");
findViewById(R.id.button_login).setOnClickListener(new LoginClickListener());
findViewById(R.id.button_signup).setOnClickListener(new SignupClickListener());
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == SETTINGS_ACTIVITY_ID) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(LoginActivity.this);
if (prefs.getString("editKey", "").equals("") && prefs.getString("editSecret", "").equals("")) {
finish();
}
else {
Intent result = new Intent();
result.putExtra("login", true);
setResult(Activity.RESULT_OK, result);
finish();
}
}
}
private class LoginClickListener implements View.OnClickListener {
public void onClick(View v) {
new AccountLister().execute();
}
}
private class SignupClickListener implements View.OnClickListener {
public void onClick(View v) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.cloudkick.com/pricing/")));
}
}
private class AccountLister extends AsyncTask<Void, Void, ArrayList<String>>{
private Integer statusCode = null;
@Override
protected void onPreExecute() {
user = ((EditText) findViewById(R.id.input_email)).getText().toString();
pass = ((EditText) findViewById(R.id.input_password)).getText().toString();
progress = ProgressDialog.show(LoginActivity.this, "", "Logging In...", true);
}
@Override
protected ArrayList<String> doInBackground(Void...voids) {
ArrayList<String> accounts = new ArrayList<String>();
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://www.cloudkick.com/oauth/list_accounts/");
ArrayList<NameValuePair> values = new ArrayList<NameValuePair>(2);
values.add(new BasicNameValuePair("user", user));
values.add(new BasicNameValuePair("password", pass));
post.setEntity(new UrlEncodedFormEntity(values));
HttpResponse response = client.execute(post);
statusCode = response.getStatusLine().getStatusCode();
InputStream is = response.getEntity().getContent();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = rd.readLine()) != null) {
accounts.add(line);
Log.i("LoginActivity", line);
}
}
catch (Exception e) {
e.printStackTrace();
statusCode = 0;
}
return accounts;
}
@Override
protected void onPostExecute(ArrayList<String> accounts) {
switch (statusCode) {
case 200:
if (accounts.size() == 1) {
new KeyRetriever().execute(accounts.get(0));
}
else {
String[] tmpAccountArray = new String[accounts.size()];
final String[] accountArray = accounts.toArray(tmpAccountArray);
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setTitle("Select an Account");
builder.setItems(accountArray, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
new KeyRetriever().execute(accountArray[item]);
}
});
AlertDialog selectAccount = builder.create();
selectAccount.show();
}
break;
case 400:
progress.dismiss();
if (accounts.get(0).equals("You have enabled multi factor authentication for this account. To access the API key list, please visit the website.")) {
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setTitle("MFA is Enabled");
String mfaMessage = ("You appear to have multi-factor authentication enabled on your account. "
+ "You will need to manually create an API key with read permissions in the "
+ "web interface, then enter it directly in the settings panel.");
builder.setMessage(mfaMessage);
builder.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent settingsActivity = new Intent(getBaseContext(), Preferences.class);
startActivityForResult(settingsActivity, SETTINGS_ACTIVITY_ID);
}
});
AlertDialog mfaDialog = builder.create();
mfaDialog.show();
}
else {
Toast.makeText(LoginActivity.this, "Invalid Username or Password", Toast.LENGTH_LONG).show();
}
break;
default:
progress.dismiss();
Toast.makeText(LoginActivity.this, "An Error Occurred Retrieving Your Accounts", Toast.LENGTH_LONG).show();
};
}
}
private class KeyRetriever extends AsyncTask<String, Void, String[]>{
private Integer statusCode = null;
@Override
protected String[] doInBackground(String...accts) {
Log.i("LoginActivity", "Selected Account: " + accts[0]);
String[] creds = new String[2];
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://www.cloudkick.com/oauth/create_consumer/");
ArrayList<NameValuePair> values = new ArrayList<NameValuePair>(2);
values.add(new BasicNameValuePair("user", user));
values.add(new BasicNameValuePair("password", pass));
values.add(new BasicNameValuePair("account", accts[0]));
values.add(new BasicNameValuePair("system", "Cloudkick for Android"));
values.add(new BasicNameValuePair("perm_read", "True"));
values.add(new BasicNameValuePair("perm_write", "False"));
values.add(new BasicNameValuePair("perm_execute", "False"));
post.setEntity(new UrlEncodedFormEntity(values));
HttpResponse response = client.execute(post);
statusCode = response.getStatusLine().getStatusCode();
Log.i("LoginActivity", "Return Code: " + statusCode);
InputStream is = response.getEntity().getContent();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
for (int i = 0; i < 2; i++) {
line = rd.readLine();
if (line == null) {
return creds;
}
creds[i] = line;
}
}
catch (Exception e) {
statusCode = 0;
}
return creds;
}
@Override
protected void onPostExecute(String[] creds) {
progress.dismiss();
if (statusCode != 200) {
// Show short error messages - this is a dirty hack
if (creds[0] != null && creds[0].startsWith("User with role")) {
Toast.makeText(LoginActivity.this, creds[0], Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(LoginActivity.this, "An Error Occurred on Login", Toast.LENGTH_LONG).show();
return;
}
}
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(LoginActivity.this);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("editKey", creds[0]);
editor.putString("editSecret", creds[1]);
editor.commit();
Intent result = new Intent();
result.putExtra("login", true);
setResult(Activity.RESULT_OK, result);
LoginActivity.this.finish();
}
}
}
| cloudkick/cloudkick-android | src/com/cloudkick/LoginActivity.java | Java | apache-2.0 | 9,030 |
package ai.api.test;
/***********************************************************************************************************************
*
* API.AI Java SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2014 by Speaktoit, Inc. (https://www.speaktoit.com)
* https://www.api.ai
*
***********************************************************************************************************************
*
* 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.
*
***********************************************************************************************************************/
public class ProtocolProdTest extends ProtocolTestBase {
// Testing keys
protected static final String ACCESS_TOKEN = "3485a96fb27744db83e78b8c4bc9e7b7";
protected String getAccessToken() {
return ACCESS_TOKEN;
}
@Override
protected String getSecondAccessToken() {
return "968235e8e4954cf0bb0dc07736725ecd";
}
protected String getRuAccessToken(){
return "07806228a357411d83064309a279c7fd";
}
protected String getBrAccessToken(){
// TODO
return "";
}
protected String getPtBrAccessToken(){
return "42db6ad6a51c47088318a8104833b66c";
}
@Override
protected String getJaAccessToken() {
// TODO
return "";
}
}
| deternan/Weather-line-bot | libai/src/test/java/ai/api/test/ProtocolProdTest.java | Java | apache-2.0 | 1,887 |
class AddResourceToVersions < ActiveRecord::Migration[6.0]
def change
add_column :versions, :resource_id, :integer
add_column :versions, :resource_type, :string
add_index :versions, [:resource_type, :resource_id]
end
end
| psu-stewardship/scholarsphere | db/migrate/20210126195635_add_resource_to_versions.rb | Ruby | apache-2.0 | 237 |
package org.drools.persistence;
import javax.transaction.xa.XAResource;
public interface PersistenceManager {
XAResource getXAResource();
Transaction getTransaction();
void save();
void load();
} | bobmcwhirter/drools | drools-core/src/main/java/org/drools/persistence/PersistenceManager.java | Java | apache-2.0 | 232 |
/*
* Copyright 2012 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 org.jboss.netty.handler.codec.serialization;
import java.util.concurrent.Executor;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.socket.oio.OioClientSocketChannelFactory;
import org.jboss.netty.channel.socket.oio.OioServerSocketChannelFactory;
public class OioOioSocketCompatibleObjectStreamEchoTest extends AbstractSocketCompatibleObjectStreamEchoTest {
@Override
protected ChannelFactory newClientSocketChannelFactory(Executor executor) {
return new OioClientSocketChannelFactory(executor);
}
@Override
protected ChannelFactory newServerSocketChannelFactory(Executor executor) {
return new OioServerSocketChannelFactory(executor, executor);
}
}
| CliffYuan/netty | src/test/java/org/jboss/netty/handler/codec/serialization/OioOioSocketCompatibleObjectStreamEchoTest.java | Java | apache-2.0 | 1,368 |
package com.coolweather.android;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.preference.PreferenceManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ScrollingView;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.coolweather.android.gson.Forecast;
import com.coolweather.android.gson.Weather;
import com.coolweather.android.service.AutoUpdateService;
import com.coolweather.android.util.HttpUtil;
import com.coolweather.android.util.Utility;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
public class WeatherActivity extends AppCompatActivity {
private ScrollView weatherLayout;
private TextView titleCity;
private TextView titleUpdateTime;
private TextView degreeText;
private TextView weatherInfoText;
private LinearLayout forecastLayout;
private TextView aqiText;
private TextView pm25Text;
private TextView comfortText;
private TextView carWashText;
private TextView sportText;
private ImageView bingPicImg;
public SwipeRefreshLayout swipeRefreshLayout;
private String mWeatherId;
public DrawerLayout drawerLayout;
private Button navButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= 21) {
View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
getWindow().setStatusBarColor(Color.TRANSPARENT);
}
setContentView(R.layout.activity_weather);
//初始条件
weatherLayout = (ScrollView) findViewById(R.id.weather_layout);
titleCity = (TextView) findViewById(R.id.title_city);
titleUpdateTime = (TextView) findViewById(R.id.title_update_time);
degreeText = (TextView) findViewById(R.id.degree_text);
weatherInfoText = (TextView) findViewById(R.id.weather_info_text);
forecastLayout = (LinearLayout) findViewById(R.id.forecast_layout);
aqiText = (TextView) findViewById(R.id.aqi_text);
pm25Text = (TextView) findViewById(R.id.pm25_text);
comfortText = (TextView) findViewById(R.id.comfort_text);
carWashText = (TextView) findViewById(R.id.car_wash_text);
sportText = (TextView) findViewById(R.id.sport_text);
bingPicImg = (ImageView) findViewById(R.id.bing_pic_img);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
navButton = (Button) findViewById(R.id.nav_button);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh);
swipeRefreshLayout.setColorSchemeResources(R.color.colorTopic);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String weatherString = prefs.getString("weather", null);
if (weatherString != null) {
//有缓存时直接解析天气数据
Weather weather = Utility.handleWeatherResponse(weatherString);
mWeatherId = weather.basic.weatherId;
showWeatherInfo(weather);
} else {
//无缓存时去服务器查询天气
mWeatherId = getIntent().getStringExtra("weather_id");
String weatherId = getIntent().getStringExtra("weather_id");
weatherLayout.setVisibility(View.INVISIBLE);
requestWeather(weatherId);
}
navButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
drawerLayout.openDrawer(GravityCompat.START);
}
});
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
requestWeather(mWeatherId);
}
});
String bingPic = prefs.getString("bing_pic", null);
if (bingPic != null) {
Glide.with(this).load(bingPic).into(bingPicImg);
} else {
loadBingPic();
}
}
/**
* 根据天气ID请求城市天气信息
*/
public void requestWeather(final String weatherId) {
String weatherUtl = "http://guolin.tech/api/weather?cityid=" + weatherId + "&key=04ae9fa43fb341b596f719aa6d6babda";
HttpUtil.sendOkHttpRequest(weatherUtl, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(WeatherActivity.this, "获取天气信息失败", Toast.LENGTH_SHORT).show();
swipeRefreshLayout.setRefreshing(false);
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String responseText = response.body().string();
final Weather weather = Utility.handleWeatherResponse(responseText);
runOnUiThread(new Runnable() {
@Override
public void run() {
if (weather != null && "ok".equals(weather.status)) {
SharedPreferences.Editor editor = PreferenceManager
.getDefaultSharedPreferences(WeatherActivity.this).edit();
editor.putString("weather", responseText);
editor.apply();
Toast.makeText(WeatherActivity.this, "成功更新最新天气", Toast.LENGTH_SHORT).show();
showWeatherInfo(weather);
} else {
Toast.makeText(WeatherActivity.this, "获取天气信息失败", Toast.LENGTH_SHORT).show();
}
swipeRefreshLayout.setRefreshing(false);
}
});
}
});
loadBingPic();
}
private void loadBingPic() {
String requestBingPic = "http://guolin.tech/api/bing_pic";
HttpUtil.sendOkHttpRequest(requestBingPic, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String bingPic = response.body().string();
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
editor.putString("bing_pic", bingPic);
editor.apply();
runOnUiThread(new Runnable() {
@Override
public void run() {
Glide.with(WeatherActivity.this).load(bingPic).into(bingPicImg);
}
});
}
});
}
/**
* 处理并展示Weather实体类中的数据
*/
private void showWeatherInfo(Weather weather) {
String cityName = weather.basic.cityName;
String updateTime = "更新时间: " + weather.basic.update.updateTime.split(" ")[1];
String degree = weather.now.temperature + "ºC";
String weatherInfo = weather.now.more.info;
titleCity.setText(cityName);
titleUpdateTime.setText(updateTime);
degreeText.setText(degree);
weatherInfoText.setText(weatherInfo);
forecastLayout.removeAllViews();
for (Forecast forecast : weather.forecastList) {
View view = LayoutInflater.from(this).inflate(R.layout.forecast_item, forecastLayout, false);
TextView dateText = (TextView) view.findViewById(R.id.date_text);
TextView infoText = (TextView) view.findViewById(R.id.info_text);
TextView maxText = (TextView) view.findViewById(R.id.max_text);
TextView minText = (TextView) view.findViewById(R.id.min_text);
dateText.setText(forecast.date);
infoText.setText(forecast.more.info);
maxText.setText(forecast.temperature.max);
minText.setText(forecast.temperature.min);
forecastLayout.addView(view);
}
if (weather.aqi != null) {
aqiText.setText(weather.aqi.city.aqi);
pm25Text.setText(weather.aqi.city.pm25);
}
String comfort = "舒适度:" + weather.suggestion.comfort.info;
String catWash = "洗车指数:" + weather.suggestion.carWash.info;
String sport = "运动指数:" + weather.suggestion.sport.info;
comfortText.setText(comfort);
carWashText.setText(catWash);
sportText.setText(sport);
weatherLayout.setVisibility(View.VISIBLE);
if (weather != null && "ok".equals(weather.status)) {
Intent intent = new Intent(this, AutoUpdateService.class);
startService(intent);
} else {
Toast.makeText(WeatherActivity.this, "获取天气信息失败", Toast.LENGTH_SHORT).show();
}
}
}
| MarkManYUN/coolweather | app/src/main/java/com/coolweather/android/WeatherActivity.java | Java | apache-2.0 | 9,815 |
# Copyright 2020, 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
#
# 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 Google::Ads::GoogleAds::V9::Enums::BudgetDeliveryMethodEnum;
use strict;
use warnings;
use Const::Exporter enums => [
UNSPECIFIED => "UNSPECIFIED",
UNKNOWN => "UNKNOWN",
STANDARD => "STANDARD",
ACCELERATED => "ACCELERATED"
];
1;
| googleads/google-ads-perl | lib/Google/Ads/GoogleAds/V9/Enums/BudgetDeliveryMethodEnum.pm | Perl | apache-2.0 | 831 |
package com.example.cdm.huntfun.activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.widget.TextView;
import com.example.cdm.huntfun.R;
import com.example.cdm.huntfun.photoView.ImageDetailFragment;
import com.example.cdm.huntfun.widget.HackyViewPager;
import java.util.List;
/**
* 图片查看器
*/
public class ImagePagerActivity extends FragmentActivity {
private static final String STATE_POSITION = "STATE_POSITION";
public static final String EXTRA_IMAGE_INDEX = "image_index";
public static final String EXTRA_IMAGE_URLS = "image_urls";
private HackyViewPager mPager;
private int pagerPosition;
private TextView indicator;
// public static Drawable DEFAULTDRAWABLE;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.umessage_image_detail_pager);
// DEFAULTDRAWABLE=this.getResources().getDrawable(R.drawable.umessage_load_default);
pagerPosition = getIntent().getIntExtra(EXTRA_IMAGE_INDEX, 0);
List<String> urls = getIntent().getStringArrayListExtra(EXTRA_IMAGE_URLS);
mPager = (HackyViewPager) findViewById(R.id.pager);
ImagePagerAdapter mAdapter = new ImagePagerAdapter(getSupportFragmentManager(), urls);
mPager.setAdapter(mAdapter);
indicator = (TextView) findViewById(R.id.indicator);
CharSequence text = getString(R.string.xq_viewpager_indicator, 1, mPager.getAdapter().getCount());
indicator.setText(text);
// 更新下标
mPager.addOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageScrollStateChanged(int arg0) {
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
@Override
public void onPageSelected(int arg0) {
CharSequence text = getString(R.string.xq_viewpager_indicator, arg0 + 1, mPager.getAdapter().getCount());
indicator.setText(text);
}
});
if (savedInstanceState != null) {
pagerPosition = savedInstanceState.getInt(STATE_POSITION);
}
mPager.setCurrentItem(pagerPosition);
}
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putInt(STATE_POSITION, mPager.getCurrentItem());
}
private class ImagePagerAdapter extends FragmentStatePagerAdapter {
public List<String> fileList;
public ImagePagerAdapter(FragmentManager fm, List<String> fileList) {
super(fm);
this.fileList = fileList;
}
@Override
public int getCount() {
return fileList == null ? 0 : fileList.size();
}
@Override
public Fragment getItem(int position) {
String url = fileList.get(position);
return ImageDetailFragment.newInstance(url);
}
}
}
| skycdm/HuntFun | app/src/main/java/com/example/cdm/huntfun/activity/ImagePagerActivity.java | Java | apache-2.0 | 2,872 |
/*
Copyright 2015 The Kubernetes 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 http
import (
"fmt"
"net"
"net/http"
"net/http/httptest"
"net/url"
"os"
"strconv"
"strings"
"testing"
"time"
"k8s.io/kubernetes/pkg/probe"
)
const FailureCode int = -1
func setEnv(key, value string) func() {
originalValue := os.Getenv(key)
os.Setenv(key, value)
if len(originalValue) > 0 {
return func() {
os.Setenv(key, originalValue)
}
}
return func() {}
}
func unsetEnv(key string) func() {
originalValue := os.Getenv(key)
os.Unsetenv(key)
if len(originalValue) > 0 {
return func() {
os.Setenv(key, originalValue)
}
}
return func() {}
}
func TestHTTPProbeProxy(t *testing.T) {
res := "welcome to http probe proxy"
localProxy := "http://127.0.0.1:9098/"
defer setEnv("http_proxy", localProxy)()
defer setEnv("HTTP_PROXY", localProxy)()
defer unsetEnv("no_proxy")()
defer unsetEnv("NO_PROXY")()
prober := New()
go func() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, res)
})
err := http.ListenAndServe(":9098", nil)
if err != nil {
t.Errorf("Failed to start foo server: localhost:9098")
}
}()
// take some time to wait server boot
time.Sleep(2 * time.Second)
url, err := url.Parse("http://example.com")
if err != nil {
t.Errorf("proxy test unexpected error: %v", err)
}
_, response, _ := prober.Probe(url, http.Header{}, time.Second*3)
if response == res {
t.Errorf("proxy test unexpected error: the probe is using proxy")
}
}
func TestHTTPProbeChecker(t *testing.T) {
handleReq := func(s int, body string) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(s)
w.Write([]byte(body))
}
}
// Echo handler that returns the contents of request headers in the body
headerEchoHandler := func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
output := ""
for k, arr := range r.Header {
for _, v := range arr {
output += fmt.Sprintf("%s: %s\n", k, v)
}
}
w.Write([]byte(output))
}
redirectHandler := func(s int, bad bool) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" {
http.Redirect(w, r, "/new", s)
} else if bad && r.URL.Path == "/new" {
w.WriteHeader(http.StatusInternalServerError)
}
}
}
prober := New()
testCases := []struct {
handler func(w http.ResponseWriter, r *http.Request)
reqHeaders http.Header
health probe.Result
accBody string
notBody string
}{
// The probe will be filled in below. This is primarily testing that an HTTP GET happens.
{
handler: handleReq(http.StatusOK, "ok body"),
health: probe.Success,
accBody: "ok body",
},
{
handler: headerEchoHandler,
reqHeaders: http.Header{
"X-Muffins-Or-Cupcakes": {"muffins"},
},
health: probe.Success,
accBody: "X-Muffins-Or-Cupcakes: muffins",
},
{
handler: headerEchoHandler,
reqHeaders: http.Header{
"User-Agent": {"foo/1.0"},
},
health: probe.Success,
accBody: "User-Agent: foo/1.0",
},
{
handler: headerEchoHandler,
reqHeaders: http.Header{
"User-Agent": {""},
},
health: probe.Success,
notBody: "User-Agent",
},
{
handler: headerEchoHandler,
reqHeaders: http.Header{},
health: probe.Success,
accBody: "User-Agent: kube-probe/",
},
{
// Echo handler that returns the contents of Host in the body
handler: func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
w.Write([]byte(r.Host))
},
reqHeaders: http.Header{
"Host": {"muffins.cupcakes.org"},
},
health: probe.Success,
accBody: "muffins.cupcakes.org",
},
{
handler: handleReq(FailureCode, "fail body"),
health: probe.Failure,
},
{
handler: handleReq(http.StatusInternalServerError, "fail body"),
health: probe.Failure,
},
{
handler: func(w http.ResponseWriter, r *http.Request) {
time.Sleep(3 * time.Second)
},
health: probe.Failure,
},
{
handler: redirectHandler(http.StatusMovedPermanently, false), // 301
health: probe.Success,
},
{
handler: redirectHandler(http.StatusMovedPermanently, true), // 301
health: probe.Failure,
},
{
handler: redirectHandler(http.StatusFound, false), // 302
health: probe.Success,
},
{
handler: redirectHandler(http.StatusFound, true), // 302
health: probe.Failure,
},
{
handler: redirectHandler(http.StatusTemporaryRedirect, false), // 307
health: probe.Success,
},
{
handler: redirectHandler(http.StatusTemporaryRedirect, true), // 307
health: probe.Failure,
},
{
handler: redirectHandler(http.StatusPermanentRedirect, false), // 308
health: probe.Success,
},
{
handler: redirectHandler(http.StatusPermanentRedirect, true), // 308
health: probe.Failure,
},
}
for i, test := range testCases {
func() {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
test.handler(w, r)
}))
defer server.Close()
u, err := url.Parse(server.URL)
if err != nil {
t.Errorf("case %d: unexpected error: %v", i, err)
}
_, port, err := net.SplitHostPort(u.Host)
if err != nil {
t.Errorf("case %d: unexpected error: %v", i, err)
}
_, err = strconv.Atoi(port)
if err != nil {
t.Errorf("case %d: unexpected error: %v", i, err)
}
health, output, err := prober.Probe(u, test.reqHeaders, 1*time.Second)
if test.health == probe.Unknown && err == nil {
t.Errorf("case %d: expected error", i)
}
if test.health != probe.Unknown && err != nil {
t.Errorf("case %d: unexpected error: %v", i, err)
}
if health != test.health {
t.Errorf("case %d: expected %v, got %v", i, test.health, health)
}
if health != probe.Failure && test.health != probe.Failure {
if !strings.Contains(output, test.accBody) {
t.Errorf("Expected response body to contain %v, got %v", test.accBody, output)
}
if test.notBody != "" && strings.Contains(output, test.notBody) {
t.Errorf("Expected response not to contain %v, got %v", test.notBody, output)
}
}
}()
}
}
| linzhaoming/origin | vendor/k8s.io/kubernetes/pkg/probe/http/http_test.go | GO | apache-2.0 | 6,745 |
/* Copyright (c) The m-m-m Team, Licensed under the Apache License, Version 2.0
* http://www.apache.org/licenses/LICENSE-2.0 */
package net.sf.mmm.util.version.impl;
import net.sf.mmm.util.version.api.DevelopmentPhase;
import net.sf.mmm.util.version.api.VersionIdentifier;
/**
* This is the implementation of {@link net.sf.mmm.util.lang.api.Formatter} for the {@link DevelopmentPhase#getValue()
* value} of the {@link VersionIdentifier#getPhase() phase}.
*
* @author Joerg Hohwiller (hohwille at users.sourceforge.net)
* @since 3.0.0
*/
public class VersionIdentifierFormatterPhaseValue extends AbstractVersionIdentifierFormatterString {
/**
* The constructor.
*
* @param prefix is the static prefix to append before the {@link VersionIdentifier#getPhase() phase}. Will be omitted
* if {@link VersionIdentifier#getPhase() phase} is {@code null}.
* @param maximumLength is the maximum number of letters for the {@link VersionIdentifier#getPhase() phase}. The
* default is {@link Integer#MAX_VALUE}.
*/
public VersionIdentifierFormatterPhaseValue(String prefix, int maximumLength) {
super(prefix, maximumLength);
}
@Override
protected String getString(VersionIdentifier value) {
DevelopmentPhase phase = value.getPhase();
if (phase != null) {
return phase.getValue();
}
return null;
}
}
| m-m-m/util | version/src/main/java/net/sf/mmm/util/version/impl/VersionIdentifierFormatterPhaseValue.java | Java | apache-2.0 | 1,372 |
---
title: "Guía para ser un buen freelance por Paul Jarvis"
date: 2015-08-5 10:00:00
description: Renuncié a mi trabajo en una agencia y busqué trabajar en otra agencia. Mi plan después de renunciar, era ir a la librería (no te rías, esto fue en los 90´s) para aprender como debía escribir mi CV. Como fui contratado directamente desde la escuela, no había escrito uno antes.
image: '../assets/images/posts/freelance.jpg'
label: Diseño
---
Renuncié a mi trabajo en una agencia y busqué trabajar en otra agencia. Mi plan después de renunciar, era ir a la librería (no te rías, esto fue en los 90´s) para aprender como debía escribir mi CV. Como fui contratado directamente desde la escuela, no había escrito uno antes.
> Me convertí en freelance por accidente
Fue curioso y gracioso recibir llamadas de los clientes con los que había trabajado en la agencia mientras iba a la biblioteca, preguntándome cual iba a ser mi siguiente trabajo. Yo manejaba practicamente todo lo relacionado con ellos y ellos apreciaban mi atención y servicio. Tanto que ellos querían continuar trabajando conmigo y estarían dispuestos a seguirme a donde fuera mi próximo trabajo.
Luego de 3 o 4 llamadas después de haber renunciado, tuve una idea...
"Tal vez pueda trabajar por mi cuenta con estos clientes, en vez de llevarlos a que trabajen con otra agencia" ¡Voy a hacerlo!. Esta decisión me acercó al mundo del freelance por el que e vivido los últimos 17 años.
Pero hay más que eso, y aunque no haya un camino para garantizar el éxito como freelance, el plan que tenía podía ayudarme. Y no solo ayudarme a hacer dinero, sino ayudarte a que disfrutes la carrera que estás construyendo. Porqué eres el jefe ahora. Si odias tu trabajo, es tu culpa.
### El plan maestro del freelance:
Las marcas no son solo para las compañias que odias. Tu marca no es un logo, eso es algo que solo va en tus tarjetas de presentación o tu web. Cuando trabajas para ti solo, tu eres tu propia marca. Todo lo que haces y dices es parte de tu marca persona.
Esto es algo bueno, porque mientras vayas adquiriendo éxito como freelance irás destacando. Haces esto contando tu historia y siendo tu mismo en tus artículos, videos, pitch de ventas, newsletters y todo lo demás. También lo haces compartiendo la historia de tus clientes, ellos son el resultado de trabajar contigo, se convierten en tus casos de estudio, portafolio, post de blog y casos de éxito.
Puedes estar atraído por compañias con unas guías de marca y estilos de copy para su web. Después de todo, si quieres ser un profesional, debes sonar como uno ¿Cierto? ERROR. Mientras demuestres más confianza, suenes natural y real, tu marca empezará a hacerse más f uerte. No tengas miedo de tener una opinión.
Tu marca funciona cuando dejas lo que realmente eres brille a través de ti, como una luz en la oscuridad. El efecto se puede ver porqué las personas correctas (las personas con las que quieres trabajar) van a aparecer junto a ti, y todos los demás serán empujados lejos.
### Se exigente
- Le digo no a varios clientes potenciales por buenas razones:
- Decir que no significa que estoy 100% comprometido con lo que actualmente estoy trabajando o haciendo, y esos clientes tienen toda mi atención y creatividad, porque luego ellos volverán por más.
- Decir que no me ayuda a no poner estres ineseariamente para completar todo o trabajar 20 horas al día.
- Decir que no podría significar rechazar el ingreso en un corto plazo, pero también significa que las person que me pagan terminan tan felices que se convierten en mi equipo de ventas en un futuro (es decir, muchos más ingresos).
- Decir que no, no significa necesariamente que no voy a trabajar con un cliente, puede también no ser ahora, pero si lo hago cuando tengo espacios para trabajar.
- Decir que no aveces significa que tengo el presentimiento que puede ser complicado trabajar con un cliente o que no encaje con la forma en que yo trabajo. Esta bien rechazar proyectos cuando sientas que no van a ir bien, porqué es probable que no lo serán. Confio en tus entrañas.
Habrá ocasiones en las que decir "no" no será una opción (no tienes trabajo pero sí cuentas que pagar), pero cuando la opción está disponible puedes hacerlo. El plan A es adherirse a tu visión y no hacer cosas que puedan no encajar. El plan B es hacer lo que se necesita para poder sobrevivir. Yo eligo la A, aunque también la B está bien, lo que me trae a mi siguiente punto.
### Conoce tu propósito
Define por qué el trabajo que haces crea una decisión de alto impacto. Conocer tu propósito te hace más facil poder elegir tus clientes, lo que compartes, lo que rechazas y lo que te mueve.
Pregúntate a ti mismo lo sigiuente:
- ¿Qué representa tu trabajo?
- ¿Cuáles son los objetivos y la visión de tu trabajo?
- ¿Qué hace la diferencia de cualquier otro feelance que comparte tus habilidades?
- ¿Qué quieres conseguir para ti mismo y un logro para tus clientes?
El instinto es un reflejo de tu propósito, si has sido honesto contigo mismo en como lo definiste. Si no lo defines bien podrás tener inquietut y ser persistente con un nuevo proyecto o un cliente, incluso si no hay ningún problema en la superficie. O sientir la necesidad de cambiar la audiencia con la que trabajas y los problemas que estás resolviendo. Tu instinto es tu evaluador interno de tu propósito, y será notorio si te desvías de el o si necesitas hacer un cambio.
### 50% trabajo, 50% prisa
No puedes solo abrir una tienda y actualizar tu bandeja de entrada (trabajar como freelance no funciona así... en realidad, nada funciona así).
No hay anda de malo con salir y vender lo que haces. Nadie vendrá a tomar tu licensia de creatividad y la va a poner una etiqueta de "vendedor empalagoso" en tu frente.
Cuando trabajas para ti, tu eres el jefe de ventas. Eso está bien, vender no significa tuitear en mayúsculas COMPRA TODAS MIS COSAS. Vender es conectar y construir confianza. Cualquiera puede hacer eso.
No importa cuales son tus habilidades o que ofreces como freelance, obtener nuevos negocios se reduce a quienes conoces. Entre más personas lleguen a saber lo que haces, más oportunidades tendrás de trabajar con más clientes. No conozcas personas dándoles un discruso extenso de todo lo que haces, empieza a conectarte con ellos (asiste a eventos, participa en comunidades online, incluso pregúntales si pueden hacer una llamada por Skype y hablar sobre lo que hacen).
**Se trata sobre conexiones reales con personas reales, hacer las preguntas correctas y concentrare en escuchar lo que tienen que decir.**
### Acá no hay competencia
En el mundo corporativo, hemos venido chocando con la competencia. Para ser mejores que ellos, para ofrecer más que ellos y hacer más por menos. Decimos lo que necesitamos decir para estar un paso por delante de ellos, ellos son el enemigo que nos va a destruir cuando tengan la oportunidad.
*Ser freelance no es nada parecido a eso, de hecho, puede ser lo opuesto.*
Los freelances son personas que hacen las mismas cosas o muy parecidas a las que nosotros hacmeos. Tienen habilidades parecidas, conocimiento e incluso pasan por las mismas pruebas y los mismos problemas que nosotros. Pero también son lo suficientemente diferentes para tener una perspectiva de las cosas a como las vemos.
Entonces, ¿Por qué los vemos como enemigos? Ellos hacen parte de nuestra misma comunidad más que cualquier otra persona.
### Presta atención a la actividad de tu negocio
No solo estás creando un trabajo para que tus clientes te paguen por el, también estas administrando proyectos, cuentas y haces seguimiento de los gastos, haciendo reuniones y documentando todo lo que haces.
### Ser freelance es un negocio
Trata tu trabajo como si fuera un negocio y de seguro destacarás sobre el 90% de otras personas que ven el trabajo como "lo haré cuando me sienta interesado por el."
Ser un freelance que hace su trabajo no significa ser excéntrico, significa combinar tus habilidades y tus capacidades de hacer negocios.
### Comparte lo que sabes
Pensar en los líderes actuales de la industria. Esos que obtienen toda la atención, trabajan con los mejores clientes, y parecen reservados a unos precios que parecen casi ridiculos.
#### ¿Qué tenemos en común?
Ellos no son los únicos con talento (aunque están muy cerca), pero todos, sin duda, comparten su conocimiento con su audiencia por mail, libros, conferencias, tutoriales, podcast, artículos y más artículos. Así es como probablemente ellos se dan a conocer, como clientes potenciales los encuentran y como tu sabes sus nombres.
Pero tu puedes hacer lo mismo. Ellos no son guardianes que te impiden agregar tu contenido a tu propia web (o Medium, Linkedin, tumblr, etc...) eres capaz de compartir tus pensamientos, opiniones e ideas en todo internet.
Agregar valor a lo que las personas les interesa hacen que quiran contratarte. ¿Cómo sabes que ellos lo valoran? Pregúntales. O escucha los problemas que tienen, lo que están tratanto de aprender o lo que quieren descubrir.
### Ama el trabajo, no los premios
Tenemos derecho a trabajar, no a los frutos por ese trabajo. El Bhagavad Gita (un antiguo texto sagrado hinduista) dice algo similar, no tenemos derecho a los frutos de nuestra labor, pero solo el trabajo en si mismo. Si se logra entender así, podremos mantener ese derecho.
Tu trabajo se verá afectado si lo haces por likes en Dribbble o retweets de personas que solo te importan por el trabajo que tienen (y no clientes con los que trabajas) porqué estás concentrado en la atención en vez de solucionar un problema. Si te gusta o no, la intención es evidente, así que asegurate de que lo que haces es ciertamente lo que quieres que otros vean y conozcan.
### No tengas miedo
No hay nada de malo con ganar dinero cuando trabajas como freelance. De hecho, ¡es asombroso! Aunque el dinero puede ser incómodo, especialmente cuando proviene de clientes que imponen sus precios. Necesitas estar 100% seguro de lo que cobras, porqué si estás inseguro de eso, tu cliente probablemente también lo será y dudará de ti.
Por suerte puedes prácticar, con amigos o compañeros (o esas personas de otro campo que conoces). Puedes prácticar con clientes potenciales. Incluso si eres la reencarnación de Dale Carnegie, tus primeras impresiones pueden no ser tan claras como te gustaría. Pero con el tiempo vas a ir tomando ritmo para explicarles porqué vales lo que les estás cobrando.
Una regla de oro es que si todos están de acuerdo a trabajar contigo cuando tu les dices tu precio, no te estás sobrecargando.
Recuerda que hacer dinero es bueno, pero hacer dinero gracias a tu propia creatividad en una forma donde se alinea con tu propósito es realmente asombroso.
### Para resumir
Las personas que realmente hacen bien su trabajo no lo hacen por dinero, para comprarse su yate privado o recibir ovaciones (en facebook), ellos lo hacen porqué quieren agregar valor mientras que otros lideran su vida como mejor les parece.
En orden de ideas, para tener una carrera duradera como freelance donde te sientas feliz con ella, tienes que prestar atención, no solo es la forma en que haces las cosas, es en como haces negocios.
No hay un camino para "triunfar como freelance", solo unas cuantas cosas (como las de arriba) a las que les debes poner atención. Anbox and start hitting refresh.
hora regresa a tu bandeja de entrada y empieza a refrescar.
Solo bromeaba.
Todo el mundo sabe que el correo se actualiza solo en estos días...
[Leer artículo original][original]
[original]: https://medium.pjrvs.com/master-working-for-yourself-without-crushing-your-soul-b8a980763d43 | metorama/metorama.github.io | _posts/2015-08-03-como-ser-freelance.markdown | Markdown | apache-2.0 | 11,817 |
package Escape;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import Escape.Controller.Controller;
import Escape.Model.Arena;
import Escape.Service.Service;
import Escape.View.Rank;
import Escape.View.View;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.LogManager;
/**
* The main class of the program.
*/
public class Escape extends JFrame {
static {
InputStream in = Escape.class.getResourceAsStream("/logging.properties");
if (in != null) {
try {
LogManager.getLogManager().readConfiguration(in);
} catch(IOException e) {
e.printStackTrace();
}
}
}
/**
* The <code>serialVersionUID</code> of the class.
*/
private static final long serialVersionUID = -3689415169655758824L;
/**
* The main JPanel of the <code>frame</code>.
*/
private JPanel contentPane;
/**
* The main <code>Arena</code> object of the program.
*/
private Arena arena;
/**
* Part of the Game tab, the main <code>View</code> object.
*/
private View view;
/**
* The main <code>Controller</code> object of the program.
*/
private Controller control;
/**
* Part of the Rank tab, the main <code>Rank</code> object.
*/
private Rank rank;
/**
* The name of the player.
* Default is "Guest".
*/
private String username = "Guest";
/**
* The password for the database.
*/
private String DAOpassword = "pwd";
/**
* Main method of the program.
* Creates the main JFrame object and asks the user to set <code>DAOpassword</code>
* and <code>username</code> before start the game.
*
* @param args command-line parameters
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Escape frame = new Escape();
frame.setVisible(true);
do{
frame.DAOpassword = JOptionPane.showInputDialog(frame, "Enter password for database!");
} while(frame.DAOpassword.equals("pwd"));
do{
frame.username = JOptionPane.showInputDialog(frame, "Enter your in-game name!");
} while(frame.username.equals("") || frame.username == null);
frame.rank.setDAOpassword(frame.DAOpassword);
frame.rank.refreshRank();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Constructor for the main JFrame object.
* Sets the <code>frame</code> and initialize the <code>arena</code>, <code>view</code>,
* <code>control</code>, <code>rank</code> variables, add tabs.
* Calls the <code>initMenu</code> for add menu.
*/
public Escape() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Escape");
setBounds(300, 0, 0, 0);
pack();
Insets insets = getInsets();
setSize(new Dimension(insets.left + insets.right + 600,
insets.top + insets.bottom + 630));
contentPane = new JPanel();
contentPane.setBackground(Color.WHITE);
arena = new Arena(6, 600);
view = new View(arena);
control = new Controller(arena, view);
view.setControl(control);
rank = new Rank();
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout());
createMenuBar();
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("Game", view);
tabbedPane.addTab("Rank", rank);
tabbedPane.setFocusable(false);
contentPane.add(tabbedPane);
setLocationRelativeTo(view.getPlayer());
}
/**
* Creates the Menu and add to the main JFrame.
* Creates the "New Game", "Save Game" and "Exit" items and
* add ActionListener for control actions.
*/
private void createMenuBar() {
JMenuBar menubar = new JMenuBar();
JMenu file = new JMenu("File");
file.setMnemonic(KeyEvent.VK_F);
JMenuItem newGameMenuItem = new JMenuItem("New Game");
newGameMenuItem.setMnemonic(KeyEvent.VK_E);
newGameMenuItem.setToolTipText("Start a new game");
newGameMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
Service.newGame(arena, control, view);
}
});
JMenuItem saveGameMenuItem = new JMenuItem("Save Game");
saveGameMenuItem.setMnemonic(KeyEvent.VK_E);
saveGameMenuItem.setToolTipText("Save the actual score and start a new game!");
saveGameMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
System.out.println(control.getPlayerScore()+control.getEnemyScore());
Service.saveGame(control, username, DAOpassword);
Service.newGame(arena, control, view);
}
});
JMenuItem exitMenuItem = new JMenuItem("Exit");
exitMenuItem.setMnemonic(KeyEvent.VK_E);
exitMenuItem.setToolTipText("Exit application");
exitMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
file.add(newGameMenuItem);
file.add(saveGameMenuItem);
file.add(exitMenuItem);
menubar.add(file);
setJMenuBar(menubar);
}
}
| Zakemi/Escape | src/main/java/Escape/Escape.java | Java | apache-2.0 | 5,644 |
/**
* 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.component.influxdb;
import org.apache.camel.Consumer;
import org.apache.camel.Processor;
import org.apache.camel.Producer;
import org.apache.camel.support.DefaultEndpoint;
import org.apache.camel.spi.Metadata;
import org.apache.camel.spi.UriEndpoint;
import org.apache.camel.spi.UriParam;
import org.apache.camel.spi.UriPath;
import org.apache.camel.support.CamelContextHelper;
import org.influxdb.InfluxDB;
/**
* The influxdb component allows you to interact with <a href="https://influxdata.com/time-series-platform/influxdb/">InfluxDB</a>, a time series database.
*/
@UriEndpoint(firstVersion = "2.18.0", scheme = "influxdb", title = "InfluxDB", syntax = "influxdb:connectionBean", label = "database", producerOnly = true)
public class InfluxDbEndpoint extends DefaultEndpoint {
private InfluxDB influxDB;
@UriPath
@Metadata(required = "true")
private String connectionBean;
@UriParam
private String databaseName;
@UriParam(defaultValue = "default")
private String retentionPolicy = "default";
@UriParam(defaultValue = "false")
private boolean batch;
@UriParam(defaultValue = InfluxDbOperations.INSERT)
private String operation = InfluxDbOperations.INSERT;
@UriParam
private String query;
public InfluxDbEndpoint(String uri, InfluxDbComponent component) {
super(uri, component);
}
@Override
public Producer createProducer() throws Exception {
return new InfluxDbProducer(this);
}
@Override
public Consumer createConsumer(Processor processor) throws Exception {
throw new UnsupportedOperationException("You cannot receive messages from this endpoint");
}
@Override
protected void doStart() throws Exception {
influxDB = CamelContextHelper.mandatoryLookup(getCamelContext(), connectionBean, InfluxDB.class);
log.debug("Resolved the connection with the name {} as {}", connectionBean, influxDB);
super.doStart();
}
@Override
protected void doStop() throws Exception {
super.doStop();
}
@Override
public boolean isSingleton() {
return true;
}
public InfluxDB getInfluxDB() {
return influxDB;
}
/**
* The Influx DB to use
*/
public void setInfluxDB(InfluxDB influxDB) {
this.influxDB = influxDB;
}
public String getDatabaseName() {
return databaseName;
}
/**
* The name of the database where the time series will be stored
*/
public void setDatabaseName(String databaseName) {
this.databaseName = databaseName;
}
public String getRetentionPolicy() {
return retentionPolicy;
}
/**
* The string that defines the retention policy to the data created by the endpoint
*/
public void setRetentionPolicy(String retentionPolicy) {
this.retentionPolicy = retentionPolicy;
}
public String getConnectionBean() {
return connectionBean;
}
/**
* Connection to the influx database, of class InfluxDB.class
*/
public void setConnectionBean(String connectionBean) {
this.connectionBean = connectionBean;
}
public boolean isBatch() {
return batch;
}
/**
* Define if this operation is a batch operation or not
*/
public void setBatch(boolean batch) {
this.batch = batch;
}
public String getOperation() {
return operation;
}
/**
* Define if this operation is an insert or a query
*/
public void setOperation(String operation) {
this.operation = operation;
}
public String getQuery() {
return query;
}
/**
* Define the query in case of operation query
*/
public void setQuery(String query) {
this.query = query;
}
}
| kevinearls/camel | components/camel-influxdb/src/main/java/org/apache/camel/component/influxdb/InfluxDbEndpoint.java | Java | apache-2.0 | 4,672 |
/*
* Copyright (C) 2008 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.xiaomi.smarthome.common.ui.dialog;
import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import java.lang.ref.WeakReference;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.CursorAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import com.xiaomi.common.R;
public class MLAlertController {
private static final int BIT_BUTTON_POSITIVE = 1;
private static final int BIT_BUTTON_NEGATIVE = 2;
private static final int BIT_BUTTON_NEUTRAL = 4;
private final Context mContext;
private final DialogInterface mDialogInterface;
private final Window mWindow;
private CharSequence mTitle;
private CharSequence mMessage;
private ListView mListView;
private View mView;
private int mViewSpacingLeft;
private int mViewSpacingTop;
private int mViewSpacingRight;
private int mViewSpacingBottom;
private boolean mViewSpacingSpecified = false;
private Button mButtonPositive;
private CharSequence mButtonPositiveText;
private Message mButtonPositiveMessage;
private Button mButtonNegative;
private CharSequence mButtonNegativeText;
private Message mButtonNegativeMessage;
private Button mButtonNeutral;
private CharSequence mButtonNeutralText;
private Message mButtonNeutralMessage;
private ScrollView mScrollView;
private int mIconId = -1;
private Drawable mIcon;
private ImageView mIconView;
private TextView mTitleView;
private TextView mMessageView;
private View mCustomTitleView;
private boolean mForceInverseBackground;
private ListAdapter mAdapter;
private int mCheckedItem = -1;
private int mAlertDialogLayout;
private int mListLayout;
private int mListLayoutWithTitle;
private int mMultiChoiceItemLayout;
private int mSingleChoiceItemLayout;
private int mListItemLayout;
// add by afei for progressDialog Top and normal is Bottom
private int mGravity;
private Handler mHandler;
private boolean mTransplantBg = false;
private boolean mAutoDismiss = true; // 对话框在点击按钮之后是否自动消失
private boolean mCustomBgTransplant = false;
View.OnClickListener mButtonHandler = new View.OnClickListener() {
public void onClick(View v) {
Message m = null;
if (v == mButtonPositive && mButtonPositiveMessage != null) {
m = Message.obtain(mButtonPositiveMessage);
} else if (v == mButtonNegative && mButtonNegativeMessage != null) {
m = Message.obtain(mButtonNegativeMessage);
} else if (v == mButtonNeutral && mButtonNeutralMessage != null) {
m = Message.obtain(mButtonNeutralMessage);
}
if (m != null) {
m.sendToTarget();
}
if (mAutoDismiss) {
// Post a message so we dismiss after the above handlers are
// executed
mHandler.obtainMessage(ButtonHandler.MSG_DISMISS_DIALOG, mDialogInterface)
.sendToTarget();
}
}
};
private static final class ButtonHandler extends Handler {
// Button clicks have Message.what as the BUTTON{1,2,3} constant
private static final int MSG_DISMISS_DIALOG = 1;
private WeakReference<DialogInterface> mDialog;
public ButtonHandler(DialogInterface dialog) {
mDialog = new WeakReference<DialogInterface>(dialog);
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case DialogInterface.BUTTON_POSITIVE:
case DialogInterface.BUTTON_NEGATIVE:
case DialogInterface.BUTTON_NEUTRAL:
((DialogInterface.OnClickListener) msg.obj).onClick(mDialog.get(), msg.what);
break;
case MSG_DISMISS_DIALOG:
((DialogInterface) msg.obj).dismiss();
}
}
}
public void sendDismissMessage() {
mHandler.obtainMessage(ButtonHandler.MSG_DISMISS_DIALOG, mDialogInterface).sendToTarget();
}
public MLAlertController(Context context, DialogInterface di, Window window) {
this(context, di, window, Gravity.BOTTOM);
}
public MLAlertController(Context context, DialogInterface di, Window window, int gravity) {
mContext = context;
mDialogInterface = di;
mWindow = window;
mHandler = new ButtonHandler(di);
mAlertDialogLayout = R.layout.ml_alert_dialog;
mListLayout = R.layout.ml_select_dialog;
mListLayoutWithTitle = R.layout.ml_select_dialog_center;
mMultiChoiceItemLayout = R.layout.ml_select_dialog_multichoice;
mSingleChoiceItemLayout = R.layout.ml_select_dialog_singlechoice;
mListItemLayout = R.layout.ml_select_dialog_item;
mGravity = gravity;
}
static boolean canTextInput(View v) {
if (v.onCheckIsTextEditor()) {
return true;
}
if (!(v instanceof ViewGroup)) {
return false;
}
ViewGroup vg = (ViewGroup) v;
int i = vg.getChildCount();
while (i > 0) {
i--;
v = vg.getChildAt(i);
if (canTextInput(v)) {
return true;
}
}
return false;
}
public void installContent() {
/* We use a custom title so never request a window title */
mWindow.requestFeature(Window.FEATURE_NO_TITLE);
mWindow.setGravity(mGravity);
if (mView == null || !canTextInput(mView)) {
mWindow.setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
}
mWindow.setContentView(mAlertDialogLayout);
setupView();
}
public void setTitle(CharSequence title) {
mTitle = title;
if (mTitleView != null) {
mTitleView.setText(title);
}
}
/**
* @see android.app.AlertDialog.Builder#setCustomTitle(View)
*/
public void setCustomTitle(View customTitleView) {
mCustomTitleView = customTitleView;
}
public void setAudoDismiss(boolean autoDismiss) {
mAutoDismiss = autoDismiss;
}
public void setMessage(CharSequence message) {
mMessage = message;
if (mMessageView != null) {
mMessageView.setText(message);
}
}
/**
* Set the view to display in the dialog.
*/
public void setView(View view) {
mView = view;
mViewSpacingSpecified = false;
}
public void setCustomTransplant(boolean b) {
mCustomBgTransplant = b;
}
/**
* Set the view to display in the dialog along with the spacing around that
* view
*/
public void setView(View view, int viewSpacingLeft, int viewSpacingTop, int viewSpacingRight,
int viewSpacingBottom) {
mView = view;
mViewSpacingSpecified = true;
mViewSpacingLeft = viewSpacingLeft;
mViewSpacingTop = viewSpacingTop;
mViewSpacingRight = viewSpacingRight;
mViewSpacingBottom = viewSpacingBottom;
}
/**
* Sets a click listener or a message to be sent when the button is clicked.
* You only need to pass one of {@code listener} or {@code msg}.
*
* @param whichButton Which button, can be one of
* {@link DialogInterface#BUTTON_POSITIVE},
* {@link DialogInterface#BUTTON_NEGATIVE}, or
* {@link DialogInterface#BUTTON_NEUTRAL}
* @param text The text to display in positive button.
* @param listener The
* {@link DialogInterface.OnClickListener} to
* use.
* @param msg The {@link Message} to be sent when clicked.
*/
public void setButton(int whichButton, CharSequence text,
DialogInterface.OnClickListener listener, Message msg) {
if (msg == null && listener != null) {
msg = mHandler.obtainMessage(whichButton, listener);
}
switch (whichButton) {
case DialogInterface.BUTTON_POSITIVE:
mButtonPositiveText = text;
mButtonPositiveMessage = msg;
break;
case DialogInterface.BUTTON_NEGATIVE:
mButtonNegativeText = text;
mButtonNegativeMessage = msg;
break;
case DialogInterface.BUTTON_NEUTRAL:
mButtonNeutralText = text;
mButtonNeutralMessage = msg;
break;
default:
throw new IllegalArgumentException("Button does not exist");
}
}
/**
* Set resId to 0 if you don't want an icon.
*
* @param resId the resourceId of the drawable to use as the icon or 0 if
* you don't want an icon.
*/
public void setIcon(int resId) {
mIconId = resId;
if (mIconView != null) {
if (resId > 0) {
mIconView.setImageResource(mIconId);
} else if (resId == 0) {
mIconView.setVisibility(View.GONE);
}
}
}
public void setIcon(Drawable icon) {
mIcon = icon;
if ((mIconView != null) && (mIcon != null)) {
mIconView.setImageDrawable(icon);
}
}
public void setInverseBackgroundForced(boolean forceInverseBackground) {
mForceInverseBackground = forceInverseBackground;
}
public ListView getListView() {
return mListView;
}
public View getView() {
return mView;
}
public Button getButton(int whichButton) {
switch (whichButton) {
case DialogInterface.BUTTON_POSITIVE:
return mButtonPositive;
case DialogInterface.BUTTON_NEGATIVE:
return mButtonNegative;
case DialogInterface.BUTTON_NEUTRAL:
return mButtonNeutral;
default:
return null;
}
}
@SuppressWarnings({
"UnusedDeclaration"
})
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU && mListView != null
&& mListView.getVisibility() == View.VISIBLE) {
this.mDialogInterface.dismiss();
}
return mScrollView != null && mScrollView.executeKeyEvent(event);
}
@SuppressWarnings({
"UnusedDeclaration"
})
public boolean onKeyUp(int keyCode, KeyEvent event) {
return mScrollView != null && mScrollView.executeKeyEvent(event);
}
private void setupView() {
LinearLayout contentPanel = (LinearLayout) mWindow.findViewById(R.id.contentPanel);
setupContent(contentPanel);
boolean hasButtons = setupButtons();
LinearLayout topPanel = (LinearLayout) mWindow.findViewById(R.id.topPanel);
boolean hasTitle = setupTitle(topPanel);
View buttonPanel = mWindow.findViewById(R.id.buttonPanel);
if (!hasButtons) {
buttonPanel.setVisibility(View.GONE);
}
FrameLayout customPanel = (FrameLayout) mWindow.findViewById(R.id.customPanel);
if (mView != null) {
// 自定义dialog透明背景
// mWindow.findViewById(R.id.parentPanel).setBackgroundColor(mContext.getResources().getColor(android.R.color.transparent));
FrameLayout custom = (FrameLayout) mWindow.findViewById(R.id.custom);
custom.addView(mView);
if (mViewSpacingSpecified) {
custom.setPadding(mViewSpacingLeft, mViewSpacingTop, mViewSpacingRight,
mViewSpacingBottom);
if (mCustomBgTransplant)
mTransplantBg = true;
}
if (mListView != null) {
((LinearLayout.LayoutParams) customPanel.getLayoutParams()).weight = 0;
}
} else {
customPanel.setVisibility(View.GONE);
}
if (mTransplantBg) {
mWindow.findViewById(R.id.parentPanel).setBackgroundColor(
mContext.getResources().getColor(android.R.color.transparent));
} else {
// mWindow.findViewById(R.id.parentPanel).setBackgroundColor(0xffffffff);
}
if (mListView != null) {
// Listview有分割线divider,因此header和listview需要显示分割线
mWindow.findViewById(R.id.title_divider_line).setVisibility(View.VISIBLE);
mWindow.findViewById(R.id.title_divider_line_bottom).setVisibility(View.VISIBLE);
} else {
mWindow.findViewById(R.id.title_divider_line).setVisibility(View.GONE);
mWindow.findViewById(R.id.title_divider_line_bottom).setVisibility(View.GONE);
}
/**
* Add margin top for the button panel if we have not any panel
*/
if (topPanel.getVisibility() == View.GONE && contentPanel.getVisibility() == View.GONE
&& customPanel.getVisibility() == View.GONE && hasButtons) {
buttonPanel.setPadding(buttonPanel.getPaddingLeft(), buttonPanel.getPaddingBottom(),
buttonPanel.getPaddingRight(), buttonPanel.getPaddingBottom());
}
/*
* Only display the divider if we have a title and a custom view or a
* message.
*/
if (hasTitle) {
// View divider = null;
// if (mMessage != null || mView != null || mListView != null) {
// divider = mWindow.findViewById(R.id.titleDivider);
// } else {
// divider = mWindow.findViewById(R.id.titleDividerTop);
// }
//
// if (divider != null) {
// divider.setVisibility(View.VISIBLE);
// }
}
setBackground(topPanel, contentPanel, customPanel, hasButtons, hasTitle, buttonPanel);
if (TextUtils.isEmpty(mTitle) && TextUtils.isEmpty(mMessage)) {
mWindow.findViewById(R.id.empty_view).setVisibility(View.GONE);
}
}
private boolean setupTitle(LinearLayout topPanel) {
boolean hasTitle = true;
if (mCustomTitleView != null) {
// Add the custom title view directly to the topPanel layout
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
topPanel.addView(mCustomTitleView, 0, lp);
// Hide the title template
View titleTemplate = mWindow.findViewById(R.id.title_template);
titleTemplate.setVisibility(View.GONE);
} else {
final boolean hasTextTitle = !TextUtils.isEmpty(mTitle);
mIconView = (ImageView) mWindow.findViewById(R.id.icon);
if (hasTextTitle) {
/* Display the title if a title is supplied, else hide it */
mTitleView = (TextView) mWindow.findViewById(R.id.alertTitle);
mTitleView.setText(mTitle);
/*
* Do this last so that if the user has supplied any icons we
* use them instead of the default ones. If the user has
* specified 0 then make it disappear.
*/
if (mIconId > 0) {
mIconView.setImageResource(mIconId);
} else if (mIcon != null) {
mIconView.setImageDrawable(mIcon);
} else if (mIconId == 0) {
/*
* Apply the padding from the icon to ensure the title is
* aligned correctly.
*/
mTitleView.setPadding(mIconView.getPaddingLeft(),
mIconView.getPaddingTop(),
mIconView.getPaddingRight(),
mIconView.getPaddingBottom());
mIconView.setVisibility(View.GONE);
}
} else {
// Hide the title template
View titleTemplate = mWindow.findViewById(R.id.title_template);
titleTemplate.setVisibility(View.GONE);
mIconView.setVisibility(View.GONE);
topPanel.setVisibility(View.GONE);
hasTitle = false;
}
}
return hasTitle;
}
private void setupContent(LinearLayout contentPanel) {
mScrollView = (ScrollView) mWindow.findViewById(R.id.scrollView);
mScrollView.setFocusable(false);
// Special case for users that only want to display a String
mMessageView = (TextView) mWindow.findViewById(R.id.message);
if (mMessageView == null) {
return;
}
if (mMessage != null) {
mMessageView.setText(mMessage);
} else {
mMessageView.setVisibility(View.GONE);
mScrollView.removeView(mMessageView);
if (mListView != null) {
contentPanel.removeView(mWindow.findViewById(R.id.scrollView));
contentPanel.addView(mListView,
new LinearLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT));
contentPanel.setLayoutParams(new LinearLayout.LayoutParams(MATCH_PARENT, 0, 1.0f));
} else {
contentPanel.setVisibility(View.GONE);
}
}
}
private boolean setupButtons() {
int whichButtons = 0;
mButtonPositive = (Button) mWindow.findViewById(R.id.button1);
mButtonPositive.setOnClickListener(mButtonHandler);
if (TextUtils.isEmpty(mButtonPositiveText)) {
mButtonPositive.setVisibility(View.GONE);
} else {
mButtonPositive.setText(mButtonPositiveText);
mButtonPositive.setVisibility(View.VISIBLE);
whichButtons = whichButtons | BIT_BUTTON_POSITIVE;
}
mButtonNegative = (Button) mWindow.findViewById(R.id.button2);
mButtonNegative.setOnClickListener(mButtonHandler);
if (TextUtils.isEmpty(mButtonNegativeText)) {
mButtonNegative.setVisibility(View.GONE);
} else {
mButtonNegative.setText(mButtonNegativeText);
mButtonNegative.setVisibility(View.VISIBLE);
whichButtons = whichButtons | BIT_BUTTON_NEGATIVE;
}
mButtonNeutral = (Button) mWindow.findViewById(R.id.button3);
mButtonNeutral.setOnClickListener(mButtonHandler);
if (TextUtils.isEmpty(mButtonNeutralText)) {
mButtonNeutral.setVisibility(View.GONE);
} else {
mButtonNeutral.setText(mButtonNeutralText);
mButtonNeutral.setVisibility(View.VISIBLE);
whichButtons = whichButtons | BIT_BUTTON_NEUTRAL;
}
if (shouldCenterSingleButton(whichButtons)) {
if (whichButtons == BIT_BUTTON_POSITIVE) {
centerButton(mButtonPositive);
} else if (whichButtons == BIT_BUTTON_NEGATIVE) {
centerButton(mButtonNegative);
} else if (whichButtons == BIT_BUTTON_NEUTRAL) {
centerButton(mButtonNeutral);
}
}
return whichButtons != 0;
}
private static boolean shouldCenterSingleButton(int whichButton) {
return whichButton == BIT_BUTTON_POSITIVE
|| whichButton == BIT_BUTTON_NEGATIVE
|| whichButton == BIT_BUTTON_NEUTRAL;
}
private void centerButton(TextView button) {
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) button.getLayoutParams();
params.gravity = Gravity.CENTER_HORIZONTAL;
params.weight = 0.5f;
button.setLayoutParams(params);
button.setBackgroundResource(R.drawable.common_button);
}
private void setBackground(LinearLayout topPanel, LinearLayout contentPanel,
View customPanel, boolean hasButtons, boolean hasTitle,
View buttonPanel) {
if (mTransplantBg) {
/* Get all the different background required */
int fullDark = mContext.getResources().getColor(android.R.color.transparent);
int topDark = mContext.getResources().getColor(android.R.color.transparent);
int centerDark = mContext.getResources().getColor(android.R.color.transparent);
int bottomDark = mContext.getResources().getColor(android.R.color.transparent);
int fullBright = mContext.getResources().getColor(android.R.color.transparent);
int topBright = mContext.getResources().getColor(android.R.color.transparent);
int centerBright = mContext.getResources().getColor(android.R.color.transparent);
int bottomBright = mContext.getResources().getColor(android.R.color.transparent);
int bottomMedium = mContext.getResources().getColor(android.R.color.transparent);
/*
* We now set the background of all of the sections of the alert.
* First collect together each section that is being displayed along
* with whether it is on a light or dark background, then run
* through them setting their backgrounds. This is complicated
* because we need to correctly use the full, top, middle, and
* bottom graphics depending on how many views they are and where
* they appear.
*/
View[] views = new View[4];
boolean[] light = new boolean[4];
View lastView = null;
boolean lastLight = false;
int pos = 0;
if (hasTitle) {
views[pos] = topPanel;
light[pos] = false;
pos++;
}
/*
* The contentPanel displays either a custom text message or a
* ListView. If it's text we should use the dark background for
* ListView we should use the light background. If neither are there
* the contentPanel will be hidden so set it as null.
*/
views[pos] = (contentPanel.getVisibility() == View.GONE)
? null : contentPanel;
light[pos] = mListView != null;
pos++;
if (customPanel != null) {
views[pos] = customPanel;
light[pos] = mForceInverseBackground;
pos++;
}
if (hasButtons) {
views[pos] = buttonPanel;
light[pos] = true;
}
boolean setView = false;
for (pos = 0; pos < views.length; pos++) {
View v = views[pos];
if (v == null) {
continue;
}
if (lastView != null) {
if (!setView) {
lastView.setBackgroundResource(lastLight ? topBright : topDark);
} else {
lastView.setBackgroundResource(lastLight ? centerBright : centerDark);
}
setView = true;
}
lastView = v;
lastLight = light[pos];
}
if (lastView != null) {
if (setView) {
/*
* ListViews will use the Bright background but buttons use
* the Medium background.
*/
lastView.setBackgroundResource(
lastLight ? (hasButtons ? bottomMedium : bottomBright) : bottomDark);
} else {
lastView.setBackgroundResource(lastLight ? fullBright : fullDark);
}
}
}
if ((mListView != null) && (mAdapter != null)) {
mListView.setAdapter(mAdapter);
if (mCheckedItem > -1) {
mListView.setItemChecked(mCheckedItem, true);
mListView.setSelection(mCheckedItem);
}
}
}
public static class RecycleListView extends ListView {
boolean mRecycleOnMeasure = true;
public RecycleListView(Context context) {
super(context);
}
public RecycleListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public RecycleListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
protected boolean recycleOnMeasure() {
return mRecycleOnMeasure;
}
}
public static class AlertParams {
public final Context mContext;
public final LayoutInflater mInflater;
public int mIconId = 0;
public Drawable mIcon;
public CharSequence mTitle;
public View mCustomTitleView;
public CharSequence mMessage;
public CharSequence mPositiveButtonText;
public DialogInterface.OnClickListener mPositiveButtonListener;
public CharSequence mNegativeButtonText;
public DialogInterface.OnClickListener mNegativeButtonListener;
public CharSequence mNeutralButtonText;
public DialogInterface.OnClickListener mNeutralButtonListener;
public boolean mCancelable;
public DialogInterface.OnCancelListener mOnCancelListener;
public DialogInterface.OnKeyListener mOnKeyListener;
public CharSequence[] mItems;
public ListAdapter mAdapter;
public DialogInterface.OnClickListener mOnClickListener;
public View mView;
public int mViewSpacingLeft;
public int mViewSpacingTop;
public int mViewSpacingRight;
public int mViewSpacingBottom;
public boolean mViewSpacingSpecified = false;
public boolean[] mCheckedItems;
public boolean mIsMultiChoice;
public boolean mIsSingleChoice;
public int mCheckedItem = -1;
public DialogInterface.OnMultiChoiceClickListener mOnCheckboxClickListener;
public Cursor mCursor;
public String mLabelColumn;
public String mIsCheckedColumn;
public boolean mForceInverseBackground;
public AdapterView.OnItemSelectedListener mOnItemSelectedListener;
public OnPrepareListViewListener mOnPrepareListViewListener;
public boolean mRecycleOnMeasure = true;
public boolean mAutoDismiss = true;
public MLAlertDialog.DismissCallBack mDismissCallBack;
public CharSequence mCustomTitle;
public boolean mCustomBgTransplant = false;
/**
* Interface definition for a callback to be invoked before the ListView
* will be bound to an adapter.
*/
public interface OnPrepareListViewListener {
/**
* Called before the ListView is bound to an adapter.
*
* @param listView The ListView that will be shown in the dialog.
*/
void onPrepareListView(ListView listView);
}
public AlertParams(Context context) {
mContext = context;
mCancelable = true;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void apply(MLAlertController dialog) {
if (mCustomTitleView != null) {
dialog.setCustomTitle(mCustomTitleView);
} else {
if (mTitle != null) {
dialog.setTitle(mTitle);
}
if (mIcon != null) {
dialog.setIcon(mIcon);
}
if (mIconId >= 0) {
dialog.setIcon(mIconId);
}
}
if (mMessage != null) {
dialog.setMessage(mMessage);
}
if (mPositiveButtonText != null) {
dialog.setButton(DialogInterface.BUTTON_POSITIVE, mPositiveButtonText,
mPositiveButtonListener, null);
}
if (mNegativeButtonText != null) {
dialog.setButton(DialogInterface.BUTTON_NEGATIVE, mNegativeButtonText,
mNegativeButtonListener, null);
}
if (mNeutralButtonText != null) {
dialog.setButton(DialogInterface.BUTTON_NEUTRAL, mNeutralButtonText,
mNeutralButtonListener, null);
}
if (mForceInverseBackground) {
dialog.setInverseBackgroundForced(true);
}
// For a list, the client can either supply an array of items or an
// adapter or a cursor
dialog.mTransplantBg = false;
if ((mItems != null) || (mCursor != null) || (mAdapter != null)) {
if (dialog.mGravity == Gravity.CENTER) {
createCenterListView(dialog);
} else {
createListView(dialog);
}
}
if (mView != null) {
if (mViewSpacingSpecified) {
dialog.setView(mView, mViewSpacingLeft, mViewSpacingTop, mViewSpacingRight,
mViewSpacingBottom);
} else {
dialog.setView(mView);
}
}
dialog.setAudoDismiss(mAutoDismiss);
dialog.setCustomTransplant(mCustomBgTransplant);
}
private void createCenterListView(final MLAlertController dialog) {
final LinearLayout customView = (LinearLayout)
mInflater.inflate(dialog.mListLayoutWithTitle, null);
final RecycleListView listView = (RecycleListView) customView
.findViewById(R.id.select_dialog_listview);
ListAdapter adapter;
int layout = R.layout.ml_center_item;
if (mCursor == null) {
adapter = (mAdapter != null) ? mAdapter
: new ArrayAdapter<CharSequence>(mContext, layout, R.id.text1, mItems);
} else {
adapter = new SimpleCursorAdapter(mContext, layout,
mCursor, new String[] {
mLabelColumn
}, new int[] {
R.id.text1
});
}
if (mCustomTitle != null) {
((TextView) (customView.findViewById(R.id.title))).setText(mCustomTitle);
}
if (mOnPrepareListViewListener != null) {
mOnPrepareListViewListener.onPrepareListView(listView);
}
/*
* Don't directly set the adapter on the ListView as we might want
* to add a footer to the ListView later.
*/
dialog.mAdapter = adapter;
listView.setAdapter(adapter);
dialog.mCheckedItem = mCheckedItem;
if (mOnClickListener != null) {
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
mOnClickListener.onClick(dialog.mDialogInterface, position);
if (!mIsSingleChoice) {
dialog.mDialogInterface.dismiss();
}
}
});
} else if (mOnCheckboxClickListener != null) {
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
if (mCheckedItems != null) {
mCheckedItems[position] = listView.isItemChecked(position);
}
mOnCheckboxClickListener.onClick(
dialog.mDialogInterface, position, listView.isItemChecked(position));
}
});
}
// Attach a given OnItemSelectedListener to the ListView
if (mOnItemSelectedListener != null) {
listView.setOnItemSelectedListener(mOnItemSelectedListener);
}
if (mOnItemSelectedListener != null) {
listView.setOnItemSelectedListener(mOnItemSelectedListener);
}
if (mIsSingleChoice) {
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
} else if (mIsMultiChoice) {
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
listView.mRecycleOnMeasure = mRecycleOnMeasure;
dialog.mView = customView;
dialog.mTransplantBg = true;
dialog.setCustomTransplant(mCustomBgTransplant);
}
private void createListView(final MLAlertController dialog) {
final RecycleListView listView = (RecycleListView)
mInflater.inflate(dialog.mListLayout, null);
ListAdapter adapter;
if (mIsMultiChoice) {
if (mCursor == null) {
adapter = new ArrayAdapter<CharSequence>(
mContext, dialog.mMultiChoiceItemLayout, R.id.text1, mItems) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
if (mCheckedItems != null) {
boolean isItemChecked = mCheckedItems[position];
if (isItemChecked) {
listView.setItemChecked(position, true);
}
}
return view;
}
};
} else {
adapter = new CursorAdapter(mContext, mCursor, false) {
private final int mLabelIndex;
private final int mIsCheckedIndex;
{
final Cursor cursor = getCursor();
mLabelIndex = cursor.getColumnIndexOrThrow(mLabelColumn);
mIsCheckedIndex = cursor.getColumnIndexOrThrow(mIsCheckedColumn);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
CheckedTextView text = (CheckedTextView) view.findViewById(R.id.text1);
text.setText(cursor.getString(mLabelIndex));
listView.setItemChecked(cursor.getPosition(),
cursor.getInt(mIsCheckedIndex) == 1);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return mInflater.inflate(dialog.mMultiChoiceItemLayout,
parent, false);
}
};
}
} else {
int layout = mIsSingleChoice
? dialog.mSingleChoiceItemLayout : dialog.mListItemLayout;
if (mCursor == null) {
adapter = (mAdapter != null) ? mAdapter
: new ArrayAdapter<CharSequence>(mContext, layout, R.id.text1, mItems);
} else {
adapter = new SimpleCursorAdapter(mContext, layout,
mCursor, new String[] {
mLabelColumn
}, new int[] {
R.id.text1
});
}
}
if (mOnPrepareListViewListener != null) {
mOnPrepareListViewListener.onPrepareListView(listView);
}
/*
* Don't directly set the adapter on the ListView as we might want
* to add a footer to the ListView later.
*/
dialog.mAdapter = adapter;
dialog.mCheckedItem = mCheckedItem;
if (mOnClickListener != null) {
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
mOnClickListener.onClick(dialog.mDialogInterface, position);
if (!mIsSingleChoice) {
dialog.mDialogInterface.dismiss();
}
}
});
} else if (mOnCheckboxClickListener != null) {
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
if (mCheckedItems != null) {
mCheckedItems[position] = listView.isItemChecked(position);
}
mOnCheckboxClickListener.onClick(
dialog.mDialogInterface, position, listView.isItemChecked(position));
}
});
}
// Attach a given OnItemSelectedListener to the ListView
if (mOnItemSelectedListener != null) {
listView.setOnItemSelectedListener(mOnItemSelectedListener);
}
if (mIsSingleChoice) {
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
} else if (mIsMultiChoice) {
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
listView.mRecycleOnMeasure = mRecycleOnMeasure;
dialog.mListView = listView;
dialog.setCustomTransplant(mCustomBgTransplant);
}
}
}
| Liyueyang/NewXmPluginSDK | common_ui/src/main/java/com/xiaomi/smarthome/common/ui/dialog/MLAlertController.java | Java | apache-2.0 | 39,780 |
/**
* Copyright 2011 Micheal Swiggs
*
* 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.reddcoin.net.discovery;
import com.google.reddcoin.params.MainNetParams;
import org.junit.Test;
import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
public class SeedPeersTest {
@Test
public void getPeer_one() throws Exception{
SeedPeers seedPeers = new SeedPeers(MainNetParams.get());
assertThat(seedPeers.getPeer(), notNullValue());
}
@Test
public void getPeer_all() throws Exception{
SeedPeers seedPeers = new SeedPeers(MainNetParams.get());
for(int i = 0; i < SeedPeers.seedAddrs.length; ++i){
assertThat("Failed on index: "+i, seedPeers.getPeer(), notNullValue());
}
assertThat(seedPeers.getPeer(), equalTo(null));
}
@Test
public void getPeers_length() throws Exception{
SeedPeers seedPeers = new SeedPeers(MainNetParams.get());
InetSocketAddress[] addresses = seedPeers.getPeers(0, TimeUnit.SECONDS);
assertThat(addresses.length, equalTo(SeedPeers.seedAddrs.length));
}
}
| reddcoin-project/reddcoinj-pow | core/src/test/java/com/google/reddcoin/net/discovery/SeedPeersTest.java | Java | apache-2.0 | 1,795 |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const options_1 = require("./options");
class TslintFixTask {
constructor(configOrPath, options) {
if (options) {
this._configOrPath = configOrPath;
this._options = options;
}
else {
this._options = configOrPath;
this._configOrPath = null;
}
}
toConfiguration() {
const path = typeof this._configOrPath == 'string' ? { tslintPath: this._configOrPath } : {};
const config = typeof this._configOrPath == 'object' && this._configOrPath !== null
? { tslintConfig: this._configOrPath }
: {};
const options = {
...this._options,
...path,
...config,
};
return { name: options_1.TslintFixName, options };
}
}
exports.TslintFixTask = TslintFixTask;
| cloudfoundry-community/asp.net5-buildpack | fixtures/node_apps/angular_dotnet/ClientApp/node_modules/@angular-devkit/schematics/tasks/tslint-fix/task.js | JavaScript | apache-2.0 | 913 |
// Copyright 2012-2013 The Rust Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use core::prelude::*;
use common::mode_run_pass;
use common::mode_run_fail;
use common::mode_compile_fail;
use common::mode_pretty;
use common::config;
use errors;
use header::load_props;
use header::TestProps;
use procsrv;
use util;
use util::logv;
use core::io::WriterUtil;
use core::io;
use core::os;
use core::str;
use core::uint;
use core::vec;
pub fn run(config: config, testfile: ~str) {
if config.verbose {
// We're going to be dumping a lot of info. Start on a new line.
io::stdout().write_str(~"\n\n");
}
let testfile = Path(testfile);
debug!("running %s", testfile.to_str());
let props = load_props(&testfile);
debug!("loaded props");
match config.mode {
mode_compile_fail => run_cfail_test(config, props, &testfile),
mode_run_fail => run_rfail_test(config, props, &testfile),
mode_run_pass => run_rpass_test(config, props, &testfile),
mode_pretty => run_pretty_test(config, props, &testfile),
mode_debug_info => run_debuginfo_test(config, props, &testfile)
}
}
fn run_cfail_test(config: config, props: TestProps, testfile: &Path) {
let ProcRes = compile_test(config, props, testfile);
if ProcRes.status == 0 {
fatal_ProcRes(~"compile-fail test compiled successfully!", ProcRes);
}
check_correct_failure_status(ProcRes);
let expected_errors = errors::load_errors(testfile);
if !expected_errors.is_empty() {
if !props.error_patterns.is_empty() {
fatal(~"both error pattern and expected errors specified");
}
check_expected_errors(expected_errors, testfile, ProcRes);
} else {
check_error_patterns(props, testfile, ProcRes);
}
}
fn run_rfail_test(config: config, props: TestProps, testfile: &Path) {
let ProcRes = if !config.jit {
let ProcRes = compile_test(config, props, testfile);
if ProcRes.status != 0 {
fatal_ProcRes(~"compilation failed!", ProcRes);
}
exec_compiled_test(config, props, testfile)
} else {
jit_test(config, props, testfile)
};
// The value our Makefile configures valgrind to return on failure
static valgrind_err: int = 100;
if ProcRes.status == valgrind_err {
fatal_ProcRes(~"run-fail test isn't valgrind-clean!", ProcRes);
}
check_correct_failure_status(ProcRes);
check_error_patterns(props, testfile, ProcRes);
}
fn check_correct_failure_status(ProcRes: ProcRes) {
// The value the rust runtime returns on failure
static rust_err: int = 101;
if ProcRes.status != rust_err {
fatal_ProcRes(
fmt!("failure produced the wrong error code: %d",
ProcRes.status),
ProcRes);
}
}
fn run_rpass_test(config: config, props: TestProps, testfile: &Path) {
if !config.jit {
let mut ProcRes = compile_test(config, props, testfile);
if ProcRes.status != 0 {
fatal_ProcRes(~"compilation failed!", ProcRes);
}
ProcRes = exec_compiled_test(config, props, testfile);
if ProcRes.status != 0 {
fatal_ProcRes(~"test run failed!", ProcRes);
}
} else {
let mut ProcRes = jit_test(config, props, testfile);
if ProcRes.status != 0 { fatal_ProcRes(~"jit failed!", ProcRes); }
}
}
fn run_pretty_test(config: config, props: TestProps, testfile: &Path) {
if props.pp_exact.is_some() {
logv(config, ~"testing for exact pretty-printing");
} else { logv(config, ~"testing for converging pretty-printing"); }
let rounds =
match props.pp_exact { Some(_) => 1, None => 2 };
let mut srcs = ~[io::read_whole_file_str(testfile).get()];
let mut round = 0;
while round < rounds {
logv(config, fmt!("pretty-printing round %d", round));
let ProcRes = print_source(config, testfile, srcs[round]);
if ProcRes.status != 0 {
fatal_ProcRes(fmt!("pretty-printing failed in round %d", round),
ProcRes);
}
srcs.push(ProcRes.stdout);
round += 1;
}
let mut expected =
match props.pp_exact {
Some(file) => {
let filepath = testfile.dir_path().push_rel(&file);
io::read_whole_file_str(&filepath).get()
}
None => { srcs[vec::len(srcs) - 2u] }
};
let mut actual = srcs[vec::len(srcs) - 1u];
if props.pp_exact.is_some() {
// Now we have to care about line endings
let cr = ~"\r";
actual = str::replace(actual, cr, ~"");
expected = str::replace(expected, cr, ~"");
}
compare_source(expected, actual);
// Finally, let's make sure it actually appears to remain valid code
let ProcRes = typecheck_source(config, props, testfile, actual);
if ProcRes.status != 0 {
fatal_ProcRes(~"pretty-printed source does not typecheck", ProcRes);
}
return;
fn print_source(config: config, testfile: &Path, src: ~str) -> ProcRes {
compose_and_run(config, testfile, make_pp_args(config, testfile),
~[], config.compile_lib_path, Some(src))
}
fn make_pp_args(config: config, _testfile: &Path) -> ProcArgs {
let prog = config.rustc_path;
let args = ~[~"-", ~"--pretty", ~"normal"];
return ProcArgs {prog: prog.to_str(), args: args};
}
fn compare_source(expected: ~str, actual: ~str) {
if expected != actual {
error(~"pretty-printed source does not match expected source");
let msg =
fmt!("\n\
expected:\n\
------------------------------------------\n\
%s\n\
------------------------------------------\n\
actual:\n\
------------------------------------------\n\
%s\n\
------------------------------------------\n\
\n",
expected, actual);
io::stdout().write_str(msg);
fail!();
}
}
fn typecheck_source(config: config, props: TestProps,
testfile: &Path, src: ~str) -> ProcRes {
compose_and_run_compiler(
config, props, testfile,
make_typecheck_args(config, props, testfile),
Some(src))
}
fn make_typecheck_args(config: config, props: TestProps, testfile: &Path) -> ProcArgs {
let prog = config.rustc_path;
let mut args = ~[~"-",
~"--no-trans", ~"--lib",
~"-L", config.build_base.to_str(),
~"-L",
aux_output_dir_name(config, testfile).to_str()];
args += split_maybe_args(config.rustcflags);
args += split_maybe_args(props.compile_flags);
return ProcArgs {prog: prog.to_str(), args: args};
}
}
fn run_debuginfo_test(config: config, props: TestProps, testfile: &Path) {
// do not optimize debuginfo tests
let config = match config.rustcflags {
Some(flags) => config {
rustcflags: Some(str::replace(flags, ~"-O", ~"")),
.. config
},
None => config
};
// compile test file (it shoud have 'compile-flags:-g' in the header)
let mut ProcRes = compile_test(config, props, testfile);
if ProcRes.status != 0 {
fatal_ProcRes(~"compilation failed!", ProcRes);
}
// write debugger script
let script_str = str::append(str::connect(props.debugger_cmds, "\n"),
~"\nquit\n");
debug!("script_str = %s", script_str);
dump_output_file(config, testfile, script_str, ~"debugger.script");
// run debugger script with gdb
#[cfg(windows)]
fn debugger() -> ~str { ~"gdb.exe" }
#[cfg(unix)]
fn debugger() -> ~str { ~"gdb" }
let debugger_script = make_out_name(config, testfile, ~"debugger.script");
let debugger_opts = ~[~"-quiet", ~"-batch", ~"-nx",
~"-command=" + debugger_script.to_str(),
make_exe_name(config, testfile).to_str()];
let ProcArgs = ProcArgs {prog: debugger(), args: debugger_opts};
ProcRes = compose_and_run(config, testfile, ProcArgs, ~[], ~"", None);
if ProcRes.status != 0 {
fatal(~"gdb failed to execute");
}
let num_check_lines = vec::len(props.check_lines);
if num_check_lines > 0 {
// check if each line in props.check_lines appears in the
// output (in order)
let mut i = 0u;
for str::each_line(ProcRes.stdout) |line| {
if props.check_lines[i].trim() == line.trim() {
i += 1u;
}
if i == num_check_lines {
// all lines checked
break;
}
}
if i != num_check_lines {
fatal_ProcRes(fmt!("line not found in debugger output: %s"
props.check_lines[i]), ProcRes);
}
}
}
fn check_error_patterns(props: TestProps,
testfile: &Path,
ProcRes: ProcRes) {
if vec::is_empty(props.error_patterns) {
fatal(~"no error pattern specified in " + testfile.to_str());
}
if ProcRes.status == 0 {
fatal(~"process did not return an error status");
}
let mut next_err_idx = 0u;
let mut next_err_pat = props.error_patterns[next_err_idx];
let mut done = false;
for str::each_line(ProcRes.stderr) |line| {
if str::contains(line, next_err_pat) {
debug!("found error pattern %s", next_err_pat);
next_err_idx += 1u;
if next_err_idx == vec::len(props.error_patterns) {
debug!("found all error patterns");
done = true;
break;
}
next_err_pat = props.error_patterns[next_err_idx];
}
}
if done { return; }
let missing_patterns =
vec::slice(props.error_patterns, next_err_idx,
vec::len(props.error_patterns));
if vec::len(missing_patterns) == 1u {
fatal_ProcRes(fmt!("error pattern '%s' not found!",
missing_patterns[0]), ProcRes);
} else {
for missing_patterns.each |pattern| {
error(fmt!("error pattern '%s' not found!", *pattern));
}
fatal_ProcRes(~"multiple error patterns not found", ProcRes);
}
}
fn check_expected_errors(expected_errors: ~[errors::ExpectedError],
testfile: &Path,
ProcRes: ProcRes) {
// true if we found the error in question
let mut found_flags = vec::from_elem(
vec::len(expected_errors), false);
if ProcRes.status == 0 {
fatal(~"process did not return an error status");
}
let prefixes = vec::map(expected_errors, |ee| {
fmt!("%s:%u:", testfile.to_str(), ee.line)
});
// Scan and extract our error/warning messages,
// which look like:
// filename:line1:col1: line2:col2: *error:* msg
// filename:line1:col1: line2:col2: *warning:* msg
// where line1:col1: is the starting point, line2:col2:
// is the ending point, and * represents ANSI color codes.
for str::each_line(ProcRes.stderr) |line| {
let mut was_expected = false;
for vec::eachi(expected_errors) |i, ee| {
if !found_flags[i] {
debug!("prefix=%s ee.kind=%s ee.msg=%s line=%s",
prefixes[i], ee.kind, ee.msg, line);
if (str::starts_with(line, prefixes[i]) &&
str::contains(line, ee.kind) &&
str::contains(line, ee.msg)) {
found_flags[i] = true;
was_expected = true;
break;
}
}
}
// ignore this msg which gets printed at the end
if str::contains(line, ~"aborting due to") {
was_expected = true;
}
if !was_expected && is_compiler_error_or_warning(str::from_slice(line)) {
fatal_ProcRes(fmt!("unexpected compiler error or warning: '%s'",
line),
ProcRes);
}
}
for uint::range(0u, vec::len(found_flags)) |i| {
if !found_flags[i] {
let ee = expected_errors[i];
fatal_ProcRes(fmt!("expected %s on line %u not found: %s",
ee.kind, ee.line, ee.msg), ProcRes);
}
}
}
fn is_compiler_error_or_warning(line: ~str) -> bool {
let mut i = 0u;
return
scan_until_char(line, ':', &mut i) &&
scan_char(line, ':', &mut i) &&
scan_integer(line, &mut i) &&
scan_char(line, ':', &mut i) &&
scan_integer(line, &mut i) &&
scan_char(line, ':', &mut i) &&
scan_char(line, ' ', &mut i) &&
scan_integer(line, &mut i) &&
scan_char(line, ':', &mut i) &&
scan_integer(line, &mut i) &&
scan_char(line, ' ', &mut i) &&
(scan_string(line, ~"error", &mut i) ||
scan_string(line, ~"warning", &mut i));
}
fn scan_until_char(haystack: ~str, needle: char, idx: &mut uint) -> bool {
if *idx >= haystack.len() {
return false;
}
let opt = str::find_char_from(haystack, needle, *idx);
if opt.is_none() {
return false;
}
*idx = opt.get();
return true;
}
fn scan_char(haystack: ~str, needle: char, idx: &mut uint) -> bool {
if *idx >= haystack.len() {
return false;
}
let range = str::char_range_at(haystack, *idx);
if range.ch != needle {
return false;
}
*idx = range.next;
return true;
}
fn scan_integer(haystack: ~str, idx: &mut uint) -> bool {
let mut i = *idx;
while i < haystack.len() {
let range = str::char_range_at(haystack, i);
if range.ch < '0' || '9' < range.ch {
break;
}
i = range.next;
}
if i == *idx {
return false;
}
*idx = i;
return true;
}
fn scan_string(haystack: ~str, needle: ~str, idx: &mut uint) -> bool {
let mut haystack_i = *idx;
let mut needle_i = 0u;
while needle_i < needle.len() {
if haystack_i >= haystack.len() {
return false;
}
let range = str::char_range_at(haystack, haystack_i);
haystack_i = range.next;
if !scan_char(needle, range.ch, &mut needle_i) {
return false;
}
}
*idx = haystack_i;
return true;
}
struct ProcArgs {prog: ~str, args: ~[~str]}
struct ProcRes {status: int, stdout: ~str, stderr: ~str, cmdline: ~str}
fn compile_test(config: config, props: TestProps,
testfile: &Path) -> ProcRes {
compile_test_(config, props, testfile, [])
}
fn jit_test(config: config, props: TestProps, testfile: &Path) -> ProcRes {
compile_test_(config, props, testfile, [~"--jit"])
}
fn compile_test_(config: config, props: TestProps,
testfile: &Path, extra_args: &[~str]) -> ProcRes {
let link_args = ~[~"-L", aux_output_dir_name(config, testfile).to_str()];
compose_and_run_compiler(
config, props, testfile,
make_compile_args(config, props, link_args + extra_args,
make_exe_name, testfile),
None)
}
fn exec_compiled_test(config: config, props: TestProps,
testfile: &Path) -> ProcRes {
// If testing the new runtime then set the RUST_NEWRT env var
let env = if config.newrt {
props.exec_env + ~[(~"RUST_NEWRT", ~"1")]
} else {
props.exec_env
};
compose_and_run(config, testfile,
make_run_args(config, props, testfile),
env,
config.run_lib_path, None)
}
fn compose_and_run_compiler(
config: config,
props: TestProps,
testfile: &Path,
args: ProcArgs,
input: Option<~str>) -> ProcRes {
if !props.aux_builds.is_empty() {
ensure_dir(&aux_output_dir_name(config, testfile));
}
let extra_link_args = ~[~"-L",
aux_output_dir_name(config, testfile).to_str()];
for vec::each(props.aux_builds) |rel_ab| {
let abs_ab = config.aux_base.push_rel(&Path(*rel_ab));
let aux_args =
make_compile_args(config, props, ~[~"--lib"] + extra_link_args,
|a,b| make_lib_name(a, b, testfile), &abs_ab);
let auxres = compose_and_run(config, &abs_ab, aux_args, ~[],
config.compile_lib_path, None);
if auxres.status != 0 {
fatal_ProcRes(
fmt!("auxiliary build of %s failed to compile: ",
abs_ab.to_str()),
auxres);
}
}
compose_and_run(config, testfile, args, ~[],
config.compile_lib_path, input)
}
fn ensure_dir(path: &Path) {
if os::path_is_dir(path) { return; }
if !os::make_dir(path, 0x1c0i32) {
fail!(fmt!("can't make dir %s", path.to_str()));
}
}
fn compose_and_run(config: config, testfile: &Path,
ProcArgs: ProcArgs,
procenv: ~[(~str, ~str)],
lib_path: ~str,
input: Option<~str>) -> ProcRes {
return program_output(config, testfile, lib_path,
ProcArgs.prog, ProcArgs.args, procenv, input);
}
fn make_compile_args(config: config, props: TestProps, extras: ~[~str],
xform: &fn(config, (&Path)) -> Path,
testfile: &Path) -> ProcArgs {
let prog = config.rustc_path;
let mut args = ~[testfile.to_str(),
~"-o", xform(config, testfile).to_str(),
~"-L", config.build_base.to_str()]
+ extras;
args += split_maybe_args(config.rustcflags);
args += split_maybe_args(props.compile_flags);
return ProcArgs {prog: prog.to_str(), args: args};
}
fn make_lib_name(config: config, auxfile: &Path, testfile: &Path) -> Path {
// what we return here is not particularly important, as it
// happens; rustc ignores everything except for the directory.
let auxname = output_testname(auxfile);
aux_output_dir_name(config, testfile).push_rel(&auxname)
}
fn make_exe_name(config: config, testfile: &Path) -> Path {
Path(output_base_name(config, testfile).to_str() +
str::from_slice(os::EXE_SUFFIX))
}
fn make_run_args(config: config, _props: TestProps, testfile: &Path) ->
ProcArgs {
let toolargs = {
// If we've got another tool to run under (valgrind),
// then split apart its command
let runtool =
match config.runtool {
Some(s) => Some(s),
None => None
};
split_maybe_args(runtool)
};
let args = toolargs + ~[make_exe_name(config, testfile).to_str()];
return ProcArgs {prog: args[0],
args: vec::slice(args, 1, args.len()).to_vec()};
}
fn split_maybe_args(argstr: Option<~str>) -> ~[~str] {
fn rm_whitespace(v: ~[~str]) -> ~[~str] {
v.filtered(|s| !str::is_whitespace(*s))
}
match argstr {
Some(s) => {
let mut ss = ~[];
for str::each_split_char(s, ' ') |s| { ss.push(s.to_owned()) }
rm_whitespace(ss)
}
None => ~[]
}
}
fn program_output(config: config, testfile: &Path, lib_path: ~str, prog: ~str,
args: ~[~str], env: ~[(~str, ~str)],
input: Option<~str>) -> ProcRes {
let cmdline =
{
let cmdline = make_cmdline(lib_path, prog, args);
logv(config, fmt!("executing %s", cmdline));
cmdline
};
let res = procsrv::run(lib_path, prog, args, env, input);
dump_output(config, testfile, res.out, res.err);
return ProcRes {status: res.status,
stdout: res.out,
stderr: res.err,
cmdline: cmdline};
}
// Linux and mac don't require adjusting the library search path
#[cfg(target_os = "linux")]
#[cfg(target_os = "macos")]
#[cfg(target_os = "freebsd")]
fn make_cmdline(_libpath: ~str, prog: ~str, args: ~[~str]) -> ~str {
fmt!("%s %s", prog, str::connect(args, ~" "))
}
#[cfg(target_os = "win32")]
fn make_cmdline(libpath: ~str, prog: ~str, args: ~[~str]) -> ~str {
fmt!("%s %s %s", lib_path_cmd_prefix(libpath), prog,
str::connect(args, ~" "))
}
// Build the LD_LIBRARY_PATH variable as it would be seen on the command line
// for diagnostic purposes
fn lib_path_cmd_prefix(path: ~str) -> ~str {
fmt!("%s=\"%s\"", util::lib_path_env_var(), util::make_new_path(path))
}
fn dump_output(config: config, testfile: &Path, out: ~str, err: ~str) {
dump_output_file(config, testfile, out, ~"out");
dump_output_file(config, testfile, err, ~"err");
maybe_dump_to_stdout(config, out, err);
}
fn dump_output_file(config: config, testfile: &Path,
out: ~str, extension: ~str) {
let outfile = make_out_name(config, testfile, extension);
let writer =
io::file_writer(&outfile, ~[io::Create, io::Truncate]).get();
writer.write_str(out);
}
fn make_out_name(config: config, testfile: &Path, extension: ~str) -> Path {
output_base_name(config, testfile).with_filetype(extension)
}
fn aux_output_dir_name(config: config, testfile: &Path) -> Path {
output_base_name(config, testfile).with_filetype("libaux")
}
fn output_testname(testfile: &Path) -> Path {
Path(testfile.filestem().get())
}
fn output_base_name(config: config, testfile: &Path) -> Path {
config.build_base
.push_rel(&output_testname(testfile))
.with_filetype(config.stage_id)
}
fn maybe_dump_to_stdout(config: config, out: ~str, err: ~str) {
if config.verbose {
let sep1 = fmt!("------%s------------------------------", ~"stdout");
let sep2 = fmt!("------%s------------------------------", ~"stderr");
let sep3 = ~"------------------------------------------";
io::stdout().write_line(sep1);
io::stdout().write_line(out);
io::stdout().write_line(sep2);
io::stdout().write_line(err);
io::stdout().write_line(sep3);
}
}
fn error(err: ~str) { io::stdout().write_line(fmt!("\nerror: %s", err)); }
fn fatal(err: ~str) -> ! { error(err); fail!(); }
fn fatal_ProcRes(err: ~str, ProcRes: ProcRes) -> ! {
let msg =
fmt!("\n\
error: %s\n\
command: %s\n\
stdout:\n\
------------------------------------------\n\
%s\n\
------------------------------------------\n\
stderr:\n\
------------------------------------------\n\
%s\n\
------------------------------------------\n\
\n",
err, ProcRes.cmdline, ProcRes.stdout, ProcRes.stderr);
io::stdout().write_str(msg);
fail!();
}
| jeltz/rust-debian-package | src/compiletest/runtest.rs | Rust | apache-2.0 | 23,259 |
/*
* Copyright 2007 JBoss 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 org.drools.core.reteoo;
import org.drools.core.base.ClassObjectType;
import org.drools.core.common.InternalFactHandle;
import org.drools.core.common.InternalWorkingMemory;
import org.drools.core.common.InternalWorkingMemoryEntryPoint;
import org.drools.core.common.PropagationContextFactory;
import org.drools.core.common.RuleBasePartitionId;
import org.drools.core.util.Iterator;
import org.drools.core.util.ObjectHashSet.ObjectEntry;
import org.drools.core.reteoo.LeftInputAdapterNode.LiaNodeMemory;
import org.drools.core.reteoo.ObjectTypeNode.ObjectTypeNodeMemory;
import org.drools.core.reteoo.builder.BuildContext;
import org.drools.core.rule.EntryPointId;
import org.drools.core.spi.ObjectType;
import org.drools.core.spi.PropagationContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* A node that is an entry point into the Rete network.
*
* As we move the design to support network partitions and concurrent processing
* of parts of the network, we also need to support multiple, independent entry
* points and this class represents that.
*
* It replaces the function of the Rete Node class in previous designs.
*
* @see ObjectTypeNode
*/
public class EntryPointNode extends ObjectSource
implements
Externalizable,
ObjectSink {
// ------------------------------------------------------------
// Instance members
// ------------------------------------------------------------
private static final long serialVersionUID = 510l;
protected static transient Logger log = LoggerFactory.getLogger(EntryPointNode.class);
/**
* The entry point ID for this node
*/
private EntryPointId entryPoint;
/**
* The object type nodes under this node
*/
private Map<ObjectType, ObjectTypeNode> objectTypeNodes;
private ObjectTypeNode queryNode;
private ObjectTypeNode activationNode;
// ------------------------------------------------------------
// Constructors
// ------------------------------------------------------------
public EntryPointNode() {
}
public EntryPointNode(final int id,
final ObjectSource objectSource,
final BuildContext context) {
this( id,
context.getPartitionId(),
context.getKnowledgeBase().getConfiguration().isMultithreadEvaluation(),
objectSource,
context.getCurrentEntryPoint() ); // irrelevant for this node, since it overrides sink management
}
public EntryPointNode(final int id,
final RuleBasePartitionId partitionId,
final boolean partitionsEnabled,
final ObjectSource objectSource,
final EntryPointId entryPoint) {
super( id,
partitionId,
partitionsEnabled,
objectSource,
999 ); // irrelevant for this node, since it overrides sink management
this.entryPoint = entryPoint;
this.objectTypeNodes = new ConcurrentHashMap<ObjectType, ObjectTypeNode>();
}
// ------------------------------------------------------------
// Instance methods
// ------------------------------------------------------------
@SuppressWarnings("unchecked")
public void readExternal(ObjectInput in) throws IOException,
ClassNotFoundException {
super.readExternal( in );
entryPoint = (EntryPointId) in.readObject();
objectTypeNodes = (Map<ObjectType, ObjectTypeNode>) in.readObject();
}
public void writeExternal(ObjectOutput out) throws IOException {
super.writeExternal( out );
out.writeObject( entryPoint );
out.writeObject( objectTypeNodes );
}
public short getType() {
return NodeTypeEnums.EntryPointNode;
}
/**
* @return the entryPoint
*/
public EntryPointId getEntryPoint() {
return entryPoint;
}
void setEntryPoint(EntryPointId entryPoint) {
this.entryPoint = entryPoint;
}
public void assertQuery(final InternalFactHandle factHandle,
final PropagationContext context,
final InternalWorkingMemory workingMemory) {
if ( queryNode == null ) {
this.queryNode = objectTypeNodes.get( ClassObjectType.DroolsQuery_ObjectType );
}
if ( queryNode != null ) {
// There may be no queries defined
this.queryNode.assertObject( factHandle, context, workingMemory );
}
}
public void retractQuery(final InternalFactHandle factHandle,
final PropagationContext context,
final InternalWorkingMemory workingMemory) {
if ( queryNode == null ) {
this.queryNode = objectTypeNodes.get( ClassObjectType.DroolsQuery_ObjectType );
}
if ( queryNode != null ) {
// There may be no queries defined
this.queryNode.retractObject( factHandle, context, workingMemory );
}
}
public void modifyQuery(final InternalFactHandle factHandle,
final PropagationContext context,
final InternalWorkingMemory workingMemory) {
if ( queryNode == null ) {
this.queryNode = objectTypeNodes.get( ClassObjectType.DroolsQuery_ObjectType );
}
if ( queryNode != null ) {
ModifyPreviousTuples modifyPreviousTuples = new ModifyPreviousTuples(factHandle.getFirstLeftTuple(), factHandle.getFirstRightTuple(), this );
factHandle.clearLeftTuples();
factHandle.clearRightTuples();
// There may be no queries defined
this.queryNode.modifyObject( factHandle, modifyPreviousTuples, context, workingMemory );
modifyPreviousTuples.retractTuples( context, workingMemory );
}
}
public ObjectTypeNode getQueryNode() {
if ( queryNode == null ) {
this.queryNode = objectTypeNodes.get( ClassObjectType.DroolsQuery_ObjectType );
}
return this.queryNode;
}
public void assertActivation(final InternalFactHandle factHandle,
final PropagationContext context,
final InternalWorkingMemory workingMemory) {
if ( activationNode == null ) {
this.activationNode = objectTypeNodes.get( ClassObjectType.Match_ObjectType );
}
if ( activationNode != null ) {
// There may be no queries defined
this.activationNode.assertObject( factHandle, context, workingMemory );
}
}
public void retractActivation(final InternalFactHandle factHandle,
final PropagationContext context,
final InternalWorkingMemory workingMemory) {
if ( activationNode == null ) {
this.activationNode = objectTypeNodes.get( ClassObjectType.Match_ObjectType );
}
if ( activationNode != null ) {
// There may be no queries defined
this.activationNode.retractObject( factHandle, context, workingMemory );
}
}
public void modifyActivation(final InternalFactHandle factHandle,
final PropagationContext context,
final InternalWorkingMemory workingMemory) {
if ( activationNode == null ) {
this.activationNode = objectTypeNodes.get( ClassObjectType.Match_ObjectType );
}
if ( activationNode != null ) {
ModifyPreviousTuples modifyPreviousTuples = new ModifyPreviousTuples(factHandle.getFirstLeftTuple(), factHandle.getFirstRightTuple(), this );
factHandle.clearLeftTuples();
factHandle.clearRightTuples();
// There may be no queries defined
this.activationNode.modifyObject( factHandle, modifyPreviousTuples, context, workingMemory );
modifyPreviousTuples.retractTuples( context, workingMemory );
}
}
public void assertObject(final InternalFactHandle handle,
final PropagationContext context,
final ObjectTypeConf objectTypeConf,
final InternalWorkingMemory workingMemory) {
if ( log.isTraceEnabled() ) {
log.trace( "Insert {}", handle.toString() );
}
ObjectTypeNode[] cachedNodes = objectTypeConf.getObjectTypeNodes();
for ( int i = 0, length = cachedNodes.length; i < length; i++ ) {
cachedNodes[i].assertObject( handle,
context,
workingMemory );
}
}
public void modifyObject(final InternalFactHandle handle,
final PropagationContext pctx,
final ObjectTypeConf objectTypeConf,
final InternalWorkingMemory wm) {
if ( log.isTraceEnabled() ) {
log.trace( "Update {}", handle.toString() );
}
ObjectTypeNode[] cachedNodes = objectTypeConf.getObjectTypeNodes();
// make a reference to the previous tuples, then null then on the handle
ModifyPreviousTuples modifyPreviousTuples = new ModifyPreviousTuples(handle.getFirstLeftTuple(), handle.getFirstRightTuple(), this );
handle.clearLeftTuples();
handle.clearRightTuples();
for ( int i = 0, length = cachedNodes.length; i < length; i++ ) {
cachedNodes[i].modifyObject( handle,
modifyPreviousTuples,
pctx, wm );
// remove any right tuples that matches the current OTN before continue the modify on the next OTN cache entry
if (i < cachedNodes.length - 1) {
RightTuple rightTuple = modifyPreviousTuples.peekRightTuple();
while ( rightTuple != null &&
(( BetaNode ) rightTuple.getRightTupleSink()).getObjectTypeNode() == cachedNodes[i] ) {
modifyPreviousTuples.removeRightTuple();
doRightDelete(pctx, wm, rightTuple);
rightTuple = modifyPreviousTuples.peekRightTuple();
}
LeftTuple leftTuple;
ObjectTypeNode otn;
while ( true ) {
leftTuple = modifyPreviousTuples.peekLeftTuple();
otn = null;
if (leftTuple != null) {
LeftTupleSink leftTupleSink = leftTuple.getLeftTupleSink();
if (leftTupleSink instanceof LeftTupleSource) {
otn = ((LeftTupleSource)leftTupleSink).getLeftTupleSource().getObjectTypeNode();
} else if (leftTupleSink instanceof RuleTerminalNode) {
otn = ((RuleTerminalNode)leftTupleSink).getObjectTypeNode();
}
}
if ( otn == null || otn == cachedNodes[i+1] ) break;
modifyPreviousTuples.removeLeftTuple();
doDeleteObject(pctx, wm, leftTuple);
}
}
}
modifyPreviousTuples.retractTuples( pctx, wm );
}
public void doDeleteObject(PropagationContext pctx, InternalWorkingMemory wm, LeftTuple leftTuple) {
LeftInputAdapterNode liaNode = (LeftInputAdapterNode) leftTuple.getLeftTupleSink().getLeftTupleSource();
LiaNodeMemory lm = ( LiaNodeMemory ) wm.getNodeMemory( liaNode );
LeftInputAdapterNode.doDeleteObject( leftTuple, pctx, lm.getSegmentMemory(), wm, liaNode, true, lm );
}
public void doRightDelete(PropagationContext pctx, InternalWorkingMemory wm, RightTuple rightTuple) {
rightTuple.setPropagationContext( pctx );
rightTuple.getRightTupleSink().retractRightTuple( rightTuple, pctx, wm );
}
public void modifyObject(InternalFactHandle factHandle,
ModifyPreviousTuples modifyPreviousTuples,
PropagationContext context,
InternalWorkingMemory workingMemory) {
// this method was silently failing, so I am now throwing an exception to make
// sure no one calls it by mistake
throw new UnsupportedOperationException( "This method should NEVER EVER be called" );
}
/**
* This is the entry point into the network for all asserted Facts. Iterates a cache
* of matching <code>ObjectTypdeNode</code>s asserting the Fact. If the cache does not
* exist it first iterates and builds the cache.
*
* @param factHandle
* The FactHandle of the fact to assert
* @param context
* The <code>PropagationContext</code> of the <code>WorkingMemory</code> action
* @param workingMemory
* The working memory session.
*/
public void assertObject(final InternalFactHandle factHandle,
final PropagationContext context,
final InternalWorkingMemory workingMemory) {
// this method was silently failing, so I am now throwing an exception to make
// sure no one calls it by mistake
throw new UnsupportedOperationException( "This method should NEVER EVER be called" );
}
/**
* Retract a fact object from this <code>RuleBase</code> and the specified
* <code>WorkingMemory</code>.
*
* @param handle
* The handle of the fact to retract.
* @param workingMemory
* The working memory session.
*/
public void retractObject(final InternalFactHandle handle,
final PropagationContext context,
final ObjectTypeConf objectTypeConf,
final InternalWorkingMemory workingMemory) {
if ( log.isTraceEnabled() ) {
log.trace( "Delete {}", handle.toString() );
}
ObjectTypeNode[] cachedNodes = objectTypeConf.getObjectTypeNodes();
if ( cachedNodes == null ) {
// it is possible that there are no ObjectTypeNodes for an object being retracted
return;
}
for ( int i = 0; i < cachedNodes.length; i++ ) {
cachedNodes[i].retractObject( handle,
context,
workingMemory );
}
}
/**
* Adds the <code>ObjectSink</code> so that it may receive
* <code>Objects</code> propagated from this <code>ObjectSource</code>.
*
* @param objectSink
* The <code>ObjectSink</code> to receive propagated
* <code>Objects</code>. Rete only accepts <code>ObjectTypeNode</code>s
* as parameters to this method, though.
*/
public void addObjectSink(final ObjectSink objectSink) {
final ObjectTypeNode node = (ObjectTypeNode) objectSink;
this.objectTypeNodes.put( node.getObjectType(),
node );
}
public void removeObjectSink(final ObjectSink objectSink) {
final ObjectTypeNode node = (ObjectTypeNode) objectSink;
this.objectTypeNodes.remove( node.getObjectType() );
}
public void attach( BuildContext context ) {
this.source.addObjectSink( this );
if (context == null ) {
return;
}
if ( context.getKnowledgeBase().getConfiguration().isPhreakEnabled() ) {
for ( InternalWorkingMemory workingMemory : context.getWorkingMemories() ) {
workingMemory.updateEntryPointsCache();
}
return;
}
for ( InternalWorkingMemory workingMemory : context.getWorkingMemories() ) {
workingMemory.updateEntryPointsCache();
PropagationContextFactory pctxFactory = workingMemory.getKnowledgeBase().getConfiguration().getComponentFactory().getPropagationContextFactory();
final PropagationContext propagationContext = pctxFactory.createPropagationContext(workingMemory.getNextPropagationIdCounter(), PropagationContext.RULE_ADDITION, null, null, null);
this.source.updateSink( this,
propagationContext,
workingMemory );
}
}
protected void doRemove(final RuleRemovalContext context,
final ReteooBuilder builder,
final InternalWorkingMemory[] workingMemories) {
}
public Map<ObjectType, ObjectTypeNode> getObjectTypeNodes() {
return this.objectTypeNodes;
}
public int hashCode() {
return this.entryPoint.hashCode();
}
public boolean equals(final Object object) {
if ( object == this ) {
return true;
}
if ( object == null || !(object instanceof EntryPointNode) ) {
return false;
}
final EntryPointNode other = (EntryPointNode) object;
return this.entryPoint.equals( other.entryPoint );
}
public void updateSink(final ObjectSink sink,
final PropagationContext context,
final InternalWorkingMemory workingMemory) {
// @todo
// JBRULES-612: the cache MUST be invalidated when a new node type is added to the network, so iterate and reset all caches.
final ObjectTypeNode node = (ObjectTypeNode) sink;
final ObjectType newObjectType = node.getObjectType();
InternalWorkingMemoryEntryPoint wmEntryPoint = (InternalWorkingMemoryEntryPoint) workingMemory.getWorkingMemoryEntryPoint( this.entryPoint.getEntryPointId() );
for ( ObjectTypeConf objectTypeConf : wmEntryPoint.getObjectTypeConfigurationRegistry().values() ) {
if ( newObjectType.isAssignableFrom( objectTypeConf.getConcreteObjectTypeNode().getObjectType() ) ) {
objectTypeConf.resetCache();
ObjectTypeNode sourceNode = objectTypeConf.getConcreteObjectTypeNode();
Iterator it = ((ObjectTypeNodeMemory) workingMemory.getNodeMemory( sourceNode )).memory.iterator();
for ( ObjectEntry entry = (ObjectEntry) it.next(); entry != null; entry = (ObjectEntry) it.next() ) {
sink.assertObject( (InternalFactHandle) entry.getValue(),
context,
workingMemory );
}
}
}
}
public boolean isObjectMemoryEnabled() {
return false;
}
public void setObjectMemoryEnabled(boolean objectMemoryEnabled) {
throw new UnsupportedOperationException( "Entry Point Node has no Object memory" );
}
public String toString() {
return "[EntryPointNode(" + this.id + ") " + this.entryPoint + " ]";
}
public void byPassModifyToBetaNode(InternalFactHandle factHandle,
ModifyPreviousTuples modifyPreviousTuples,
PropagationContext context,
InternalWorkingMemory workingMemory) {
throw new UnsupportedOperationException();
}
@Override
public long calculateDeclaredMask(List<String> settableProperties) {
throw new UnsupportedOperationException();
}
}
| bxf12315/drools | drools-core/src/main/java/org/drools/core/reteoo/EntryPointNode.java | Java | apache-2.0 | 20,815 |
<?php
namespace Tests\unit\Composer\Read\Register;
use ModbusTcpClient\Packet\ModbusFunction\ReadHoldingRegistersResponse;
use ModbusTcpClient\Composer\Read\Register\ByteReadRegisterAddress;
use PHPUnit\Framework\TestCase;
class ByteReadRegisterAddressTest extends TestCase
{
public function testGetSize()
{
$address = new ByteReadRegisterAddress(1, true);
$this->assertEquals(1, $address->getSize());
}
public function testGetName()
{
$address = new ByteReadRegisterAddress(1, true, 'direction');
$this->assertEquals('direction', $address->getName());
}
public function testDefaultGetName()
{
$address = new ByteReadRegisterAddress(1, true);
$this->assertEquals('byte_1_1', $address->getName());
$address = new ByteReadRegisterAddress(1, false);
$this->assertEquals('byte_1_0', $address->getName());
}
public function testExtract()
{
$responsePacket = new ReadHoldingRegistersResponse("\x02\x00\x05", 3, 33152);
$this->assertEquals(5, (new ByteReadRegisterAddress(0, true))->extract($responsePacket));
$this->assertEquals(0, (new ByteReadRegisterAddress(0, false))->extract($responsePacket));
}
public function testExtractWithCallback()
{
$responsePacket = new ReadHoldingRegistersResponse("\x02\x00\x05", 3, 33152);
$address = new ByteReadRegisterAddress(0, true, null, function ($data) {
return 'prefix_' . $data;
});
$this->assertEquals('prefix_5', $address->extract($responsePacket));
}
}
| aldas/modbus-tcp-client | tests/unit/Composer/Read/Register/ByteReadRegisterAddressTest.php | PHP | apache-2.0 | 1,598 |
/*
* Copyright 2012-2017 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.route53.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
* <p>
* A complex type that contains information about that can be associated with your hosted zone.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListVPCAssociationAuthorizations"
* target="_top">AWS API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ListVPCAssociationAuthorizationsRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The ID of the hosted zone for which you want a list of VPCs that can be associated with the hosted zone.
* </p>
*/
private String hostedZoneId;
/**
* <p>
* <i>Optional</i>: If a response includes a <code>NextToken</code> element, there are more VPCs that can be
* associated with the specified hosted zone. To get the next page of results, submit another request, and include
* the value of <code>NextToken</code> from the response in the <code>nexttoken</code> parameter in another
* <code>ListVPCAssociationAuthorizations</code> request.
* </p>
*/
private String nextToken;
/**
* <p>
* <i>Optional</i>: An integer that specifies the maximum number of VPCs that you want Amazon Route 53 to return. If
* you don't specify a value for <code>MaxResults</code>, Amazon Route 53 returns up to 50 VPCs per page.
* </p>
*/
private String maxResults;
/**
* <p>
* The ID of the hosted zone for which you want a list of VPCs that can be associated with the hosted zone.
* </p>
*
* @param hostedZoneId
* The ID of the hosted zone for which you want a list of VPCs that can be associated with the hosted zone.
*/
public void setHostedZoneId(String hostedZoneId) {
this.hostedZoneId = hostedZoneId;
}
/**
* <p>
* The ID of the hosted zone for which you want a list of VPCs that can be associated with the hosted zone.
* </p>
*
* @return The ID of the hosted zone for which you want a list of VPCs that can be associated with the hosted zone.
*/
public String getHostedZoneId() {
return this.hostedZoneId;
}
/**
* <p>
* The ID of the hosted zone for which you want a list of VPCs that can be associated with the hosted zone.
* </p>
*
* @param hostedZoneId
* The ID of the hosted zone for which you want a list of VPCs that can be associated with the hosted zone.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListVPCAssociationAuthorizationsRequest withHostedZoneId(String hostedZoneId) {
setHostedZoneId(hostedZoneId);
return this;
}
/**
* <p>
* <i>Optional</i>: If a response includes a <code>NextToken</code> element, there are more VPCs that can be
* associated with the specified hosted zone. To get the next page of results, submit another request, and include
* the value of <code>NextToken</code> from the response in the <code>nexttoken</code> parameter in another
* <code>ListVPCAssociationAuthorizations</code> request.
* </p>
*
* @param nextToken
* <i>Optional</i>: If a response includes a <code>NextToken</code> element, there are more VPCs that can be
* associated with the specified hosted zone. To get the next page of results, submit another request, and
* include the value of <code>NextToken</code> from the response in the <code>nexttoken</code> parameter in
* another <code>ListVPCAssociationAuthorizations</code> request.
*/
public void setNextToken(String nextToken) {
this.nextToken = nextToken;
}
/**
* <p>
* <i>Optional</i>: If a response includes a <code>NextToken</code> element, there are more VPCs that can be
* associated with the specified hosted zone. To get the next page of results, submit another request, and include
* the value of <code>NextToken</code> from the response in the <code>nexttoken</code> parameter in another
* <code>ListVPCAssociationAuthorizations</code> request.
* </p>
*
* @return <i>Optional</i>: If a response includes a <code>NextToken</code> element, there are more VPCs that can be
* associated with the specified hosted zone. To get the next page of results, submit another request, and
* include the value of <code>NextToken</code> from the response in the <code>nexttoken</code> parameter in
* another <code>ListVPCAssociationAuthorizations</code> request.
*/
public String getNextToken() {
return this.nextToken;
}
/**
* <p>
* <i>Optional</i>: If a response includes a <code>NextToken</code> element, there are more VPCs that can be
* associated with the specified hosted zone. To get the next page of results, submit another request, and include
* the value of <code>NextToken</code> from the response in the <code>nexttoken</code> parameter in another
* <code>ListVPCAssociationAuthorizations</code> request.
* </p>
*
* @param nextToken
* <i>Optional</i>: If a response includes a <code>NextToken</code> element, there are more VPCs that can be
* associated with the specified hosted zone. To get the next page of results, submit another request, and
* include the value of <code>NextToken</code> from the response in the <code>nexttoken</code> parameter in
* another <code>ListVPCAssociationAuthorizations</code> request.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListVPCAssociationAuthorizationsRequest withNextToken(String nextToken) {
setNextToken(nextToken);
return this;
}
/**
* <p>
* <i>Optional</i>: An integer that specifies the maximum number of VPCs that you want Amazon Route 53 to return. If
* you don't specify a value for <code>MaxResults</code>, Amazon Route 53 returns up to 50 VPCs per page.
* </p>
*
* @param maxResults
* <i>Optional</i>: An integer that specifies the maximum number of VPCs that you want Amazon Route 53 to
* return. If you don't specify a value for <code>MaxResults</code>, Amazon Route 53 returns up to 50 VPCs
* per page.
*/
public void setMaxResults(String maxResults) {
this.maxResults = maxResults;
}
/**
* <p>
* <i>Optional</i>: An integer that specifies the maximum number of VPCs that you want Amazon Route 53 to return. If
* you don't specify a value for <code>MaxResults</code>, Amazon Route 53 returns up to 50 VPCs per page.
* </p>
*
* @return <i>Optional</i>: An integer that specifies the maximum number of VPCs that you want Amazon Route 53 to
* return. If you don't specify a value for <code>MaxResults</code>, Amazon Route 53 returns up to 50 VPCs
* per page.
*/
public String getMaxResults() {
return this.maxResults;
}
/**
* <p>
* <i>Optional</i>: An integer that specifies the maximum number of VPCs that you want Amazon Route 53 to return. If
* you don't specify a value for <code>MaxResults</code>, Amazon Route 53 returns up to 50 VPCs per page.
* </p>
*
* @param maxResults
* <i>Optional</i>: An integer that specifies the maximum number of VPCs that you want Amazon Route 53 to
* return. If you don't specify a value for <code>MaxResults</code>, Amazon Route 53 returns up to 50 VPCs
* per page.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListVPCAssociationAuthorizationsRequest withMaxResults(String maxResults) {
setMaxResults(maxResults);
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 (getHostedZoneId() != null)
sb.append("HostedZoneId: ").append(getHostedZoneId()).append(",");
if (getNextToken() != null)
sb.append("NextToken: ").append(getNextToken()).append(",");
if (getMaxResults() != null)
sb.append("MaxResults: ").append(getMaxResults());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ListVPCAssociationAuthorizationsRequest == false)
return false;
ListVPCAssociationAuthorizationsRequest other = (ListVPCAssociationAuthorizationsRequest) obj;
if (other.getHostedZoneId() == null ^ this.getHostedZoneId() == null)
return false;
if (other.getHostedZoneId() != null && other.getHostedZoneId().equals(this.getHostedZoneId()) == false)
return false;
if (other.getNextToken() == null ^ this.getNextToken() == null)
return false;
if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
return false;
if (other.getMaxResults() == null ^ this.getMaxResults() == null)
return false;
if (other.getMaxResults() != null && other.getMaxResults().equals(this.getMaxResults()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getHostedZoneId() == null) ? 0 : getHostedZoneId().hashCode());
hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
hashCode = prime * hashCode + ((getMaxResults() == null) ? 0 : getMaxResults().hashCode());
return hashCode;
}
@Override
public ListVPCAssociationAuthorizationsRequest clone() {
return (ListVPCAssociationAuthorizationsRequest) super.clone();
}
}
| dagnir/aws-sdk-java | aws-java-sdk-route53/src/main/java/com/amazonaws/services/route53/model/ListVPCAssociationAuthorizationsRequest.java | Java | apache-2.0 | 11,109 |
/*
* 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.kylin.invertedindex.index;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.roaringbitmap.RoaringBitmap;
/**
* @author yangli9
*/
public interface ColumnValueContainer {
void append(ImmutableBytesWritable valueBytes);
void closeForChange();
int getSize();
// works only after closeForChange()
void getValueAt(int i, ImmutableBytesWritable valueBytes);
RoaringBitmap getBitMap(Integer startId, Integer endId);
int getMaxValueId();
}
| lemire/incubator-kylin | invertedindex/src/main/java/org/apache/kylin/invertedindex/index/ColumnValueContainer.java | Java | apache-2.0 | 1,361 |
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<title></title>
<link rel="stylesheet" href="css/my-css.css" media="screen" type="text/css" />
</head>
<body>
<img src="http://autoshanghai2015-cdn.prvalue.cn/img/p25.png" style="height:100%;width:100%">
</body>
</html> | PRVALUE/D3-Auto-Shanghai-2015 | report/25.html | HTML | apache-2.0 | 372 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="pl">
<head>
<!-- Generated by javadoc -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class com.google.code.play2.spm.routes.Play2RoutesSourcePositionMapper (Play! 2.x Source Position Mappers 1.0.0-beta8 API)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class com.google.code.play2.spm.routes.Play2RoutesSourcePositionMapper (Play! 2.x Source Position Mappers 1.0.0-beta8 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../com/google/code/play2/spm/routes/Play2RoutesSourcePositionMapper.html" title="class in com.google.code.play2.spm.routes">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?com/google/code/play2/spm/routes/class-use/Play2RoutesSourcePositionMapper.html" target="_top">Frames</a></li>
<li><a href="Play2RoutesSourcePositionMapper.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class com.google.code.play2.spm.routes.Play2RoutesSourcePositionMapper" class="title">Uses of Class<br>com.google.code.play2.spm.routes.Play2RoutesSourcePositionMapper</h2>
</div>
<div class="classUseContainer">No usage of com.google.code.play2.spm.routes.Play2RoutesSourcePositionMapper</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../com/google/code/play2/spm/routes/Play2RoutesSourcePositionMapper.html" title="class in com.google.code.play2.spm.routes">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?com/google/code/play2/spm/routes/class-use/Play2RoutesSourcePositionMapper.html" target="_top">Frames</a></li>
<li><a href="Play2RoutesSourcePositionMapper.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2013–2017. All rights reserved.</small></p>
</body>
</html>
| play2-maven-plugin/play2-maven-plugin.github.io | play2-maven-plugin/1.0.0-beta8/play2-source-position-mappers/apidocs/com/google/code/play2/spm/routes/class-use/Play2RoutesSourcePositionMapper.html | HTML | apache-2.0 | 4,945 |
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<h3>
标题
</h3><!-- cellpadding="2" cellspacing="0" -->
<table style="width:100%;" border="1">
<tbody>
<tr>
<td>
<h3>标题1</h3>
</td>
<td>
<h3>标题1</h3>
</td>
</tr>
<tr>
<td>
内容1
</td>
<td>
内容2
</td>
</tr>
<tr>
<td>
内容3
</td>
<td>
内容4
</td>
</tr>
</tbody>
</table>
<p>
表格说明
</p>
</body>
</html> | xiangxik/castle-platform | castle-themes/castle-theme-adminlte/src/main/resources/META-INF/adminlte/vendor/kindeditor/plugins/template/html/2.html | HTML | apache-2.0 | 507 |
/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2014-2020 Couchbase, 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.
*/
#ifndef _WIN32
#include <cerrno>
#endif
#include "connect.h"
#include "ioutils.h"
#include "hostlist.h"
#include "iotable.h"
#include "ssl.h"
lcbio_CSERR lcbio_mkcserr(int syserr)
{
switch (syserr) {
case 0:
return LCBIO_CSERR_CONNECTED;
case EINTR:
return LCBIO_CSERR_INTR;
case EWOULDBLOCK:
#ifdef USE_EAGAIN
case EAGAIN:
#endif
case EINPROGRESS:
case EALREADY:
return LCBIO_CSERR_BUSY;
case EISCONN:
return LCBIO_CSERR_CONNECTED;
#ifdef _WIN32
case EINVAL:
return LCBIO_CSERR_EINVAL;
#endif
default:
return LCBIO_CSERR_EFAIL;
}
}
void lcbio_mksyserr(lcbio_OSERR in, lcbio_OSERR *out)
{
switch (in) {
case EINTR:
case EWOULDBLOCK:
#ifdef USE_EAGAIN
case EAGAIN:
#endif
case EINVAL:
case EINPROGRESS:
case EISCONN:
case EALREADY:
return;
default:
*out = in;
break;
}
}
static lcb_STATUS ioerr2lcberr(lcbio_OSERR in, const lcb_settings *settings)
{
switch (in) {
case 0:
return LCB_ERR_SOCKET_SHUTDOWN;
case ECONNREFUSED:
return LCB_ERR_CONNECTION_REFUSED;
case ENETUNREACH:
case EHOSTUNREACH:
case EHOSTDOWN:
return LCB_ERR_NODE_UNREACHABLE;
case EMFILE:
case ENFILE:
return LCB_ERR_FD_LIMIT_REACHED;
case EADDRINUSE:
case EADDRNOTAVAIL:
return LCB_ERR_CANNOT_GET_PORT;
case ECONNRESET:
case ECONNABORTED:
return LCB_ERR_CONNECTION_RESET;
default:
lcb_log(settings, "lcbio", LCB_LOG_WARN, __FILE__, __LINE__,
"OS errno %d (%s) does not have a direct client error code equivalent. Using NETWORK_ERROR", in,
strerror(in));
return LCB_ERR_NETWORK;
}
}
lcb_STATUS lcbio_mklcberr(lcbio_OSERR in, const lcb_settings *settings)
{
if (settings->detailed_neterr == 0) {
lcb_log(settings, "lcbio", LCB_LOG_WARN, __FILE__, __LINE__, "Translating errno=%d (%s), %s to LCB_ERR_NETWORK",
in, strerror(in), lcb_strerror_short(ioerr2lcberr(in, settings)));
return LCB_ERR_NETWORK;
}
return ioerr2lcberr(in, settings);
}
lcb_socket_t lcbio_E_ai2sock(lcbio_TABLE *io, struct addrinfo **ai, int *connerr)
{
lcb_socket_t ret = INVALID_SOCKET;
*connerr = 0;
for (; *ai; *ai = (*ai)->ai_next) {
ret = io->E_socket(*ai);
if (ret != INVALID_SOCKET) {
return ret;
} else {
*connerr = io->get_errno();
}
}
return ret;
}
lcb_sockdata_t *lcbio_C_ai2sock(lcbio_TABLE *io, struct addrinfo **ai, int *connerr)
{
lcb_sockdata_t *ret = nullptr;
for (; *ai; *ai = (*ai)->ai_next) {
ret = io->C_socket(*ai);
if (ret) {
return ret;
} else {
*connerr = IOT_ERRNO(io);
}
}
return ret;
}
static int saddr_to_host_and_port(struct sockaddr *saddr, int len, char *host, lcb_size_t nhost, char *port,
lcb_size_t nport)
{
return getnameinfo(saddr, len, host, nhost, port, nport, NI_NUMERICHOST | NI_NUMERICSERV);
}
static int saddr_to_string(struct sockaddr *saddr, int len, char *buf, lcb_size_t nbuf)
{
char h[NI_MAXHOST + 1];
char p[NI_MAXSERV + 1];
int rv;
rv = saddr_to_host_and_port(saddr, len, h, sizeof(h), p, sizeof(p));
if (rv < 0) {
return 0;
}
if (snprintf(buf, nbuf, "%s;%s", h, p) < 0) {
return 0;
}
return 1;
}
static void lcbio_cache_local_name(lcbio_CONNINFO *sock)
{
char addr_str[NI_MAXHOST + 1];
switch (sock->sa_local.ss_family) {
case AF_INET: {
auto *addr = (struct sockaddr_in *)&sock->sa_local;
inet_ntop(AF_INET, &(addr->sin_addr), addr_str, sizeof(addr_str));
strncpy(sock->ep_local.host, addr_str, sizeof(sock->ep_local.host));
snprintf(sock->ep_local.port, sizeof(sock->ep_local.port), "%d", (int)ntohs(addr->sin_port));
} break;
case AF_INET6: {
auto *addr = (struct sockaddr_in6 *)&sock->sa_local;
inet_ntop(AF_INET6, &(addr->sin6_addr), addr_str, sizeof(addr_str));
strncpy(sock->ep_local.host, addr_str, sizeof(sock->ep_local.host));
snprintf(sock->ep_local.port, sizeof(sock->ep_local.port), "%d", (int)ntohs(addr->sin6_port));
} break;
}
snprintf(sock->ep_local_host_and_port, sizeof(sock->ep_local_host_and_port), "%s:%s", sock->ep_local.host,
sock->ep_local.port);
}
void lcbio__load_socknames(lcbio_SOCKET *sock)
{
int n_salocal, n_saremote, rv;
struct lcb_nameinfo_st ni {
};
lcbio_CONNINFO *info = sock->info;
n_salocal = sizeof(info->sa_local);
n_saremote = sizeof(info->sa_remote);
ni.local.name = (struct sockaddr *)&info->sa_local;
ni.local.len = &n_salocal;
ni.remote.name = (struct sockaddr *)&info->sa_remote;
ni.remote.len = &n_saremote;
if (!IOT_IS_EVENT(sock->io)) {
if (!sock->u.sd) {
return;
}
rv = IOT_V1(sock->io).nameinfo(IOT_ARG(sock->io), sock->u.sd, &ni);
if (ni.local.len == nullptr || ni.remote.len == nullptr || rv < 0) {
return;
}
} else {
socklen_t sl_tmp = sizeof(info->sa_local);
if (sock->u.fd == INVALID_SOCKET) {
return;
}
rv = getsockname(sock->u.fd, ni.local.name, &sl_tmp);
n_salocal = sl_tmp;
if (rv < 0) {
return;
}
rv = getpeername(sock->u.fd, ni.remote.name, &sl_tmp);
n_saremote = sl_tmp;
if (rv < 0) {
return;
}
}
info->naddr = n_salocal;
lcbio_cache_local_name(info);
}
int lcbio_get_nameinfo(lcbio_SOCKET *sock, struct lcbio_NAMEINFO *nistrs)
{
lcbio_CONNINFO *info = sock->info;
if (!info) {
return 0;
}
if (!info->naddr) {
return 0;
}
if (!saddr_to_string((struct sockaddr *)&info->sa_remote, info->naddr, nistrs->remote, sizeof(nistrs->remote))) {
return 0;
}
if (!saddr_to_string((struct sockaddr *)&info->sa_local, info->naddr, nistrs->local, sizeof(nistrs->local))) {
return 0;
}
return 1;
}
int lcbio_is_netclosed(lcbio_SOCKET *sock, int flags)
{
lcbio_pTABLE iot = sock->io;
if (iot->is_E()) {
return iot->E_check_closed(sock->u.fd, flags);
} else {
return iot->C_check_closed(sock->u.sd, flags);
}
}
lcb_STATUS lcbio_enable_sockopt(lcbio_SOCKET *s, int cntl)
{
lcbio_pTABLE iot = s->io;
int rv;
int value = 1;
if (!iot->has_cntl()) {
return LCB_ERR_UNSUPPORTED_OPERATION;
}
if (iot->is_E()) {
rv = iot->E_cntl(s->u.fd, LCB_IO_CNTL_SET, cntl, &value);
} else {
rv = iot->C_cntl(s->u.sd, LCB_IO_CNTL_SET, cntl, &value);
}
if (rv != 0) {
return lcbio_mklcberr(IOT_ERRNO(iot), s->settings);
} else {
return LCB_SUCCESS;
}
}
const char *lcbio_strsockopt(int cntl)
{
switch (cntl) {
case LCB_IO_CNTL_TCP_KEEPALIVE:
return "TCP_KEEPALIVE";
case LCB_IO_CNTL_TCP_NODELAY:
return "TCP_NODELAY";
default:
return "FIXME: Unknown option";
}
}
int lcbio_ssl_supported(void)
{
#ifdef LCB_NO_SSL
return 0;
#else
return 1;
#endif
}
lcbio_pSSLCTX lcbio_ssl_new__fallback(const char *, const char *, const char *, int, lcb_STATUS *errp, lcb_settings *)
{
if (errp) {
*errp = LCB_ERR_SDK_FEATURE_UNAVAILABLE;
}
return nullptr;
}
#ifdef LCB_NO_SSL
void lcbio_ssl_free(lcbio_pSSLCTX) {}
lcb_STATUS lcbio_ssl_apply(lcbio_SOCKET *, lcbio_pSSLCTX)
{
return LCB_ERR_SDK_FEATURE_UNAVAILABLE;
}
int lcbio_ssl_check(lcbio_SOCKET *)
{
return 0;
}
lcb_STATUS lcbio_ssl_get_error(lcbio_SOCKET *)
{
return LCB_SUCCESS;
}
void lcbio_ssl_global_init(void) {}
lcb_STATUS lcbio_sslify_if_needed(lcbio_SOCKET *, lcb_settings *)
{
return LCB_SUCCESS;
}
#endif
| couchbase/libcouchbase | src/lcbio/ioutils.cc | C++ | apache-2.0 | 8,898 |
package org.valuereporter.observation;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.valuereporter.QueryOperations;
import org.valuereporter.WriteOperations;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
/**
* @author <a href="mailto:[email protected]">Erik Drolshammer</a>
*/
@Component
@Path("/observedmethods")
public class ObservedMethodsResouce {
private static final Logger log = LoggerFactory.getLogger(ObservedMethodsResouce.class);
private final QueryOperations queryOperations;
private final WriteOperations writeOperations;
private final ObjectMapper mapper;
/**
@Autowired
public ObservedMethodsResouce(QueryOperations queryOperations, WriteOperations writeOperations, ObjectMapper mapper) {
this.queryOperations = queryOperations;
this.writeOperations = writeOperations;
this.mapper = mapper;
}
**/
@Autowired
public ObservedMethodsResouce(ObservationsService observationsService, ObjectMapper mapper) {
this.queryOperations = observationsService;
this.writeOperations = observationsService;
this.mapper = mapper;
}
//http://localhost:4901/reporter/observe/observedmethods/{prefix}/{name}
/**
* A request with no filtering parameters should return a list of all observations.
*
* @param prefix prefix used to identify running process
* @param name package.classname.method
* @return List of observations
*/
@GET
@Path("/{prefix}/{name}")
@Produces(MediaType.APPLICATION_JSON)
public Response findObservationsByName(@PathParam("prefix") String prefix,@PathParam("name") String name) {
final List<ObservedMethod> observedMethods;
//Should also support no queryParams -> findAll
if (name != null ) {
log.trace("findObservationsByName name={}", name);
observedMethods = queryOperations.findObservationsByName(prefix, name);
} else {
throw new UnsupportedOperationException("You must supply a name. <package.classname.method>");
}
Writer strWriter = new StringWriter();
try {
mapper.writeValue(strWriter, observedMethods);
} catch (IOException e) {
log.error("Could not convert {} ObservedMethod to JSON.", observedMethods.size(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("Error converting to requested format.").build();
}
return Response.ok(strWriter.toString()).build();
}
//http://localhost:4901/reporter/observe/observedmethods/{prefix}
@POST
@Path("/{prefix}")
@Produces(MediaType.APPLICATION_JSON)
public Response addObservationMethod(@PathParam("prefix") String prefix, String jsonBody){
log.trace("addObservationMethod prefix {} , jsonBody {}.", prefix, jsonBody);
List<ObservedMethod> observedMethods = null;
try {
observedMethods = mapper.readValue(jsonBody, new TypeReference<ArrayList<ObservedMethodJson>>(){ });
if (observedMethods != null) {
for (ObservedMethod observedMethod : observedMethods) {
observedMethod.setPrefix(prefix);
}
}
} catch (IOException e) {
log.warn("Unexpected error trying to produce list of ObservedMethod from \n prefix {} \n json {}, \n Reason {}",prefix, jsonBody, e.getMessage());
return Response.status(Response.Status.NOT_ACCEPTABLE).entity("Error converting to requested format.").build();
}
long updatedCount = writeOperations.addObservations(prefix,observedMethods);
String message = "added " + updatedCount + " observedMethods.";
Writer strWriter = new StringWriter();
try {
mapper.writeValue(strWriter, message);
} catch (IOException e) {
log.error("Could not convert {} to JSON.", updatedCount, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("Error converting to requested format.").build();
}
return Response.ok(strWriter.toString()).build();
}
}
| altran/Valuereporter | src/main/java/org/valuereporter/observation/ObservedMethodsResouce.java | Java | apache-2.0 | 4,690 |
package com.lee.game;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import com.lee.base.activity.BaseActivity;
import com.lee.base.application.PackageNameContainer;
import com.noobyang.log.LogUtil;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
/**
* Main Activity
* <p/>
* Created by LiYang on 2019/4/8.
*/
public class MainActivity extends BaseActivity {
private static final String ACTION_SAMPLE_CODE = "com.lee.main.action.SAMPLE_CODE_GAME";
private static final String EXTRA_NAME_PATH = "com.lee.main.Path";
private static final String PATH_DIVIDED_SYMBOLS = ".";
private static final String PATH_DIVIDED_SYMBOLS_REGEX = "\\.";
@BindView(R.id.tv_path)
TextView tvPath;
@BindView(R.id.rv_sample_code)
RecyclerView rvSampleCode;
private PackageManager packageManager;
private List<SampleCodeEntity> sampleCodeEntities;
private SampleCodeAdapter sampleCodeAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
initData();
initView();
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
updateSampleCodes();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
private void initData() {
packageManager = getPackageManager();
sampleCodeAdapter = new SampleCodeAdapter(this, sampleCodeEntities, itemClickListener);
}
private void initView() {
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
rvSampleCode.setLayoutManager(layoutManager);
rvSampleCode.setAdapter(sampleCodeAdapter);
updateSampleCodes();
}
private void updateSampleCodes() {
String path = getIntent().getStringExtra(EXTRA_NAME_PATH);
initSampleCodes(path);
sampleCodeAdapter.setData(sampleCodeEntities);
sampleCodeAdapter.notifyDataSetChanged();
setPathText(path);
}
private void setPathText(String path) {
if (TextUtils.isEmpty(path)) {
tvPath.setText(R.string.app_name);
} else {
tvPath.setText(path);
}
}
protected void initSampleCodes(String path) {
if (sampleCodeEntities == null) {
sampleCodeEntities = new ArrayList<>();
} else {
sampleCodeEntities.clear();
}
List<ResolveInfo> sampleCodeResolveInfoList = getSampleCodeResolveInfoList();
if (sampleCodeResolveInfoList == null || sampleCodeResolveInfoList.size() == 0) {
return;
}
String[] prefixPaths;
String currentPrefixPath;
Map<String, Boolean> folderLabel = new HashMap<>();
String label;
String[] labelPath;
String sampleCodeLabel;
for (ResolveInfo sampleCodeResolveInfo : sampleCodeResolveInfoList) {
if (TextUtils.isEmpty(path)) {
prefixPaths = null;
currentPrefixPath = null;
} else {
path = getRelativeName(path);
prefixPaths = path.split(PATH_DIVIDED_SYMBOLS_REGEX);
currentPrefixPath = path + PATH_DIVIDED_SYMBOLS;
}
label = getRelativeName(sampleCodeResolveInfo.activityInfo.name);
LogUtil.d("getData currentPrefixPath = " + currentPrefixPath + "---label = " + label);
if (TextUtils.isEmpty(currentPrefixPath) || label.startsWith(currentPrefixPath)) {
labelPath = label.split(PATH_DIVIDED_SYMBOLS_REGEX);
int prefixPathsLen = prefixPaths == null ? 0 : prefixPaths.length;
sampleCodeLabel = labelPath[prefixPathsLen];
if (prefixPathsLen == labelPath.length - 1) {
// activity
addActivityItem(sampleCodeEntities, sampleCodeLabel,
sampleCodeResolveInfo.activityInfo.applicationInfo.packageName,
sampleCodeResolveInfo.activityInfo.name);
} else {
// folder
if (folderLabel.get(sampleCodeLabel) == null) {
addFolderItem(sampleCodeEntities, sampleCodeLabel, currentPrefixPath);
folderLabel.put(sampleCodeLabel, true);
}
}
}
}
Collections.sort(sampleCodeEntities, comparator);
}
private String getRelativeName(String className) {
if (TextUtils.isEmpty(className)) {
return className;
}
for (String packageName : PackageNameContainer.getPackageNames()) {
if (className.startsWith(packageName + PATH_DIVIDED_SYMBOLS)) {
return className.substring(packageName.length() + 1);
}
}
return className;
}
private List<ResolveInfo> getSampleCodeResolveInfoList() {
Intent sampleCodeIntent = new Intent(ACTION_SAMPLE_CODE, null);
sampleCodeIntent.addCategory(Intent.CATEGORY_SAMPLE_CODE);
return packageManager.queryIntentActivities(sampleCodeIntent, 0);
}
private final static Comparator<SampleCodeEntity> comparator =
new Comparator<SampleCodeEntity>() {
private final Collator collator = Collator.getInstance();
public int compare(SampleCodeEntity entity1, SampleCodeEntity entity2) {
return collator.compare(entity1.getTitle(), entity2.getTitle());
}
};
private void addActivityItem(List<SampleCodeEntity> data, String sampleCodeLabel,
String packageName, String className) {
Intent activityIntent = new Intent();
activityIntent.setClassName(packageName, className);
addItem(data, SampleCodeEntity.SampleCodeType.SAMPLE_CODE_TYPE_ACTIVITY, sampleCodeLabel, activityIntent);
}
private void addFolderItem(List<SampleCodeEntity> data, String sampleCodeLabel,
String currentPrefixPath) {
Intent folderIntent = new Intent();
folderIntent.setClass(this, MainActivity.class);
String path = TextUtils.isEmpty(currentPrefixPath) ? sampleCodeLabel : currentPrefixPath + sampleCodeLabel;
folderIntent.putExtra(EXTRA_NAME_PATH, path);
addItem(data, SampleCodeEntity.SampleCodeType.SAMPLE_CODE_TYPE_FOLDER, sampleCodeLabel, folderIntent);
}
protected void addItem(List<SampleCodeEntity> data, int type, String title, Intent intent) {
SampleCodeEntity entity = new SampleCodeEntity(type, title, intent);
data.add(entity);
}
private SampleCodeAdapter.OnItemClickListener itemClickListener =
new SampleCodeAdapter.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
SampleCodeEntity entity = sampleCodeEntities.get(position);
if (entity != null) {
Intent intent = entity.getIntent();
intent.addCategory(Intent.CATEGORY_SAMPLE_CODE);
startActivity(intent);
}
}
};
}
| noobyang/AndroidStudy | game/src/main/java/com/lee/game/MainActivity.java | Java | apache-2.0 | 7,946 |
<?php
namespace Obj;
class Encoder {
private $key;
private $cipher;
private $mode;
/**
*
* args - array(
* 'hash' => hash method
* 'key' => path to private key
* 'encrypt' => encryption method
* )
*/
public function __construct($key, $cipher = MCRYPT_RIJNDAEL_128, $mode = MCRYPT_MODE_CBC) {
$keyString = file_get_contents($key, true);
$this->key = pack('H*', $keyString);
$this->cipher = $cipher;
$this->mode = $mode;
}
/**
* hash
*/
public static function hash($input, $hash = 'md5') {
return hash($hash, $input);
}
public function encrypt($plaintext) {
$key_size = strlen($this->key);
// create a random IV to use with CBC encoding
$iv_size = mcrypt_get_iv_size($this->cipher, $this->mode);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$ciphertext = mcrypt_encrypt($this->cipher, $this->key,
$plaintext, $this->mode, $iv);
$ciphertext = $iv . $ciphertext;
// encode the resulting cipher text so it can be represented by a string
$ciphertext_base64 = base64_encode($ciphertext);
return $ciphertext_base64;
}
public function decrypt($ciphertext_base64) {
$ciphertext_dec = base64_decode($ciphertext_base64);
$iv_size = mcrypt_get_iv_size($this->cipher, $this->mode);
// retrieves the IV, iv_size should be created using mcrypt_get_iv_size()
$iv_dec = substr($ciphertext_dec, 0, $iv_size);
// retrieves the cipher text (everything except the $iv_size in the front)
$ciphertext_dec = substr($ciphertext_dec, $iv_size);
// may remove 00h valued characters from end of plain text
$plaintext_dec = mcrypt_decrypt($this->cipher, $this->key,
$ciphertext_dec, $this->mode, $iv_dec);
return $plaintext_dec;
}
/**
* Generates a random string from the given charset of input length
*/
public static function randomString($length = 10, $set = null) {
if ($set == null) {
$set = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
}
$len = strlen($set);
$str = '';
while ($length--) {
$str .= $set[mt_rand(0, $len - 1)];
}
return $str;
}
}
?> | bnewcomer/code-samples | PHP_Projects/api-php/Obj/Encoder.php | PHP | apache-2.0 | 2,134 |
<?php
/*
* Copyright 2018 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.
*/
namespace Apigee\Edge\Api\Monetization\Controller;
use Apigee\Edge\Api\Monetization\Entity\BalanceInterface;
use Apigee\Edge\Api\Monetization\Entity\PrepaidBalanceInterface;
use Apigee\Edge\Controller\EntityControllerInterface;
interface PrepaidBalanceControllerInterface extends EntityControllerInterface, PaginatedEntityListingControllerInterface
{
/**
* @param string $currencyCode
*
* @return \Apigee\Edge\Api\Monetization\Entity\BalanceInterface|null
*/
public function getByCurrency(string $currencyCode): ?BalanceInterface;
/**
* @param float $amount
* @param string $currencyCode
*
* @return \Apigee\Edge\Api\Monetization\Entity\BalanceInterface
*/
public function topUpBalance(float $amount, string $currencyCode): BalanceInterface;
/**
* Enables and modifies recurring payment settings.
*
* @param string $currencyCode
* @param string $paymentProviderId
* @param float $replenishAmount
* @param float $recurringAmount
*
* @return \Apigee\Edge\Api\Monetization\Entity\BalanceInterface
*/
public function setupRecurringPayments(string $currencyCode, string $paymentProviderId, float $replenishAmount, float $recurringAmount): BalanceInterface;
/**
* Deactivate recurring payments.
*
* @param string $currencyCode
* @param string $paymentProviderId
*
* @return \Apigee\Edge\Api\Monetization\Entity\BalanceInterface
*/
public function disableRecurringPayments(string $currencyCode, string $paymentProviderId): BalanceInterface;
/**
* Gets prepaid balances.
*
* @param \DateTimeImmutable $billingMonth
*
* @return \Apigee\Edge\Api\Monetization\Entity\PrepaidBalanceInterface[]
*/
public function getPrepaidBalance(\DateTimeImmutable $billingMonth): array;
/**
* Gets prepaid balance by currency.
*
* @param string $currencyCode
* @param \DateTimeImmutable $billingMonth
*
* @return \Apigee\Edge\Api\Monetization\Entity\PrepaidBalanceInterface|null
*/
public function getPrepaidBalanceByCurrency(string $currencyCode, \DateTimeImmutable $billingMonth): ?PrepaidBalanceInterface;
}
| apigee/apigee-client-php | src/Api/Monetization/Controller/PrepaidBalanceControllerInterface.php | PHP | apache-2.0 | 2,834 |
using System;
using System.Globalization;
using System.Resources;
using System.Diagnostics;
using System.Reflection;
namespace Routrek.SSHC
{
/// <summary>
/// StringResource ÌTvÌà¾Å·B
/// </summary>
internal class StringResources {
private string _resourceName;
private ResourceManager _resMan;
public StringResources(string name, Assembly asm) {
_resourceName = name;
LoadResourceManager(name, asm);
}
public string GetString(string id)
{
try
{
return _resMan.GetString(id); //൱êªx¢æ¤Èç±ÌNXÅLbV
ÅàÂê΢¢¾ë¤
}
catch
{
return "error loading string";
}
}
private void LoadResourceManager(string name, Assembly asm) {
//ÊÍpêEú{굩µÈ¢
CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentUICulture;
//if(ci.Name.StartsWith("ja"))
//_resMan = new ResourceManager(name+"_ja", asm);
//else
_resMan = new ResourceManager(name, asm);
}
}
} | ehazlett/sshconsole | TerminalControl/StringResource.cs | C# | apache-2.0 | 1,022 |
/*
* Copyright 2014 http://Bither.net
*
* 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 net.bither.util;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import net.bither.BitherApplication;
import net.bither.bitherj.utils.Utils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class FileUtil {
// old tickerName file
private static final String HUOBI_TICKER_NAME = "huobi.ticker";
private static final String BITSTAMP_TICKER_NAME = "bitstamp.ticker";
private static final String BTCE_TICKER_NAME = "btce.ticker";
private static final String OKCOIN_TICKER_NAME = "okcoin.ticker";
private static final String CHBTC_TICKER_NAME = "chbtc.ticker";
private static final String BTCCHINA_TICKER_NAME = "btcchina.ticker";
private static final String BITHER_BACKUP_SDCARD_DIR = "BitherBackup";
private static final String BITHER_BACKUP_ROM_DIR = "backup";
private static final String BITHER_BACKUP_HOT_FILE_NAME = "keys";
private static final String EXCAHNGE_TICKER_NAME = "exchange.ticker";
private static final String EXCHANGE_KLINE_NAME = "exchange.kline";
private static final String EXCHANGE_DEPTH_NAME = "exchange.depth";
private static final String PRICE_ALERT = "price.alert";
private static final String EXCHANGERATE = "exchangerate";
private static final String CURRENCIES_RATE = "currencies_rate";
private static final String MARKET_CAHER = "mark";
private static final String IMAGE_CACHE_DIR = "image";
private static final String IMAGE_SHARE_FILE_NAME = "share.jpg";
private static final String IMAGE_CACHE_UPLOAD = IMAGE_CACHE_DIR + "/upload";
private static final String IMAGE_CACHE_612 = IMAGE_CACHE_DIR + "/612";
private static final String IMAGE_CACHE_150 = IMAGE_CACHE_DIR + "/150";
private static final String AD_CACHE = "ad";
private static final String AD_NAME = "ad.json";
private static final String AD_IMAGE_EN_CACHE = AD_CACHE + "/img_en";
private static final String AD_IMAGE_ZH_CN_CACHE = AD_CACHE + "/img_zh_CN";
private static final String AD_IMAGE_ZH_TW_CACHE = AD_CACHE + "/img_zh_TW";
/**
* sdCard exist
*/
public static boolean existSdCardMounted() {
String storageState = android.os.Environment.getExternalStorageState();
if (Utils.isEmpty(storageState)) {
return false;
}
return Utils.compareString(storageState,
android.os.Environment.MEDIA_MOUNTED);
}
public static File getSDPath() {
File sdDir = Environment.getExternalStorageDirectory();
return sdDir;
}
public static File getBackupSdCardDir() {
File backupDir = new File(getSDPath(), BITHER_BACKUP_SDCARD_DIR);
if (!backupDir.exists()) {
backupDir.mkdirs();
}
return backupDir;
}
public static File getBackupFileOfCold() {
File file = new File(getBackupSdCardDir(),
DateTimeUtil.getNameForFile(System.currentTimeMillis())
+ ".bak"
);
return file;
}
public static List<File> getBackupFileListOfCold() {
File dir = getBackupSdCardDir();
List<File> fileList = new ArrayList<File>();
File[] files = dir.listFiles();
if (files != null && files.length > 0) {
files = orderByDateDesc(files);
for (File file : files) {
if (StringUtil.checkBackupFileOfCold(file.getName())) {
fileList.add(file);
}
}
}
return fileList;
}
private static File getBackupRomDir() {
File backupDir = new File(Utils.getWalletRomCache(), BITHER_BACKUP_ROM_DIR);
if (!backupDir.exists()) {
backupDir.mkdirs();
}
return backupDir;
}
public static File getBackupKeyOfHot() {
File backupDir = getBackupRomDir();
return new File(backupDir, BITHER_BACKUP_HOT_FILE_NAME);
}
public static File getDiskDir(String dirName, Boolean createNomedia) {
File dir = getDiskCacheDir(BitherApplication.mContext, dirName);
if (!dir.exists()) {
dir.mkdirs();
if (createNomedia) {
try {
File noMediaFile = new File(dir, ".nomedia");
noMediaFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return dir;
}
public static Uri saveShareImage(Bitmap bmp) {
File dir = getDiskDir(IMAGE_CACHE_DIR, true);
File jpg = new File(dir, IMAGE_SHARE_FILE_NAME);
NativeUtil.compressBitmap(bmp, 85, jpg.getAbsolutePath(), true);
return Uri.fromFile(jpg);
}
public static File getExternalCacheDir(Context context) {
// if (SdkUtils.hasFroyo()) {
//
// return context.getCacheDir();
// }
// Before Froyo we need to construct the external cache dir ourselves
final String cacheDir = "/Android/data/" + context.getPackageName()
+ "/cache/";
return new File(Environment.getExternalStorageDirectory().getPath()
+ cacheDir);
}
public static File getDiskCacheDir(Context context, String uniqueName) {
File extCacheDir = getExternalCacheDir(context);
final String cachePath = (Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState()) || !isExternalStorageRemovable())
&& extCacheDir != null ? extCacheDir.getPath() : context
.getCacheDir().getPath();
return new File(cachePath + File.separator + uniqueName);
}
@TargetApi(9)
public static boolean isExternalStorageRemovable() {
if (SdkUtils.hasGingerbread()) {
return Environment.isExternalStorageRemovable();
}
return true;
}
private static File getMarketCache() {
return getDiskDir(MARKET_CAHER, false);
}
public static File getAdImageEnDir() {
return getDiskDir(AD_IMAGE_EN_CACHE, true);
}
public static File getAdImagZhCnDir() {
return getDiskDir(AD_IMAGE_ZH_CN_CACHE, true);
}
public static File getAdImagZhTwDir() {
return getDiskDir(AD_IMAGE_ZH_TW_CACHE, true);
}
private static File getAdDir() {
return getDiskDir(AD_CACHE, false);
}
public static File getUploadImageDir() {
return getDiskDir(IMAGE_CACHE_UPLOAD, true);
}
public static File getAvatarDir() {
return getDiskDir(IMAGE_CACHE_612, true);
}
public static File getSmallAvatarDir() {
return getDiskDir(IMAGE_CACHE_150, true);
}
public static File getExchangeRateFile() {
File file = getDiskDir("", false);
return new File(file, EXCHANGERATE);
}
public static File getCurrenciesRateFile() {
File file = getDiskDir("", false);
return new File(file, CURRENCIES_RATE);
}
public static File getTickerFile() {
File file = getMarketCache();
file = new File(file, EXCAHNGE_TICKER_NAME);
return file;
}
public static File getPriceAlertFile() {
File marketDir = getMarketCache();
return new File(marketDir, PRICE_ALERT);
}
public static File getKlineFile() {
File file = getMarketCache();
file = new File(file, EXCHANGE_KLINE_NAME);
return file;
}
public static File getDepthFile() {
File file = getMarketCache();
file = new File(file, EXCHANGE_DEPTH_NAME);
return file;
}
public static File getAdFile() {
File file = getAdDir();
file = new File(file, AD_NAME);
return file;
}
@SuppressWarnings("resource")
public static Object deserialize(File file) {
FileInputStream fos = null;
try {
if (!file.exists()) {
return null;
}
fos = new FileInputStream(file);
ObjectInputStream ois;
ois = new ObjectInputStream(fos);
Object object = ois.readObject();
return object;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void serializeObject(File file, Object object) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(object);
oos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static File[] orderByDateDesc(File[] fs) {
Arrays.sort(fs, new Comparator<File>() {
public int compare(File f1, File f2) {
long diff = f1.lastModified() - f2.lastModified();
if (diff > 0) {
return -1;//-1 f1 before f2
} else if (diff == 0) {
return 0;
} else {
return 1;
}
}
public boolean equals(Object obj) {
return true;
}
});
return fs;
}
public static void copyFile(File src, File tar) throws Exception {
if (src.isFile()) {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
InputStream is = new FileInputStream(src);
bis = new BufferedInputStream(is);
OutputStream op = new FileOutputStream(tar);
bos = new BufferedOutputStream(op);
byte[] bt = new byte[8192];
int len = bis.read(bt);
while (len != -1) {
bos.write(bt, 0, len);
len = bis.read(bt);
}
bis.close();
bos.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
}
} else if (src.isDirectory()) {
File[] files = src.listFiles();
tar.mkdir();
for (int i = 0;
i < files.length;
i++) {
copyFile(files[i].getAbsoluteFile(),
new File(tar.getAbsoluteFile() + File.separator
+ files[i].getName())
);
}
} else {
throw new FileNotFoundException();
}
}
public static void delFolder(String folderPath) {
try {
delAllFile(folderPath);
String filePath = folderPath;
filePath = filePath.toString();
java.io.File myFilePath = new java.io.File(filePath);
myFilePath.delete();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void delAllFile(String path) {
File file = new File(path);
if (!file.exists()) {
return;
}
if (!file.isDirectory()) {
return;
}
String[] tempList = file.list();
if (tempList == null) {
return;
}
File temp = null;
for (int i = 0;
i < tempList.length;
i++) {
if (path.endsWith(File.separator)) {
temp = new File(path + tempList[i]);
} else {
temp = new File(path + File.separator + tempList[i]);
}
if (temp.isFile()) {
temp.delete();
}
if (temp.isDirectory()) {
delAllFile(path + "/" + tempList[i]);
delFolder(path + "/" + tempList[i]);
}
}
}
public static void upgradeTickerFile() {
File marketDir = getMarketCache();
File file = new File(marketDir, BITSTAMP_TICKER_NAME);
fileExistAndDelete(file);
file = new File(marketDir, BTCE_TICKER_NAME);
fileExistAndDelete(file);
file = new File(marketDir, HUOBI_TICKER_NAME);
fileExistAndDelete(file);
file = new File(marketDir, OKCOIN_TICKER_NAME);
fileExistAndDelete(file);
file = new File(marketDir, CHBTC_TICKER_NAME);
fileExistAndDelete(file);
file = new File(marketDir, BTCCHINA_TICKER_NAME);
fileExistAndDelete(file);
}
public static boolean fileExistAndDelete(File file) {
return file.exists() && file.delete();
}
public static File convertUriToFile(Activity activity, Uri uri) {
File file = null;
try {
String[] proj = {MediaStore.Images.Media.DATA};
@SuppressWarnings("deprecation")
Cursor actualimagecursor = activity.managedQuery(uri, proj, null,
null, null);
if (actualimagecursor != null) {
int actual_image_column_index = actualimagecursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
actualimagecursor.moveToFirst();
String img_path = actualimagecursor
.getString(actual_image_column_index);
if (!Utils.isEmpty(img_path)) {
file = new File(img_path);
}
} else {
file = new File(new URI(uri.toString()));
if (file.exists()) {
return file;
}
}
} catch (Exception e) {
}
return file;
}
public static int getOrientationOfFile(String fileName) {
int orientation = 0;
try {
ExifInterface exif = new ExifInterface(fileName);
String orientationString = exif
.getAttribute(ExifInterface.TAG_ORIENTATION);
if (Utils.isNubmer(orientationString)) {
int orc = Integer.valueOf(orientationString);
switch (orc) {
case ExifInterface.ORIENTATION_ROTATE_90:
orientation = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
orientation = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
orientation = 270;
break;
default:
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return orientation;
}
}
| bither/bither-android | bither-android/src/net/bither/util/FileUtil.java | Java | apache-2.0 | 16,209 |
# Internet Exchange
An Internet exchange point, also known as IX or IXP, is an infrastructure
through which autonomous systems exchange traffic. An IX can be a single local
LAN or it can be spread across multiple locations.
## In Peering Manager
Inside Peering Manager, you create an Internet exchange to then create one or
more peering BGP sessions. Only Internet Exchange Peering Sessions can be
related to an Internet exchange. For each Internet exchange you create,
the following properties can be configured (n.b. some are optional):
* `Name`: human-readable name attached to the IX.
* `Slug`: unique configuration and URL friendly name; usually it is
automatically generated from the IXP's name.
* `Local Autonomous System`: your autonomous system connected to this IX.
* `Comments`: text to explain what the Internet exchange is for. Can use
Markdown formatting.
* `Check BGP Session States`: whether Peering Manager should poll the state
of BGP sessions at this IX.
* `Import Routing Policies`: a list of routing policies to apply when
receiving prefixes though BGP sessions at this IX.
* `Export Routing Policies`: a list of routing policies to apply when
advertising prefixes though BGP sessions at this IX.
* `PeeringDB ID`: an integer which is the ID of the IX LAN inside PeeringDB.
This setting is required for Peering Manager to discover potential
unconfigured BGP sessions.[^1]
* `IPv6 Address`: an IPv6 address used to connect to the Internet exchange
network. [^2]
* `IPv4 Address`: an IPv4 address used to connect to the Internet exchange
network. [^2]
* `Router`: a router connected to the Internet exchange. This is used to then
generate and install configurations.[^2]
* `Tags`: a list of tags to help identifying and searching for a group.
Please note that an Internet exchange is a kind of BGP group with more specific
properties aimed to match the purpose of an Internet exchange network. However
while a group can be configured on more than one router, an IX can only be
attached to a single router. This means that if you are connected more than
once to an IX, you'll have to create one IX object per connection.
[^1]: This is no longer user edible
[^2]: This moved to the [Connection](../../net/connection/) tab
| respawner/peering-manager | docs/models/peering/internetexchange.md | Markdown | apache-2.0 | 2,268 |
# Peperomia crinigera Trel. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Piperales/Piperaceae/Peperomia/Peperomia crinigera/README.md | Markdown | apache-2.0 | 175 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace pool
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
| knifecaojia/CoinsPro | Src/pool/Program.cs | C# | apache-2.0 | 494 |
package io.react2.scalata.exporters
import com.mongodb.{WriteConcern, BulkWriteOperation, BasicDBObject, MongoClient}
import io.react2.scalata.Context
import io.react2.scalata.plugins.Plugin
import scala.util.control.NonFatal
/**
* @author dbalduini
*/
class MongoExporter(val args: Plugin.Args) extends Exporter {
val verbose = args("verbose", false)
val database = args("database", "test")
val collection = args("collection", "scalata")
val host = args("host", "localhost")
val port = args("port", 27017)
val mongo = new MongoClient(host, port)
val db = mongo.getDB(database)
val coll = db.getCollection(collection)
var maybeBulk: Option[BulkWriteOperation] = None
@transient var counter = 0
val total = Context.NUMBER_OF_LINES.get
override def export(f: Any): Unit = {
val doc = f.asInstanceOf[BasicDBObject]
try {
if(verbose)
println(doc.toString)
val bulk = maybeBulk match {
case None =>
maybeBulk = Some(coll.initializeUnorderedBulkOperation)
maybeBulk.get
case Some(b) => b
}
bulk.insert(doc)
counter = counter + 1
flush()
} catch {
case NonFatal(t) =>
t.printStackTrace()
}
}
private def flush(): Unit = {
val percentage = (counter.toFloat * 100) / total
if (percentage != 0 && percentage % 10 == 0) {
println(s"Current percentage processed: $counter / $total / $percentage%")
maybeBulk match {
case Some(bulk) =>
val wc = new WriteConcern(0)
bulk.execute(wc)
maybeBulk = None
case None =>
}
}
}
}
| React2/scalata | src/main/scala/io/react2/scalata/exporters/MongoExporter.scala | Scala | apache-2.0 | 1,637 |
package org.cobbzilla.util.jdbc;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DbUrlUtil {
public static final Pattern JDBC_URL_REGEX = Pattern.compile("^jdbc:postgresql://[\\.\\w]+:\\d+/(.+)$");
public static String setDbName(String url, String dbName) {
final Matcher matcher = JDBC_URL_REGEX.matcher(url);
if (!matcher.find()) return url;
final String renamed = matcher.replaceFirst(dbName);
return renamed;
}
}
| cobbzilla/cobbzilla-utils | src/main/java/org/cobbzilla/util/jdbc/DbUrlUtil.java | Java | apache-2.0 | 495 |
/*
Copyright (C) 2014 by Project Tox <https://tox.im>
This file is part of qTox, a Qt-based graphical interface for Tox.
This program is libre 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 COPYING file for more details.
*/
#ifndef GROUPCHATFORM_H
#define GROUPCHATFORM_H
#include <QLabel>
#include <QWidget>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QGridLayout>
#include <QTextEdit>
#include <QScrollArea>
#include <QTime>
#include "widget/tool/chattextedit.h"
#include "ui_widget.h"
// Spacing in px inserted when the author of the last message changes
#define AUTHOR_CHANGE_SPACING 5
class Group;
class GroupChatForm : public QObject
{
Q_OBJECT
public:
GroupChatForm(Group* chatGroup);
~GroupChatForm();
void show(Ui::Widget& ui);
void setName(QString newName);
void addGroupMessage(QString message, int peerId);
void addMessage(QString author, QString message, QString date=QTime::currentTime().toString("hh:mm"));
void addMessage(QLabel* author, QLabel* message, QLabel* date);
void onUserListChanged();
signals:
void sendMessage(int, QString);
private slots:
void onSendTriggered();
void onSliderRangeChanged();
void onChatContextMenuRequested(QPoint pos);
void onSaveLogClicked();
private:
Group* group;
QHBoxLayout *headLayout, *mainFootLayout;
QVBoxLayout *headTextLayout, *mainLayout;
QGridLayout *mainChatLayout;
QLabel *avatar, *name, *nusers, *namesList;
ChatTextEdit *msgEdit;
QPushButton *sendButton;
QScrollArea *chatArea;
QWidget *main, *head, *chatAreaWidget;
QString previousName;
int curRow;
bool lockSliderToBottom;
};
#endif // GROUPCHATFORM_H
| mickelfeng/qt_learning | BroadCast_QT/widget/form/groupchatform.h | C | apache-2.0 | 2,098 |
'use strict';
var fs = require('fs');
var path = require('path');
var util = require('util');
var dbg = require('debug');
// process.env.TABTAB_DEBUG = process.env.TABTAB_DEBUG || '/tmp/tabtab.log';
var out = process.env.TABTAB_DEBUG ? fs.createWriteStream(process.env.TABTAB_DEBUG, { flags: 'a' }) : null;
module.exports = debug;
// Internal: Facade to debug module, which provides the exact same interface.
//
// The added benefit is with the TABTAB_DEBUG environment variable, which when
// defined, will write debug output to the specified filename.
//
// Usefull when debugging tab completion, as logs on stdout / stderr are either
// shallowed or used as tab completion results.
//
// namespace - The String namespace to use when TABTAB_DEBUG is not defined,
// delegates to debug module.
//
// Examples
//
// // Use with following command to redirect output to file
// // TABTAB_DEBUG="debug.log" tabtab ...
// debug('Foo');
function debug(namespace) {
var log = dbg(namespace);
return function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
args = args.map(function (arg) {
if (typeof arg === 'string') return arg;
return JSON.stringify(arg);
});
out && out.write(util.format.apply(util, args) + '\n');
out || log.apply(null, args);
};
} | bhav0904/netDelSolution | node_modules/tabtab/src/debug.js | JavaScript | apache-2.0 | 1,398 |
<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<title>PHPXRef 0.7.1 : Unnamed Project : Variable Reference: $_never_allowed_regex</title>
<link rel="stylesheet" href="../sample.css" type="text/css">
<link rel="stylesheet" href="../sample-print.css" type="text/css" media="print">
<style id="hilight" type="text/css"></style>
<meta http-equiv="content-type" content="text/html;charset=iso-8859-1">
</head>
<body bgcolor="#ffffff" text="#000000" link="#801800" vlink="#300540" alink="#ffffff">
<table class="pagetitle" width="100%">
<tr>
<td valign="top" class="pagetitle">
[ <a href="../index.html">Index</a> ]
</td>
<td align="right" class="pagetitle">
<h2 style="margin-bottom: 0px">PHP Cross Reference of Unnamed Project</h2>
</td>
</tr>
</table>
<!-- Generated by PHPXref 0.7.1 at Thu Oct 23 18:57:41 2014 -->
<!-- PHPXref (c) 2000-2010 Gareth Watts - [email protected] -->
<!-- http://phpxref.sourceforge.net/ -->
<script src="../phpxref.js" type="text/javascript"></script>
<script language="JavaScript" type="text/javascript">
<!--
ext='.html';
relbase='../';
subdir='_variables';
filename='index.html';
cookiekey='phpxref';
handleNavFrame(relbase, subdir, filename);
logVariable('_never_allowed_regex');
// -->
</script>
<script language="JavaScript" type="text/javascript">
if (gwGetCookie('xrefnav')=='off')
document.write('<p class="navlinks">[ <a href="javascript:navOn()">Show Explorer<\/a> ]<\/p>');
else
document.write('<p class="navlinks">[ <a href="javascript:navOff()">Hide Explorer<\/a> ]<\/p>');
</script>
<noscript>
<p class="navlinks">
[ <a href="../nav.html" target="_top">Show Explorer</a> ]
[ <a href="index.html" target="_top">Hide Navbar</a> ]
</p>
</noscript>
[<a href="../index.html">Top level directory</a>]<br>
<script language="JavaScript" type="text/javascript">
<!--
document.writeln('<table align="right" class="searchbox-link"><tr><td><a class="searchbox-link" href="javascript:void(0)" onMouseOver="showSearchBox()">Search</a><br>');
document.writeln('<table border="0" cellspacing="0" cellpadding="0" class="searchbox" id="searchbox">');
document.writeln('<tr><td class="searchbox-title">');
document.writeln('<a class="searchbox-title" href="javascript:showSearchPopup()">Search History +</a>');
document.writeln('<\/td><\/tr>');
document.writeln('<tr><td class="searchbox-body" id="searchbox-body">');
document.writeln('<form name="search" style="margin:0px; padding:0px" onSubmit=\'return jump()\'>');
document.writeln('<a class="searchbox-body" href="../_classes/index.html">Class<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="classname"><br>');
document.writeln('<a id="funcsearchlink" class="searchbox-body" href="../_functions/index.html">Function<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="funcname"><br>');
document.writeln('<a class="searchbox-body" href="../_variables/index.html">Variable<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="varname"><br>');
document.writeln('<a class="searchbox-body" href="../_constants/index.html">Constant<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="constname"><br>');
document.writeln('<a class="searchbox-body" href="../_tables/index.html">Table<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="tablename"><br>');
document.writeln('<input type="submit" class="searchbox-button" value="Search">');
document.writeln('<\/form>');
document.writeln('<\/td><\/tr><\/table>');
document.writeln('<\/td><\/tr><\/table>');
// -->
</script>
<div id="search-popup" class="searchpopup"><p id="searchpopup-title" class="searchpopup-title">title</p><div id="searchpopup-body" class="searchpopup-body">Body</div><p class="searchpopup-close"><a href="javascript:gwCloseActive()">[close]</a></p></div>
<h3>Variable Cross Reference</h3>
<h2><a href="index.html#_never_allowed_regex">$_never_allowed_regex</a></h2>
<b>Defined at:</b><ul>
<li><a href="../bonfire/codeigniter/core/Security.php.html">/bonfire/codeigniter/core/Security.php</A> -> <a href="../bonfire/codeigniter/core/Security.php.source.html#l91"> line 91</A></li>
</ul>
<br><b>Referenced 2 times:</b><ul>
<li><a href="../bonfire/codeigniter/core/Security.php.html">/bonfire/codeigniter/core/Security.php</a> -> <a href="../bonfire/codeigniter/core/Security.php.source.html#l91"> line 91</a></li>
<li><a href="../bonfire/codeigniter/core/Security.php.html">/bonfire/codeigniter/core/Security.php</a> -> <a href="../bonfire/codeigniter/core/Security.php.source.html#l837"> line 837</a></li>
</ul>
<!-- A link to the phpxref site in your customized footer file is appreciated ;-) -->
<br><hr>
<table width="100%">
<tr><td>Generated: Thu Oct 23 18:57:41 2014</td>
<td align="right"><i>Cross-referenced by <a href="http://phpxref.sourceforge.net/">PHPXref 0.7.1</a></i></td>
</tr>
</table>
</body></html>
| inputx/code-ref-doc | bonfire/_variables/_never_allowed_regex.html | HTML | apache-2.0 | 5,015 |
<?php
/**
* This is the model class for table "product_type".
*
* The followings are the available columns in table 'product_type':
* @property string $product_type_id
* @property string $parent_product_type_id
* @property string $name
* @property string $created
*
* The followings are the available model relations:
* @property Product[] $products
* @property ProductMultiDay[] $productMultiDays
* @property ProductOneDay[] $productOneDays
*/
class ProductType extends CActiveRecord
{
/**
* Returns the static model of the specified AR class.
* @param string $className active record class name.
* @return ProductType the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
/**
* @return string the associated database table name
*/
public function tableName()
{
return 'product_type';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('parent_product_type_id', 'length', 'max'=>10),
);
}
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array();
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'product_type_id' => 'Product Type',
'parent_product_type_id' => 'Parent Product Type',
'name' => 'Name',
'created' => 'Created',
);
}
} | CdGitHub/live | protected/models/ProductType.php | PHP | apache-2.0 | 1,879 |
=begin
Copyright 2012-2013 inBloom, Inc. and 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.
=end
require_relative '../lib/Shared/data_utility.rb'
require_relative '../lib/Shared/EntityClasses/enum/GradeLevelType.rb'
require_relative 'spec_helper'
# specifications for data utility
describe "DataUtility" do
before(:all) do
@yaml = YAML.load_file(File.join(File.dirname(__FILE__),'../config.yml'))
@prng = Random.new(@yaml['seed'])
end
after(:all) do
@yaml = nil
@prng = nil
end
describe "Generates correct _id for each supported entity" do
describe "#get_staff_unique_state_id" do
it "will generate a staff unique state id with the correct format" do
DataUtility.get_staff_unique_state_id(146724).should match("stff-0000146724")
end
end
describe "#get_teacher_unique_state_id" do
it "will generate a teacher unique state id with the correct format" do
DataUtility.get_teacher_unique_state_id(146724).should match("tech-0000146724")
end
end
end
describe "Handles requests for entities correctly" do
describe "--> request to get staff unique state id with string" do
it "will return the string that was input" do
DataUtility.get_staff_unique_state_id("rrogers").should match("rrogers")
end
end
describe "--> request to get staff unique state id with integer" do
it "will return the corresponding staff unique state id" do
DataUtility.get_staff_unique_state_id(17).should match("stff-0000000017")
end
end
describe "--> request to get teacher unique state id with string" do
it "will return the string that was input" do
DataUtility.get_teacher_unique_state_id("cgray").should match("cgray")
end
end
describe "--> request to get teacher unique state id with integer" do
it "will return the corresponding teacher unique state id" do
DataUtility.get_teacher_unique_state_id(18).should match("tech-0000000018")
end
end
describe "--> request to get random elementary school grade" do
it "will always return only grades that are in elementary school" do
grades = [:KINDERGARTEN, :FIRST_GRADE, :SECOND_GRADE, :THIRD_GRADE, :FOURTH_GRADE, :FIFTH_GRADE]
(1..25).each do
grades.include?(DataUtility.get_random_grade_for_type(@prng, "elementary")).should be_true
end
end
end
describe "--> request to get random middle school grade" do
it "will always return only grades that are in middle school" do
grades = [:SIXTH_GRADE, :SEVENTH_GRADE, :EIGHTH_GRADE]
(1..25).each do
grades.include?(DataUtility.get_random_grade_for_type(@prng, "middle")).should be_true
end
end
end
describe "--> request to get random high school grade" do
it "will always return only grades that are in high school" do
grades = [:NINTH_GRADE, :TENTH_GRADE, :ELEVENTH_GRADE, :TWELFTH_GRADE]
(1..25).each do
grades.include?(DataUtility.get_random_grade_for_type(@prng, "high")).should be_true
end
end
end
describe "--> request to get subset of choices" do
it "will return a subset of choices with correct size" do
options = [1,2,3,4,5,6,7,8,9,10]
subset = DataUtility.select_num_from_options(@prng, 5, options)
subset.size.should eq 5
subset.each do |number|
options.include?(number).should be_true
end
end
it "will return choices if the number specified is larger than the size of choices" do
options = [1,2,3,4,5,6,7,8,9,10]
subset = DataUtility.select_num_from_options(@prng, 15, options)
subset.size.should eq 10
subset.should eq options
end
it "will return an empty array is the number specified is zero" do
options = [1,2,3,4,5,6,7,8,9,10]
subset = DataUtility.select_num_from_options(@prng, 0, options)
subset.size.should eq 0
end
end
end
end
| inbloom/secure-data-service | tools/odin/spec/data_utility_spec.rb | Ruby | apache-2.0 | 4,529 |
from changes.api.serializer import Crumbler, register
from changes.models.node import Cluster
@register(Cluster)
class ClusterCrumbler(Crumbler):
def crumble(self, instance, attrs):
return {
'id': instance.id.hex,
'name': instance.label,
'dateCreated': instance.date_created,
}
| dropbox/changes | changes/api/serializer/models/cluster.py | Python | apache-2.0 | 336 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>20130925</title>
<style type="text/css">
.visiNone
{
display: none;
}
.hide
{
visibility: hidden;
}
.block
{
display: block;
}
.list
{
display: list-item;
}
a:link, a:visited
{
background: #efb57c;
border: 2px outset #efb57c;
}
a
{
display: block;
width: 150px;
height: 20px;
margin-top: 10px;
text-align: center;
}
a:focus, a:hover
{
background: #daa670;
border: 2px outset #daa670;
color: black;
}
a:active
{
background: #bb8e6d;
border: 2px outset #bb8e6d;
}
.miniPhoto: hover .bigPhoto
{
display: none;
}
#popImg a, img
{
border: none;
}
#popImg a img.bigPhoto
{
height: 0;
width: 0;
border-width: 0;
}
#popImg a:hover img.bigPhoto
{
position: absolute;
top: 1000px;
left: 160px;
height: 458px;
width: 500px;
}
</style>
</head>
<body>
<h1>20130925</h1>
<p>Show a series of dynamic effect of link & image.</p>
<p class="visiNone">
<img src="../images/Prime.jpg" alt="first image" />
</p>
<p class="hide">
<img src="../images/Prime.jpg" alt="second image" />
</p>
<p class="block">
<img src="../images/Prime.jpg" alt="third image" />
</p>
<p class="list">
<img src="../images/Prime_preview.jpg" alt="small image 1" />
<img src="../images/Prime_preview.jpg" alt="small image 2" />
<img src="../images/Prime_preview.jpg" alt="small image 3" />
</p>
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
<a href="#">Link 4</a>
<div id="popImg">
<a class="checkImg" href="#">
<img class="smallPhoto" src="../images/Prime_preview.jpg" alt="mini image" />
<img class="bigPhoto" src="../images/Prime.jpg" alt="big image" />
</a>
</div>
</div>
</body>
</html>
| fatbigbright/HTMLExercises | public/201309/20130925.html | HTML | apache-2.0 | 2,409 |
# Erodium choulettianum Coss. ex Batt. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Geraniales/Geraniaceae/Erodium/Erodium choulettianum/README.md | Markdown | apache-2.0 | 186 |
/**
* 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.ozone.ozShell;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.stream.Collectors;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.hdds.cli.MissingSubcommandException;
import org.apache.hadoop.hdds.client.ReplicationFactor;
import org.apache.hadoop.hdds.conf.OzoneConfiguration;
import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
import org.apache.hadoop.hdfs.DFSUtil;
import org.apache.hadoop.ozone.MiniOzoneCluster;
import org.apache.hadoop.ozone.OzoneAcl;
import org.apache.hadoop.ozone.OzoneAcl.OzoneACLRights;
import org.apache.hadoop.ozone.OzoneAcl.OzoneACLType;
import org.apache.hadoop.ozone.OzoneConsts;
import org.apache.hadoop.ozone.client.OzoneBucket;
import org.apache.hadoop.ozone.client.OzoneKey;
import org.apache.hadoop.ozone.client.OzoneVolume;
import org.apache.hadoop.ozone.client.VolumeArgs;
import org.apache.hadoop.ozone.client.io.OzoneOutputStream;
import org.apache.hadoop.ozone.client.protocol.ClientProtocol;
import org.apache.hadoop.ozone.client.rest.OzoneException;
import org.apache.hadoop.ozone.client.rest.RestClient;
import org.apache.hadoop.ozone.client.rpc.RpcClient;
import org.apache.hadoop.ozone.om.helpers.ServiceInfo;
import org.apache.hadoop.ozone.web.ozShell.Shell;
import org.apache.hadoop.ozone.web.request.OzoneQuota;
import org.apache.hadoop.ozone.web.response.BucketInfo;
import org.apache.hadoop.ozone.web.response.KeyInfo;
import org.apache.hadoop.ozone.web.response.VolumeInfo;
import org.apache.hadoop.ozone.web.utils.JsonUtils;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.test.GenericTestUtils;
import com.google.common.base.Strings;
import org.apache.commons.lang3.RandomStringUtils;
import static org.apache.hadoop.ozone.OzoneConfigKeys.OZONE_REPLICATION;
import static org.apache.hadoop.ozone.om.OMConfigKeys.OZONE_OM_ADDRESS_KEY;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import picocli.CommandLine;
import picocli.CommandLine.ExecutionException;
import picocli.CommandLine.IExceptionHandler2;
import picocli.CommandLine.ParameterException;
import picocli.CommandLine.ParseResult;
import picocli.CommandLine.RunLast;
/**
* This test class specified for testing Ozone shell command.
*/
@RunWith(value = Parameterized.class)
public class TestOzoneShell {
private static final Logger LOG =
LoggerFactory.getLogger(TestOzoneShell.class);
/**
* Set the timeout for every test.
*/
@Rule
public Timeout testTimeout = new Timeout(300000);
private static String url;
private static File baseDir;
private static OzoneConfiguration conf = null;
private static MiniOzoneCluster cluster = null;
private static ClientProtocol client = null;
private static Shell shell = null;
private final ByteArrayOutputStream out = new ByteArrayOutputStream();
private final ByteArrayOutputStream err = new ByteArrayOutputStream();
private static final PrintStream OLD_OUT = System.out;
private static final PrintStream OLD_ERR = System.err;
@Parameterized.Parameters
public static Collection<Object[]> clientProtocol() {
Object[][] params = new Object[][] {
{RpcClient.class},
{RestClient.class}};
return Arrays.asList(params);
}
@Parameterized.Parameter
public Class clientProtocol;
/**
* Create a MiniDFSCluster for testing with using distributed Ozone
* handler type.
*
* @throws Exception
*/
@BeforeClass
public static void init() throws Exception {
conf = new OzoneConfiguration();
String path = GenericTestUtils.getTempPath(
TestOzoneShell.class.getSimpleName());
baseDir = new File(path);
baseDir.mkdirs();
shell = new Shell();
cluster = MiniOzoneCluster.newBuilder(conf)
.setNumDatanodes(3)
.build();
conf.setInt(OZONE_REPLICATION, ReplicationFactor.THREE.getValue());
conf.setQuietMode(false);
client = new RpcClient(conf);
cluster.waitForClusterToBeReady();
}
/**
* shutdown MiniDFSCluster.
*/
@AfterClass
public static void shutdown() {
if (cluster != null) {
cluster.shutdown();
}
if (baseDir != null) {
FileUtil.fullyDelete(baseDir, true);
}
}
@Before
public void setup() {
System.setOut(new PrintStream(out));
System.setErr(new PrintStream(err));
if(clientProtocol.equals(RestClient.class)) {
String hostName = cluster.getOzoneManager().getHttpServer()
.getHttpAddress().getHostName();
int port = cluster
.getOzoneManager().getHttpServer().getHttpAddress().getPort();
url = String.format("http://" + hostName + ":" + port);
} else {
List<ServiceInfo> services = null;
try {
services = cluster.getOzoneManager().getServiceList();
} catch (IOException e) {
LOG.error("Could not get service list from OM");
}
String hostName = services.stream().filter(
a -> a.getNodeType().equals(HddsProtos.NodeType.OM))
.collect(Collectors.toList()).get(0).getHostname();
String port = cluster.getOzoneManager().getRpcPort();
url = String.format("o3://" + hostName + ":" + port);
}
}
@After
public void reset() {
// reset stream after each unit test
out.reset();
err.reset();
// restore system streams
System.setOut(OLD_OUT);
System.setErr(OLD_ERR);
}
@Test
public void testCreateVolume() throws Exception {
LOG.info("Running testCreateVolume");
String volumeName = "volume" + RandomStringUtils.randomNumeric(5);
testCreateVolume(volumeName, "");
volumeName = "volume" + RandomStringUtils.randomNumeric(5);
testCreateVolume("/////" + volumeName, "");
testCreateVolume("/////", "Volume name is required");
testCreateVolume("/////vol/123",
"Invalid volume name. Delimiters (/) not allowed in volume name");
}
private void testCreateVolume(String volumeName, String errorMsg)
throws Exception {
err.reset();
String userName = "bilbo";
String[] args = new String[] {"volume", "create", url + "/" + volumeName,
"--user", userName, "--root"};
if (Strings.isNullOrEmpty(errorMsg)) {
execute(shell, args);
} else {
executeWithError(shell, args, errorMsg);
return;
}
String truncatedVolumeName =
volumeName.substring(volumeName.lastIndexOf('/') + 1);
OzoneVolume volumeInfo = client.getVolumeDetails(truncatedVolumeName);
assertEquals(truncatedVolumeName, volumeInfo.getName());
assertEquals(userName, volumeInfo.getOwner());
}
private void execute(Shell ozoneShell, String[] args) {
List<String> arguments = new ArrayList(Arrays.asList(args));
LOG.info("Executing shell command with args {}", arguments);
CommandLine cmd = ozoneShell.getCmd();
IExceptionHandler2<List<Object>> exceptionHandler =
new IExceptionHandler2<List<Object>>() {
@Override
public List<Object> handleParseException(ParameterException ex,
String[] args) {
throw ex;
}
@Override
public List<Object> handleExecutionException(ExecutionException ex,
ParseResult parseResult) {
throw ex;
}
};
cmd.parseWithHandlers(new RunLast(),
exceptionHandler, args);
}
/**
* Test to create volume without specifying --user or -u.
* @throws Exception
*/
@Test
public void testCreateVolumeWithoutUser() throws Exception {
String volumeName = "volume" + RandomStringUtils.randomNumeric(1);
String[] args = new String[] {"volume", "create", url + "/" + volumeName,
"--root"};
execute(shell, args);
String truncatedVolumeName =
volumeName.substring(volumeName.lastIndexOf('/') + 1);
OzoneVolume volumeInfo = client.getVolumeDetails(truncatedVolumeName);
assertEquals(truncatedVolumeName, volumeInfo.getName());
assertEquals(UserGroupInformation.getCurrentUser().getUserName(),
volumeInfo.getOwner());
}
@Test
public void testDeleteVolume() throws Exception {
LOG.info("Running testDeleteVolume");
String volumeName = "volume" + RandomStringUtils.randomNumeric(5);
VolumeArgs volumeArgs = VolumeArgs.newBuilder()
.setOwner("bilbo")
.setQuota("100TB")
.build();
client.createVolume(volumeName, volumeArgs);
OzoneVolume volume = client.getVolumeDetails(volumeName);
assertNotNull(volume);
String[] args = new String[] {"volume", "delete", url + "/" + volumeName};
execute(shell, args);
String output = out.toString();
assertTrue(output.contains("Volume " + volumeName + " is deleted"));
// verify if volume has been deleted
try {
client.getVolumeDetails(volumeName);
fail("Get volume call should have thrown.");
} catch (IOException e) {
GenericTestUtils.assertExceptionContains(
"Info Volume failed, error:VOLUME_NOT_FOUND", e);
}
volumeName = "volume" + RandomStringUtils.randomNumeric(5);
volumeArgs = VolumeArgs.newBuilder()
.setOwner("bilbo")
.setQuota("100TB")
.build();
client.createVolume(volumeName, volumeArgs);
volume = client.getVolumeDetails(volumeName);
assertNotNull(volume);
//volumeName prefixed with /
String volumeNameWithSlashPrefix = "/" + volumeName;
args = new String[] {"volume", "delete",
url + "/" + volumeNameWithSlashPrefix};
execute(shell, args);
output = out.toString();
assertTrue(output.contains("Volume " + volumeName + " is deleted"));
// verify if volume has been deleted
try {
client.getVolumeDetails(volumeName);
fail("Get volume call should have thrown.");
} catch (IOException e) {
GenericTestUtils.assertExceptionContains(
"Info Volume failed, error:VOLUME_NOT_FOUND", e);
}
}
@Test
public void testInfoVolume() throws Exception {
LOG.info("Running testInfoVolume");
String volumeName = "volume" + RandomStringUtils.randomNumeric(5);
VolumeArgs volumeArgs = VolumeArgs.newBuilder()
.setOwner("bilbo")
.setQuota("100TB")
.build();
client.createVolume(volumeName, volumeArgs);
//volumeName supplied as-is
String[] args = new String[] {"volume", "info", url + "/" + volumeName};
execute(shell, args);
String output = out.toString();
assertTrue(output.contains(volumeName));
assertTrue(output.contains("createdOn")
&& output.contains(OzoneConsts.OZONE_TIME_ZONE));
//volumeName prefixed with /
String volumeNameWithSlashPrefix = "/" + volumeName;
args = new String[] {"volume", "info",
url + "/" + volumeNameWithSlashPrefix};
execute(shell, args);
output = out.toString();
assertTrue(output.contains(volumeName));
assertTrue(output.contains("createdOn")
&& output.contains(OzoneConsts.OZONE_TIME_ZONE));
// test infoVolume with invalid volume name
args = new String[] {"volume", "info",
url + "/" + volumeName + "/invalid-name"};
executeWithError(shell, args, "Invalid volume name. " +
"Delimiters (/) not allowed in volume name");
// get info for non-exist volume
args = new String[] {"volume", "info", url + "/invalid-volume"};
executeWithError(shell, args, "VOLUME_NOT_FOUND");
}
@Test
public void testShellIncompleteCommand() throws Exception {
LOG.info("Running testShellIncompleteCommand");
String expectedError = "Incomplete command";
String[] args = new String[] {}; //executing 'ozone sh'
executeWithError(shell, args, expectedError,
"Usage: ozone sh [-hV] [--verbose] [-D=<String=String>]..." +
" [COMMAND]");
args = new String[] {"volume"}; //executing 'ozone sh volume'
executeWithError(shell, args, expectedError,
"Usage: ozone sh volume [-hV] [COMMAND]");
args = new String[] {"bucket"}; //executing 'ozone sh bucket'
executeWithError(shell, args, expectedError,
"Usage: ozone sh bucket [-hV] [COMMAND]");
args = new String[] {"key"}; //executing 'ozone sh key'
executeWithError(shell, args, expectedError,
"Usage: ozone sh key [-hV] [COMMAND]");
}
@Test
public void testUpdateVolume() throws Exception {
LOG.info("Running testUpdateVolume");
String volumeName = "volume" + RandomStringUtils.randomNumeric(5);
String userName = "bilbo";
VolumeArgs volumeArgs = VolumeArgs.newBuilder()
.setOwner("bilbo")
.setQuota("100TB")
.build();
client.createVolume(volumeName, volumeArgs);
OzoneVolume vol = client.getVolumeDetails(volumeName);
assertEquals(userName, vol.getOwner());
assertEquals(OzoneQuota.parseQuota("100TB").sizeInBytes(), vol.getQuota());
String[] args = new String[] {"volume", "update", url + "/" + volumeName,
"--quota", "500MB"};
execute(shell, args);
vol = client.getVolumeDetails(volumeName);
assertEquals(userName, vol.getOwner());
assertEquals(OzoneQuota.parseQuota("500MB").sizeInBytes(), vol.getQuota());
String newUser = "new-user";
args = new String[] {"volume", "update", url + "/" + volumeName,
"--user", newUser};
execute(shell, args);
vol = client.getVolumeDetails(volumeName);
assertEquals(newUser, vol.getOwner());
//volume with / prefix
String volumeWithPrefix = "/" + volumeName;
String newUser2 = "new-user2";
args = new String[] {"volume", "update", url + "/" + volumeWithPrefix,
"--user", newUser2};
execute(shell, args);
vol = client.getVolumeDetails(volumeName);
assertEquals(newUser2, vol.getOwner());
// test error conditions
args = new String[] {"volume", "update", url + "/invalid-volume",
"--user", newUser};
executeWithError(shell, args, "Info Volume failed, error:VOLUME_NOT_FOUND");
err.reset();
args = new String[] {"volume", "update", url + "/invalid-volume",
"--quota", "500MB"};
executeWithError(shell, args, "Info Volume failed, error:VOLUME_NOT_FOUND");
}
/**
* Execute command, assert exeception message and returns true if error
* was thrown.
*/
private void executeWithError(Shell ozoneShell, String[] args,
String expectedError) {
if (Strings.isNullOrEmpty(expectedError)) {
execute(ozoneShell, args);
} else {
try {
execute(ozoneShell, args);
fail("Exception is expected from command execution " + Arrays
.asList(args));
} catch (Exception ex) {
if (!Strings.isNullOrEmpty(expectedError)) {
Throwable exceptionToCheck = ex;
if (exceptionToCheck.getCause() != null) {
exceptionToCheck = exceptionToCheck.getCause();
}
Assert.assertTrue(
String.format(
"Error of shell code doesn't contain the " +
"exception [%s] in [%s]",
expectedError, exceptionToCheck.getMessage()),
exceptionToCheck.getMessage().contains(expectedError));
}
}
}
}
/**
* Execute command, assert exception message and returns true if error
* was thrown and contains the specified usage string.
*/
private void executeWithError(Shell ozoneShell, String[] args,
String expectedError, String usage) {
if (Strings.isNullOrEmpty(expectedError)) {
execute(ozoneShell, args);
} else {
try {
execute(ozoneShell, args);
fail("Exception is expected from command execution " + Arrays
.asList(args));
} catch (Exception ex) {
if (!Strings.isNullOrEmpty(expectedError)) {
Throwable exceptionToCheck = ex;
if (exceptionToCheck.getCause() != null) {
exceptionToCheck = exceptionToCheck.getCause();
}
Assert.assertTrue(
String.format(
"Error of shell code doesn't contain the " +
"exception [%s] in [%s]",
expectedError, exceptionToCheck.getMessage()),
exceptionToCheck.getMessage().contains(expectedError));
Assert.assertTrue(
exceptionToCheck instanceof MissingSubcommandException);
Assert.assertTrue(
((MissingSubcommandException)exceptionToCheck)
.getUsage().contains(usage));
}
}
}
}
@Test
public void testListVolume() throws Exception {
LOG.info("Running testListVolume");
String protocol = clientProtocol.getName().toLowerCase();
String commandOutput, commandError;
List<VolumeInfo> volumes;
final int volCount = 20;
final String user1 = "test-user-a-" + protocol;
final String user2 = "test-user-b-" + protocol;
// Create 20 volumes, 10 for user1 and another 10 for user2.
for (int x = 0; x < volCount; x++) {
String volumeName;
String userName;
if (x % 2 == 0) {
// create volume [test-vol0, test-vol2, ..., test-vol18] for user1
userName = user1;
volumeName = "test-vol-" + protocol + x;
} else {
// create volume [test-vol1, test-vol3, ..., test-vol19] for user2
userName = user2;
volumeName = "test-vol-" + protocol + x;
}
VolumeArgs volumeArgs = VolumeArgs.newBuilder()
.setOwner(userName)
.setQuota("100TB")
.build();
client.createVolume(volumeName, volumeArgs);
OzoneVolume vol = client.getVolumeDetails(volumeName);
assertNotNull(vol);
}
String[] args = new String[] {"volume", "list", url + "/abcde", "--user",
user1, "--length", "100"};
executeWithError(shell, args, "Invalid URI");
err.reset();
// test -length option
args = new String[] {"volume", "list", url + "/", "--user",
user1, "--length", "100"};
execute(shell, args);
commandOutput = out.toString();
volumes = (List<VolumeInfo>) JsonUtils
.toJsonList(commandOutput, VolumeInfo.class);
assertEquals(10, volumes.size());
for (VolumeInfo volume : volumes) {
assertEquals(volume.getOwner().getName(), user1);
assertTrue(volume.getCreatedOn().contains(OzoneConsts.OZONE_TIME_ZONE));
}
out.reset();
args = new String[] {"volume", "list", url + "/", "--user",
user1, "--length", "2"};
execute(shell, args);
commandOutput = out.toString();
volumes = (List<VolumeInfo>) JsonUtils
.toJsonList(commandOutput, VolumeInfo.class);
assertEquals(2, volumes.size());
// test --prefix option
out.reset();
args =
new String[] {"volume", "list", url + "/", "--user", user1, "--length",
"100", "--prefix", "test-vol-" + protocol + "1"};
execute(shell, args);
commandOutput = out.toString();
volumes = (List<VolumeInfo>) JsonUtils
.toJsonList(commandOutput, VolumeInfo.class);
assertEquals(5, volumes.size());
// return volume names should be [test-vol10, test-vol12, ..., test-vol18]
for (int i = 0; i < volumes.size(); i++) {
assertEquals(volumes.get(i).getVolumeName(),
"test-vol-" + protocol + ((i + 5) * 2));
assertEquals(volumes.get(i).getOwner().getName(), user1);
}
// test -start option
out.reset();
args =
new String[] {"volume", "list", url + "/", "--user", user2, "--length",
"100", "--start", "test-vol-" + protocol + "15"};
execute(shell, args);
commandOutput = out.toString();
volumes = (List<VolumeInfo>) JsonUtils
.toJsonList(commandOutput, VolumeInfo.class);
assertEquals(2, volumes.size());
assertEquals(volumes.get(0).getVolumeName(), "test-vol-" + protocol + "17");
assertEquals(volumes.get(1).getVolumeName(), "test-vol-" + protocol + "19");
assertEquals(volumes.get(0).getOwner().getName(), user2);
assertEquals(volumes.get(1).getOwner().getName(), user2);
// test error conditions
err.reset();
args = new String[] {"volume", "list", url + "/", "--user",
user2, "--length", "-1"};
executeWithError(shell, args, "the length should be a positive number");
err.reset();
args = new String[] {"volume", "list", url + "/", "--user",
user2, "--length", "invalid-length"};
executeWithError(shell, args, "For input string: \"invalid-length\"");
}
@Test
public void testCreateBucket() throws Exception {
LOG.info("Running testCreateBucket");
OzoneVolume vol = creatVolume();
String bucketName = "bucket" + RandomStringUtils.randomNumeric(5);
String[] args = new String[] {"bucket", "create",
url + "/" + vol.getName() + "/" + bucketName};
execute(shell, args);
OzoneBucket bucketInfo = vol.getBucket(bucketName);
assertEquals(vol.getName(),
bucketInfo.getVolumeName());
assertEquals(bucketName, bucketInfo.getName());
// test create a bucket in a non-exist volume
args = new String[] {"bucket", "create",
url + "/invalid-volume/" + bucketName};
executeWithError(shell, args, "Info Volume failed, error:VOLUME_NOT_FOUND");
// test createBucket with invalid bucket name
args = new String[] {"bucket", "create",
url + "/" + vol.getName() + "/" + bucketName + "/invalid-name"};
executeWithError(shell, args,
"Invalid bucket name. Delimiters (/) not allowed in bucket name");
}
@Test
public void testDeleteBucket() throws Exception {
LOG.info("Running testDeleteBucket");
OzoneVolume vol = creatVolume();
String bucketName = "bucket" + RandomStringUtils.randomNumeric(5);
vol.createBucket(bucketName);
OzoneBucket bucketInfo = vol.getBucket(bucketName);
assertNotNull(bucketInfo);
String[] args = new String[] {"bucket", "delete",
url + "/" + vol.getName() + "/" + bucketName};
execute(shell, args);
// verify if bucket has been deleted in volume
try {
vol.getBucket(bucketName);
fail("Get bucket should have thrown.");
} catch (IOException e) {
GenericTestUtils.assertExceptionContains(
"Info Bucket failed, error: BUCKET_NOT_FOUND", e);
}
// test delete bucket in a non-exist volume
args = new String[] {"bucket", "delete",
url + "/invalid-volume" + "/" + bucketName};
executeWithError(shell, args, "Info Volume failed, error:VOLUME_NOT_FOUND");
err.reset();
// test delete non-exist bucket
args = new String[] {"bucket", "delete",
url + "/" + vol.getName() + "/invalid-bucket"};
executeWithError(shell, args,
"Delete Bucket failed, error:BUCKET_NOT_FOUND");
}
@Test
public void testInfoBucket() throws Exception {
LOG.info("Running testInfoBucket");
OzoneVolume vol = creatVolume();
String bucketName = "bucket" + RandomStringUtils.randomNumeric(5);
vol.createBucket(bucketName);
String[] args = new String[] {"bucket", "info",
url + "/" + vol.getName() + "/" + bucketName};
execute(shell, args);
String output = out.toString();
assertTrue(output.contains(bucketName));
assertTrue(output.contains("createdOn")
&& output.contains(OzoneConsts.OZONE_TIME_ZONE));
// test infoBucket with invalid bucket name
args = new String[] {"bucket", "info",
url + "/" + vol.getName() + "/" + bucketName + "/invalid-name"};
executeWithError(shell, args,
"Invalid bucket name. Delimiters (/) not allowed in bucket name");
// test get info from a non-exist bucket
args = new String[] {"bucket", "info",
url + "/" + vol.getName() + "/invalid-bucket" + bucketName};
executeWithError(shell, args,
"Info Bucket failed, error: BUCKET_NOT_FOUND");
}
@Test
public void testUpdateBucket() throws Exception {
LOG.info("Running testUpdateBucket");
OzoneVolume vol = creatVolume();
String bucketName = "bucket" + RandomStringUtils.randomNumeric(5);
vol.createBucket(bucketName);
OzoneBucket bucket = vol.getBucket(bucketName);
int aclSize = bucket.getAcls().size();
String[] args = new String[] {"bucket", "update",
url + "/" + vol.getName() + "/" + bucketName, "--addAcl",
"user:frodo:rw,group:samwise:r"};
execute(shell, args);
String output = out.toString();
assertTrue(output.contains("createdOn")
&& output.contains(OzoneConsts.OZONE_TIME_ZONE));
bucket = vol.getBucket(bucketName);
assertEquals(2 + aclSize, bucket.getAcls().size());
OzoneAcl acl = bucket.getAcls().get(aclSize);
assertTrue(acl.getName().equals("frodo")
&& acl.getType() == OzoneACLType.USER
&& acl.getRights()== OzoneACLRights.READ_WRITE);
args = new String[] {"bucket", "update",
url + "/" + vol.getName() + "/" + bucketName, "--removeAcl",
"user:frodo:rw"};
execute(shell, args);
bucket = vol.getBucket(bucketName);
acl = bucket.getAcls().get(aclSize);
assertEquals(1 + aclSize, bucket.getAcls().size());
assertTrue(acl.getName().equals("samwise")
&& acl.getType() == OzoneACLType.GROUP
&& acl.getRights()== OzoneACLRights.READ);
// test update bucket for a non-exist bucket
args = new String[] {"bucket", "update",
url + "/" + vol.getName() + "/invalid-bucket", "--addAcl",
"user:frodo:rw"};
executeWithError(shell, args,
"Info Bucket failed, error: BUCKET_NOT_FOUND");
}
@Test
public void testListBucket() throws Exception {
LOG.info("Running testListBucket");
List<BucketInfo> buckets;
String commandOutput;
int bucketCount = 11;
OzoneVolume vol = creatVolume();
List<String> bucketNames = new ArrayList<>();
// create bucket from test-bucket0 to test-bucket10
for (int i = 0; i < bucketCount; i++) {
String name = "test-bucket" + i;
bucketNames.add(name);
vol.createBucket(name);
OzoneBucket bucket = vol.getBucket(name);
assertNotNull(bucket);
}
// test listBucket with invalid volume name
String[] args = new String[] {"bucket", "list",
url + "/" + vol.getName() + "/invalid-name"};
executeWithError(shell, args, "Invalid volume name. " +
"Delimiters (/) not allowed in volume name");
// test -length option
args = new String[] {"bucket", "list",
url + "/" + vol.getName(), "--length", "100"};
execute(shell, args);
commandOutput = out.toString();
buckets = (List<BucketInfo>) JsonUtils.toJsonList(commandOutput,
BucketInfo.class);
assertEquals(11, buckets.size());
// sort bucket names since the return buckets isn't in created order
Collections.sort(bucketNames);
// return bucket names should be [test-bucket0, test-bucket1,
// test-bucket10, test-bucket2, ,..., test-bucket9]
for (int i = 0; i < buckets.size(); i++) {
assertEquals(buckets.get(i).getBucketName(), bucketNames.get(i));
assertEquals(buckets.get(i).getVolumeName(), vol.getName());
assertTrue(buckets.get(i).getCreatedOn()
.contains(OzoneConsts.OZONE_TIME_ZONE));
}
out.reset();
args = new String[] {"bucket", "list", url + "/" + vol.getName(),
"--length", "3"};
execute(shell, args);
commandOutput = out.toString();
buckets = (List<BucketInfo>) JsonUtils.toJsonList(commandOutput,
BucketInfo.class);
assertEquals(3, buckets.size());
// return bucket names should be [test-bucket0,
// test-bucket1, test-bucket10]
assertEquals(buckets.get(0).getBucketName(), "test-bucket0");
assertEquals(buckets.get(1).getBucketName(), "test-bucket1");
assertEquals(buckets.get(2).getBucketName(), "test-bucket10");
// test --prefix option
out.reset();
args = new String[] {"bucket", "list", url + "/" + vol.getName(),
"--length", "100", "--prefix", "test-bucket1"};
execute(shell, args);
commandOutput = out.toString();
buckets = (List<BucketInfo>) JsonUtils.toJsonList(commandOutput,
BucketInfo.class);
assertEquals(2, buckets.size());
// return bucket names should be [test-bucket1, test-bucket10]
assertEquals(buckets.get(0).getBucketName(), "test-bucket1");
assertEquals(buckets.get(1).getBucketName(), "test-bucket10");
// test -start option
out.reset();
args = new String[] {"bucket", "list", url + "/" + vol.getName(),
"--length", "100", "--start", "test-bucket7"};
execute(shell, args);
commandOutput = out.toString();
buckets = (List<BucketInfo>) JsonUtils.toJsonList(commandOutput,
BucketInfo.class);
assertEquals(2, buckets.size());
assertEquals(buckets.get(0).getBucketName(), "test-bucket8");
assertEquals(buckets.get(1).getBucketName(), "test-bucket9");
// test error conditions
err.reset();
args = new String[] {"bucket", "list", url + "/" + vol.getName(),
"--length", "-1"};
executeWithError(shell, args, "the length should be a positive number");
}
@Test
public void testPutKey() throws Exception {
LOG.info("Running testPutKey");
OzoneBucket bucket = creatBucket();
String volumeName = bucket.getVolumeName();
String bucketName = bucket.getName();
String keyName = "key" + RandomStringUtils.randomNumeric(5);
String[] args = new String[] {"key", "put",
url + "/" + volumeName + "/" + bucketName + "/" + keyName,
createTmpFile()};
execute(shell, args);
OzoneKey keyInfo = bucket.getKey(keyName);
assertEquals(keyName, keyInfo.getName());
// test put key in a non-exist bucket
args = new String[] {"key", "put",
url + "/" + volumeName + "/invalid-bucket/" + keyName,
createTmpFile()};
executeWithError(shell, args,
"Info Bucket failed, error: BUCKET_NOT_FOUND");
}
@Test
public void testGetKey() throws Exception {
LOG.info("Running testGetKey");
String keyName = "key" + RandomStringUtils.randomNumeric(5);
OzoneBucket bucket = creatBucket();
String volumeName = bucket.getVolumeName();
String bucketName = bucket.getName();
String dataStr = "test-data";
OzoneOutputStream keyOutputStream =
bucket.createKey(keyName, dataStr.length());
keyOutputStream.write(dataStr.getBytes());
keyOutputStream.close();
String tmpPath = baseDir.getAbsolutePath() + "/testfile-"
+ UUID.randomUUID().toString();
String[] args = new String[] {"key", "get",
url + "/" + volumeName + "/" + bucketName + "/" + keyName,
tmpPath};
execute(shell, args);
byte[] dataBytes = new byte[dataStr.length()];
try (FileInputStream randFile = new FileInputStream(new File(tmpPath))) {
randFile.read(dataBytes);
}
assertEquals(dataStr, DFSUtil.bytes2String(dataBytes));
tmpPath = baseDir.getAbsolutePath() + File.separatorChar + keyName;
args = new String[] {"key", "get",
url + "/" + volumeName + "/" + bucketName + "/" + keyName,
baseDir.getAbsolutePath()};
execute(shell, args);
dataBytes = new byte[dataStr.length()];
try (FileInputStream randFile = new FileInputStream(new File(tmpPath))) {
randFile.read(dataBytes);
}
assertEquals(dataStr, DFSUtil.bytes2String(dataBytes));
}
@Test
public void testDeleteKey() throws Exception {
LOG.info("Running testDeleteKey");
String keyName = "key" + RandomStringUtils.randomNumeric(5);
OzoneBucket bucket = creatBucket();
String volumeName = bucket.getVolumeName();
String bucketName = bucket.getName();
String dataStr = "test-data";
OzoneOutputStream keyOutputStream =
bucket.createKey(keyName, dataStr.length());
keyOutputStream.write(dataStr.getBytes());
keyOutputStream.close();
OzoneKey keyInfo = bucket.getKey(keyName);
assertEquals(keyName, keyInfo.getName());
String[] args = new String[] {"key", "delete",
url + "/" + volumeName + "/" + bucketName + "/" + keyName};
execute(shell, args);
// verify if key has been deleted in the bucket
try {
bucket.getKey(keyName);
fail("Get key should have thrown.");
} catch (IOException e) {
GenericTestUtils.assertExceptionContains(
"Lookup key failed, error:KEY_NOT_FOUND", e);
}
// test delete key in a non-exist bucket
args = new String[] {"key", "delete",
url + "/" + volumeName + "/invalid-bucket/" + keyName};
executeWithError(shell, args,
"Info Bucket failed, error: BUCKET_NOT_FOUND");
err.reset();
// test delete a non-exist key in bucket
args = new String[] {"key", "delete",
url + "/" + volumeName + "/" + bucketName + "/invalid-key"};
executeWithError(shell, args, "Delete key failed, error:KEY_NOT_FOUND");
}
@Test
public void testInfoKeyDetails() throws Exception {
LOG.info("Running testInfoKey");
String keyName = "key" + RandomStringUtils.randomNumeric(5);
OzoneBucket bucket = creatBucket();
String volumeName = bucket.getVolumeName();
String bucketName = bucket.getName();
String dataStr = "test-data";
OzoneOutputStream keyOutputStream =
bucket.createKey(keyName, dataStr.length());
keyOutputStream.write(dataStr.getBytes());
keyOutputStream.close();
String[] args = new String[] {"key", "info",
url + "/" + volumeName + "/" + bucketName + "/" + keyName};
// verify the response output
execute(shell, args);
String output = out.toString();
assertTrue(output.contains(keyName));
assertTrue(
output.contains("createdOn") && output.contains("modifiedOn") && output
.contains(OzoneConsts.OZONE_TIME_ZONE));
assertTrue(
output.contains("containerID") && output.contains("localID") && output
.contains("length") && output.contains("offset"));
// reset stream
out.reset();
err.reset();
// get the info of a non-exist key
args = new String[] {"key", "info",
url + "/" + volumeName + "/" + bucketName + "/invalid-key"};
// verify the response output
// get the non-exist key info should be failed
executeWithError(shell, args, "Lookup key failed, error:KEY_NOT_FOUND");
}
@Test
public void testInfoDirKey() throws Exception {
LOG.info("Running testInfoKey for Dir Key");
String dirKeyName = "test/";
String keyNameOnly = "test";
OzoneBucket bucket = creatBucket();
String volumeName = bucket.getVolumeName();
String bucketName = bucket.getName();
String dataStr = "test-data";
OzoneOutputStream keyOutputStream =
bucket.createKey(dirKeyName, dataStr.length());
keyOutputStream.write(dataStr.getBytes());
keyOutputStream.close();
String[] args = new String[] {"key", "info",
url + "/" + volumeName + "/" + bucketName + "/" + dirKeyName};
// verify the response output
execute(shell, args);
String output = out.toString();
assertTrue(output.contains(dirKeyName));
assertTrue(output.contains("createdOn") &&
output.contains("modifiedOn") &&
output.contains(OzoneConsts.OZONE_TIME_ZONE));
args = new String[] {"key", "info",
url + "/" + volumeName + "/" + bucketName + "/" + keyNameOnly};
executeWithError(shell, args, "Lookup key failed, error:KEY_NOT_FOUND");
out.reset();
err.reset();
}
@Test
public void testListKey() throws Exception {
LOG.info("Running testListKey");
String commandOutput;
List<KeyInfo> keys;
int keyCount = 11;
OzoneBucket bucket = creatBucket();
String volumeName = bucket.getVolumeName();
String bucketName = bucket.getName();
String keyName;
List<String> keyNames = new ArrayList<>();
for (int i = 0; i < keyCount; i++) {
keyName = "test-key" + i;
keyNames.add(keyName);
String dataStr = "test-data";
OzoneOutputStream keyOutputStream =
bucket.createKey(keyName, dataStr.length());
keyOutputStream.write(dataStr.getBytes());
keyOutputStream.close();
}
// test listKey with invalid bucket name
String[] args = new String[] {"key", "list",
url + "/" + volumeName + "/" + bucketName + "/invalid-name"};
executeWithError(shell, args, "Invalid bucket name. " +
"Delimiters (/) not allowed in bucket name");
// test -length option
args = new String[] {"key", "list",
url + "/" + volumeName + "/" + bucketName, "--length", "100"};
execute(shell, args);
commandOutput = out.toString();
keys = (List<KeyInfo>) JsonUtils.toJsonList(commandOutput,
KeyInfo.class);
assertEquals(11, keys.size());
// sort key names since the return keys isn't in created order
Collections.sort(keyNames);
// return key names should be [test-key0, test-key1,
// test-key10, test-key2, ,..., test-key9]
for (int i = 0; i < keys.size(); i++) {
assertEquals(keys.get(i).getKeyName(), keyNames.get(i));
// verify the creation/modification time of key
assertTrue(keys.get(i).getCreatedOn()
.contains(OzoneConsts.OZONE_TIME_ZONE));
assertTrue(keys.get(i).getModifiedOn()
.contains(OzoneConsts.OZONE_TIME_ZONE));
}
out.reset();
args =
new String[] {"key", "list", url + "/" + volumeName + "/" + bucketName,
"--length", "3"};
execute(shell, args);
commandOutput = out.toString();
keys = (List<KeyInfo>) JsonUtils.toJsonList(commandOutput,
KeyInfo.class);
assertEquals(3, keys.size());
// return key names should be [test-key0, test-key1, test-key10]
assertEquals(keys.get(0).getKeyName(), "test-key0");
assertEquals(keys.get(1).getKeyName(), "test-key1");
assertEquals(keys.get(2).getKeyName(), "test-key10");
// test --prefix option
out.reset();
args =
new String[] {"key", "list", url + "/" + volumeName + "/" + bucketName,
"--length", "100", "--prefix", "test-key1"};
execute(shell, args);
commandOutput = out.toString();
keys = (List<KeyInfo>) JsonUtils.toJsonList(commandOutput,
KeyInfo.class);
assertEquals(2, keys.size());
// return key names should be [test-key1, test-key10]
assertEquals(keys.get(0).getKeyName(), "test-key1");
assertEquals(keys.get(1).getKeyName(), "test-key10");
// test -start option
out.reset();
args =
new String[] {"key", "list", url + "/" + volumeName + "/" + bucketName,
"--length", "100", "--start", "test-key7"};
execute(shell, args);
commandOutput = out.toString();
keys = (List<KeyInfo>) JsonUtils.toJsonList(commandOutput,
KeyInfo.class);
assertEquals(keys.get(0).getKeyName(), "test-key8");
assertEquals(keys.get(1).getKeyName(), "test-key9");
// test error conditions
err.reset();
args =
new String[] {"key", "list", url + "/" + volumeName + "/" + bucketName,
"--length", "-1"};
executeWithError(shell, args, "the length should be a positive number");
}
@Test
public void testS3BucketMapping() throws IOException {
List<ServiceInfo> services =
cluster.getOzoneManager().getServiceList();
String omHostName = services.stream().filter(
a -> a.getNodeType().equals(HddsProtos.NodeType.OM))
.collect(Collectors.toList()).get(0).getHostname();
String omPort = cluster.getOzoneManager().getRpcPort();
String setOmAddress =
"--set=" + OZONE_OM_ADDRESS_KEY + "=" + omHostName + ":" + omPort;
String s3Bucket = "bucket1";
String commandOutput;
createS3Bucket("ozone", s3Bucket);
//WHEN
String[] args =
new String[] {setOmAddress, "bucket",
"path", s3Bucket};
execute(shell, args);
//THEN
commandOutput = out.toString();
String volumeName = client.getOzoneVolumeName(s3Bucket);
assertTrue(commandOutput.contains("Volume name for S3Bucket is : " +
volumeName));
assertTrue(commandOutput.contains(OzoneConsts.OZONE_URI_SCHEME + "://" +
s3Bucket + "." + volumeName));
out.reset();
//Trying to get map for an unknown bucket
args = new String[] {setOmAddress, "bucket", "path",
"unknownbucket"};
executeWithError(shell, args, "S3_BUCKET_NOT_FOUND");
// No bucket name
args = new String[] {setOmAddress, "bucket", "path"};
executeWithError(shell, args, "Missing required parameter");
// Invalid bucket name
args = new String[] {setOmAddress, "bucket", "path", "/asd/multipleslash"};
executeWithError(shell, args, "S3_BUCKET_NOT_FOUND");
}
private void createS3Bucket(String userName, String s3Bucket) {
try {
client.createS3Bucket("ozone", s3Bucket);
} catch (IOException ex) {
GenericTestUtils.assertExceptionContains("S3_BUCKET_ALREADY_EXISTS", ex);
}
}
private OzoneVolume creatVolume() throws OzoneException, IOException {
String volumeName = RandomStringUtils.randomNumeric(5) + "volume";
VolumeArgs volumeArgs = VolumeArgs.newBuilder()
.setOwner("bilbo")
.setQuota("100TB")
.build();
try {
client.createVolume(volumeName, volumeArgs);
} catch (Exception ex) {
Assert.assertEquals("PartialGroupNameException",
ex.getCause().getClass().getSimpleName());
}
OzoneVolume volume = client.getVolumeDetails(volumeName);
return volume;
}
private OzoneBucket creatBucket() throws OzoneException, IOException {
OzoneVolume vol = creatVolume();
String bucketName = RandomStringUtils.randomNumeric(5) + "bucket";
vol.createBucket(bucketName);
OzoneBucket bucketInfo = vol.getBucket(bucketName);
return bucketInfo;
}
/**
* Create a temporary file used for putting key.
* @return the created file's path string
* @throws Exception
*/
private String createTmpFile() throws Exception {
// write a new file that used for putting key
File tmpFile = new File(baseDir,
"/testfile-" + UUID.randomUUID().toString());
FileOutputStream randFile = new FileOutputStream(tmpFile);
Random r = new Random();
for (int x = 0; x < 10; x++) {
char c = (char) (r.nextInt(26) + 'a');
randFile.write(c);
}
randFile.close();
return tmpFile.getAbsolutePath();
}
}
| xiao-chen/hadoop | hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/ozShell/TestOzoneShell.java | Java | apache-2.0 | 43,840 |
require 'pad_utils'
require_relative '../template/test'
# Test name
test_name = "ZipExtractZip"
class ZipExtractZipTest < Test
def prepare
# Add test preparation here
end
def run_test
PadUtils.extract_zip("fixtures/archive.zip", "results/extracted")
if !PadUtils.file_exist?("results/extracted/penguin02.jpg") || !PadUtils.file_exist?("results/extracted/others/panda.jpg")
@errors << "Seems files were not extracted"
end
end
def cleanup
# Add cleanup code here
end
end
| nicoschuele/pad_utils | test/units/zip_extract_zip_test.rb | Ruby | apache-2.0 | 514 |
/*
+----------------------------------------------------------------------+
| PHP Version 5 |
+----------------------------------------------------------------------+
| Copyright 2012 Couchbase, 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. |
+----------------------------------------------------------------------+
*/
#include "internal.h"
/* @todo This is a copy of the logic used by the cluster management
* I should refactor this out so I have a generic http execution
* method.
*/
struct flush_ctx {
lcb_error_t error;
lcb_http_status_t status;
char *payload;
};
static void rest_flush_callback(lcb_http_request_t request,
lcb_t instance,
const void *cookie,
lcb_error_t error,
const lcb_http_resp_t *resp)
{
struct flush_ctx *ctx = (void *)cookie;
assert(cookie != NULL);
ctx->error = error;
ctx->payload = NULL;
if (resp->version != 0) {
/* @todo add an error code I may use */
ctx->error = LCB_NOT_SUPPORTED;
} else {
ctx->status = resp->v.v0.status;
if (resp->v.v0.nbytes != 0) {
ctx->payload = emalloc(resp->v.v0.nbytes + 1);
if (ctx->payload != NULL) {
memcpy(ctx->payload, resp->v.v0.bytes, resp->v.v0.nbytes);
ctx->payload[resp->v.v0.nbytes] = '\0';
}
}
}
}
static void do_rest_flush(INTERNAL_FUNCTION_PARAMETERS,
int oo,
php_couchbase_res *res)
{
struct flush_ctx ctx;
lcb_error_t rc;
lcb_http_cmd_t cmd;
lcb_t instance;
char *path;
lcb_http_complete_callback old;
instance = res->handle;
path = ecalloc(strlen(res->bucket) + 80, 1);
sprintf(path, "/pools/default/buckets/%s/controller/doFlush",
res->bucket);
memset(&ctx, 0, sizeof(ctx));
memset(&cmd, 0, sizeof(cmd));
cmd.v.v0.path = path;
cmd.v.v0.npath = strlen(path);
cmd.v.v0.method = LCB_HTTP_METHOD_POST;
cmd.v.v0.content_type = "application/x-www-form-urlencoded";
old = lcb_set_http_complete_callback(instance, rest_flush_callback);
rc = lcb_make_http_request(instance, &ctx, LCB_HTTP_TYPE_MANAGEMENT,
&cmd, NULL);
old = lcb_set_http_complete_callback(instance, old);
efree(path);
if (rc == LCB_SUCCESS) {
rc = ctx.error;
}
res->rc = rc;
if (rc != LCB_SUCCESS) {
/* An error occured occurred on libcouchbase level */
if (ctx.payload) {
efree(ctx.payload);
}
couchbase_report_error(INTERNAL_FUNCTION_PARAM_PASSTHRU, oo,
cb_lcb_exception, "Failed to flush bucket: %s",
lcb_strerror(instance, rc));
return;
}
switch (ctx.status) {
case LCB_HTTP_STATUS_OK:
case LCB_HTTP_STATUS_ACCEPTED:
efree(ctx.payload);
RETURN_TRUE;
case LCB_HTTP_STATUS_UNAUTHORIZED:
couchbase_report_error(INTERNAL_FUNCTION_PARAM_PASSTHRU, oo,
cb_auth_exception, "Incorrect credentials");
break;
default:
if (ctx.payload == NULL) {
couchbase_report_error(INTERNAL_FUNCTION_PARAM_PASSTHRU, oo,
cb_server_exception,
"{\"errors\":{\"http response\": %d }}",
(int)ctx.status);
} else {
couchbase_report_error(INTERNAL_FUNCTION_PARAM_PASSTHRU, oo,
cb_server_exception,
ctx.payload);
}
}
if (ctx.payload != NULL) {
efree(ctx.payload);
}
}
static void memcached_flush_callback(lcb_t handle,
const void *cookie,
lcb_error_t error,
const lcb_flush_resp_t *resp)
{
if (error != LCB_SUCCESS) {
*((lcb_error_t *)cookie) = error;
}
}
static void do_memcached_flush(INTERNAL_FUNCTION_PARAMETERS,
int oo,
php_couchbase_res *res)
{
lcb_error_t retval;
lcb_error_t cberr = LCB_SUCCESS;
lcb_flush_cmd_t cmd;
const lcb_flush_cmd_t *const commands[] = { &cmd };
lcb_t instance;
instance = res->handle;
memset(&cmd, 0, sizeof(cmd));
lcb_set_flush_callback(instance, memcached_flush_callback);
retval = lcb_flush(instance, (const void *)&cberr, 1, commands);
if (retval == LCB_SUCCESS) {
retval = cberr;
}
res->rc = retval;
if (retval == LCB_SUCCESS) {
RETURN_TRUE;
} else {
char errmsg[256];
sprintf(errmsg, "Failed to flush bucket: %s",
lcb_strerror(instance, retval));
couchbase_report_error(INTERNAL_FUNCTION_PARAM_PASSTHRU, oo,
cb_lcb_exception, errmsg);
}
}
PHP_COUCHBASE_LOCAL
void php_couchbase_flush_impl(INTERNAL_FUNCTION_PARAMETERS, int oo)
{
php_couchbase_res *res;
lcb_t instance;
int argflags = oo ? PHP_COUCHBASE_ARG_F_OO : PHP_COUCHBASE_ARG_F_FUNCTIONAL;
PHP_COUCHBASE_GET_PARAMS(res, argflags, "");
instance = res->handle;
lcb_behavior_set_syncmode(instance, LCB_SYNCHRONOUS);
if (COUCHBASE_G(restflush)) {
do_rest_flush(INTERNAL_FUNCTION_PARAM_PASSTHRU, oo, res);
} else {
do_memcached_flush(INTERNAL_FUNCTION_PARAM_PASSTHRU, oo, res);
}
lcb_behavior_set_syncmode(instance, LCB_ASYNCHRONOUS);
}
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
| couchbase/php-ext-couchbase | flush.c | C | apache-2.0 | 5,684 |
/*
* Copyright 2015 Adaptris Ltd.
*
* 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.adaptris.core.services.jdbc;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import org.junit.Test;
import com.adaptris.core.CoreException;
import com.adaptris.core.jdbc.JdbcConnection;
import com.adaptris.core.util.JdbcUtil;
import com.adaptris.core.util.LifecycleHelper;
import com.adaptris.util.KeyValuePair;
import com.adaptris.util.KeyValuePairSet;
public abstract class JdbcMapInsertCase {
protected static final String CONTENT =
"firstname=alice\n" +
"lastname=smith\n" +
"dob=2017-01-01";
protected static final String INVALID_COLUMN =
"fi$rstname=alice\n" + "la$stname=smith\n" + "dob=2017-01-01";
protected static final String JDBC_DRIVER = "org.apache.derby.jdbc.EmbeddedDriver";
protected static final String JDBC_URL = "jdbc:derby:memory:JDCB_OBJ_DB;create=true";
protected static final String TABLE_NAME = "people";
protected static final String DROP_STMT = String.format("DROP TABLE %s", TABLE_NAME);
protected static final String CREATE_STMT = String.format("CREATE TABLE %s (firstname VARCHAR(128) NOT NULL, "
+ "lastname VARCHAR(128) NOT NULL, "
+ "dob DATE)",
TABLE_NAME);
protected static final String CREATE_QUOTED = String.format(
"CREATE TABLE %s (\"firstname\" VARCHAR(128) NOT NULL, \"lastname\" VARCHAR(128) NOT NULL, \"dob\" DATE)", TABLE_NAME);
@Test
public void testService_Init() throws Exception {
JdbcMapInsert service = createService();
try {
LifecycleHelper.init(service);
fail();
} catch (CoreException expected) {
}
service.setTable("hello");
LifecycleHelper.init(service);
}
protected abstract JdbcMapInsert createService();
protected static void doAssert(int expectedCount) throws Exception {
Connection c = null;
PreparedStatement p = null;
try {
c = createConnection();
p = c.prepareStatement(String.format("SELECT * FROM %s", TABLE_NAME));
ResultSet rs = p.executeQuery();
int count = 0;
while (rs.next()) {
count++;
assertEquals("smith", rs.getString("lastname"));
}
assertEquals(expectedCount, count);
JdbcUtil.closeQuietly(rs);
} finally {
JdbcUtil.closeQuietly(p);
JdbcUtil.closeQuietly(c);
}
}
protected static Connection createConnection() throws Exception {
Connection c = null;
Class.forName(JDBC_DRIVER);
c = DriverManager.getConnection(JDBC_URL);
c.setAutoCommit(true);
return c;
}
protected static void createDatabase() throws Exception {
createDatabase(CREATE_STMT);
}
protected static void createDatabase(String createStmt) throws Exception {
Connection c = null;
Statement s = null;
try {
c = createConnection();
s = c.createStatement();
executeQuietly(s, DROP_STMT);
s.execute(createStmt);
}
finally {
JdbcUtil.closeQuietly(s);
JdbcUtil.closeQuietly(c);
}
}
protected static void executeQuietly(Statement s, String sql) {
try {
s.execute(sql);
} catch (Exception e) {
;
}
}
protected static <T extends JdbcMapInsert> T configureForTests(T t) {
JdbcMapInsert service = t;
JdbcConnection connection = new JdbcConnection();
connection.setConnectUrl(JDBC_URL);
connection.setDriverImp(JDBC_DRIVER);
service.setConnection(connection);
KeyValuePairSet mappings = new KeyValuePairSet();
mappings.add(new KeyValuePair("dob", JdbcMapInsert.BasicType.Date.name()));
service.withTable(TABLE_NAME).withMappings(mappings);
return t;
}
}
| adaptris/interlok | interlok-core/src/test/java/com/adaptris/core/services/jdbc/JdbcMapInsertCase.java | Java | apache-2.0 | 4,375 |
/*
* Project Scelight
*
* Copyright (c) 2013 Andras Belicza <[email protected]>
*
* This software is the property of Andras Belicza.
* Copying, modifying, distributing, refactoring without the author's permission
* is prohibited and protected by Law.
*/
package hu.scelight.gui.page.replist.column.impl;
import hu.scelight.gui.icon.Icons;
import hu.scelight.gui.page.replist.column.BaseColumn;
import hu.scelight.sc2.rep.repproc.RepProcessor;
import java.util.Date;
/**
* Replay date column.
*
* @author Andras Belicza
*/
public class DateColumn extends BaseColumn< Date > {
/**
* Creates a new {@link DateColumn}.
*/
public DateColumn() {
super( "Date", Icons.F_CALENDAR_BLUE, "Replay date", Date.class, true );
}
@Override
public Date getData( final RepProcessor repProc ) {
return repProc.replay.details.getTime();
}
}
| icza/scelight | src-app/hu/scelight/gui/page/replist/column/impl/DateColumn.java | Java | apache-2.0 | 896 |
# Shrinker
`Shrinker` will remove all R.class and R\$\*\*.class and all constant integer fields will be inlined by [`asm`](http://asm.ow2.org/) and [`transform-api`](http://tools.android.com/tech-docs/new-build-system/transform-api).
*I have post more details on my own blog (in Chinese), [click here](http://yrom.net/blog/2018/01/12/android-gradle-plugin-for-shrinking-fields-in-dex/) to check it out.*
## Usage
 You can get `shrinker` from [jitpack](https://jitpack.io)
To apply `shrinker` to your android application:
**Step1.** Add it in your `buildscript` section of app's build.gradle
```
buildscript {
repositories {
//...
maven { url 'https://jitpack.io' }
}
dependencies {
classpath 'net.yrom:shrinker:0.2.9'
}
}
```
**Step2.** Apply it **after** the Android plugin
```
apply plugin: 'com.android.application'
//...
apply plugin: 'net.yrom.shrinker'
```
**NOTE** that `shrinker` plugin requires android gradle build tools version at least 3.0.0 and it will be disabled if run in debug build.
### Show case
There is a small [test](tree/master/test) application which depends on so many support libraries, would show how many fields `shrinked`.
Run with `shrinker`:
```
./gradlew :test:assembleRelease -PENABLE_SHRINKER
```
Run with `removeUnusedCode`:
```groovy
android {
buildTypes {
release {
...
postprocessing {
removeUnusedCode = true
}
}
}
...
}
```
Content below counts by [dexcount-gradle-plugin](https://github.com/KeepSafe/dexcount-gradle-plugin)
| options | methods | fields | classes |
| --------------------------- | ------- | ------ | ------- |
| origin | 22164 | 14367 | 2563 |
| shrinker | 21979 | 7805 | 2392 |
| removeUnusedCode | 11338 | 6655 | 1296 |
| shrinker & removeUnusedCode | 11335 | 3302 | 1274 |
## License
```
Copyright 2017 Yrom
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.
``` | yrom/shrinker | README.md | Markdown | apache-2.0 | 2,606 |
"""Tests for the CSRF helper."""
import unittest
import mock
import webapp2
import webtest
from ctc.helpers import csrf
from ctc.testing import testutil
MOCKED_TIME = 123
# Tests don't need docstrings, so pylint: disable=C0111
# Tests can test protected members, so pylint: disable=W0212
class CsrfTests(testutil.CtcTestCase):
# Helpers
class TestHandler(csrf.CsrfHandler):
"""A handler for testing whether or not requests are CSRF protected."""
def get(self):
self.response.write('CSRF Token:%s' % self.csrf_token)
def post(self):
pass
def put(self):
pass
def delete(self):
pass
def setUp(self):
super(CsrfTests, self).setUp()
# The CSRF library uses the time, so we mock it out.
self.time_mock = mock.Mock()
csrf.time = self.time_mock
self.time_mock.time = mock.Mock(return_value=MOCKED_TIME)
# The handler tests need a WSGIApplication.
app = webapp2.WSGIApplication([('/', self.TestHandler)])
self.testapp = webtest.TestApp(app)
def test_get_secret_key(self):
first_key = csrf._get_secret_key()
self.assertEqual(len(first_key), 32)
second_key = csrf._get_secret_key()
self.assertEqual(first_key, second_key)
def test_tokens_are_equal(self):
# It should fail if the tokens aren't equal length.
self.assertFalse(csrf._tokens_are_equal('a', 'ab'))
# It should fail if the tokens are different.
self.assertFalse(csrf._tokens_are_equal('abcde', 'abcdf'))
# It should succeed if the tokens are the same.
self.assertTrue(csrf._tokens_are_equal('abcde', 'abcde'))
# Make Token
def test_make_token_includes_time(self):
self.login()
# It should get the current time.
token1 = csrf.make_token()
self.assertEqual(token1.split()[-1], str(MOCKED_TIME))
# It should use the provided time.
token2 = csrf.make_token(token_time='456')
self.assertEqual(token2.split()[-1], '456')
# Different time should cause the digest to be different.
self.assertNotEqual(token1.split()[0], token2.split()[0])
token3 = csrf.make_token(token_time='456')
self.assertEqual(token2, token3)
def test_make_token_requires_login(self):
token1 = csrf.make_token()
self.assertIsNone(token1)
self.login()
token2 = csrf.make_token()
self.assertIsNotNone(token2)
def test_make_token_includes_path(self):
self.login()
# It should get the current path.
self.testbed.setup_env(PATH_INFO='/action/1', overwrite=True)
token1 = csrf.make_token(token_time='123')
self.testbed.setup_env(PATH_INFO='/action/23', overwrite=True)
token2 = csrf.make_token(token_time='123')
token3 = csrf.make_token(token_time='123')
self.assertNotEqual(token1, token2)
self.assertEqual(token2, token3)
# It should let the client pass in a path.
token4 = csrf.make_token(path='/action/4', token_time='123')
token5 = csrf.make_token(path='/action/56', token_time='123')
token6 = csrf.make_token(path='/action/56', token_time='123')
self.assertNotEqual(token4, token5)
self.assertEqual(token5, token6)
# Token Is Valid
def test_token_is_valid(self):
self.login()
# Token is required.
self.assertFalse(csrf.token_is_valid(None))
# Token needs to have a timestamp on it.
self.assertFalse(csrf.token_is_valid('hello'))
# The timestamp needs to be within the current date range.
self.time_mock.time = mock.Mock(return_value=9999999999999)
self.assertFalse(csrf.token_is_valid('hello 123'))
# The user needs to be logged in.
token = csrf.make_token()
self.logout()
self.assertFalse(csrf.token_is_valid(token))
self.login()
# Modifying the token should break everything.
modified_token = '0' + token[1:]
if token == modified_token:
modified_token = '1' + token[1:]
self.assertFalse(csrf.token_is_valid(modified_token))
# The original token that we got should work.
self.assertTrue(csrf.token_is_valid(token))
def test_get_has_csrf_token(self):
self.login()
response = self.testapp.get('/', status=200).body
self.assertIn('CSRF Token:', response)
self.assertEqual(response.split(':')[-1], csrf.make_token())
def test_mutators_require_csrf_token(self):
self.login()
self.testapp.put('/', status=403)
self.testapp.post('/', status=403)
self.testapp.delete('/', status=403)
csrf_param = 'csrf_token=' + csrf.make_token(path='/')
self.testapp.put('/', params=csrf_param, status=200)
self.testapp.post('/', params=csrf_param, status=200)
# Though the spec allows DELETE to have a body, it tends to be ignored
# by servers (http://stackoverflow.com/questions/299628), and webapp2
# ignores it as well, so we have to put the params in the URL.
self.testapp.delete('/?' + csrf_param, status=200)
if __name__ == '__main__':
unittest.main()
| samking/code-the-change-projects | ctc/helpers/csrf_test.py | Python | apache-2.0 | 5,296 |
/*
* #%L
* FlatPack serialization code
* %%
* Copyright (C) 2012 Perka 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.
* #L%
*/
package com.getperka.flatpack.codex;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import javax.inject.Inject;
import org.junit.Test;
import com.getperka.flatpack.FlatPackTest;
import com.getperka.flatpack.HasUuid;
import com.getperka.flatpack.codexes.ArrayCodex;
import com.getperka.flatpack.codexes.ListCodex;
import com.getperka.flatpack.codexes.SetCodex;
import com.getperka.flatpack.domain.Employee;
import com.getperka.flatpack.domain.Person;
import com.getperka.flatpack.util.FlatPackCollections;
import com.google.inject.TypeLiteral;
/**
* Tests serializing collections of things.
*/
public class CollectionCodexTest extends FlatPackTest {
@Inject
private TypeLiteral<ArrayCodex<Person>> arrayPerson;
@Inject
private TypeLiteral<ArrayCodex<String>> arrayString;
@Inject
private TypeLiteral<ListCodex<Person>> listPerson;
@Inject
private TypeLiteral<ListCodex<String>> listString;
@Inject
private TypeLiteral<SetCodex<String>> setString;
@Inject
private Employee employee;
@Test
public void testArray() {
String[] in = { "Hello", " ", "", null, "World!" };
String[] out = testCodex(arrayString, in);
assertArrayEquals(in, out);
Set<HasUuid> scanned = FlatPackCollections.setForIteration();
Employee[] in2 = { employee, null, employee };
Person[] out2 = testCodex(arrayPerson, in2, scanned);
assertEquals(Collections.singleton(employee), scanned);
/*
* Because we're testing without a full flatpack structure, all we can expect is that a HasUuid
* is created with the same UUID. The concrete type would normally be specified in the data
* section, however it is missing, so we expect the configured type of the codex instead.
*/
Person p = out2[0];
assertNotNull(p);
assertEquals(Person.class, p.getClass());
assertEquals(employee.getUuid(), p.getUuid());
}
@Test
public void testList() {
List<String> in = Arrays.asList("Hello", " ", "", null, "World!");
Collection<String> out = testCodex(listString, in);
assertEquals(in, out);
Set<HasUuid> scanned = FlatPackCollections.setForIteration();
List<Person> in2 = Arrays.<Person> asList(employee, null, employee);
Collection<Person> out2 = testCodex(listPerson, in2, scanned);
assertEquals(Collections.singleton(employee), scanned);
/*
* Because we're testing without a full flatpack structure, all we can expect is that a HasUuid
* is created with the same UUID. The concrete type would normally be specified in the data
* section, however it is missing, so we expect the configured type of the codex instead.
*/
Person p = ((List<Person>) out2).get(0);
assertNotNull(p);
assertEquals(Person.class, p.getClass());
assertEquals(employee.getUuid(), p.getUuid());
}
@Test
public void testNull() {
assertNull(testCodex(arrayString, null));
assertNull(testCodex(listString, null));
assertNull(testCodex(setString, null));
}
@Test
public void testSet() {
Set<String> in = new LinkedHashSet<String>(Arrays.asList("Hello", " ", "", null, "World!"));
Set<String> out = testCodex(setString, in);
assertEquals(in, out);
}
}
| perka/flatpack-java | core/src/test/java/com/getperka/flatpack/codex/CollectionCodexTest.java | Java | apache-2.0 | 4,155 |
/**
* FreeRDP: A Remote Desktop Protocol Implementation
* RDP Settings
*
* Copyright 2009-2011 Jay Sorg
*
* 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.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "certificate.h"
#include "capabilities.h"
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <ctype.h>
#include <winpr/crt.h>
#include <winpr/file.h>
#include <winpr/path.h>
#include <winpr/sysinfo.h>
#include <winpr/registry.h>
#include <freerdp/settings.h>
#include <freerdp/build-config.h>
#include <ctype.h>
#ifdef _WIN32
#pragma warning(push)
#pragma warning(disable: 4244)
#endif
static const char client_dll[] = "C:\\Windows\\System32\\mstscax.dll";
#define REG_QUERY_DWORD_VALUE(_key, _subkey, _type, _value, _size, _result) \
_size = sizeof(DWORD); \
if (RegQueryValueEx(_key, _subkey, NULL, &_type, (BYTE*) &_value, &_size) == ERROR_SUCCESS) \
_result = _value
#define REG_QUERY_BOOL_VALUE(_key, _subkey, _type, _value, _size, _result) \
_size = sizeof(DWORD); \
if (RegQueryValueEx(_key, _subkey, NULL, &_type, (BYTE*) &_value, &_size) == ERROR_SUCCESS) \
_result = _value ? TRUE : FALSE
#define SERVER_KEY "Software\\" FREERDP_VENDOR_STRING "\\" \
FREERDP_PRODUCT_STRING "\\Server"
#define CLIENT_KEY "Software\\" FREERDP_VENDOR_STRING "\\" \
FREERDP_PRODUCT_STRING "\\Client"
#define BITMAP_CACHE_KEY CLIENT_KEY "\\BitmapCacheV2"
#define GLYPH_CACHE_KEY CLIENT_KEY "\\GlyphCache"
#define POINTER_CACHE_KEY CLIENT_KEY "\\PointerCache"
static void settings_client_load_hkey_local_machine(rdpSettings* settings)
{
HKEY hKey;
LONG status;
DWORD dwType;
DWORD dwSize;
DWORD dwValue;
status = RegOpenKeyExA(HKEY_LOCAL_MACHINE, CLIENT_KEY, 0,
KEY_READ | KEY_WOW64_64KEY, &hKey);
if (status == ERROR_SUCCESS)
{
REG_QUERY_DWORD_VALUE(hKey, _T("DesktopWidth"), dwType, dwValue, dwSize,
settings->DesktopWidth);
REG_QUERY_DWORD_VALUE(hKey, _T("DesktopHeight"), dwType, dwValue, dwSize,
settings->DesktopHeight);
REG_QUERY_BOOL_VALUE(hKey, _T("Fullscreen"), dwType, dwValue, dwSize,
settings->Fullscreen);
REG_QUERY_DWORD_VALUE(hKey, _T("ColorDepth"), dwType, dwValue, dwSize,
settings->ColorDepth);
REG_QUERY_DWORD_VALUE(hKey, _T("KeyboardType"), dwType, dwValue, dwSize,
settings->KeyboardType);
REG_QUERY_DWORD_VALUE(hKey, _T("KeyboardSubType"), dwType, dwValue, dwSize,
settings->KeyboardSubType);
REG_QUERY_DWORD_VALUE(hKey, _T("KeyboardFunctionKeys"), dwType, dwValue, dwSize,
settings->KeyboardFunctionKey);
REG_QUERY_DWORD_VALUE(hKey, _T("KeyboardLayout"), dwType, dwValue, dwSize,
settings->KeyboardLayout);
REG_QUERY_BOOL_VALUE(hKey, _T("ExtSecurity"), dwType, dwValue, dwSize,
settings->ExtSecurity);
REG_QUERY_BOOL_VALUE(hKey, _T("NlaSecurity"), dwType, dwValue, dwSize,
settings->NlaSecurity);
REG_QUERY_BOOL_VALUE(hKey, _T("TlsSecurity"), dwType, dwValue, dwSize,
settings->TlsSecurity);
REG_QUERY_BOOL_VALUE(hKey, _T("RdpSecurity"), dwType, dwValue, dwSize,
settings->RdpSecurity);
REG_QUERY_BOOL_VALUE(hKey, _T("MstscCookieMode"), dwType, dwValue, dwSize,
settings->MstscCookieMode);
REG_QUERY_DWORD_VALUE(hKey, _T("CookieMaxLength"), dwType, dwValue, dwSize,
settings->CookieMaxLength);
REG_QUERY_BOOL_VALUE(hKey, _T("BitmapCache"), dwType, dwValue, dwSize,
settings->BitmapCacheEnabled);
REG_QUERY_BOOL_VALUE(hKey, _T("OffscreenBitmapCache"), dwType, dwValue, dwSize,
settings->OffscreenSupportLevel);
REG_QUERY_DWORD_VALUE(hKey, _T("OffscreenBitmapCacheSize"), dwType, dwValue,
dwSize, settings->OffscreenCacheSize);
REG_QUERY_DWORD_VALUE(hKey, _T("OffscreenBitmapCacheEntries"), dwType, dwValue,
dwSize, settings->OffscreenCacheEntries);
RegCloseKey(hKey);
}
status = RegOpenKeyExA(HKEY_LOCAL_MACHINE, BITMAP_CACHE_KEY, 0,
KEY_READ | KEY_WOW64_64KEY, &hKey);
if (status == ERROR_SUCCESS)
{
REG_QUERY_DWORD_VALUE(hKey, _T("NumCells"), dwType, dwValue, dwSize,
settings->BitmapCacheV2NumCells);
REG_QUERY_DWORD_VALUE(hKey, _T("Cell0NumEntries"), dwType, dwValue, dwSize,
settings->BitmapCacheV2CellInfo[0].numEntries);
REG_QUERY_BOOL_VALUE(hKey, _T("Cell0Persistent"), dwType, dwValue, dwSize,
settings->BitmapCacheV2CellInfo[0].persistent);
REG_QUERY_DWORD_VALUE(hKey, _T("Cell1NumEntries"), dwType, dwValue, dwSize,
settings->BitmapCacheV2CellInfo[1].numEntries);
REG_QUERY_BOOL_VALUE(hKey, _T("Cell1Persistent"), dwType, dwValue, dwSize,
settings->BitmapCacheV2CellInfo[1].persistent);
REG_QUERY_DWORD_VALUE(hKey, _T("Cell2NumEntries"), dwType, dwValue, dwSize,
settings->BitmapCacheV2CellInfo[2].numEntries);
REG_QUERY_BOOL_VALUE(hKey, _T("Cell2Persistent"), dwType, dwValue, dwSize,
settings->BitmapCacheV2CellInfo[2].persistent);
REG_QUERY_DWORD_VALUE(hKey, _T("Cell3NumEntries"), dwType, dwValue, dwSize,
settings->BitmapCacheV2CellInfo[3].numEntries);
REG_QUERY_BOOL_VALUE(hKey, _T("Cell3Persistent"), dwType, dwValue, dwSize,
settings->BitmapCacheV2CellInfo[3].persistent);
REG_QUERY_DWORD_VALUE(hKey, _T("Cell4NumEntries"), dwType, dwValue, dwSize,
settings->BitmapCacheV2CellInfo[4].numEntries);
REG_QUERY_BOOL_VALUE(hKey, _T("Cell4Persistent"), dwType, dwValue, dwSize,
settings->BitmapCacheV2CellInfo[4].persistent);
REG_QUERY_BOOL_VALUE(hKey, _T("AllowCacheWaitingList"), dwType, dwValue, dwSize,
settings->AllowCacheWaitingList);
RegCloseKey(hKey);
}
status = RegOpenKeyExA(HKEY_LOCAL_MACHINE, GLYPH_CACHE_KEY,
0, KEY_READ | KEY_WOW64_64KEY, &hKey);
if (status == ERROR_SUCCESS)
{
REG_QUERY_DWORD_VALUE(hKey, _T("SupportLevel"), dwType, dwValue, dwSize,
settings->GlyphSupportLevel);
REG_QUERY_DWORD_VALUE(hKey, _T("Cache0NumEntries"), dwType, dwValue, dwSize,
settings->GlyphCache[0].cacheEntries);
REG_QUERY_DWORD_VALUE(hKey, _T("Cache0MaxCellSize"), dwType, dwValue, dwSize,
settings->GlyphCache[0].cacheMaximumCellSize);
REG_QUERY_DWORD_VALUE(hKey, _T("Cache1NumEntries"), dwType, dwValue, dwSize,
settings->GlyphCache[1].cacheEntries);
REG_QUERY_DWORD_VALUE(hKey, _T("Cache1MaxCellSize"), dwType, dwValue, dwSize,
settings->GlyphCache[1].cacheMaximumCellSize);
REG_QUERY_DWORD_VALUE(hKey, _T("Cache2NumEntries"), dwType, dwValue, dwSize,
settings->GlyphCache[2].cacheEntries);
REG_QUERY_DWORD_VALUE(hKey, _T("Cache2MaxCellSize"), dwType, dwValue, dwSize,
settings->GlyphCache[2].cacheMaximumCellSize);
REG_QUERY_DWORD_VALUE(hKey, _T("Cache3NumEntries"), dwType, dwValue, dwSize,
settings->GlyphCache[3].cacheEntries);
REG_QUERY_DWORD_VALUE(hKey, _T("Cache3MaxCellSize"), dwType, dwValue, dwSize,
settings->GlyphCache[3].cacheMaximumCellSize);
REG_QUERY_DWORD_VALUE(hKey, _T("Cache4NumEntries"), dwType, dwValue, dwSize,
settings->GlyphCache[4].cacheEntries);
REG_QUERY_DWORD_VALUE(hKey, _T("Cache4MaxCellSize"), dwType, dwValue, dwSize,
settings->GlyphCache[4].cacheMaximumCellSize);
REG_QUERY_DWORD_VALUE(hKey, _T("Cache5NumEntries"), dwType, dwValue, dwSize,
settings->GlyphCache[5].cacheEntries);
REG_QUERY_DWORD_VALUE(hKey, _T("Cache5MaxCellSize"), dwType, dwValue, dwSize,
settings->GlyphCache[5].cacheMaximumCellSize);
REG_QUERY_DWORD_VALUE(hKey, _T("Cache6NumEntries"), dwType, dwValue, dwSize,
settings->GlyphCache[6].cacheEntries);
REG_QUERY_DWORD_VALUE(hKey, _T("Cache6MaxCellSize"), dwType, dwValue, dwSize,
settings->GlyphCache[6].cacheMaximumCellSize);
REG_QUERY_DWORD_VALUE(hKey, _T("Cache7NumEntries"), dwType, dwValue, dwSize,
settings->GlyphCache[7].cacheEntries);
REG_QUERY_DWORD_VALUE(hKey, _T("Cache7MaxCellSize"), dwType, dwValue, dwSize,
settings->GlyphCache[7].cacheMaximumCellSize);
REG_QUERY_DWORD_VALUE(hKey, _T("Cache8NumEntries"), dwType, dwValue, dwSize,
settings->GlyphCache[8].cacheEntries);
REG_QUERY_DWORD_VALUE(hKey, _T("Cache8MaxCellSize"), dwType, dwValue, dwSize,
settings->GlyphCache[8].cacheMaximumCellSize);
REG_QUERY_DWORD_VALUE(hKey, _T("Cache9NumEntries"), dwType, dwValue, dwSize,
settings->GlyphCache[9].cacheEntries);
REG_QUERY_DWORD_VALUE(hKey, _T("Cache9MaxCellSize"), dwType, dwValue, dwSize,
settings->GlyphCache[9].cacheMaximumCellSize);
REG_QUERY_DWORD_VALUE(hKey, _T("FragCacheNumEntries"), dwType, dwValue, dwSize,
settings->FragCache->cacheEntries);
REG_QUERY_DWORD_VALUE(hKey, _T("FragCacheMaxCellSize"), dwType, dwValue, dwSize,
settings->FragCache->cacheMaximumCellSize);
RegCloseKey(hKey);
}
status = RegOpenKeyExA(HKEY_LOCAL_MACHINE, POINTER_CACHE_KEY,
0, KEY_READ | KEY_WOW64_64KEY, &hKey);
if (status == ERROR_SUCCESS)
{
REG_QUERY_BOOL_VALUE(hKey, _T("LargePointer"), dwType, dwValue, dwSize,
settings->LargePointerFlag);
REG_QUERY_BOOL_VALUE(hKey, _T("ColorPointer"), dwType, dwValue, dwSize,
settings->ColorPointerFlag);
REG_QUERY_DWORD_VALUE(hKey, _T("PointerCacheSize"), dwType, dwValue, dwSize,
settings->PointerCacheSize);
RegCloseKey(hKey);
}
}
static void settings_server_load_hkey_local_machine(rdpSettings* settings)
{
HKEY hKey;
LONG status;
DWORD dwType;
DWORD dwSize;
DWORD dwValue;
status = RegOpenKeyExA(HKEY_LOCAL_MACHINE, SERVER_KEY,
0, KEY_READ | KEY_WOW64_64KEY, &hKey);
if (status != ERROR_SUCCESS)
return;
REG_QUERY_BOOL_VALUE(hKey, _T("ExtSecurity"), dwType, dwValue, dwSize,
settings->ExtSecurity);
REG_QUERY_BOOL_VALUE(hKey, _T("NlaSecurity"), dwType, dwValue, dwSize,
settings->NlaSecurity);
REG_QUERY_BOOL_VALUE(hKey, _T("TlsSecurity"), dwType, dwValue, dwSize,
settings->TlsSecurity);
REG_QUERY_BOOL_VALUE(hKey, _T("RdpSecurity"), dwType, dwValue, dwSize,
settings->RdpSecurity);
RegCloseKey(hKey);
}
static void settings_load_hkey_local_machine(rdpSettings* settings)
{
if (settings->ServerMode)
settings_server_load_hkey_local_machine(settings);
else
settings_client_load_hkey_local_machine(settings);
}
static BOOL settings_get_computer_name(rdpSettings* settings)
{
DWORD nSize = 0;
CHAR* computerName;
if (GetComputerNameExA(ComputerNameNetBIOS, NULL, &nSize) || GetLastError() != ERROR_MORE_DATA)
return FALSE;
computerName = calloc(nSize, sizeof(CHAR));
if (!computerName)
return FALSE;
if (!GetComputerNameExA(ComputerNameNetBIOS, computerName, &nSize))
{
free(computerName);
return FALSE;
}
if (nSize > MAX_COMPUTERNAME_LENGTH)
computerName[MAX_COMPUTERNAME_LENGTH] = '\0';
settings->ComputerName = computerName;
if (!settings->ComputerName)
return FALSE;
return TRUE;
}
BOOL freerdp_settings_set_default_order_support(rdpSettings* settings)
{
if (!settings)
return FALSE;
ZeroMemory(settings->OrderSupport, 32);
settings->OrderSupport[NEG_DSTBLT_INDEX] = TRUE;
settings->OrderSupport[NEG_PATBLT_INDEX] = TRUE;
settings->OrderSupport[NEG_SCRBLT_INDEX] = TRUE;
settings->OrderSupport[NEG_OPAQUE_RECT_INDEX] = TRUE;
settings->OrderSupport[NEG_DRAWNINEGRID_INDEX] = FALSE;
settings->OrderSupport[NEG_MULTIDSTBLT_INDEX] = FALSE;
settings->OrderSupport[NEG_MULTIPATBLT_INDEX] = FALSE;
settings->OrderSupport[NEG_MULTISCRBLT_INDEX] = FALSE;
settings->OrderSupport[NEG_MULTIOPAQUERECT_INDEX] = TRUE;
settings->OrderSupport[NEG_MULTI_DRAWNINEGRID_INDEX] = FALSE;
settings->OrderSupport[NEG_LINETO_INDEX] = TRUE;
settings->OrderSupport[NEG_POLYLINE_INDEX] = TRUE;
settings->OrderSupport[NEG_MEMBLT_INDEX] = settings->BitmapCacheEnabled;
settings->OrderSupport[NEG_MEM3BLT_INDEX] = settings->BitmapCacheEnabled;
settings->OrderSupport[NEG_MEMBLT_V2_INDEX] = settings->BitmapCacheEnabled;
settings->OrderSupport[NEG_MEM3BLT_V2_INDEX] = settings->BitmapCacheEnabled;
settings->OrderSupport[NEG_SAVEBITMAP_INDEX] = FALSE;
settings->OrderSupport[NEG_GLYPH_INDEX_INDEX] = settings->GlyphSupportLevel != GLYPH_SUPPORT_NONE;
settings->OrderSupport[NEG_FAST_INDEX_INDEX] = settings->GlyphSupportLevel != GLYPH_SUPPORT_NONE;
settings->OrderSupport[NEG_FAST_GLYPH_INDEX] = settings->GlyphSupportLevel != GLYPH_SUPPORT_NONE;
settings->OrderSupport[NEG_POLYGON_SC_INDEX] = FALSE;
settings->OrderSupport[NEG_POLYGON_CB_INDEX] = FALSE;
settings->OrderSupport[NEG_ELLIPSE_SC_INDEX] = FALSE;
settings->OrderSupport[NEG_ELLIPSE_CB_INDEX] = FALSE;
return TRUE;
}
rdpSettings* freerdp_settings_new(DWORD flags)
{
char* base;
rdpSettings* settings;
settings = (rdpSettings*) calloc(1, sizeof(rdpSettings));
if (!settings)
return NULL;
settings->ServerMode = (flags & FREERDP_SETTINGS_SERVER_MODE) ? TRUE : FALSE;
settings->WaitForOutputBufferFlush = TRUE;
settings->MaxTimeInCheckLoop = 100;
settings->DesktopWidth = 1024;
settings->DesktopHeight = 768;
settings->Workarea = FALSE;
settings->Fullscreen = FALSE;
settings->GrabKeyboard = TRUE;
settings->Decorations = TRUE;
settings->RdpVersion = RDP_VERSION_5_PLUS;
settings->ColorDepth = 16;
settings->ExtSecurity = FALSE;
settings->NlaSecurity = TRUE;
settings->TlsSecurity = TRUE;
settings->RdpSecurity = TRUE;
settings->NegotiateSecurityLayer = TRUE;
settings->RestrictedAdminModeRequired = FALSE;
settings->MstscCookieMode = FALSE;
settings->CookieMaxLength = DEFAULT_COOKIE_MAX_LENGTH;
settings->ClientBuild = 2600;
settings->KeyboardType = 4;
settings->KeyboardSubType = 0;
settings->KeyboardFunctionKey = 12;
settings->KeyboardLayout = 0;
settings->UseRdpSecurityLayer = FALSE;
settings->SaltedChecksum = TRUE;
settings->ServerPort = 3389;
settings->GatewayPort = 443;
settings->DesktopResize = TRUE;
settings->ToggleFullscreen = TRUE;
settings->DesktopPosX = UINT32_MAX;
settings->DesktopPosY = UINT32_MAX;
settings->SoftwareGdi = TRUE;
settings->UnmapButtons = FALSE;
settings->PerformanceFlags = PERF_FLAG_NONE;
settings->AllowFontSmoothing = TRUE;
settings->AllowDesktopComposition = FALSE;
settings->DisableWallpaper = FALSE;
settings->DisableFullWindowDrag = TRUE;
settings->DisableMenuAnims = TRUE;
settings->DisableThemes = FALSE;
settings->ConnectionType = CONNECTION_TYPE_LAN;
settings->EncryptionMethods = ENCRYPTION_METHOD_NONE;
settings->EncryptionLevel = ENCRYPTION_LEVEL_NONE;
settings->FIPSMode = FALSE;
settings->CompressionEnabled = TRUE;
settings->LogonNotify = TRUE;
settings->BrushSupportLevel = BRUSH_COLOR_FULL;
settings->CompressionLevel = PACKET_COMPR_TYPE_RDP61;
settings->Authentication = TRUE;
settings->AuthenticationOnly = FALSE;
settings->CredentialsFromStdin = FALSE;
settings->DisableCredentialsDelegation = FALSE;
settings->AuthenticationLevel = 2;
settings->ChannelCount = 0;
settings->ChannelDefArraySize = 32;
settings->ChannelDefArray = (CHANNEL_DEF*) calloc(settings->ChannelDefArraySize,
sizeof(CHANNEL_DEF));
if (!settings->ChannelDefArray)
goto out_fail;
settings->SupportMonitorLayoutPdu = FALSE;
settings->MonitorCount = 0;
settings->MonitorDefArraySize = 32;
settings->MonitorDefArray = (rdpMonitor*) calloc(settings->MonitorDefArraySize,
sizeof(rdpMonitor));
if (!settings->MonitorDefArray)
goto out_fail;
settings->MonitorLocalShiftX = 0;
settings->MonitorLocalShiftY = 0;
settings->MonitorIds = (UINT32*) calloc(16, sizeof(UINT32));
if (!settings->MonitorIds)
goto out_fail;
if (!settings_get_computer_name(settings))
goto out_fail;
settings->ReceivedCapabilities = calloc(1, 32);
if (!settings->ReceivedCapabilities)
goto out_fail;
settings->ClientProductId = calloc(1, 32);
if (!settings->ClientProductId)
goto out_fail;
settings->ClientHostname = calloc(1, 32);
if (!settings->ClientHostname)
goto out_fail;
gethostname(settings->ClientHostname, 31);
settings->ClientHostname[31] = 0;
settings->ColorPointerFlag = TRUE;
settings->LargePointerFlag = TRUE;
settings->PointerCacheSize = 20;
settings->SoundBeepsEnabled = TRUE;
settings->DrawGdiPlusEnabled = FALSE;
settings->DrawAllowSkipAlpha = TRUE;
settings->DrawAllowColorSubsampling = FALSE;
settings->DrawAllowDynamicColorFidelity = FALSE;
settings->FrameMarkerCommandEnabled = TRUE;
settings->SurfaceFrameMarkerEnabled = TRUE;
settings->BitmapCacheV3Enabled = FALSE;
settings->BitmapCacheEnabled = TRUE;
settings->BitmapCachePersistEnabled = FALSE;
settings->AllowCacheWaitingList = TRUE;
settings->BitmapCacheV2NumCells = 5;
settings->BitmapCacheV2CellInfo = (BITMAP_CACHE_V2_CELL_INFO*) malloc(sizeof(
BITMAP_CACHE_V2_CELL_INFO) * 6);
if (!settings->BitmapCacheV2CellInfo)
goto out_fail;
settings->BitmapCacheV2CellInfo[0].numEntries = 600;
settings->BitmapCacheV2CellInfo[0].persistent = FALSE;
settings->BitmapCacheV2CellInfo[1].numEntries = 600;
settings->BitmapCacheV2CellInfo[1].persistent = FALSE;
settings->BitmapCacheV2CellInfo[2].numEntries = 2048;
settings->BitmapCacheV2CellInfo[2].persistent = FALSE;
settings->BitmapCacheV2CellInfo[3].numEntries = 4096;
settings->BitmapCacheV2CellInfo[3].persistent = FALSE;
settings->BitmapCacheV2CellInfo[4].numEntries = 2048;
settings->BitmapCacheV2CellInfo[4].persistent = FALSE;
settings->NoBitmapCompressionHeader = TRUE;
settings->RefreshRect = TRUE;
settings->SuppressOutput = TRUE;
settings->GlyphSupportLevel = GLYPH_SUPPORT_NONE;
settings->GlyphCache = malloc(sizeof(GLYPH_CACHE_DEFINITION) * 10);
if (!settings->GlyphCache)
goto out_fail;
settings->FragCache = malloc(sizeof(GLYPH_CACHE_DEFINITION));
if (!settings->FragCache)
goto out_fail;
settings->GlyphCache[0].cacheEntries = 254;
settings->GlyphCache[0].cacheMaximumCellSize = 4;
settings->GlyphCache[1].cacheEntries = 254;
settings->GlyphCache[1].cacheMaximumCellSize = 4;
settings->GlyphCache[2].cacheEntries = 254;
settings->GlyphCache[2].cacheMaximumCellSize = 8;
settings->GlyphCache[3].cacheEntries = 254;
settings->GlyphCache[3].cacheMaximumCellSize = 8;
settings->GlyphCache[4].cacheEntries = 254;
settings->GlyphCache[4].cacheMaximumCellSize = 16;
settings->GlyphCache[5].cacheEntries = 254;
settings->GlyphCache[5].cacheMaximumCellSize = 32;
settings->GlyphCache[6].cacheEntries = 254;
settings->GlyphCache[6].cacheMaximumCellSize = 64;
settings->GlyphCache[7].cacheEntries = 254;
settings->GlyphCache[7].cacheMaximumCellSize = 128;
settings->GlyphCache[8].cacheEntries = 254;
settings->GlyphCache[8].cacheMaximumCellSize = 256;
settings->GlyphCache[9].cacheEntries = 64;
settings->GlyphCache[9].cacheMaximumCellSize = 256;
settings->FragCache->cacheEntries = 256;
settings->FragCache->cacheMaximumCellSize = 256;
settings->OffscreenSupportLevel = TRUE;
settings->OffscreenCacheSize = 7680;
settings->OffscreenCacheEntries = 2000;
settings->DrawNineGridCacheSize = 2560;
settings->DrawNineGridCacheEntries = 256;
settings->ClientDir = _strdup(client_dll);
if (!settings->ClientDir)
goto out_fail;
settings->RemoteWndSupportLevel = WINDOW_LEVEL_SUPPORTED_EX;
settings->RemoteAppNumIconCaches = 3;
settings->RemoteAppNumIconCacheEntries = 12;
settings->VirtualChannelChunkSize = CHANNEL_CHUNK_LENGTH;
settings->MultifragMaxRequestSize = (flags & FREERDP_SETTINGS_SERVER_MODE) ?
0 : 0xFFFF;
settings->GatewayUseSameCredentials = FALSE;
settings->GatewayBypassLocal = FALSE;
settings->GatewayRpcTransport = TRUE;
settings->GatewayHttpTransport = TRUE;
settings->GatewayUdpTransport = TRUE;
settings->FastPathInput = TRUE;
settings->FastPathOutput = TRUE;
settings->LongCredentialsSupported = TRUE;
settings->FrameAcknowledge = 2;
settings->MouseMotion = TRUE;
settings->NSCodecColorLossLevel = 3;
settings->NSCodecAllowSubsampling = TRUE;
settings->NSCodecAllowDynamicColorFidelity = TRUE;
settings->AutoReconnectionEnabled = FALSE;
settings->AutoReconnectMaxRetries = 20;
settings->GfxThinClient = TRUE;
settings->GfxSmallCache = FALSE;
settings->GfxProgressive = FALSE;
settings->GfxProgressiveV2 = FALSE;
settings->GfxH264 = FALSE;
settings->GfxAVC444 = FALSE;
settings->GfxSendQoeAck = FALSE;
settings->ClientAutoReconnectCookie = (ARC_CS_PRIVATE_PACKET*) calloc(1,
sizeof(ARC_CS_PRIVATE_PACKET));
if (!settings->ClientAutoReconnectCookie)
goto out_fail;
settings->ServerAutoReconnectCookie = (ARC_SC_PRIVATE_PACKET*) calloc(1,
sizeof(ARC_SC_PRIVATE_PACKET));
if (!settings->ServerAutoReconnectCookie)
goto out_fail;
settings->ClientTimeZone = (LPTIME_ZONE_INFORMATION) calloc(1,
sizeof(TIME_ZONE_INFORMATION));
if (!settings->ClientTimeZone)
goto out_fail;
settings->DeviceArraySize = 16;
settings->DeviceArray = (RDPDR_DEVICE**) calloc(1,
sizeof(RDPDR_DEVICE*) * settings->DeviceArraySize);
if (!settings->DeviceArray)
goto out_fail;
settings->StaticChannelArraySize = 16;
settings->StaticChannelArray = (ADDIN_ARGV**)
calloc(1, sizeof(ADDIN_ARGV*) * settings->StaticChannelArraySize);
if (!settings->StaticChannelArray)
goto out_fail;
settings->DynamicChannelArraySize = 16;
settings->DynamicChannelArray = (ADDIN_ARGV**)
calloc(1, sizeof(ADDIN_ARGV*) * settings->DynamicChannelArraySize);
if (!settings->DynamicChannelArray)
goto out_fail;
if (!settings->ServerMode)
{
settings->RedirectClipboard = TRUE;
/* these values are used only by the client part */
settings->HomePath = GetKnownPath(KNOWN_PATH_HOME);
if (!settings->HomePath)
goto out_fail;
/* For default FreeRDP continue using same config directory
* as in old releases.
* Custom builds use <Vendor>/<Product> as config folder. */
if (_stricmp(FREERDP_VENDOR_STRING, FREERDP_PRODUCT_STRING))
{
base = GetKnownSubPath(KNOWN_PATH_XDG_CONFIG_HOME,
FREERDP_VENDOR_STRING);
if (base)
{
settings->ConfigPath = GetCombinedPath(
base,
FREERDP_PRODUCT_STRING);
}
free(base);
}
else
{
int i;
char product[sizeof(FREERDP_PRODUCT_STRING)];
memset(product, 0, sizeof(product));
for (i = 0; i < sizeof(product); i++)
product[i] = tolower(FREERDP_PRODUCT_STRING[i]);
settings->ConfigPath = GetKnownSubPath(
KNOWN_PATH_XDG_CONFIG_HOME,
product);
}
if (!settings->ConfigPath)
goto out_fail;
}
settings_load_hkey_local_machine(settings);
settings->SettingsModified = (BYTE*) calloc(1, sizeof(rdpSettings) / 8);
if (!settings->SettingsModified)
goto out_fail;
settings->ActionScript = _strdup("~/.config/freerdp/action.sh");
settings->SmartcardLogon = FALSE;
settings->TlsSecLevel = 1;
settings->OrderSupport = calloc(1, 32);
if (!settings->OrderSupport)
goto out_fail;
if (!freerdp_settings_set_default_order_support(settings))
goto out_fail;
return settings;
out_fail:
free(settings->HomePath);
free(settings->ConfigPath);
free(settings->DynamicChannelArray);
free(settings->StaticChannelArray);
free(settings->DeviceArray);
free(settings->ClientTimeZone);
free(settings->ServerAutoReconnectCookie);
free(settings->ClientAutoReconnectCookie);
free(settings->ClientDir);
free(settings->FragCache);
free(settings->GlyphCache);
free(settings->BitmapCacheV2CellInfo);
free(settings->ClientProductId);
free(settings->ClientHostname);
free(settings->OrderSupport);
free(settings->ReceivedCapabilities);
free(settings->ComputerName);
free(settings->MonitorIds);
free(settings->MonitorDefArray);
free(settings->ChannelDefArray);
free(settings);
return NULL;
}
rdpSettings* freerdp_settings_clone(rdpSettings* settings)
{
UINT32 index;
rdpSettings* _settings;
_settings = (rdpSettings*) calloc(1, sizeof(rdpSettings));
if (_settings)
{
CopyMemory(_settings, settings, sizeof(rdpSettings));
/* char* values */
#define CHECKED_STRDUP(name) if (settings->name && !(_settings->name = _strdup(settings->name))) goto out_fail
CHECKED_STRDUP(ServerHostname); /* 20 */
CHECKED_STRDUP(Username); /* 21 */
CHECKED_STRDUP(Password); /* 22 */
CHECKED_STRDUP(Domain); /* 23 */
CHECKED_STRDUP(PasswordHash); /* 24 */
CHECKED_STRDUP(AcceptedCert); /* 27 */
_settings->ClientHostname = NULL; /* 134 */
_settings->ClientProductId = NULL; /* 135 */
CHECKED_STRDUP(AlternateShell); /* 640 */
CHECKED_STRDUP(ShellWorkingDirectory); /* 641 */
CHECKED_STRDUP(ClientAddress); /* 769 */
CHECKED_STRDUP(ClientDir); /* 770 */
CHECKED_STRDUP(DynamicDSTTimeZoneKeyName); /* 897 */
CHECKED_STRDUP(RemoteAssistanceSessionId); /* 1025 */
CHECKED_STRDUP(RemoteAssistancePassStub); /* 1026 */
CHECKED_STRDUP(RemoteAssistancePassword); /* 1027 */
CHECKED_STRDUP(RemoteAssistanceRCTicket); /* 1028 */
CHECKED_STRDUP(AuthenticationServiceClass); /* 1098 */
CHECKED_STRDUP(AllowedTlsCiphers); /* 1101 */
CHECKED_STRDUP(NtlmSamFile); /* 1103 */
CHECKED_STRDUP(PreconnectionBlob); /* 1155 */
CHECKED_STRDUP(RedirectionAcceptedCert); /* 1231 */
CHECKED_STRDUP(KerberosKdc); /* 1344 */
CHECKED_STRDUP(KerberosRealm); /* 1345 */
CHECKED_STRDUP(CertificateName); /* 1409 */
CHECKED_STRDUP(CertificateFile); /* 1410 */
CHECKED_STRDUP(PrivateKeyFile); /* 1411 */
CHECKED_STRDUP(RdpKeyFile); /* 1412 */
CHECKED_STRDUP(CertificateContent); /* 1416 */
CHECKED_STRDUP(PrivateKeyContent); /* 1417 */
CHECKED_STRDUP(RdpKeyContent); /* 1418 */
CHECKED_STRDUP(WindowTitle); /* 1542 */
CHECKED_STRDUP(WmClass); /* 1549 */
CHECKED_STRDUP(ComputerName); /* 1664 */
CHECKED_STRDUP(ConnectionFile); /* 1728 */
CHECKED_STRDUP(AssistanceFile); /* 1729 */
CHECKED_STRDUP(HomePath); /* 1792 */
CHECKED_STRDUP(ConfigPath); /* 1793 */
CHECKED_STRDUP(CurrentPath); /* 1794 */
CHECKED_STRDUP(DumpRemoteFxFile); /* 1858 */
CHECKED_STRDUP(PlayRemoteFxFile); /* 1859 */
CHECKED_STRDUP(GatewayHostname); /* 1986 */
CHECKED_STRDUP(GatewayUsername); /* 1987 */
CHECKED_STRDUP(GatewayPassword); /* 1988 */
CHECKED_STRDUP(GatewayDomain); /* 1989 */
CHECKED_STRDUP(GatewayAccessToken); /* 1997 */
CHECKED_STRDUP(GatewayAcceptedCert); /* 1998 */
CHECKED_STRDUP(ProxyHostname); /* 2016 */
CHECKED_STRDUP(RemoteApplicationName); /* 2113 */
CHECKED_STRDUP(RemoteApplicationIcon); /* 2114 */
CHECKED_STRDUP(RemoteApplicationProgram); /* 2115 */
CHECKED_STRDUP(RemoteApplicationFile); /* 2116 */
CHECKED_STRDUP(RemoteApplicationGuid); /* 2117 */
CHECKED_STRDUP(RemoteApplicationCmdLine); /* 2118 */
CHECKED_STRDUP(ImeFileName); /* 2628 */
CHECKED_STRDUP(DrivesToRedirect); /* 4290 */
CHECKED_STRDUP(ActionScript);
/**
* Manual Code
*/
_settings->LoadBalanceInfo = NULL;
_settings->LoadBalanceInfoLength = 0;
_settings->TargetNetAddress = NULL;
_settings->RedirectionTargetFQDN = NULL;
_settings->RedirectionTargetNetBiosName = NULL;
_settings->RedirectionUsername = NULL;
_settings->RedirectionDomain = NULL;
_settings->RedirectionPassword = NULL;
_settings->RedirectionPasswordLength = 0;
_settings->RedirectionTsvUrl = NULL;
_settings->RedirectionTsvUrlLength = 0;
_settings->TargetNetAddressCount = 0;
_settings->TargetNetAddresses = NULL;
_settings->TargetNetPorts = NULL;
if (settings->LoadBalanceInfo && settings->LoadBalanceInfoLength)
{
_settings->LoadBalanceInfo = (BYTE*) calloc(1,
settings->LoadBalanceInfoLength + 2);
if (!_settings->LoadBalanceInfo)
goto out_fail;
CopyMemory(_settings->LoadBalanceInfo, settings->LoadBalanceInfo,
settings->LoadBalanceInfoLength);
_settings->LoadBalanceInfoLength = settings->LoadBalanceInfoLength;
}
if (_settings->ServerRandomLength)
{
_settings->ServerRandom = (BYTE*) malloc(_settings->ServerRandomLength);
if (!_settings->ServerRandom)
goto out_fail;
CopyMemory(_settings->ServerRandom, settings->ServerRandom,
_settings->ServerRandomLength);
_settings->ServerRandomLength = settings->ServerRandomLength;
}
if (_settings->ClientRandomLength)
{
_settings->ClientRandom = (BYTE*) malloc(_settings->ClientRandomLength);
if (!_settings->ClientRandom)
goto out_fail;
CopyMemory(_settings->ClientRandom, settings->ClientRandom,
_settings->ClientRandomLength);
_settings->ClientRandomLength = settings->ClientRandomLength;
}
if (settings->RdpServerCertificate)
{
_settings->RdpServerCertificate = certificate_clone(
settings->RdpServerCertificate);
if (!_settings->RdpServerCertificate)
goto out_fail;
}
_settings->ChannelCount = settings->ChannelCount;
_settings->ChannelDefArraySize = settings->ChannelDefArraySize;
if (_settings->ChannelDefArraySize > 0)
{
_settings->ChannelDefArray = (CHANNEL_DEF*) calloc(settings->ChannelDefArraySize,
sizeof(CHANNEL_DEF));
if (!_settings->ChannelDefArray)
goto out_fail;
CopyMemory(_settings->ChannelDefArray, settings->ChannelDefArray,
sizeof(CHANNEL_DEF) * settings->ChannelDefArraySize);
}
else
_settings->ChannelDefArray = NULL;
_settings->MonitorCount = settings->MonitorCount;
_settings->MonitorDefArraySize = settings->MonitorDefArraySize;
if (_settings->MonitorDefArraySize > 0)
{
_settings->MonitorDefArray = (rdpMonitor*) calloc(settings->MonitorDefArraySize,
sizeof(rdpMonitor));
if (!_settings->MonitorDefArray)
goto out_fail;
CopyMemory(_settings->MonitorDefArray, settings->MonitorDefArray,
sizeof(rdpMonitor) * settings->MonitorDefArraySize);
}
else
_settings->MonitorDefArray = NULL;
_settings->MonitorIds = (UINT32*) calloc(16, sizeof(UINT32));
if (!_settings->MonitorIds)
goto out_fail;
CopyMemory(_settings->MonitorIds, settings->MonitorIds, 16 * sizeof(UINT32));
_settings->ReceivedCapabilities = malloc(32);
if (!_settings->ReceivedCapabilities)
goto out_fail;
_settings->OrderSupport = malloc(32);
if (!_settings->OrderSupport)
goto out_fail;
if (!_settings->ReceivedCapabilities || !_settings->OrderSupport)
goto out_fail;
CopyMemory(_settings->ReceivedCapabilities, settings->ReceivedCapabilities, 32);
CopyMemory(_settings->OrderSupport, settings->OrderSupport, 32);
_settings->ClientHostname = _strdup(settings->ClientHostname);
if (!_settings->ClientHostname)
goto out_fail;
_settings->ClientProductId = _strdup(settings->ClientProductId);
if (!_settings->ClientProductId)
goto out_fail;
_settings->BitmapCacheV2CellInfo = (BITMAP_CACHE_V2_CELL_INFO*) malloc(sizeof(
BITMAP_CACHE_V2_CELL_INFO) * 6);
if (!_settings->BitmapCacheV2CellInfo)
goto out_fail;
CopyMemory(_settings->BitmapCacheV2CellInfo, settings->BitmapCacheV2CellInfo,
sizeof(BITMAP_CACHE_V2_CELL_INFO) * 6);
_settings->GlyphCache = malloc(sizeof(GLYPH_CACHE_DEFINITION) * 10);
if (!_settings->GlyphCache)
goto out_fail;
_settings->FragCache = malloc(sizeof(GLYPH_CACHE_DEFINITION));
if (!_settings->FragCache)
goto out_fail;
CopyMemory(_settings->GlyphCache, settings->GlyphCache,
sizeof(GLYPH_CACHE_DEFINITION) * 10);
CopyMemory(_settings->FragCache, settings->FragCache,
sizeof(GLYPH_CACHE_DEFINITION));
_settings->ClientAutoReconnectCookie = (ARC_CS_PRIVATE_PACKET*) malloc(sizeof(
ARC_CS_PRIVATE_PACKET));
if (!_settings->ClientAutoReconnectCookie)
goto out_fail;
_settings->ServerAutoReconnectCookie = (ARC_SC_PRIVATE_PACKET*) malloc(sizeof(
ARC_SC_PRIVATE_PACKET));
if (!_settings->ServerAutoReconnectCookie)
goto out_fail;
CopyMemory(_settings->ClientAutoReconnectCookie,
settings->ClientAutoReconnectCookie, sizeof(ARC_CS_PRIVATE_PACKET));
CopyMemory(_settings->ServerAutoReconnectCookie,
settings->ServerAutoReconnectCookie, sizeof(ARC_SC_PRIVATE_PACKET));
_settings->ClientTimeZone = (LPTIME_ZONE_INFORMATION) malloc(sizeof(
TIME_ZONE_INFORMATION));
if (!_settings->ClientTimeZone)
goto out_fail;
CopyMemory(_settings->ClientTimeZone, settings->ClientTimeZone,
sizeof(TIME_ZONE_INFORMATION));
_settings->TargetNetAddressCount = settings->TargetNetAddressCount;
if (settings->TargetNetAddressCount > 0)
{
_settings->TargetNetAddresses = (char**) calloc(settings->TargetNetAddressCount,
sizeof(char*));
if (!_settings->TargetNetAddresses)
{
_settings->TargetNetAddressCount = 0;
goto out_fail;
}
for (index = 0; index < settings->TargetNetAddressCount; index++)
{
_settings->TargetNetAddresses[index] = _strdup(
settings->TargetNetAddresses[index]);
if (!_settings->TargetNetAddresses[index])
{
while (index)
free(_settings->TargetNetAddresses[--index]);
free(_settings->TargetNetAddresses);
_settings->TargetNetAddresses = NULL;
_settings->TargetNetAddressCount = 0;
goto out_fail;
}
}
if (settings->TargetNetPorts)
{
_settings->TargetNetPorts = (UINT32*) calloc(settings->TargetNetAddressCount,
sizeof(UINT32));
if (!_settings->TargetNetPorts)
goto out_fail;
for (index = 0; index < settings->TargetNetAddressCount; index++)
_settings->TargetNetPorts[index] = settings->TargetNetPorts[index];
}
}
_settings->DeviceCount = settings->DeviceCount;
_settings->DeviceArraySize = settings->DeviceArraySize;
_settings->DeviceArray = (RDPDR_DEVICE**) calloc(_settings->DeviceArraySize,
sizeof(RDPDR_DEVICE*));
if (!_settings->DeviceArray && _settings->DeviceArraySize)
{
_settings->DeviceCount = 0;
_settings->DeviceArraySize = 0;
goto out_fail;
}
if (_settings->DeviceArraySize < _settings->DeviceCount)
{
_settings->DeviceCount = 0;
_settings->DeviceArraySize = 0;
goto out_fail;
}
for (index = 0; index < _settings->DeviceCount; index++)
{
_settings->DeviceArray[index] = freerdp_device_clone(
settings->DeviceArray[index]);
if (!_settings->DeviceArray[index])
goto out_fail;
}
_settings->StaticChannelCount = settings->StaticChannelCount;
_settings->StaticChannelArraySize = settings->StaticChannelArraySize;
_settings->StaticChannelArray = (ADDIN_ARGV**) calloc(
_settings->StaticChannelArraySize, sizeof(ADDIN_ARGV*));
if (!_settings->StaticChannelArray && _settings->StaticChannelArraySize)
{
_settings->StaticChannelArraySize = 0;
_settings->ChannelCount = 0;
goto out_fail;
}
if (_settings->StaticChannelArraySize < _settings->StaticChannelCount)
{
_settings->StaticChannelArraySize = 0;
_settings->ChannelCount = 0;
goto out_fail;
}
for (index = 0; index < _settings->StaticChannelCount; index++)
{
_settings->StaticChannelArray[index] = freerdp_static_channel_clone(
settings->StaticChannelArray[index]);
if (!_settings->StaticChannelArray[index])
goto out_fail;
}
_settings->DynamicChannelCount = settings->DynamicChannelCount;
_settings->DynamicChannelArraySize = settings->DynamicChannelArraySize;
_settings->DynamicChannelArray = (ADDIN_ARGV**) calloc(
_settings->DynamicChannelArraySize, sizeof(ADDIN_ARGV*));
if (!_settings->DynamicChannelArray && _settings->DynamicChannelArraySize)
{
_settings->DynamicChannelCount = 0;
_settings->DynamicChannelArraySize = 0;
goto out_fail;
}
if (_settings->DynamicChannelArraySize < _settings->DynamicChannelCount)
{
_settings->DynamicChannelCount = 0;
_settings->DynamicChannelArraySize = 0;
goto out_fail;
}
for (index = 0; index < _settings->DynamicChannelCount; index++)
{
_settings->DynamicChannelArray[index] = freerdp_dynamic_channel_clone(
settings->DynamicChannelArray[index]);
if (!_settings->DynamicChannelArray[index])
goto out_fail;
}
_settings->SettingsModified = (BYTE*) calloc(1, sizeof(rdpSettings) / 8);
if (!_settings->SettingsModified)
goto out_fail;
}
return _settings;
out_fail:
/* In case any memory allocation failed during clone, some bytes might leak.
*
* freerdp_settings_free can't be reliable used at this point since it could
* free memory of pointers copied by CopyMemory and detecting and freeing
* each allocation separately is quite painful.
*/
free(_settings);
return NULL;
}
void freerdp_settings_free(rdpSettings* settings)
{
if (!settings)
return;
free(settings->ServerHostname);
free(settings->Username);
free(settings->Password);
free(settings->Domain);
free(settings->PasswordHash);
free(settings->AcceptedCert);
free(settings->AlternateShell);
free(settings->ShellWorkingDirectory);
free(settings->ComputerName);
free(settings->ChannelDefArray);
free(settings->MonitorDefArray);
free(settings->MonitorIds);
free(settings->ClientAddress);
free(settings->ClientDir);
free(settings->AllowedTlsCiphers);
free(settings->NtlmSamFile);
free(settings->CertificateFile);
free(settings->PrivateKeyFile);
free(settings->ConnectionFile);
free(settings->AssistanceFile);
free(settings->ReceivedCapabilities);
free(settings->OrderSupport);
free(settings->ClientHostname);
free(settings->ClientProductId);
free(settings->ServerRandom);
free(settings->ClientRandom);
free(settings->ServerCertificate);
free(settings->RdpKeyFile);
certificate_free(settings->RdpServerCertificate);
free(settings->CertificateContent);
free(settings->PrivateKeyContent);
free(settings->RdpKeyContent);
free(settings->ClientAutoReconnectCookie);
free(settings->ServerAutoReconnectCookie);
free(settings->ClientTimeZone);
free(settings->BitmapCacheV2CellInfo);
free(settings->GlyphCache);
free(settings->FragCache);
key_free(settings->RdpServerRsaKey);
free(settings->ConfigPath);
free(settings->CurrentPath);
free(settings->HomePath);
free(settings->LoadBalanceInfo);
free(settings->TargetNetAddress);
free(settings->RedirectionTargetFQDN);
free(settings->RedirectionTargetNetBiosName);
free(settings->RedirectionUsername);
free(settings->RedirectionDomain);
free(settings->RedirectionPassword);
free(settings->RedirectionTsvUrl);
free(settings->RedirectionAcceptedCert);
free(settings->RemoteAssistanceSessionId);
free(settings->RemoteAssistancePassword);
free(settings->RemoteAssistancePassStub);
free(settings->RemoteAssistanceRCTicket);
free(settings->AuthenticationServiceClass);
free(settings->GatewayHostname);
free(settings->GatewayUsername);
free(settings->GatewayPassword);
free(settings->GatewayDomain);
free(settings->GatewayAccessToken);
free(settings->GatewayAcceptedCert);
free(settings->CertificateName);
free(settings->DynamicDSTTimeZoneKeyName);
free(settings->PreconnectionBlob);
free(settings->KerberosKdc);
free(settings->KerberosRealm);
free(settings->DumpRemoteFxFile);
free(settings->PlayRemoteFxFile);
free(settings->RemoteApplicationName);
free(settings->RemoteApplicationIcon);
free(settings->RemoteApplicationProgram);
free(settings->RemoteApplicationFile);
free(settings->RemoteApplicationGuid);
free(settings->RemoteApplicationCmdLine);
free(settings->ImeFileName);
free(settings->DrivesToRedirect);
free(settings->WindowTitle);
free(settings->WmClass);
free(settings->ActionScript);
freerdp_target_net_addresses_free(settings);
freerdp_device_collection_free(settings);
freerdp_static_channel_collection_free(settings);
freerdp_dynamic_channel_collection_free(settings);
free(settings->SettingsModified);
free(settings);
}
#ifdef _WIN32
#pragma warning(pop)
#endif
| bmiklautz/debian-freerdp2 | libfreerdp/core/settings.c | C | apache-2.0 | 41,463 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML
><HEAD
><TITLE
>dblink_cancel_query</TITLE
><META
NAME="GENERATOR"
CONTENT="Modular DocBook HTML Stylesheet Version 1.79"><LINK
REV="MADE"
HREF="mailto:[email protected]"><LINK
REL="HOME"
TITLE="PostgreSQL 9.2.8 Documentation"
HREF="index.html"><LINK
REL="UP"
TITLE="dblink"
HREF="dblink.html"><LINK
REL="PREVIOUS"
TITLE="dblink_get_result"
HREF="contrib-dblink-get-result.html"><LINK
REL="NEXT"
TITLE="dblink_get_pkey"
HREF="contrib-dblink-get-pkey.html"><LINK
REL="STYLESHEET"
TYPE="text/css"
HREF="stylesheet.css"><META
HTTP-EQUIV="Content-Type"
CONTENT="text/html; charset=ISO-8859-1"><META
NAME="creation"
CONTENT="2014-03-17T19:46:29"></HEAD
><BODY
CLASS="REFENTRY"
><DIV
CLASS="NAVHEADER"
><TABLE
SUMMARY="Header navigation table"
WIDTH="100%"
BORDER="0"
CELLPADDING="0"
CELLSPACING="0"
><TR
><TH
COLSPAN="5"
ALIGN="center"
VALIGN="bottom"
><A
HREF="index.html"
>PostgreSQL 9.2.8 Documentation</A
></TH
></TR
><TR
><TD
WIDTH="10%"
ALIGN="left"
VALIGN="top"
><A
TITLE="dblink_get_result"
HREF="contrib-dblink-get-result.html"
ACCESSKEY="P"
>Prev</A
></TD
><TD
WIDTH="10%"
ALIGN="left"
VALIGN="top"
><A
HREF="dblink.html"
ACCESSKEY="U"
>Up</A
></TD
><TD
WIDTH="60%"
ALIGN="center"
VALIGN="bottom"
></TD
><TD
WIDTH="20%"
ALIGN="right"
VALIGN="top"
><A
TITLE="dblink_get_pkey"
HREF="contrib-dblink-get-pkey.html"
ACCESSKEY="N"
>Next</A
></TD
></TR
></TABLE
><HR
ALIGN="LEFT"
WIDTH="100%"></DIV
><H1
><A
NAME="CONTRIB-DBLINK-CANCEL-QUERY"
></A
>dblink_cancel_query</H1
><DIV
CLASS="REFNAMEDIV"
><A
NAME="AEN142312"
></A
><H2
>Name</H2
>dblink_cancel_query -- cancels any active query on the named connection</DIV
><DIV
CLASS="REFSYNOPSISDIV"
><A
NAME="AEN142315"
></A
><H2
>Synopsis</H2
><PRE
CLASS="SYNOPSIS"
>dblink_cancel_query(text connname) returns text</PRE
></DIV
><DIV
CLASS="REFSECT1"
><A
NAME="AEN142317"
></A
><H2
>Description</H2
><P
> <CODE
CLASS="FUNCTION"
>dblink_cancel_query</CODE
> attempts to cancel any query that
is in progress on the named connection. Note that this is not
certain to succeed (since, for example, the remote query might
already have finished). A cancel request simply improves the
odds that the query will fail soon. You must still complete the
normal query protocol, for example by calling
<CODE
CLASS="FUNCTION"
>dblink_get_result</CODE
>.
</P
></DIV
><DIV
CLASS="REFSECT1"
><A
NAME="AEN142322"
></A
><H2
>Arguments</H2
><P
></P
><DIV
CLASS="VARIABLELIST"
><DL
><DT
><TT
CLASS="PARAMETER"
>conname</TT
></DT
><DD
><P
> Name of the connection to use.
</P
></DD
></DL
></DIV
></DIV
><DIV
CLASS="REFSECT1"
><A
NAME="AEN142330"
></A
><H2
>Return Value</H2
><P
> Returns <TT
CLASS="LITERAL"
>OK</TT
> if the cancel request has been sent, or
the text of an error message on failure.
</P
></DIV
><DIV
CLASS="REFSECT1"
><A
NAME="AEN142334"
></A
><H2
>Examples</H2
><PRE
CLASS="PROGRAMLISTING"
>SELECT dblink_cancel_query('dtest1');</PRE
></DIV
><DIV
CLASS="NAVFOOTER"
><HR
ALIGN="LEFT"
WIDTH="100%"><TABLE
SUMMARY="Footer navigation table"
WIDTH="100%"
BORDER="0"
CELLPADDING="0"
CELLSPACING="0"
><TR
><TD
WIDTH="33%"
ALIGN="left"
VALIGN="top"
><A
HREF="contrib-dblink-get-result.html"
ACCESSKEY="P"
>Prev</A
></TD
><TD
WIDTH="34%"
ALIGN="center"
VALIGN="top"
><A
HREF="index.html"
ACCESSKEY="H"
>Home</A
></TD
><TD
WIDTH="33%"
ALIGN="right"
VALIGN="top"
><A
HREF="contrib-dblink-get-pkey.html"
ACCESSKEY="N"
>Next</A
></TD
></TR
><TR
><TD
WIDTH="33%"
ALIGN="left"
VALIGN="top"
>dblink_get_result</TD
><TD
WIDTH="34%"
ALIGN="center"
VALIGN="top"
><A
HREF="dblink.html"
ACCESSKEY="U"
>Up</A
></TD
><TD
WIDTH="33%"
ALIGN="right"
VALIGN="top"
>dblink_get_pkey</TD
></TR
></TABLE
></DIV
></BODY
></HTML
> | ArcherCraftStore/ArcherVMPeridot | pgsql/doc/postgresql/html/contrib-dblink-cancel-query.html | HTML | apache-2.0 | 3,817 |
// Copyright (c) 2015-2016 Yuya Ochiai
// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import AutoLaunch from 'auto-launch';
import {app} from 'electron';
function shouldQuitApp(cmd) {
if (process.platform !== 'win32') {
return false;
}
const squirrelCommands = ['--squirrel-install', '--squirrel-updated', '--squirrel-uninstall', '--squirrel-obsolete'];
return squirrelCommands.includes(cmd);
}
async function setupAutoLaunch(cmd) {
const appLauncher = new AutoLaunch({
name: app.getName(),
isHidden: true,
});
if (cmd === '--squirrel-uninstall') {
// If we're uninstalling, make sure we also delete our auto launch registry key
await appLauncher.disable();
} else if (cmd === '--squirrel-install' || cmd === '--squirrel-updated') {
// If we're updating and already have an registry entry for auto launch, make sure to update the path
const enabled = await appLauncher.isEnabled();
if (enabled) {
await appLauncher.enable();
}
}
}
export default function squirrelStartup(callback) {
if (process.platform === 'win32') {
const cmd = process.argv[1];
setupAutoLaunch(cmd).then(() => {
if (require('electron-squirrel-startup') && callback) { // eslint-disable-line global-require
callback();
}
});
return shouldQuitApp(cmd);
}
return false;
}
| yuya-oc/desktop | src/main/squirrelStartup.js | JavaScript | apache-2.0 | 1,409 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.