repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
cuijinquan/DexHunter | dalvik/dexgen/src/com/android/dexgen/dex/file/ItemType.java | 3387 | /*
* 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.android.dexgen.dex.file;
import com.android.dexgen.util.ToHuman;
/**
* Enumeration of all the top-level item types.
*/
public enum ItemType implements ToHuman {
TYPE_HEADER_ITEM( 0x0000, "header_item"),
TYPE_STRING_ID_ITEM( 0x0001, "string_id_item"),
TYPE_TYPE_ID_ITEM( 0x0002, "type_id_item"),
TYPE_PROTO_ID_ITEM( 0x0003, "proto_id_item"),
TYPE_FIELD_ID_ITEM( 0x0004, "field_id_item"),
TYPE_METHOD_ID_ITEM( 0x0005, "method_id_item"),
TYPE_CLASS_DEF_ITEM( 0x0006, "class_def_item"),
TYPE_MAP_LIST( 0x1000, "map_list"),
TYPE_TYPE_LIST( 0x1001, "type_list"),
TYPE_ANNOTATION_SET_REF_LIST( 0x1002, "annotation_set_ref_list"),
TYPE_ANNOTATION_SET_ITEM( 0x1003, "annotation_set_item"),
TYPE_CLASS_DATA_ITEM( 0x2000, "class_data_item"),
TYPE_CODE_ITEM( 0x2001, "code_item"),
TYPE_STRING_DATA_ITEM( 0x2002, "string_data_item"),
TYPE_DEBUG_INFO_ITEM( 0x2003, "debug_info_item"),
TYPE_ANNOTATION_ITEM( 0x2004, "annotation_item"),
TYPE_ENCODED_ARRAY_ITEM( 0x2005, "encoded_array_item"),
TYPE_ANNOTATIONS_DIRECTORY_ITEM(0x2006, "annotations_directory_item"),
TYPE_MAP_ITEM( -1, "map_item"),
TYPE_TYPE_ITEM( -1, "type_item"),
TYPE_EXCEPTION_HANDLER_ITEM( -1, "exception_handler_item"),
TYPE_ANNOTATION_SET_REF_ITEM( -1, "annotation_set_ref_item");
/** value when represented in a {@link MapItem} */
private final int mapValue;
/** {@code non-null;} name of the type */
private final String typeName;
/** {@code non-null;} the short human name */
private final String humanName;
/**
* Constructs an instance.
*
* @param mapValue value when represented in a {@link MapItem}
* @param typeName {@code non-null;} name of the type
*/
private ItemType(int mapValue, String typeName) {
this.mapValue = mapValue;
this.typeName = typeName;
// Make the human name.
String human = typeName;
if (human.endsWith("_item")) {
human = human.substring(0, human.length() - 5);
}
this.humanName = human.replace('_', ' ');
}
/**
* Gets the map value.
*
* @return the map value
*/
public int getMapValue() {
return mapValue;
}
/**
* Gets the type name.
*
* @return {@code non-null;} the type name
*/
public String getTypeName() {
return typeName;
}
/** {@inheritDoc} */
public String toHuman() {
return humanName;
}
}
| apache-2.0 |
curso007/camel | tests/camel-itest-karaf/src/test/java/org/apache/camel/itest/karaf/CamelDrillTest.java | 1192 | /**
* 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.itest.karaf;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.junit.PaxExam;
@RunWith(PaxExam.class)
public class CamelDrillTest extends BaseKarafTest {
public static final String COMPONENT = extractName(CamelDrillTest.class);
@Test
public void test() throws Exception {
testComponent(COMPONENT);
}
}
| apache-2.0 |
android-ia/platform_tools_idea | platform/vcs-impl/src/com/intellij/openapi/vcs/actions/ContentsLines.java | 2888 | /*
* Copyright 2000-2011 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.vcs.actions;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.text.StringUtil;
import java.util.ArrayList;
import java.util.List;
/**
* @author irengrig
* Date: 4/27/11
* Time: 3:42 PM
*/
public class ContentsLines {
private final static Logger LOG = Logger.getInstance("#com.intellij.openapi.vcs.actions.ContentsLines");
private final SplittingIterator mySplittingIterator;
private final List<Integer> myLinesStartOffsets;
private final String myContents;
private boolean myLineEndsFinished;
public ContentsLines(final String contents) {
myContents = contents;
mySplittingIterator = new SplittingIterator(contents);
myLinesStartOffsets = new ArrayList<Integer>();
}
public String getLineContents(final int number) {
assert !myLineEndsFinished || myLinesStartOffsets.size() > number;
// we need to know end
if (myLineEndsFinished || (myLinesStartOffsets.size() > (number + 1))) {
return extractCalculated(number);
}
while (((myLinesStartOffsets.size() - 1) < (number + 1)) && (!myLineEndsFinished) && mySplittingIterator.hasNext()) {
final Integer nextStart = mySplittingIterator.next();
myLinesStartOffsets.add(nextStart);
}
myLineEndsFinished = myLinesStartOffsets.size() < (number + 1);
return extractCalculated(number);
}
private String extractCalculated(int number) {
try {
String text = myContents.substring(myLinesStartOffsets.get(number),
(number + 1 >= myLinesStartOffsets.size())
? myContents.length()
: myLinesStartOffsets.get(number + 1));
text = text.endsWith("\r\n") ? text.substring(0, text.length() - 2) : text;
text = (text.endsWith("\r") || text.endsWith("\n")) ? text.substring(0, text.length() - 1) : text;
return text;
} catch (IndexOutOfBoundsException e) {
LOG.error("Loaded contents lines: " + StringUtil.getLineBreakCount(myContents), e);
throw e;
}
}
public boolean isLineEndsFinished() {
return myLineEndsFinished;
}
public int getKnownLinesNumber() {
return myLineEndsFinished ? myLinesStartOffsets.size() : -1;
}
}
| apache-2.0 |
marsorp/blog | presto166/presto-main/src/main/java/com/facebook/presto/operator/aggregation/state/DigestAndPercentileState.java | 1199 | /*
* 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.facebook.presto.operator.aggregation.state;
import com.facebook.presto.spi.function.AccumulatorState;
import com.facebook.presto.spi.function.AccumulatorStateMetadata;
import io.airlift.stats.QuantileDigest;
@AccumulatorStateMetadata(stateSerializerClass = DigestAndPercentileStateSerializer.class, stateFactoryClass = DigestAndPercentileStateFactory.class)
public interface DigestAndPercentileState
extends AccumulatorState
{
QuantileDigest getDigest();
void setDigest(QuantileDigest digest);
double getPercentile();
void setPercentile(double percentile);
void addMemoryUsage(int value);
}
| apache-2.0 |
bbrouwer/spring-boot | spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFileTests.java | 2740 | /*
* Copyright 2012-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.devtools.restart.classloader;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.boot.devtools.restart.classloader.ClassLoaderFile.Kind;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link ClassLoaderFile}.
*
* @author Phillip Webb
*/
public class ClassLoaderFileTests {
public static final byte[] BYTES = "ABC".getBytes();
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void kindMustNotBeNull() {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Kind must not be null");
new ClassLoaderFile(null, null);
}
@Test
public void addedContentsMustNotBeNull() throws Exception {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Contents must not be null");
new ClassLoaderFile(Kind.ADDED, null);
}
@Test
public void modifiedContentsMustNotBeNull() throws Exception {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Contents must not be null");
new ClassLoaderFile(Kind.MODIFIED, null);
}
@Test
public void deletedContentsMustBeNull() throws Exception {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Contents must be null");
new ClassLoaderFile(Kind.DELETED, new byte[10]);
}
@Test
public void added() throws Exception {
ClassLoaderFile file = new ClassLoaderFile(Kind.ADDED, BYTES);
assertThat(file.getKind()).isEqualTo(ClassLoaderFile.Kind.ADDED);
assertThat(file.getContents()).isEqualTo(BYTES);
}
@Test
public void modified() throws Exception {
ClassLoaderFile file = new ClassLoaderFile(Kind.MODIFIED, BYTES);
assertThat(file.getKind()).isEqualTo(ClassLoaderFile.Kind.MODIFIED);
assertThat(file.getContents()).isEqualTo(BYTES);
}
@Test
public void deleted() throws Exception {
ClassLoaderFile file = new ClassLoaderFile(Kind.DELETED, null);
assertThat(file.getKind()).isEqualTo(ClassLoaderFile.Kind.DELETED);
assertThat(file.getContents()).isNull();
}
}
| apache-2.0 |
YMartsynkevych/camel | components/camel-cassandraql/src/main/java/org/apache/camel/processor/aggregate/cassandra/CassandraAggregationRepository.java | 15570 | /**
* 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.processor.aggregate.cassandra;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.ConsistencyLevel;
import com.datastax.driver.core.PreparedStatement;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.querybuilder.Delete;
import com.datastax.driver.core.querybuilder.Insert;
import com.datastax.driver.core.querybuilder.Select;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.spi.AggregationRepository;
import org.apache.camel.spi.RecoverableAggregationRepository;
import org.apache.camel.support.ServiceSupport;
import org.apache.camel.utils.cassandra.CassandraSessionHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.datastax.driver.core.querybuilder.QueryBuilder.bindMarker;
import static com.datastax.driver.core.querybuilder.QueryBuilder.eq;
import static org.apache.camel.utils.cassandra.CassandraUtils.append;
import static org.apache.camel.utils.cassandra.CassandraUtils.applyConsistencyLevel;
import static org.apache.camel.utils.cassandra.CassandraUtils.concat;
import static org.apache.camel.utils.cassandra.CassandraUtils.generateDelete;
import static org.apache.camel.utils.cassandra.CassandraUtils.generateInsert;
import static org.apache.camel.utils.cassandra.CassandraUtils.generateSelect;
/**
* Implementation of {@link AggregationRepository} using Cassandra table to store
* exchanges.
* Advice: use LeveledCompaction for this table and tune read/write consistency levels.
* Warning: Cassandra is not the best tool for queuing use cases
* See: http://www.datastax.com/dev/blog/cassandra-anti-patterns-queues-and-queue-like-datasets
*/
public class CassandraAggregationRepository extends ServiceSupport implements RecoverableAggregationRepository {
/**
* Logger
*/
private static final Logger LOGGER = LoggerFactory.getLogger(CassandraAggregationRepository.class);
/**
* Session holder
*/
private CassandraSessionHolder sessionHolder;
/**
* Table name
*/
private String table = "CAMEL_AGGREGATION";
/**
* Exchange Id column name
*/
private String exchangeIdColumn = "EXCHANGE_ID";
/**
* Exchange column name
*/
private String exchangeColumn = "EXCHANGE";
/**
* Values used as primary key prefix
*/
private Object[] prefixPKValues = new Object[0];
/**
* Primary key columns
*/
private String[] pkColumns = {"KEY"};
/**
* Exchange marshaller/unmarshaller
*/
private final CassandraCamelCodec exchangeCodec = new CassandraCamelCodec();
/**
* Time to live in seconds used for inserts
*/
private Integer ttl;
/**
* Writeconsistency level
*/
private ConsistencyLevel writeConsistencyLevel;
/**
* Read consistency level
*/
private ConsistencyLevel readConsistencyLevel;
private PreparedStatement insertStatement;
private PreparedStatement selectStatement;
private PreparedStatement deleteStatement;
/**
* Prepared statement used to get exchangeIds and exchange ids
*/
private PreparedStatement selectKeyIdStatement;
/**
* Prepared statement used to delete with key and exchange id
*/
private PreparedStatement deleteIfIdStatement;
private long recoveryIntervalInMillis = 5000;
private boolean useRecovery = true;
private String deadLetterUri;
private int maximumRedeliveries;
public CassandraAggregationRepository() {
}
public CassandraAggregationRepository(Session session) {
this.sessionHolder = new CassandraSessionHolder(session);
}
public CassandraAggregationRepository(Cluster cluster, String keyspace) {
this.sessionHolder = new CassandraSessionHolder(cluster, keyspace);
}
/**
* Generate primary key values from aggregation key.
*/
protected Object[] getPKValues(String key) {
return append(prefixPKValues, key);
}
/**
* Get aggregation key colum name.
*/
private String getKeyColumn() {
return pkColumns[pkColumns.length - 1];
}
private String[] getAllColumns() {
return append(pkColumns, exchangeIdColumn, exchangeColumn);
}
//--------------------------------------------------------------------------
// Service support
@Override
protected void doStart() throws Exception {
sessionHolder.start();
initInsertStatement();
initSelectStatement();
initDeleteStatement();
initSelectKeyIdStatement();
initDeleteIfIdStatement();
}
@Override
protected void doStop() throws Exception {
sessionHolder.stop();
}
// -------------------------------------------------------------------------
// Add exchange to repository
private void initInsertStatement() {
Insert insert = generateInsert(table,
getAllColumns(),
false, ttl);
insert = applyConsistencyLevel(insert, writeConsistencyLevel);
LOGGER.debug("Generated Insert {}", insert);
insertStatement = getSession().prepare(insert);
}
/**
* Insert or update exchange in aggregation table.
*/
@Override
public Exchange add(CamelContext camelContext, String key, Exchange exchange) {
final Object[] idValues = getPKValues(key);
LOGGER.debug("Inserting key {} exchange {}", idValues, exchange);
try {
ByteBuffer marshalledExchange = exchangeCodec.marshallExchange(camelContext, exchange);
Object[] cqlParams = concat(idValues, new Object[]{exchange.getExchangeId(), marshalledExchange});
getSession().execute(insertStatement.bind(cqlParams));
return exchange;
} catch (IOException iOException) {
throw new CassandraAggregationException("Failed to write exchange", exchange, iOException);
}
}
// -------------------------------------------------------------------------
// Get exchange from repository
protected void initSelectStatement() {
Select select = generateSelect(table,
getAllColumns(),
pkColumns);
select = (Select) applyConsistencyLevel(select, readConsistencyLevel);
LOGGER.debug("Generated Select {}", select);
selectStatement = getSession().prepare(select);
}
/**
* Get exchange from aggregation table by aggregation key.
*/
@Override
public Exchange get(CamelContext camelContext, String key) {
Object[] pkValues = getPKValues(key);
LOGGER.debug("Selecting key {} ", pkValues);
Row row = getSession().execute(selectStatement.bind(pkValues)).one();
Exchange exchange = null;
if (row != null) {
try {
exchange = exchangeCodec.unmarshallExchange(camelContext, row.getBytes(exchangeColumn));
} catch (IOException iOException) {
throw new CassandraAggregationException("Failed to read exchange", exchange, iOException);
} catch (ClassNotFoundException classNotFoundException) {
throw new CassandraAggregationException("Failed to read exchange", exchange, classNotFoundException);
}
}
return exchange;
}
// -------------------------------------------------------------------------
// Confirm exchange in repository
private void initDeleteIfIdStatement() {
Delete delete = generateDelete(table, pkColumns, false);
Delete.Conditions deleteIf = delete.onlyIf(eq(exchangeIdColumn, bindMarker()));
deleteIf = applyConsistencyLevel(deleteIf, writeConsistencyLevel);
LOGGER.debug("Generated Delete If Id {}", deleteIf);
deleteIfIdStatement = getSession().prepare(deleteIf);
}
/**
* Remove exchange by Id from aggregation table.
*/
@Override
public void confirm(CamelContext camelContext, String exchangeId) {
String keyColumn = getKeyColumn();
LOGGER.debug("Selecting Ids");
List<Row> rows = selectKeyIds();
for (Row row : rows) {
if (row.getString(exchangeIdColumn).equals(exchangeId)) {
String key = row.getString(keyColumn);
Object[] cqlParams = append(getPKValues(key), exchangeId);
LOGGER.debug("Deleting If Id {} ", cqlParams);
getSession().execute(deleteIfIdStatement.bind(cqlParams));
}
}
}
// -------------------------------------------------------------------------
// Remove exchange from repository
private void initDeleteStatement() {
Delete delete = generateDelete(table, pkColumns, false);
delete = applyConsistencyLevel(delete, writeConsistencyLevel);
LOGGER.debug("Generated Delete {}", delete);
deleteStatement = getSession().prepare(delete);
}
/**
* Remove exchange by aggregation key from aggregation table.
*/
@Override
public void remove(CamelContext camelContext, String key, Exchange exchange) {
Object[] idValues = getPKValues(key);
LOGGER.debug("Deleting key {}", (Object) idValues);
getSession().execute(deleteStatement.bind(idValues));
}
// -------------------------------------------------------------------------
private void initSelectKeyIdStatement() {
Select select = generateSelect(table,
new String[]{getKeyColumn(), exchangeIdColumn}, // Key + Exchange Id columns
pkColumns, pkColumns.length - 1); // Where fixed PK columns
select = applyConsistencyLevel(select, readConsistencyLevel);
LOGGER.debug("Generated Select keys {}", select);
selectKeyIdStatement = getSession().prepare(select);
}
protected List<Row> selectKeyIds() {
LOGGER.debug("Selecting keys {}", getPrefixPKValues());
return getSession().execute(selectKeyIdStatement.bind(getPrefixPKValues())).all();
}
/**
* Get aggregation exchangeIds from aggregation table.
*/
@Override
public Set<String> getKeys() {
List<Row> rows = selectKeyIds();
Set<String> keys = new HashSet<String>(rows.size());
String keyColumnName = getKeyColumn();
for (Row row : rows) {
keys.add(row.getString(keyColumnName));
}
return keys;
}
/**
* Get exchange IDs to be recovered
*
* @return Exchange IDs
*/
@Override
public Set<String> scan(CamelContext camelContext) {
List<Row> rows = selectKeyIds();
Set<String> exchangeIds = new HashSet<String>(rows.size());
for (Row row : rows) {
exchangeIds.add(row.getString(exchangeIdColumn));
}
return exchangeIds;
}
/**
* Get exchange by exchange ID.
* This is far from optimal.
*/
@Override
public Exchange recover(CamelContext camelContext, String exchangeId) {
List<Row> rows = selectKeyIds();
String keyColumnName = getKeyColumn();
String lKey = null;
for (Row row : rows) {
String lExchangeId = row.getString(exchangeIdColumn);
if (lExchangeId.equals(exchangeId)) {
lKey = row.getString(keyColumnName);
break;
}
}
return lKey == null ? null : get(camelContext, lKey);
}
// -------------------------------------------------------------------------
// Getters and Setters
public Session getSession() {
return sessionHolder.getSession();
}
public void setSession(Session session) {
this.sessionHolder = new CassandraSessionHolder(session);
}
public String getTable() {
return table;
}
public void setTable(String table) {
this.table = table;
}
public Object[] getPrefixPKValues() {
return prefixPKValues;
}
public void setPrefixPKValues(Object... prefixPKValues) {
this.prefixPKValues = prefixPKValues;
}
public String[] getPKColumns() {
return pkColumns;
}
public void setPKColumns(String... pkColumns) {
this.pkColumns = pkColumns;
}
public String getExchangeIdColumn() {
return exchangeIdColumn;
}
public void setExchangeIdColumn(String exchangeIdColumn) {
this.exchangeIdColumn = exchangeIdColumn;
}
public ConsistencyLevel getWriteConsistencyLevel() {
return writeConsistencyLevel;
}
public void setWriteConsistencyLevel(ConsistencyLevel writeConsistencyLevel) {
this.writeConsistencyLevel = writeConsistencyLevel;
}
public ConsistencyLevel getReadConsistencyLevel() {
return readConsistencyLevel;
}
public void setReadConsistencyLevel(ConsistencyLevel readConsistencyLevel) {
this.readConsistencyLevel = readConsistencyLevel;
}
public String getExchangeColumn() {
return exchangeColumn;
}
public void setExchangeColumn(String exchangeColumnName) {
this.exchangeColumn = exchangeColumnName;
}
public Integer getTtl() {
return ttl;
}
public void setTtl(Integer ttl) {
this.ttl = ttl;
}
@Override
public long getRecoveryIntervalInMillis() {
return recoveryIntervalInMillis;
}
public void setRecoveryIntervalInMillis(long recoveryIntervalInMillis) {
this.recoveryIntervalInMillis = recoveryIntervalInMillis;
}
@Override
public void setRecoveryInterval(long interval, TimeUnit timeUnit) {
this.recoveryIntervalInMillis = timeUnit.toMillis(interval);
}
@Override
public void setRecoveryInterval(long recoveryIntervalInMillis) {
this.recoveryIntervalInMillis = recoveryIntervalInMillis;
}
@Override
public boolean isUseRecovery() {
return useRecovery;
}
@Override
public void setUseRecovery(boolean useRecovery) {
this.useRecovery = useRecovery;
}
@Override
public String getDeadLetterUri() {
return deadLetterUri;
}
@Override
public void setDeadLetterUri(String deadLetterUri) {
this.deadLetterUri = deadLetterUri;
}
@Override
public int getMaximumRedeliveries() {
return maximumRedeliveries;
}
@Override
public void setMaximumRedeliveries(int maximumRedeliveries) {
this.maximumRedeliveries = maximumRedeliveries;
}
}
| apache-2.0 |
RohanHart/camel | components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/MongoDbTailableCursorConsumer.java | 2469 | /**
* 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.mongodb;
import java.util.concurrent.ExecutorService;
import org.apache.camel.Processor;
import org.apache.camel.impl.DefaultConsumer;
/**
* The MongoDb consumer.
*/
public class MongoDbTailableCursorConsumer extends DefaultConsumer {
private final MongoDbEndpoint endpoint;
private ExecutorService executor;
private MongoDbTailingProcess tailingProcess;
public MongoDbTailableCursorConsumer(MongoDbEndpoint endpoint, Processor processor) {
super(endpoint, processor);
this.endpoint = endpoint;
}
@Override
protected void doStop() throws Exception {
super.doStop();
if (tailingProcess != null) {
tailingProcess.stop();
}
if (executor != null) {
endpoint.getCamelContext().getExecutorServiceManager().shutdown(executor);
executor = null;
}
}
@Override
protected void doStart() throws Exception {
super.doStart();
executor = endpoint.getCamelContext().getExecutorServiceManager().newFixedThreadPool(this, endpoint.getEndpointUri(), 1);
MongoDbTailTrackingManager trackingManager = initTailTracking();
tailingProcess = new MongoDbTailingProcess(endpoint, this, trackingManager);
tailingProcess.initializeProcess();
executor.execute(tailingProcess);
}
protected MongoDbTailTrackingManager initTailTracking() throws Exception {
MongoDbTailTrackingManager answer = new MongoDbTailTrackingManager(endpoint.getMongoConnection(), endpoint.getTailTrackingConfig());
answer.initialize();
return answer;
}
}
| apache-2.0 |
rokn/Count_Words_2015 | testing/openjdk2/corba/src/share/classes/org/omg/CORBA/INTERNAL.java | 3557 | /*
* Copyright (c) 1995, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.omg.CORBA;
/**
* This exception indicates an internal failure in an ORB, for
* example, if an ORB has detected corruption of its internal
* data structures.<P>
* It contains a minor code, which gives more detailed information about
* what caused the exception, and a completion status. It may also contain
* a string describing the exception.
* <P>
* See the section <A href="../../../../technotes/guides/idl/jidlExceptions.html#minorcodemeanings">meaning
* of minor codes</A> to see the minor codes for this exception.
*
* @see <A href="../../../../technotes/guides/idl/jidlExceptions.html">documentation on
* Java IDL exceptions</A>
* @since JDK1.2
*/
public final class INTERNAL extends SystemException {
/**
* Constructs an <code>INTERNAL</code> exception with a default
* minor code of 0 and a completion state of COMPLETED_NO.
*/
public INTERNAL() {
this("");
}
/**
* Constructs an <code>INTERNAL</code> exception with the specified detail
* message, a minor code of 0, and a completion state of COMPLETED_NO.
* @param s the String containing a detail message
*/
public INTERNAL(String s) {
this(s, 0, CompletionStatus.COMPLETED_NO);
}
/**
* Constructs an <code>INTERNAL</code> exception with the specified
* minor code and completion status.
* @param minor the minor code
* @param completed an instance of <code>CompletionStatus</code>
* that indicates the completion status of the method
* that threw this exception
*/
public INTERNAL(int minor, CompletionStatus completed) {
this("", minor, completed);
}
/**
* Constructs an <code>INTERNAL</code> exception with the specified detail
* message, minor code, and completion status.
* A detail message is a String that describes this particular exception.
* @param s the String containing a detail message
* @param minor the minor code
* @param completed an instance of <code>CompletionStatus</code>
* that indicates the completion status of the method
* that threw this exception
*/
public INTERNAL(String s, int minor, CompletionStatus completed) {
super(s, minor, completed);
}
}
| mit |
logzio/camel | camel-core/src/main/java/org/apache/camel/component/file/FileConsumer.java | 7113 | /**
* 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.file;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import org.apache.camel.Processor;
import org.apache.camel.util.FileUtil;
import org.apache.camel.util.ObjectHelper;
/**
* File consumer.
*/
public class FileConsumer extends GenericFileConsumer<File> {
private String endpointPath;
public FileConsumer(GenericFileEndpoint<File> endpoint, Processor processor, GenericFileOperations<File> operations) {
super(endpoint, processor, operations);
this.endpointPath = endpoint.getConfiguration().getDirectory();
}
@Override
protected boolean pollDirectory(String fileName, List<GenericFile<File>> fileList, int depth) {
log.trace("pollDirectory from fileName: {}", fileName);
depth++;
File directory = new File(fileName);
if (!directory.exists() || !directory.isDirectory()) {
log.debug("Cannot poll as directory does not exists or its not a directory: {}", directory);
if (getEndpoint().isDirectoryMustExist()) {
throw new GenericFileOperationFailedException("Directory does not exist: " + directory);
}
return true;
}
log.trace("Polling directory: {}", directory.getPath());
File[] dirFiles = directory.listFiles();
if (dirFiles == null || dirFiles.length == 0) {
// no files in this directory to poll
if (log.isTraceEnabled()) {
log.trace("No files found in directory: {}", directory.getPath());
}
return true;
} else {
// we found some files
if (log.isTraceEnabled()) {
log.trace("Found {} in directory: {}", dirFiles.length, directory.getPath());
}
}
List<File> files = Arrays.asList(dirFiles);
for (File file : files) {
// check if we can continue polling in files
if (!canPollMoreFiles(fileList)) {
return false;
}
// trace log as Windows/Unix can have different views what the file is?
if (log.isTraceEnabled()) {
log.trace("Found file: {} [isAbsolute: {}, isDirectory: {}, isFile: {}, isHidden: {}]",
new Object[]{file, file.isAbsolute(), file.isDirectory(), file.isFile(), file.isHidden()});
}
// creates a generic file
GenericFile<File> gf = asGenericFile(endpointPath, file, getEndpoint().getCharset());
if (file.isDirectory()) {
if (endpoint.isRecursive() && depth < endpoint.getMaxDepth() && isValidFile(gf, true, files)) {
// recursive scan and add the sub files and folders
String subDirectory = fileName + File.separator + file.getName();
boolean canPollMore = pollDirectory(subDirectory, fileList, depth);
if (!canPollMore) {
return false;
}
}
} else {
// Windows can report false to a file on a share so regard it always as a file (if its not a directory)
if (depth >= endpoint.minDepth && isValidFile(gf, false, files)) {
log.trace("Adding valid file: {}", file);
// matched file so add
fileList.add(gf);
}
}
}
return true;
}
@Override
protected boolean isMatched(GenericFile<File> file, String doneFileName, List<File> files) {
String onlyName = FileUtil.stripPath(doneFileName);
// the done file name must be among the files
for (File f : files) {
if (f.getName().equals(onlyName)) {
return true;
}
}
log.trace("Done file: {} does not exist", doneFileName);
return false;
}
/**
* Creates a new GenericFile<File> based on the given file.
*
* @param endpointPath the starting directory the endpoint was configured with
* @param file the source file
* @return wrapped as a GenericFile
*/
public static GenericFile<File> asGenericFile(String endpointPath, File file, String charset) {
GenericFile<File> answer = new GenericFile<File>();
// use file specific binding
answer.setBinding(new FileBinding());
answer.setCharset(charset);
answer.setEndpointPath(endpointPath);
answer.setFile(file);
answer.setFileNameOnly(file.getName());
answer.setFileLength(file.length());
answer.setDirectory(file.isDirectory());
// must use FileUtil.isAbsolute to have consistent check for whether the file is
// absolute or not. As windows do not consider \ paths as absolute where as all
// other OS platforms will consider \ as absolute. The logic in Camel mandates
// that we align this for all OS. That is why we must use FileUtil.isAbsolute
// to return a consistent answer for all OS platforms.
answer.setAbsolute(FileUtil.isAbsolute(file));
answer.setAbsoluteFilePath(file.getAbsolutePath());
answer.setLastModified(file.lastModified());
// compute the file path as relative to the starting directory
File path;
String endpointNormalized = FileUtil.normalizePath(endpointPath);
if (file.getPath().startsWith(endpointNormalized + File.separator)) {
// skip duplicate endpoint path
path = new File(ObjectHelper.after(file.getPath(), endpointNormalized + File.separator));
} else {
path = new File(file.getPath());
}
if (path.getParent() != null) {
answer.setRelativeFilePath(path.getParent() + File.separator + file.getName());
} else {
answer.setRelativeFilePath(path.getName());
}
// the file name should be the relative path
answer.setFileName(answer.getRelativeFilePath());
// use file as body as we have converters if needed as stream
answer.setBody(file);
return answer;
}
@Override
public FileEndpoint getEndpoint() {
return (FileEndpoint) super.getEndpoint();
}
}
| apache-2.0 |
guiquanz/binnavi | src/main/java/com/google/security/zynamics/binnavi/ZyGraph/Menus/Actions/CRemoveGroupAction.java | 1730 | /*
Copyright 2015 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.google.security.zynamics.binnavi.ZyGraph.Menus.Actions;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import com.google.security.zynamics.binnavi.disassembly.CGroupNode;
import com.google.security.zynamics.binnavi.disassembly.views.INaviView;
/**
* Action class used for removing group nodes from a graph.
*/
public final class CRemoveGroupAction extends AbstractAction {
/**
* Used for serialization.
*/
private static final long serialVersionUID = 3268013685079704040L;
/**
* View from which the group node is removed.
*/
private final INaviView m_graph;
/**
* Group node to be removed from the graph.
*/
private final CGroupNode m_node;
/**
* Create a new action object.
*
* @param view View from which the group node is removed.
* @param node Group node to be removed from the graph.
*/
public CRemoveGroupAction(final INaviView view, final CGroupNode node) {
super("Remove Group");
m_graph = view;
m_node = node;
}
@Override
public void actionPerformed(final ActionEvent event) {
m_graph.getContent().deleteNode(m_node);
}
}
| apache-2.0 |
guiquanz/binnavi | src/main/java/com/google/security/zynamics/zylib/gui/zygraph/editmode/states/CBackgroundDraggedRightState.java | 2814 | /*
Copyright 2015 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.google.security.zynamics.zylib.gui.zygraph.editmode.states;
import java.awt.event.MouseEvent;
import com.google.common.base.Preconditions;
import com.google.security.zynamics.zylib.gui.zygraph.editmode.CStateChange;
import com.google.security.zynamics.zylib.gui.zygraph.editmode.IMouseState;
import com.google.security.zynamics.zylib.gui.zygraph.editmode.IMouseStateChange;
import com.google.security.zynamics.zylib.yfileswrap.gui.zygraph.AbstractZyGraph;
import com.google.security.zynamics.zylib.yfileswrap.gui.zygraph.edges.ZyGraphEdge;
import com.google.security.zynamics.zylib.yfileswrap.gui.zygraph.editmode.CStateFactory;
import com.google.security.zynamics.zylib.yfileswrap.gui.zygraph.editmode.helpers.CMousePressedHandler;
import com.google.security.zynamics.zylib.yfileswrap.gui.zygraph.nodes.ZyGraphNode;
public class CBackgroundDraggedRightState implements IMouseState {
private final CStateFactory<?, ?> m_factory;
private final AbstractZyGraph<?, ?> m_graph;
public CBackgroundDraggedRightState(final CStateFactory<?, ?> factory,
final AbstractZyGraph<?, ?> graph) {
m_factory = Preconditions.checkNotNull(factory, "Error: factory argument can not be null");
m_graph = Preconditions.checkNotNull(graph, "Error: graph argument can not be null");
}
public AbstractZyGraph<?, ?> getGraph() {
return m_graph;
}
@Override
public CStateFactory<? extends ZyGraphNode<?>, ? extends ZyGraphEdge<?, ?, ?>> getStateFactory() {
return m_factory;
}
@Override
public IMouseStateChange mouseDragged(final MouseEvent event, final AbstractZyGraph<?, ?> graph) {
return new CStateChange(this, true);
}
@Override
public IMouseStateChange mouseMoved(final MouseEvent event, final AbstractZyGraph<?, ?> graph) {
return new CStateChange(this, true);
}
@Override
public IMouseStateChange mousePressed(final MouseEvent event, final AbstractZyGraph<?, ?> graph) {
return CMousePressedHandler.handleMousePressed(m_factory, this, graph, event);
}
@Override
public IMouseStateChange mouseReleased(final MouseEvent event, final AbstractZyGraph<?, ?> graph) {
return new CStateChange(m_factory.createBackgroundClickedRightState(event), true);
}
}
| apache-2.0 |
pbibalan/multibit | src/main/java/org/multibit/viewsystem/swing/action/ShowOpenUriCancelAction.java | 2867 | /**
* Copyright 2011 multibit.org
*
* Licensed under the MIT license (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://opensource.org/licenses/mit-license.php
*
* 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.multibit.viewsystem.swing.action;
import org.multibit.controller.Controller;
import org.multibit.model.bitcoin.BitcoinModel;
import org.multibit.viewsystem.View;
import org.multibit.viewsystem.dataproviders.ShowUriDialogDataProvider;
import org.multibit.viewsystem.swing.view.dialogs.ShowOpenUriDialog;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* This {@link Action} represents a cancel action to go back to the parent view for the open uri command
*/
public class ShowOpenUriCancelAction extends AbstractAction {
private static final long serialVersionUID = 191354561231234705L;
private Controller controller;
private ShowUriDialogDataProvider dataProvider;
private ShowOpenUriDialog showOpenUriDialog;
/**
* Creates a new {@link ShowOpenUriCancelAction}.
*/
public ShowOpenUriCancelAction(Controller controller, ShowUriDialogDataProvider dataProvider, ShowOpenUriDialog showOpenUriDialog) {
super(controller.getLocaliser().getString("showOpenUriView.noText"));
this.controller = controller;
this.dataProvider = dataProvider;
this.showOpenUriDialog = showOpenUriDialog;
MnemonicUtil mnemonicUtil = new MnemonicUtil(controller.getLocaliser());
putValue(SHORT_DESCRIPTION, controller.getLocaliser().getString("cancelBackToParentAction.tooltip"));
putValue(MNEMONIC_KEY, mnemonicUtil.getMnemonic("canceBackToParentAction.mnemonicKey"));
}
/**
* return to the transactions view
*/
@Override
public void actionPerformed(ActionEvent e) {
// Item showDialogItem = dataProvider.getData().getItem(BitcoinModel.OPEN_URI_SHOW_DIALOG);
if (dataProvider != null) {
String openUriDialogAsString = (Boolean.valueOf(dataProvider.isShowUriDialog())).toString();
controller.getModel().setUserPreference(BitcoinModel.OPEN_URI_SHOW_DIALOG, openUriDialogAsString);
}
// we do not want to use the uri as the user clicked cancel
controller.getModel().setUserPreference(BitcoinModel.OPEN_URI_USE_URI, "false");
showOpenUriDialog.setVisible(false);
controller.displayView(View.TRANSACTIONS_VIEW);
}
} | mit |
ahb0327/intellij-community | plugins/cvs/javacvs-src/org/netbeans/lib/cvsclient/response/AbstractResponseHandler.java | 637 | package org.netbeans.lib.cvsclient.response;
/**
* @author Thomas Singer
*/
abstract class AbstractResponseHandler
implements IResponseHandler {
// Implemented ============================================================
public final void processOkResponse(IResponseServices responseServices) {
responseServices.getEventSender().notifyTerminationListeners(false);
}
public final void processErrorResponse(byte[] message, IResponseServices responseServices) {
responseServices.getEventSender().notifyMessageListeners(message, true, false);
responseServices.getEventSender().notifyTerminationListeners(true);
}
}
| apache-2.0 |
kanpol/zd | src/org/jf/dexlib2/dexbacked/value/DexBackedFieldEncodedValue.java | 2388 | /*
* Copyright 2012, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.jf.dexlib2.dexbacked.value;
import org.jf.dexlib2.base.value.BaseFieldEncodedValue;
import org.jf.dexlib2.dexbacked.DexBackedDexFile;
import org.jf.dexlib2.dexbacked.DexReader;
import org.jf.dexlib2.dexbacked.reference.DexBackedFieldReference;
import org.jf.dexlib2.iface.reference.FieldReference;
import javax.annotation.Nonnull;
public class DexBackedFieldEncodedValue extends BaseFieldEncodedValue {
@Nonnull public final DexBackedDexFile dexFile;
private final int fieldIndex;
public DexBackedFieldEncodedValue(@Nonnull DexReader reader, int valueArg) {
this.dexFile = reader.dexBuf;
fieldIndex = reader.readSizedSmallUint(valueArg + 1);
}
@Nonnull @Override public FieldReference getValue() {
return new DexBackedFieldReference(dexFile, fieldIndex);
}
}
| apache-2.0 |
clumsy/intellij-community | platform/platform-api/src/com/intellij/openapi/ui/popup/JBPopupAdapter.java | 854 | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.ui.popup;
/**
* @author yole
*/
public abstract class JBPopupAdapter implements JBPopupListener {
public void beforeShown(LightweightWindowEvent event) {
}
public void onClosed(LightweightWindowEvent event) {
}
} | apache-2.0 |
caot/intellij-community | plugins/cvs/javacvs-src/org/netbeans/lib/cvsclient/event/IModuleExpansionListener.java | 629 | /*
* Sun Public License Notice
*
* The contents of this file are subject to the Sun Public License
* Version 1.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://www.sun.com/
*
* The Original Code is NetBeans. The Initial Developer of the Original
* Code is Sun Microsystems, Inc. Portions Copyright 1997-2000 Sun
* Microsystems, Inc. All Rights Reserved.
*/
package org.netbeans.lib.cvsclient.event;
/**
* @author Thomas Singer
*/
public interface IModuleExpansionListener {
void moduleExpanded(String module);
}
| apache-2.0 |
asedunov/intellij-community | java/java-tests/testData/refactoring/introduceParameterObject/typeParametersWithChosenSubtype/after/Test.java | 441 | import java.util.Collection;
import java.util.List;
public class Test<U extends List> {
public Collection foo(Param param) {
return param.getP();
}
public void context1(U p) {
Collection v = foo(new Param(p));
}
private static class Param {
private final Collection p;
private Param(Collection p) {
this.p = p;
}
public Collection getP() {
return p;
}
}
}
| apache-2.0 |
Allive1/pinpoint | thirdparty/google-guava/src/main/java/com/google/common/collect/Collections2.java | 21923 | /*
* Copyright (C) 2008 The Guava 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 com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Predicates.and;
import static com.google.common.base.Predicates.in;
import static com.google.common.base.Predicates.not;
import static com.google.common.collect.CollectPreconditions.checkNonnegative;
import static com.google.common.math.LongMath.binomial;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.math.IntMath;
import com.google.common.primitives.Ints;
import java.util.AbstractCollection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nullable;
/**
* Provides static methods for working with {@code Collection} instances.
*
* @author Chris Povirk
* @author Mike Bostock
* @author Jared Levy
* @since 2.0
*/
@CheckReturnValue
@GwtCompatible
public final class Collections2 {
private Collections2() {}
/**
* Returns the elements of {@code unfiltered} that satisfy a predicate. The
* returned collection is a live view of {@code unfiltered}; changes to one
* affect the other.
*
* <p>The resulting collection's iterator does not support {@code remove()},
* but all other collection methods are supported. When given an element that
* doesn't satisfy the predicate, the collection's {@code add()} and {@code
* addAll()} methods throw an {@link IllegalArgumentException}. When methods
* such as {@code removeAll()} and {@code clear()} are called on the filtered
* collection, only elements that satisfy the filter will be removed from the
* underlying collection.
*
* <p>The returned collection isn't threadsafe or serializable, even if
* {@code unfiltered} is.
*
* <p>Many of the filtered collection's methods, such as {@code size()},
* iterate across every element in the underlying collection and determine
* which elements satisfy the filter. When a live view is <i>not</i> needed,
* it may be faster to copy {@code Iterables.filter(unfiltered, predicate)}
* and use the copy.
*
* <p><b>Warning:</b> {@code predicate} must be <i>consistent with equals</i>,
* as documented at {@link Predicate#apply}. Do not provide a predicate such
* as {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent
* with equals. (See {@link Iterables#filter(Iterable, Class)} for related
* functionality.)
*/
// TODO(kevinb): how can we omit that Iterables link when building gwt
// javadoc?
@CheckReturnValue
public static <E> Collection<E> filter(Collection<E> unfiltered, Predicate<? super E> predicate) {
if (unfiltered instanceof FilteredCollection) {
// Support clear(), removeAll(), and retainAll() when filtering a filtered
// collection.
return ((FilteredCollection<E>) unfiltered).createCombined(predicate);
}
return new FilteredCollection<E>(checkNotNull(unfiltered), checkNotNull(predicate));
}
/**
* Delegates to {@link Collection#contains}. Returns {@code false} if the
* {@code contains} method throws a {@code ClassCastException} or
* {@code NullPointerException}.
*/
static boolean safeContains(Collection<?> collection, @Nullable Object object) {
checkNotNull(collection);
try {
return collection.contains(object);
} catch (ClassCastException e) {
return false;
} catch (NullPointerException e) {
return false;
}
}
/**
* Delegates to {@link Collection#remove}. Returns {@code false} if the
* {@code remove} method throws a {@code ClassCastException} or
* {@code NullPointerException}.
*/
static boolean safeRemove(Collection<?> collection, @Nullable Object object) {
checkNotNull(collection);
try {
return collection.remove(object);
} catch (ClassCastException e) {
return false;
} catch (NullPointerException e) {
return false;
}
}
static class FilteredCollection<E> extends AbstractCollection<E> {
final Collection<E> unfiltered;
final Predicate<? super E> predicate;
FilteredCollection(Collection<E> unfiltered, Predicate<? super E> predicate) {
this.unfiltered = unfiltered;
this.predicate = predicate;
}
FilteredCollection<E> createCombined(Predicate<? super E> newPredicate) {
return new FilteredCollection<E>(unfiltered, Predicates.<E>and(predicate, newPredicate));
// .<E> above needed to compile in JDK 5
}
@Override
public boolean add(E element) {
checkArgument(predicate.apply(element));
return unfiltered.add(element);
}
@Override
public boolean addAll(Collection<? extends E> collection) {
for (E element : collection) {
checkArgument(predicate.apply(element));
}
return unfiltered.addAll(collection);
}
@Override
public void clear() {
Iterables.removeIf(unfiltered, predicate);
}
@Override
public boolean contains(@Nullable Object element) {
if (safeContains(unfiltered, element)) {
@SuppressWarnings("unchecked") // element is in unfiltered, so it must be an E
E e = (E) element;
return predicate.apply(e);
}
return false;
}
@Override
public boolean containsAll(Collection<?> collection) {
return containsAllImpl(this, collection);
}
@Override
public boolean isEmpty() {
return !Iterables.any(unfiltered, predicate);
}
@Override
public Iterator<E> iterator() {
return Iterators.filter(unfiltered.iterator(), predicate);
}
@Override
public boolean remove(Object element) {
return contains(element) && unfiltered.remove(element);
}
@Override
public boolean removeAll(final Collection<?> collection) {
return Iterables.removeIf(unfiltered, and(predicate, Predicates.<Object>in(collection)));
}
@Override
public boolean retainAll(final Collection<?> collection) {
return Iterables.removeIf(unfiltered, and(predicate, not(Predicates.<Object>in(collection))));
}
@Override
public int size() {
return Iterators.size(iterator());
}
@Override
public Object[] toArray() {
// creating an ArrayList so filtering happens once
return Lists.newArrayList(iterator()).toArray();
}
@Override
public <T> T[] toArray(T[] array) {
return Lists.newArrayList(iterator()).toArray(array);
}
}
/**
* Returns a collection that applies {@code function} to each element of
* {@code fromCollection}. The returned collection is a live view of {@code
* fromCollection}; changes to one affect the other.
*
* <p>The returned collection's {@code add()} and {@code addAll()} methods
* throw an {@link UnsupportedOperationException}. All other collection
* methods are supported, as long as {@code fromCollection} supports them.
*
* <p>The returned collection isn't threadsafe or serializable, even if
* {@code fromCollection} is.
*
* <p>When a live view is <i>not</i> needed, it may be faster to copy the
* transformed collection and use the copy.
*
* <p>If the input {@code Collection} is known to be a {@code List}, consider
* {@link Lists#transform}. If only an {@code Iterable} is available, use
* {@link Iterables#transform}.
*/
public static <F, T> Collection<T> transform(
Collection<F> fromCollection, Function<? super F, T> function) {
return new TransformedCollection<F, T>(fromCollection, function);
}
static class TransformedCollection<F, T> extends AbstractCollection<T> {
final Collection<F> fromCollection;
final Function<? super F, ? extends T> function;
TransformedCollection(Collection<F> fromCollection, Function<? super F, ? extends T> function) {
this.fromCollection = checkNotNull(fromCollection);
this.function = checkNotNull(function);
}
@Override
public void clear() {
fromCollection.clear();
}
@Override
public boolean isEmpty() {
return fromCollection.isEmpty();
}
@Override
public Iterator<T> iterator() {
return Iterators.transform(fromCollection.iterator(), function);
}
@Override
public int size() {
return fromCollection.size();
}
}
/**
* Returns {@code true} if the collection {@code self} contains all of the
* elements in the collection {@code c}.
*
* <p>This method iterates over the specified collection {@code c}, checking
* each element returned by the iterator in turn to see if it is contained in
* the specified collection {@code self}. If all elements are so contained,
* {@code true} is returned, otherwise {@code false}.
*
* @param self a collection which might contain all elements in {@code c}
* @param c a collection whose elements might be contained by {@code self}
*/
static boolean containsAllImpl(Collection<?> self, Collection<?> c) {
return Iterables.all(c, Predicates.in(self));
}
/**
* An implementation of {@link Collection#toString()}.
*/
static String toStringImpl(final Collection<?> collection) {
StringBuilder sb = newStringBuilderForCollection(collection.size()).append('[');
STANDARD_JOINER.appendTo(
sb,
Iterables.transform(
collection,
new Function<Object, Object>() {
@Override
public Object apply(Object input) {
return input == collection ? "(this Collection)" : input;
}
}));
return sb.append(']').toString();
}
/**
* Returns best-effort-sized StringBuilder based on the given collection size.
*/
static StringBuilder newStringBuilderForCollection(int size) {
checkNonnegative(size, "size");
return new StringBuilder((int) Math.min(size * 8L, Ints.MAX_POWER_OF_TWO));
}
/**
* Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557
*/
static <T> Collection<T> cast(Iterable<T> iterable) {
return (Collection<T>) iterable;
}
static final Joiner STANDARD_JOINER = Joiner.on(", ").useForNull("null");
/**
* Returns a {@link Collection} of all the permutations of the specified
* {@link Iterable}.
*
* <p><i>Notes:</i> This is an implementation of the algorithm for
* Lexicographical Permutations Generation, described in Knuth's "The Art of
* Computer Programming", Volume 4, Chapter 7, Section 7.2.1.2. The
* iteration order follows the lexicographical order. This means that
* the first permutation will be in ascending order, and the last will be in
* descending order.
*
* <p>Duplicate elements are considered equal. For example, the list [1, 1]
* will have only one permutation, instead of two. This is why the elements
* have to implement {@link Comparable}.
*
* <p>An empty iterable has only one permutation, which is an empty list.
*
* <p>This method is equivalent to
* {@code Collections2.orderedPermutations(list, Ordering.natural())}.
*
* @param elements the original iterable whose elements have to be permuted.
* @return an immutable {@link Collection} containing all the different
* permutations of the original iterable.
* @throws NullPointerException if the specified iterable is null or has any
* null elements.
* @since 12.0
*/
@Beta
public static <E extends Comparable<? super E>> Collection<List<E>> orderedPermutations(
Iterable<E> elements) {
return orderedPermutations(elements, Ordering.natural());
}
/**
* Returns a {@link Collection} of all the permutations of the specified
* {@link Iterable} using the specified {@link Comparator} for establishing
* the lexicographical ordering.
*
* <p>Examples: <pre> {@code
*
* for (List<String> perm : orderedPermutations(asList("b", "c", "a"))) {
* println(perm);
* }
* // -> ["a", "b", "c"]
* // -> ["a", "c", "b"]
* // -> ["b", "a", "c"]
* // -> ["b", "c", "a"]
* // -> ["c", "a", "b"]
* // -> ["c", "b", "a"]
*
* for (List<Integer> perm : orderedPermutations(asList(1, 2, 2, 1))) {
* println(perm);
* }
* // -> [1, 1, 2, 2]
* // -> [1, 2, 1, 2]
* // -> [1, 2, 2, 1]
* // -> [2, 1, 1, 2]
* // -> [2, 1, 2, 1]
* // -> [2, 2, 1, 1]}</pre>
*
* <p><i>Notes:</i> This is an implementation of the algorithm for
* Lexicographical Permutations Generation, described in Knuth's "The Art of
* Computer Programming", Volume 4, Chapter 7, Section 7.2.1.2. The
* iteration order follows the lexicographical order. This means that
* the first permutation will be in ascending order, and the last will be in
* descending order.
*
* <p>Elements that compare equal are considered equal and no new permutations
* are created by swapping them.
*
* <p>An empty iterable has only one permutation, which is an empty list.
*
* @param elements the original iterable whose elements have to be permuted.
* @param comparator a comparator for the iterable's elements.
* @return an immutable {@link Collection} containing all the different
* permutations of the original iterable.
* @throws NullPointerException If the specified iterable is null, has any
* null elements, or if the specified comparator is null.
* @since 12.0
*/
@Beta
public static <E> Collection<List<E>> orderedPermutations(
Iterable<E> elements, Comparator<? super E> comparator) {
return new OrderedPermutationCollection<E>(elements, comparator);
}
private static final class OrderedPermutationCollection<E> extends AbstractCollection<List<E>> {
final ImmutableList<E> inputList;
final Comparator<? super E> comparator;
final int size;
OrderedPermutationCollection(Iterable<E> input, Comparator<? super E> comparator) {
this.inputList = Ordering.from(comparator).immutableSortedCopy(input);
this.comparator = comparator;
this.size = calculateSize(inputList, comparator);
}
/**
* The number of permutations with repeated elements is calculated as
* follows:
* <ul>
* <li>For an empty list, it is 1 (base case).</li>
* <li>When r numbers are added to a list of n-r elements, the number of
* permutations is increased by a factor of (n choose r).</li>
* </ul>
*/
private static <E> int calculateSize(
List<E> sortedInputList, Comparator<? super E> comparator) {
long permutations = 1;
int n = 1;
int r = 1;
while (n < sortedInputList.size()) {
int comparison = comparator.compare(sortedInputList.get(n - 1), sortedInputList.get(n));
if (comparison < 0) {
// We move to the next non-repeated element.
permutations *= binomial(n, r);
r = 0;
if (!isPositiveInt(permutations)) {
return Integer.MAX_VALUE;
}
}
n++;
r++;
}
permutations *= binomial(n, r);
if (!isPositiveInt(permutations)) {
return Integer.MAX_VALUE;
}
return (int) permutations;
}
@Override
public int size() {
return size;
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public Iterator<List<E>> iterator() {
return new OrderedPermutationIterator<E>(inputList, comparator);
}
@Override
public boolean contains(@Nullable Object obj) {
if (obj instanceof List) {
List<?> list = (List<?>) obj;
return isPermutation(inputList, list);
}
return false;
}
@Override
public String toString() {
return "orderedPermutationCollection(" + inputList + ")";
}
}
private static final class OrderedPermutationIterator<E> extends AbstractIterator<List<E>> {
List<E> nextPermutation;
final Comparator<? super E> comparator;
OrderedPermutationIterator(List<E> list, Comparator<? super E> comparator) {
this.nextPermutation = Lists.newArrayList(list);
this.comparator = comparator;
}
@Override
protected List<E> computeNext() {
if (nextPermutation == null) {
return endOfData();
}
ImmutableList<E> next = ImmutableList.copyOf(nextPermutation);
calculateNextPermutation();
return next;
}
void calculateNextPermutation() {
int j = findNextJ();
if (j == -1) {
nextPermutation = null;
return;
}
int l = findNextL(j);
Collections.swap(nextPermutation, j, l);
int n = nextPermutation.size();
Collections.reverse(nextPermutation.subList(j + 1, n));
}
int findNextJ() {
for (int k = nextPermutation.size() - 2; k >= 0; k--) {
if (comparator.compare(nextPermutation.get(k), nextPermutation.get(k + 1)) < 0) {
return k;
}
}
return -1;
}
int findNextL(int j) {
E ak = nextPermutation.get(j);
for (int l = nextPermutation.size() - 1; l > j; l--) {
if (comparator.compare(ak, nextPermutation.get(l)) < 0) {
return l;
}
}
throw new AssertionError("this statement should be unreachable");
}
}
/**
* Returns a {@link Collection} of all the permutations of the specified
* {@link Collection}.
*
* <p><i>Notes:</i> This is an implementation of the Plain Changes algorithm
* for permutations generation, described in Knuth's "The Art of Computer
* Programming", Volume 4, Chapter 7, Section 7.2.1.2.
*
* <p>If the input list contains equal elements, some of the generated
* permutations will be equal.
*
* <p>An empty collection has only one permutation, which is an empty list.
*
* @param elements the original collection whose elements have to be permuted.
* @return an immutable {@link Collection} containing all the different
* permutations of the original collection.
* @throws NullPointerException if the specified collection is null or has any
* null elements.
* @since 12.0
*/
@Beta
public static <E> Collection<List<E>> permutations(Collection<E> elements) {
return new PermutationCollection<E>(ImmutableList.copyOf(elements));
}
private static final class PermutationCollection<E> extends AbstractCollection<List<E>> {
final ImmutableList<E> inputList;
PermutationCollection(ImmutableList<E> input) {
this.inputList = input;
}
@Override
public int size() {
return IntMath.factorial(inputList.size());
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public Iterator<List<E>> iterator() {
return new PermutationIterator<E>(inputList);
}
@Override
public boolean contains(@Nullable Object obj) {
if (obj instanceof List) {
List<?> list = (List<?>) obj;
return isPermutation(inputList, list);
}
return false;
}
@Override
public String toString() {
return "permutations(" + inputList + ")";
}
}
private static class PermutationIterator<E> extends AbstractIterator<List<E>> {
final List<E> list;
final int[] c;
final int[] o;
int j;
PermutationIterator(List<E> list) {
this.list = new ArrayList<E>(list);
int n = list.size();
c = new int[n];
o = new int[n];
Arrays.fill(c, 0);
Arrays.fill(o, 1);
j = Integer.MAX_VALUE;
}
@Override
protected List<E> computeNext() {
if (j <= 0) {
return endOfData();
}
ImmutableList<E> next = ImmutableList.copyOf(list);
calculateNextPermutation();
return next;
}
void calculateNextPermutation() {
j = list.size() - 1;
int s = 0;
// Handle the special case of an empty list. Skip the calculation of the
// next permutation.
if (j == -1) {
return;
}
while (true) {
int q = c[j] + o[j];
if (q < 0) {
switchDirection();
continue;
}
if (q == j + 1) {
if (j == 0) {
break;
}
s++;
switchDirection();
continue;
}
Collections.swap(list, j - c[j] + s, j - q + s);
c[j] = q;
break;
}
}
void switchDirection() {
o[j] = -o[j];
j--;
}
}
/**
* Returns {@code true} if the second list is a permutation of the first.
*/
private static boolean isPermutation(List<?> first, List<?> second) {
if (first.size() != second.size()) {
return false;
}
Multiset<?> firstMultiset = HashMultiset.create(first);
Multiset<?> secondMultiset = HashMultiset.create(second);
return firstMultiset.equals(secondMultiset);
}
private static boolean isPositiveInt(long n) {
return n >= 0 && n <= Integer.MAX_VALUE;
}
}
| apache-2.0 |
asedunov/intellij-community | platform/core-impl/src/com/intellij/refactoring/rename/FragmentaryPsiReference.java | 783 | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.refactoring.rename;
public interface FragmentaryPsiReference extends BindablePsiReference {
boolean isReadOnlyFragment();
boolean isFragmentOnlyRename();
}
| apache-2.0 |
marktriggs/nyu-sakai-10.4 | msgcntr/messageforums-app/src/java/org/sakaiproject/tool/messageforums/jsf/ShowAreaRender.java | 4065 | /**********************************************************************************
* $URL: https://source.sakaiproject.org/svn/msgcntr/trunk/messageforums-app/src/java/org/sakaiproject/tool/messageforums/jsf/ShowAreaRender.java $
* $Id: ShowAreaRender.java 9227 2006-05-15 15:02:42Z cwen@iupui.edu $
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008 The Sakai Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ECL-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
package org.sakaiproject.tool.messageforums.jsf;
import java.io.IOException;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.render.Renderer;
/**
* @author Chen Wen
* @version $Id$
*/
public class ShowAreaRender extends Renderer
{
public boolean supportsComponentType(UIComponent component)
{
return (component instanceof ShowAreaComponent);
}
public void encodeBegin(FacesContext context, UIComponent component)
throws IOException
{
ResponseWriter writer = context.getResponseWriter();
String value = (String) component.getAttributes().get("value");
String hideBorder = (String) component.getAttributes().get("hideBorder");
String showInputTextArea = (String) component.getAttributes().get(
"showInputTextArea");
if ((value != null) && (!"".equals(value)))
{
int pos;
// writer.write("<div>");
value = value.replaceAll("<strong>", "<b>");
value = value.replaceAll("</strong>", "</b>");
// writer.write("<table STYLE=\"table-layout:fixed\" width=300><tr width=\"100%\"><td
// width=\"100%\" STYLE=\"word-wrap: break-all; white-space: -moz-pre-wrap;
// text-overflow:ellipsis; overflow: auto;\">");
value = value.replaceAll("<a title=", "<a target=\"_new\" title=");
// value = value.replaceAll("<a href=",
// "<a title=\"Open a new window\" target=\"_new\" href=");
if (hideBorder != null && "true".equals(hideBorder))
{
writer
.write("<div class=\"textPanel\">");
//gsilver .write("<table border=\"0\" id=\"message_table\" cellpadding=\"0\" width=\"90%\"><tr width=\"95%\"><td width=\"100%\" STYLE=\"word-wrap: break-word\">");
writer.write(value);
writer.write("</div>");
}
else
if (showInputTextArea != null && "true".equals(showInputTextArea))
{
writer.write("<textarea id=\"msgForum:forums:1:forum_extended_description\" name=\"msgForum:forums:1:forum_extended_description\" cols=\"100\" rows=\"5\" disabled=\"disabled\">");
writer.write(value);
writer.write("</textarea>");
}
else
{
writer
.write("<div class=\"textPanel bordered\">");
// .write("<table border=\"1\" id=\"message_table\" cellpadding=\"7\" style=\"border-collapse: collapse; table-layout:fixed\" width=\"90%\"><tr width=\"95%\"><td width=\"100%\" STYLE=\"word-wrap: break-word\">");
writer.write(value);
writer.write("</div>");
}
}
}
public void encodeEnd(FacesContext context, UIComponent component)
throws IOException
{
ResponseWriter writer = context.getResponseWriter();
String value = (String) component.getAttributes().get("value");
if ((value != null) && (!"".equals(value)))
{
}
}
}
| apache-2.0 |
rokn/Count_Words_2015 | testing/openjdk2/langtools/test/tools/javac/generics/5009937/T5009937.java | 402 | /*
* @test /nodynamiccopyright/
* @bug 5009937
* @summary hiding versus generics versus binary compatibility
* @author Maurizio Cimadamore
*
* @compile/fail/ref=T5009937.out -XDrawDiagnostics T5009937.java
*/
public class T5009937<X> {
static class A {
static void m(T5009937<String> l) {}
}
static class B extends A {
static void m(T5009937<Integer> l) {}
}
}
| mit |
rokn/Count_Words_2015 | testing/openjdk2/hotspot/agent/src/share/classes/sun/jvm/hotspot/debugger/cdbg/AccessControl.java | 1310 | /*
* Copyright (c) 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
package sun.jvm.hotspot.debugger.cdbg;
public interface AccessControl {
public static final int NO_PROTECTION = 0;
public static final int PRIVATE = 1;
public static final int PROTECTED = 2;
public static final int PUBLIC = 3;
}
| mit |
gfyoung/elasticsearch | server/src/main/java/org/elasticsearch/rest/action/document/package-info.java | 973 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* {@link org.elasticsearch.rest.RestHandler}s for actions that can be taken on documents like index, update, get, and delete.
*/
package org.elasticsearch.rest.action.document;
| apache-2.0 |
weipinghe/elasticsearch | core/src/test/java/org/elasticsearch/indices/flush/FlushIT.java | 11844 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.indices.flush;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.indices.flush.FlushResponse;
import org.elasticsearch.action.admin.indices.stats.IndexStats;
import org.elasticsearch.action.admin.indices.stats.ShardStats;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.cluster.routing.allocation.command.MoveAllocationCommand;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.engine.Engine;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.test.ESIntegTestCase;
import org.elasticsearch.test.junit.annotations.TestLogging;
import org.junit.Test;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import static org.hamcrest.Matchers.emptyIterable;
import static org.hamcrest.Matchers.equalTo;
public class FlushIT extends ESIntegTestCase {
@Test
public void testWaitIfOngoing() throws InterruptedException {
createIndex("test");
ensureGreen("test");
final int numIters = scaledRandomIntBetween(10, 30);
for (int i = 0; i < numIters; i++) {
for (int j = 0; j < 10; j++) {
client().prepareIndex("test", "test").setSource("{}").get();
}
final CountDownLatch latch = new CountDownLatch(10);
final CopyOnWriteArrayList<Throwable> errors = new CopyOnWriteArrayList<>();
for (int j = 0; j < 10; j++) {
client().admin().indices().prepareFlush("test").setWaitIfOngoing(true).execute(new ActionListener<FlushResponse>() {
@Override
public void onResponse(FlushResponse flushResponse) {
try {
// dont' use assertAllSuccesssful it uses a randomized context that belongs to a different thread
assertThat("Unexpected ShardFailures: " + Arrays.toString(flushResponse.getShardFailures()), flushResponse.getFailedShards(), equalTo(0));
latch.countDown();
} catch (Throwable ex) {
onFailure(ex);
}
}
@Override
public void onFailure(Throwable e) {
errors.add(e);
latch.countDown();
}
});
}
latch.await();
assertThat(errors, emptyIterable());
}
}
@TestLogging("indices:TRACE")
public void testSyncedFlush() throws ExecutionException, InterruptedException, IOException {
internalCluster().ensureAtLeastNumDataNodes(2);
prepareCreate("test").setSettings(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1).get();
ensureGreen();
IndexStats indexStats = client().admin().indices().prepareStats("test").get().getIndex("test");
for (ShardStats shardStats : indexStats.getShards()) {
assertNull(shardStats.getCommitStats().getUserData().get(Engine.SYNC_COMMIT_ID));
}
ShardsSyncedFlushResult result;
if (randomBoolean()) {
logger.info("--> sync flushing shard 0");
result = SyncedFlushUtil.attemptSyncedFlush(internalCluster(), new ShardId("test", 0));
} else {
logger.info("--> sync flushing index [test]");
IndicesSyncedFlushResult indicesResult = SyncedFlushUtil.attemptSyncedFlush(internalCluster(), "test");
result = indicesResult.getShardsResultPerIndex().get("test").get(0);
}
assertFalse(result.failed());
assertThat(result.totalShards(), equalTo(indexStats.getShards().length));
assertThat(result.successfulShards(), equalTo(indexStats.getShards().length));
indexStats = client().admin().indices().prepareStats("test").get().getIndex("test");
String syncId = result.syncId();
for (ShardStats shardStats : indexStats.getShards()) {
final String shardSyncId = shardStats.getCommitStats().getUserData().get(Engine.SYNC_COMMIT_ID);
assertThat(shardSyncId, equalTo(syncId));
}
// now, start new node and relocate a shard there and see if sync id still there
String newNodeName = internalCluster().startNode();
ClusterState clusterState = client().admin().cluster().prepareState().get().getState();
ShardRouting shardRouting = clusterState.getRoutingTable().index("test").shard(0).iterator().next();
String currentNodeName = clusterState.nodes().resolveNode(shardRouting.currentNodeId()).name();
assertFalse(currentNodeName.equals(newNodeName));
internalCluster().client().admin().cluster().prepareReroute().add(new MoveAllocationCommand(new ShardId("test", 0), currentNodeName, newNodeName)).get();
client().admin().cluster().prepareHealth()
.setWaitForRelocatingShards(0)
.get();
indexStats = client().admin().indices().prepareStats("test").get().getIndex("test");
for (ShardStats shardStats : indexStats.getShards()) {
assertNotNull(shardStats.getCommitStats().getUserData().get(Engine.SYNC_COMMIT_ID));
}
client().admin().indices().prepareUpdateSettings("test").setSettings(Settings.builder().put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 0).build()).get();
ensureGreen("test");
indexStats = client().admin().indices().prepareStats("test").get().getIndex("test");
for (ShardStats shardStats : indexStats.getShards()) {
assertNotNull(shardStats.getCommitStats().getUserData().get(Engine.SYNC_COMMIT_ID));
}
client().admin().indices().prepareUpdateSettings("test").setSettings(Settings.builder().put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, internalCluster().numDataNodes() - 1).build()).get();
ensureGreen("test");
indexStats = client().admin().indices().prepareStats("test").get().getIndex("test");
for (ShardStats shardStats : indexStats.getShards()) {
assertNotNull(shardStats.getCommitStats().getUserData().get(Engine.SYNC_COMMIT_ID));
}
}
@TestLogging("indices:TRACE")
public void testSyncedFlushWithConcurrentIndexing() throws Exception {
internalCluster().ensureAtLeastNumDataNodes(3);
createIndex("test");
client().admin().indices().prepareUpdateSettings("test").setSettings(
Settings.builder().put("index.translog.disable_flush", true).put("index.refresh_interval", -1).put("index.number_of_replicas", internalCluster().numDataNodes() - 1))
.get();
ensureGreen();
final AtomicBoolean stop = new AtomicBoolean(false);
final AtomicInteger numDocs = new AtomicInteger(0);
Thread indexingThread = new Thread() {
@Override
public void run() {
while (stop.get() == false) {
client().prepareIndex().setIndex("test").setType("doc").setSource("{}").get();
numDocs.incrementAndGet();
}
}
};
indexingThread.start();
IndexStats indexStats = client().admin().indices().prepareStats("test").get().getIndex("test");
for (ShardStats shardStats : indexStats.getShards()) {
assertNull(shardStats.getCommitStats().getUserData().get(Engine.SYNC_COMMIT_ID));
}
logger.info("--> trying sync flush");
IndicesSyncedFlushResult syncedFlushResult = SyncedFlushUtil.attemptSyncedFlush(internalCluster(), "test");
logger.info("--> sync flush done");
stop.set(true);
indexingThread.join();
indexStats = client().admin().indices().prepareStats("test").get().getIndex("test");
assertFlushResponseEqualsShardStats(indexStats.getShards(), syncedFlushResult.getShardsResultPerIndex().get("test"));
refresh();
assertThat(client().prepareCount().get().getCount(), equalTo((long) numDocs.get()));
logger.info("indexed {} docs", client().prepareCount().get().getCount());
logClusterState();
internalCluster().fullRestart();
ensureGreen();
assertThat(client().prepareCount().get().getCount(), equalTo((long) numDocs.get()));
}
private void assertFlushResponseEqualsShardStats(ShardStats[] shardsStats, List<ShardsSyncedFlushResult> syncedFlushResults) {
for (final ShardStats shardStats : shardsStats) {
for (final ShardsSyncedFlushResult shardResult : syncedFlushResults) {
if (shardStats.getShardRouting().getId() == shardResult.shardId().getId()) {
for (Map.Entry<ShardRouting, SyncedFlushService.SyncedFlushResponse> singleResponse : shardResult.shardResponses().entrySet()) {
if (singleResponse.getKey().currentNodeId().equals(shardStats.getShardRouting().currentNodeId())) {
if (singleResponse.getValue().success()) {
logger.info("{} sync flushed on node {}", singleResponse.getKey().shardId(), singleResponse.getKey().currentNodeId());
assertNotNull(shardStats.getCommitStats().getUserData().get(Engine.SYNC_COMMIT_ID));
} else {
logger.info("{} sync flush failed for on node {}", singleResponse.getKey().shardId(), singleResponse.getKey().currentNodeId());
assertNull(shardStats.getCommitStats().getUserData().get(Engine.SYNC_COMMIT_ID));
}
}
}
}
}
}
}
@Test
public void testUnallocatedShardsDoesNotHang() throws InterruptedException {
// create an index but disallow allocation
prepareCreate("test").setSettings(Settings.builder().put("index.routing.allocation.include._name", "nonexistent")).get();
// this should not hang but instead immediately return with empty result set
List<ShardsSyncedFlushResult> shardsResult = SyncedFlushUtil.attemptSyncedFlush(internalCluster(), "test").getShardsResultPerIndex().get("test");
// just to make sure the test actually tests the right thing
int numShards = client().admin().indices().prepareGetSettings("test").get().getIndexToSettings().get("test").getAsInt(IndexMetaData.SETTING_NUMBER_OF_SHARDS, -1);
assertThat(shardsResult.size(), equalTo(numShards));
assertThat(shardsResult.get(0).failureReason(), equalTo("no active shards"));
}
}
| apache-2.0 |
raviagarwal7/buck | third-party/java/dx/src/com/android/dx/rop/cst/CstString.java | 12314 | /*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.dx.rop.cst;
import com.android.dx.rop.type.Type;
import com.android.dx.util.ByteArray;
import com.android.dx.util.Hex;
/**
* Constants of type {@code CONSTANT_Utf8_info} or {@code CONSTANT_String_info}.
*/
public final class CstString extends TypedConstant {
/**
* {@code non-null;} instance representing {@code ""}, that is, the
* empty string
*/
public static final CstString EMPTY_STRING = new CstString("");
/** {@code non-null;} the UTF-8 value as a string */
private final String string;
/** {@code non-null;} the UTF-8 value as bytes */
private final ByteArray bytes;
/**
* Converts a string into its MUTF-8 form. MUTF-8 differs from normal UTF-8
* in the handling of character '\0' and surrogate pairs.
*
* @param string {@code non-null;} the string to convert
* @return {@code non-null;} the UTF-8 bytes for it
*/
public static byte[] stringToUtf8Bytes(String string) {
int len = string.length();
byte[] bytes = new byte[len * 3]; // Avoid having to reallocate.
int outAt = 0;
for (int i = 0; i < len; i++) {
char c = string.charAt(i);
if ((c != 0) && (c < 0x80)) {
bytes[outAt] = (byte) c;
outAt++;
} else if (c < 0x800) {
bytes[outAt] = (byte) (((c >> 6) & 0x1f) | 0xc0);
bytes[outAt + 1] = (byte) ((c & 0x3f) | 0x80);
outAt += 2;
} else {
bytes[outAt] = (byte) (((c >> 12) & 0x0f) | 0xe0);
bytes[outAt + 1] = (byte) (((c >> 6) & 0x3f) | 0x80);
bytes[outAt + 2] = (byte) ((c & 0x3f) | 0x80);
outAt += 3;
}
}
byte[] result = new byte[outAt];
System.arraycopy(bytes, 0, result, 0, outAt);
return result;
}
/**
* Converts an array of UTF-8 bytes into a string.
*
* @param bytes {@code non-null;} the bytes to convert
* @return {@code non-null;} the converted string
*/
public static String utf8BytesToString(ByteArray bytes) {
int length = bytes.size();
char[] chars = new char[length]; // This is sized to avoid a realloc.
int outAt = 0;
for (int at = 0; length > 0; /*at*/) {
int v0 = bytes.getUnsignedByte(at);
char out;
switch (v0 >> 4) {
case 0x00: case 0x01: case 0x02: case 0x03:
case 0x04: case 0x05: case 0x06: case 0x07: {
// 0XXXXXXX -- single-byte encoding
length--;
if (v0 == 0) {
// A single zero byte is illegal.
return throwBadUtf8(v0, at);
}
out = (char) v0;
at++;
break;
}
case 0x0c: case 0x0d: {
// 110XXXXX -- two-byte encoding
length -= 2;
if (length < 0) {
return throwBadUtf8(v0, at);
}
int v1 = bytes.getUnsignedByte(at + 1);
if ((v1 & 0xc0) != 0x80) {
return throwBadUtf8(v1, at + 1);
}
int value = ((v0 & 0x1f) << 6) | (v1 & 0x3f);
if ((value != 0) && (value < 0x80)) {
/*
* This should have been represented with
* one-byte encoding.
*/
return throwBadUtf8(v1, at + 1);
}
out = (char) value;
at += 2;
break;
}
case 0x0e: {
// 1110XXXX -- three-byte encoding
length -= 3;
if (length < 0) {
return throwBadUtf8(v0, at);
}
int v1 = bytes.getUnsignedByte(at + 1);
if ((v1 & 0xc0) != 0x80) {
return throwBadUtf8(v1, at + 1);
}
int v2 = bytes.getUnsignedByte(at + 2);
if ((v1 & 0xc0) != 0x80) {
return throwBadUtf8(v2, at + 2);
}
int value = ((v0 & 0x0f) << 12) | ((v1 & 0x3f) << 6) |
(v2 & 0x3f);
if (value < 0x800) {
/*
* This should have been represented with one- or
* two-byte encoding.
*/
return throwBadUtf8(v2, at + 2);
}
out = (char) value;
at += 3;
break;
}
default: {
// 10XXXXXX, 1111XXXX -- illegal
return throwBadUtf8(v0, at);
}
}
chars[outAt] = out;
outAt++;
}
return new String(chars, 0, outAt);
}
/**
* Helper for {@link #utf8BytesToString}, which throws the right
* exception for a bogus utf-8 byte.
*
* @param value the byte value
* @param offset the file offset
* @return never
* @throws IllegalArgumentException always thrown
*/
private static String throwBadUtf8(int value, int offset) {
throw new IllegalArgumentException("bad utf-8 byte " + Hex.u1(value) +
" at offset " + Hex.u4(offset));
}
/**
* Constructs an instance from a {@code String}.
*
* @param string {@code non-null;} the UTF-8 value as a string
*/
public CstString(String string) {
if (string == null) {
throw new NullPointerException("string == null");
}
this.string = string.intern();
this.bytes = new ByteArray(stringToUtf8Bytes(string));
}
/**
* Constructs an instance from some UTF-8 bytes.
*
* @param bytes {@code non-null;} array of the UTF-8 bytes
*/
public CstString(ByteArray bytes) {
if (bytes == null) {
throw new NullPointerException("bytes == null");
}
this.bytes = bytes;
this.string = utf8BytesToString(bytes).intern();
}
/** {@inheritDoc} */
@Override
public boolean equals(Object other) {
if (!(other instanceof CstString)) {
return false;
}
return string.equals(((CstString) other).string);
}
/** {@inheritDoc} */
@Override
public int hashCode() {
return string.hashCode();
}
/** {@inheritDoc} */
@Override
protected int compareTo0(Constant other) {
return string.compareTo(((CstString) other).string);
}
/** {@inheritDoc} */
@Override
public String toString() {
return "string{\"" + toHuman() + "\"}";
}
/** {@inheritDoc} */
@Override
public String typeName() {
return "utf8";
}
/** {@inheritDoc} */
@Override
public boolean isCategory2() {
return false;
}
/** {@inheritDoc} */
public String toHuman() {
int len = string.length();
StringBuilder sb = new StringBuilder(len * 3 / 2);
for (int i = 0; i < len; i++) {
char c = string.charAt(i);
if ((c >= ' ') && (c < 0x7f)) {
if ((c == '\'') || (c == '\"') || (c == '\\')) {
sb.append('\\');
}
sb.append(c);
} else if (c <= 0x7f) {
switch (c) {
case '\n': sb.append("\\n"); break;
case '\r': sb.append("\\r"); break;
case '\t': sb.append("\\t"); break;
default: {
/*
* Represent the character as an octal escape.
* If the next character is a valid octal
* digit, disambiguate by using the
* three-digit form.
*/
char nextChar =
(i < (len - 1)) ? string.charAt(i + 1) : 0;
boolean displayZero =
(nextChar >= '0') && (nextChar <= '7');
sb.append('\\');
for (int shift = 6; shift >= 0; shift -= 3) {
char outChar = (char) (((c >> shift) & 7) + '0');
if ((outChar != '0') || displayZero) {
sb.append(outChar);
displayZero = true;
}
}
if (! displayZero) {
// Ironic edge case: The original value was 0.
sb.append('0');
}
break;
}
}
} else {
sb.append("\\u");
sb.append(Character.forDigit(c >> 12, 16));
sb.append(Character.forDigit((c >> 8) & 0x0f, 16));
sb.append(Character.forDigit((c >> 4) & 0x0f, 16));
sb.append(Character.forDigit(c & 0x0f, 16));
}
}
return sb.toString();
}
/**
* Gets the value as a human-oriented string, surrounded by double
* quotes.
*
* @return {@code non-null;} the quoted string
*/
public String toQuoted() {
return '\"' + toHuman() + '\"';
}
/**
* Gets the value as a human-oriented string, surrounded by double
* quotes, but ellipsizes the result if it is longer than the given
* maximum length
*
* @param maxLength {@code >= 5;} the maximum length of the string to return
* @return {@code non-null;} the quoted string
*/
public String toQuoted(int maxLength) {
String string = toHuman();
int length = string.length();
String ellipses;
if (length <= (maxLength - 2)) {
ellipses = "";
} else {
string = string.substring(0, maxLength - 5);
ellipses = "...";
}
return '\"' + string + ellipses + '\"';
}
/**
* Gets the UTF-8 value as a string.
* The returned string is always already interned.
*
* @return {@code non-null;} the UTF-8 value as a string
*/
public String getString() {
return string;
}
/**
* Gets the UTF-8 value as UTF-8 encoded bytes.
*
* @return {@code non-null;} an array of the UTF-8 bytes
*/
public ByteArray getBytes() {
return bytes;
}
/**
* Gets the size of this instance as UTF-8 code points. That is,
* get the number of bytes in the UTF-8 encoding of this instance.
*
* @return {@code >= 0;} the UTF-8 size
*/
public int getUtf8Size() {
return bytes.size();
}
/**
* Gets the size of this instance as UTF-16 code points. That is,
* get the number of 16-bit chars in the UTF-16 encoding of this
* instance. This is the same as the {@code length} of the
* Java {@code String} representation of this instance.
*
* @return {@code >= 0;} the UTF-16 size
*/
public int getUtf16Size() {
return string.length();
}
public Type getType() {
return Type.STRING;
}
}
| apache-2.0 |
SanDisk-Open-Source/SSD_Dashboard | uefi/gcc/gcc-4.6.3/libjava/classpath/javax/swing/event/ListSelectionListener.java | 2273 | /* ListSelectionListener.java --
Copyright (C) 2002, 2006, Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package javax.swing.event;
import java.util.EventListener;
import javax.swing.ListSelectionModel;
/**
* A listener that receives {@link ListSelectionEvent} notifications,
* typically from a {@link ListSelectionModel} when it is modified.
*
* @author Andrew Selkirk
* @author Ronald Veldema
*/
public interface ListSelectionListener extends EventListener
{
/**
* Receives notification of a {@link ListSelectionEvent}.
*
* @param event the event.
*/
void valueChanged(ListSelectionEvent event);
}
| gpl-2.0 |
tseen/Federated-HDFS | tseenliu/FedHDFS-hadoop-src/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/webapp/view/TestTwoColumnCssPage.java | 2128 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.yarn.webapp.view;
import org.apache.hadoop.yarn.MockApps;
import org.apache.hadoop.yarn.webapp.Controller;
import org.apache.hadoop.yarn.webapp.WebApps;
import org.apache.hadoop.yarn.webapp.test.WebAppTests;
import org.apache.hadoop.yarn.webapp.view.HtmlPage;
import org.apache.hadoop.yarn.webapp.view.TwoColumnCssLayout;
import org.junit.Test;
public class TestTwoColumnCssPage {
public static class TestController extends Controller {
@Override
public void index() {
set("title", "Testing a Two Column Layout");
set("ui.accordion.id", "nav");
render(TwoColumnCssLayout.class);
}
public void names() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 8; ++i) {
sb.append(MockApps.newAppName()).append(' ');
}
setTitle(sb.toString());
}
public void textnames() {
names();
renderText($("title"));
}
}
public static class TestView extends HtmlPage {
@Override
public void render(Page.HTML<_> html) {
html.
title($("title")).
h1($("title"))._();
}
}
@Test public void shouldNotThrow() {
WebAppTests.testPage(TwoColumnCssLayout.class);
}
public static void main(String[] args) {
WebApps.$for("test").at(8888).inDevMode().start().joinThread();
}
}
| apache-2.0 |
dantuffery/elasticsearch | src/test/java/org/elasticsearch/indices/analysis/DummyIndicesAnalysis.java | 1937 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.indices.analysis;
import org.elasticsearch.common.component.AbstractComponent;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.analysis.*;
public class DummyIndicesAnalysis extends AbstractComponent {
@Inject
public DummyIndicesAnalysis(Settings settings, IndicesAnalysisService indicesAnalysisService) {
super(settings);
indicesAnalysisService.analyzerProviderFactories().put("dummy",
new PreBuiltAnalyzerProviderFactory("dummy", AnalyzerScope.INDICES,
new DummyAnalyzer()));
indicesAnalysisService.tokenFilterFactories().put("dummy_token_filter",
new PreBuiltTokenFilterFactoryFactory(new DummyTokenFilterFactory()));
indicesAnalysisService.charFilterFactories().put("dummy_char_filter",
new PreBuiltCharFilterFactoryFactory(new DummyCharFilterFactory()));
indicesAnalysisService.tokenizerFactories().put("dummy_tokenizer",
new PreBuiltTokenizerFactoryFactory(new DummyTokenizerFactory()));
}
}
| apache-2.0 |
getlantern/avian | classpath/java/util/TreeMap.java | 5063 | /* Copyright (c) 2008-2013, Avian Contributors
Permission to use, copy, modify, and/or distribute this software
for any purpose with or without fee is hereby granted, provided
that the above copyright notice and this permission notice appear
in all copies.
There is NO WARRANTY for this software. See license.txt for
details. */
package java.util;
public class TreeMap<K,V> implements Map<K,V> {
private TreeSet<MyEntry<K,V>> set;
public TreeMap(final Comparator<K> comparator) {
set = new TreeSet(new Comparator<MyEntry<K,V>>() {
public int compare(MyEntry<K,V> a, MyEntry<K,V> b) {
return comparator.compare(a.key, b.key);
}
});
}
public TreeMap() {
this(new Comparator<K>() {
public int compare(K a, K b) {
return ((Comparable) a).compareTo(b);
}
});
}
public String toString() {
return Collections.toString(this);
}
public V get(Object key) {
MyEntry<K,V> e = set.find(new MyEntry(key, null));
return e == null ? null : e.value;
}
public V put(K key, V value) {
MyEntry<K,V> e = set.addAndReplace(new MyEntry(key, value));
return e == null ? null : e.value;
}
public void putAll(Map<? extends K,? extends V> elts) {
for (Map.Entry<? extends K, ? extends V> entry : elts.entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
public V remove(Object key) {
MyEntry<K,V> e = set.removeAndReturn(new MyEntry(key, null));
return e == null ? null : e.value;
}
public void clear() {
set.clear();
}
public int size() {
return set.size();
}
public boolean isEmpty() {
return size() == 0;
}
public boolean containsKey(Object key) {
return set.contains(new MyEntry(key, null));
}
private boolean equal(Object a, Object b) {
return a == null ? b == null : a.equals(b);
}
public boolean containsValue(Object value) {
for (V v: values()) {
if (equal(v, value)) {
return true;
}
}
return false;
}
public Set<Entry<K, V>> entrySet() {
return (Set<Entry<K, V>>) (Set) set;
}
public Set<K> keySet() {
return new KeySet();
}
public Collection<V> values() {
return new Values();
}
private static class MyEntry<K,V> implements Entry<K,V> {
public final K key;
public V value;
public MyEntry(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
public V setValue(V value) {
V old = this.value;
this.value = value;
return old;
}
}
private class KeySet extends AbstractSet<K> {
public int size() {
return TreeMap.this.size();
}
public boolean isEmpty() {
return TreeMap.this.isEmpty();
}
public boolean contains(Object key) {
return containsKey(key);
}
public boolean add(K key) {
return set.addAndReplace(new MyEntry(key, null)) != null;
}
public boolean addAll(Collection<? extends K> collection) {
boolean change = false;
for (K k: collection) if (add(k)) change = true;
return change;
}
public boolean remove(Object key) {
return set.removeAndReturn(new MyEntry(key, null)) != null;
}
public Object[] toArray() {
return toArray(new Object[size()]);
}
public <T> T[] toArray(T[] array) {
return Collections.toArray(this, array);
}
public void clear() {
TreeMap.this.clear();
}
public Iterator<K> iterator() {
return new Collections.KeyIterator(set.iterator());
}
}
private class Values implements Collection<V> {
public int size() {
return TreeMap.this.size();
}
public boolean isEmpty() {
return TreeMap.this.isEmpty();
}
public boolean contains(Object value) {
return containsValue(value);
}
public boolean containsAll(Collection<?> c) {
if (c == null) {
throw new NullPointerException("collection is null");
}
Iterator<?> it = c.iterator();
while (it.hasNext()) {
if (! contains(it.next())) {
return false;
}
}
return true;
}
public boolean add(V value) {
throw new UnsupportedOperationException();
}
public boolean addAll(Collection<? extends V> collection) {
throw new UnsupportedOperationException();
}
public boolean remove(Object value) {
throw new UnsupportedOperationException();
}
public boolean removeAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
public Object[] toArray() {
return toArray(new Object[size()]);
}
public <T> T[] toArray(T[] array) {
return Collections.toArray(this, array);
}
public void clear() {
TreeMap.this.clear();
}
public Iterator<V> iterator() {
return new Collections.ValueIterator(set.iterator());
}
}
}
| isc |
zendtech/eclipse-diff | src/main/java/com/zend/php/releng/eclipsediff/FileDiff.java | 2774 | /*****************************************************************************
* Copyright (c) 2013, Zend Technologies Ltd.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
****************************************************************************/
package com.zend.php.releng.eclipsediff;
import static com.zend.php.releng.eclipsediff.report.ReportEntryType.MODIFIED;
import static com.zend.php.releng.eclipsediff.utils.FileUtils.crc32;
import static com.zend.php.releng.eclipsediff.utils.FileUtils.isFeatureXml;
import static com.zend.php.releng.eclipsediff.utils.FileUtils.isManifest;
import static com.zend.php.releng.eclipsediff.utils.FileUtils.isZip;
import static com.zend.php.releng.eclipsediff.utils.JarUtils.isJar;
import java.io.File;
import java.io.IOException;
import com.zend.php.releng.eclipsediff.report.Report;
public class FileDiff extends AbstractDiff {
private File original;
private File other;
protected FileDiff(File original, File other) {
super(original.getAbsolutePath(), other.getAbsolutePath());
this.original = original;
this.other = other;
if (!original.isFile())
throw new IllegalArgumentException(original.getName()
+ " is not file");
if (!other.isFile())
throw new IllegalArgumentException(other.getName() + " is not file");
}
@Override
public void execute(Report report) throws Exception {
try {
if (isManifest(original)) {
new ManifestDiff(original, other).execute(report);
} else if (isFeatureXml(original)) {
new FeatureXmlDiff(original, other).execute(report);
} else if (isJar(original)) {
new JarDiff(original, other).execute(report);
} else if (isZip(original)) {
new ZipDiff(original, other).execute(report);
} else {
compareChecksums(report);
}
} catch (Exception e) {
// in case of error - fall back to comparing checksums
compareChecksums(report);
}
}
private void compareChecksums(Report report) throws IOException {
if (original.length() != other.length()
|| crc32(original) != crc32(other)) {
report.add(MODIFIED, originalPath);
}
}
}
| isc |
atomicint/aj8 | server/src/src/main/java/org/apollo/game/msg/decoder/SecondItemActionMessageDecoder.java | 1173 | package org.apollo.game.msg.decoder;
import org.apollo.game.model.Interfaces.InterfaceOption;
import org.apollo.game.msg.MessageDecoder;
import org.apollo.game.msg.annotate.DecodesMessage;
import org.apollo.game.msg.impl.ItemActionMessage;
import org.apollo.net.codec.game.DataOrder;
import org.apollo.net.codec.game.DataTransformation;
import org.apollo.net.codec.game.DataType;
import org.apollo.net.codec.game.GamePacket;
import org.apollo.net.codec.game.GamePacketReader;
/**
* An {@link MessageDecoder} for the {@link ItemActionMessage}.
*
* @author Graham
*/
@DecodesMessage(117)
public final class SecondItemActionMessageDecoder implements MessageDecoder<ItemActionMessage> {
@Override
public ItemActionMessage decode(GamePacket packet) {
GamePacketReader reader = new GamePacketReader(packet);
int interfaceId = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD);
int id = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD);
int slot = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE);
return new ItemActionMessage(InterfaceOption.OPTION_TWO, interfaceId, id, slot);
}
} | isc |
steve-goldman/volksempfaenger | app/src/main/java/net/x4a42/volksempfaenger/service/playback/PlaybackServiceProxyBuilder.java | 2276 | package net.x4a42.volksempfaenger.service.playback;
import android.app.NotificationManager;
import android.content.Context;
import net.x4a42.volksempfaenger.data.playlist.Playlist;
import net.x4a42.volksempfaenger.data.playlist.PlaylistProvider;
import net.x4a42.volksempfaenger.event.episodedownload.EpisodeDownloadEventReceiver;
import net.x4a42.volksempfaenger.event.episodedownload.EpisodeDownloadEventReceiverBuilder;
class PlaybackServiceProxyBuilder
{
public PlaybackServiceProxy build(PlaybackService service)
{
Controller controller
= new ControllerBuilder().build(service);
BackgroundPositionSaver positionSaver
= new BackgroundPositionSaverBuilder().build(service, controller);
IntentParser intentParser = new IntentParser();
MediaButtonReceiver mediaButtonReceiver
= new MediaButtonReceiverBuilder().build(service);
MediaSessionManager mediaSessionManager
= new MediaSessionManagerBuilder().build(service);
NotificationManager notificationManager
= (NotificationManager) service.getSystemService(Context.NOTIFICATION_SERVICE);
PlaybackNotificationBuilder playbackNotificationBuilder
= new PlaybackNotificationBuilder(service);
Playlist playlist = new PlaylistProvider(service).get();
EpisodeDownloadEventReceiver episodeDownloadEventReceiver
= new EpisodeDownloadEventReceiverBuilder().build();
PlaybackServiceProxy proxy
= new PlaybackServiceProxy(positionSaver,
controller,
intentParser,
mediaButtonReceiver,
mediaSessionManager,
notificationManager,
playbackNotificationBuilder,
playlist,
episodeDownloadEventReceiver);
controller.setListener(proxy);
intentParser.setListener(proxy);
episodeDownloadEventReceiver.setListener(proxy);
return proxy;
}
}
| isc |
io7m/jspatial | com.io7m.jspatial.api/src/main/java/com/io7m/jspatial/api/quadtrees/QuadTreeReadableLType.java | 3289 | /*
* Copyright © 2017 <code@io7m.com> http://io7m.com
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
* IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package com.io7m.jspatial.api.quadtrees;
import com.io7m.jregions.core.unparameterized.areas.AreaL;
import com.io7m.jspatial.api.Ray2D;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.SortedSet;
import java.util.function.BiFunction;
/**
* The type of readable quadtrees with {@code long} integer coordinates.
*
* @param <A> The precise type of quadtree members
*
* @since 3.0.0
*/
public interface QuadTreeReadableLType<A> extends QuadTreeReadableType
{
/**
* @return The tree bounds
*/
AreaL bounds();
/**
* Determine whether or not the object has already been inserted into the tree.
*
* @param item The object
*
* @return {@code true} iff the object is in the tree
*/
boolean contains(A item);
/**
* Apply {@code f} to each element of the tree.
*
* @param f A mapping function
* @param <B> The type of result elements
*
* @return A new tree
*/
<B> QuadTreeReadableLType<B> map(BiFunction<A, AreaL, B> f);
/**
* Iterate over all quadrants within the tree.
*
* @param context A contextual value passed to {@code f}
* @param f An iteration function
* @param <C> The type of context values
*/
<C> void iterateQuadrants(
C context,
QuadTreeQuadrantIterationLType<A, C> f);
/**
* @param item The item
*
* @return The bounding area that was specified for {@code item}
*
* @throws NoSuchElementException Iff the item is not present in the tree
*/
AreaL areaFor(A item)
throws NoSuchElementException;
/**
* Returns all objects in the tree that are completely contained within {@code area}, saving the
* results to {@code items}.
*
* @param area The area to examine
* @param items The returned items
*/
void containedBy(
AreaL area,
Set<A> items);
/**
* Returns all objects in the tree that are overlapped {@code area}, saving the results to {@code
* items}.
*
* @param area The area to examine
* @param items The returned items
*/
void overlappedBy(
AreaL area,
Set<A> items);
/**
* Returns all objects that are intersected by the given ray. The objects are returned in order of
* distance from the origin of the ray: The first object returned will be the object nearest to
* the origin.
*
* @param ray The ray
* @param items The intersected items
*/
void raycast(
Ray2D ray,
SortedSet<QuadTreeRaycastResultL<A>> items);
}
| isc |
yvesmh/eulerprobs | src/com/mancera/eulerproj/problem0019/TwentiethCenturyDate.java | 2088 | package com.mancera.eulerproj.problem0019;
public class TwentiethCenturyDate {
private final int day;
private final int month;
private final int year;
private final int dayOfTheWeek;
private final int daysInCurrentMonth;
private final boolean isLeapYear;
private static final int[] daysInMonth = {
0, // nothing at 0 index, won't use it
31, //january
28, //february
31, //march
30, //april
31, //may
30, //june
31, //july
31, //august
30, //september
31, //october
30, //november
31 //december
};
public TwentiethCenturyDate(int day, int month, int year, int dayOfWeek) {
this.day = day;
this.month = month;
this.year = year;
this.dayOfTheWeek = dayOfWeek;
boolean isLeapYear = false;
if(year % 4 == 0) {
if(year % 100 == 0){
if(year % 400 == 0) {
isLeapYear = true;
}
} else {
isLeapYear = true;
}
}
this.isLeapYear = isLeapYear;
this.daysInCurrentMonth = month == 2 && isLeapYear? 29: daysInMonth[month];
}
public TwentiethCenturyDate nextMonth() {
int nextDayOfTheWeek = this.dayOfTheWeek + (this.daysInCurrentMonth % 7);
//if it's bigger than 7, it subtracts 7, if not, it stays the same
nextDayOfTheWeek %= 7;
int nextMonth = this.month;
int nextYear = this.year;
if(this.month == 12) {
nextMonth = 1;
nextYear++;
} else {
nextMonth++;
}
return new TwentiethCenturyDate(this.day, nextMonth, nextYear, nextDayOfTheWeek);
}
public TwentiethCenturyDate nextYear() {
int daysInYear = this.isLeapYear? 366: 365;
int nextDayOfWeek = this.dayOfTheWeek + (daysInYear % 7);
nextDayOfWeek %= 7;
return new TwentiethCenturyDate(this.day, this.month, this.year +1, nextDayOfWeek);
}
// 1 = sunday
// 2 = monday
// 3 = tuesday
// 4 = wednesday
// 5 = thursday
// 6 = friday
// 7 = saturday
public int getDayOfTheWeek() {
return this.dayOfTheWeek;
}
public boolean isTwentiethCentury() {
return this.year >= 1901 && this.year <= 2000;
}
}
| mit |
sniffy/sniffy | sniffy-core/src/test/java/io/sniffy/sql/PreparedStatementInvocationHandlerTest.java | 5253 | package io.sniffy.sql;
import io.qameta.allure.Issue;
import io.sniffy.BaseTest;
import io.sniffy.CurrentThreadSpy;
import io.sniffy.Sniffy;
import io.sniffy.Spy;
import org.junit.Test;
import java.io.IOException;
import java.lang.reflect.Proxy;
import java.sql.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.OptionalInt;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class PreparedStatementInvocationHandlerTest extends BaseTest {
@Test
@Issue("issues/337")
public void testExecuteBatchSuccessNoInfo() throws SQLException, IOException {
PreparedStatement target = mock(PreparedStatement.class);
when(target.executeBatch()).thenReturn(new int[]{Statement.SUCCESS_NO_INFO, Statement.EXECUTE_FAILED});
PreparedStatement sniffyPreparedStatement = (PreparedStatement) Proxy.newProxyInstance(
PreparedStatementInvocationHandlerTest.class.getClassLoader(),
new Class[]{PreparedStatement.class},
new PreparedStatementInvocationHandler(target, null, "jdbc:test:connection:url", "sa", "UPDATE TAB SET FOO = ?")
);
try (CurrentThreadSpy spy = Sniffy.spyCurrentThread()) {
sniffyPreparedStatement.executeBatch();
List<SqlStats> sqlStatsList = new ArrayList<>(spy.getExecutedStatements().values());
assertEquals(1, sqlStatsList.size());
SqlStats sqlStats = sqlStatsList.get(0);
assertEquals(1, sqlStats.queries.intValue());
assertEquals(0, sqlStats.rows.intValue());
}
}
@Test
@Issue("issues/337")
public void testExecuteLongBatchSuccessNoInfo() throws SQLException, IOException {
PreparedStatement target = mock(PreparedStatement.class);
when(target.executeLargeBatch()).thenReturn(new long[]{Statement.SUCCESS_NO_INFO, Statement.EXECUTE_FAILED});
PreparedStatement sniffyPreparedStatement = (PreparedStatement) Proxy.newProxyInstance(
PreparedStatementInvocationHandlerTest.class.getClassLoader(),
new Class[]{PreparedStatement.class},
new PreparedStatementInvocationHandler(target, null, "jdbc:test:connection:url", "sa", "UPDATE TAB SET FOO = ?")
);
try (CurrentThreadSpy spy = Sniffy.spyCurrentThread()) {
sniffyPreparedStatement.executeLargeBatch();
List<SqlStats> sqlStatsList = new ArrayList<>(spy.getExecutedStatements().values());
assertEquals(1, sqlStatsList.size());
SqlStats sqlStats = sqlStatsList.get(0);
assertEquals(1, sqlStats.queries.intValue());
assertEquals(0, sqlStats.rows.intValue());
}
}
@Test
public void testExecuteBatch() throws Exception {
try (Connection connection = openConnection();
PreparedStatement preparedStatement = connection.prepareStatement(INSERT_PREPARED_STATEMENT)) {
preparedStatement.setString(1, "foo");
preparedStatement.addBatch();
int[] result = preparedStatement.executeBatch();
assertEquals(1, result.length);
}
}
@Test
public void testExecuteBatchCountUpdatedRows() throws Exception {
try (@SuppressWarnings("unused") Spy $= Sniffy.expect(SqlQueries.exactRows(2));
Connection connection = openConnection();
PreparedStatement preparedStatement = connection.prepareStatement(INSERT_PREPARED_STATEMENT)) {
preparedStatement.setString(1, "foo");
preparedStatement.addBatch();
preparedStatement.setString(1, "bar");
preparedStatement.addBatch();
int[] result = preparedStatement.executeBatch();
OptionalInt rowsAffected = Arrays.stream(result).filter(i -> i != -1).reduce((a, b) -> a + b);
assertTrue(rowsAffected.isPresent());
assertEquals(2, rowsAffected.getAsInt());
}
}
@Test
public void testExecuteEmptyBatch() throws Exception {
try (Connection connection = openConnection();
PreparedStatement preparedStatement = connection.prepareStatement(INSERT_PREPARED_STATEMENT)) {
int[] result = preparedStatement.executeBatch();
assertEquals(0, result.length);
}
}
@Test
public void testExecuteInsertPreparedStatement() throws Exception {
try (Connection connection = openConnection();
PreparedStatement preparedStatement = connection.prepareStatement(INSERT_PREPARED_STATEMENT)) {
preparedStatement.setString(1, "foo");
int result = preparedStatement.executeUpdate();
assertEquals(1, result);
}
}
@Test
public void getConnectionFromPreparedStatement() throws SQLException {
try (Connection connection = DriverManager.getConnection("sniffy:jdbc:h2:mem:", "sa", "sa");
PreparedStatement statement = connection.prepareStatement("SELECT 1 FROM DUAL")) {
assertEquals(connection, statement.getConnection());
}
}
} | mit |
zalando/intellij-swagger | src/main/java/org/zalando/intellij/swagger/file/icon/SwaggerIconProvider.java | 527 | package org.zalando.intellij.swagger.file.icon;
import com.intellij.openapi.components.ServiceManager;
import javax.swing.Icon;
import org.zalando.intellij.swagger.index.IndexService;
import org.zalando.intellij.swagger.index.swagger.SwaggerIndexService;
public class SwaggerIconProvider extends SpecIconProvider {
@Override
protected Icon getIcon() {
return Icons.SWAGGER_API_ICON;
}
@Override
protected IndexService getIndexService() {
return ServiceManager.getService(SwaggerIndexService.class);
}
}
| mit |
980f/ezjava | src/pers/hal42/timer/TimeBomber.java | 3867 | package pers.hal42.timer;
import pers.hal42.logging.ErrorLogStream;
import pers.hal42.thread.ThreadX;
/**
* Intended use: timeout on background activity outside of Java
* set a timebomb ticking, when it blows it calls your function.
* defuse() it if the desired event happens in a timely fashion.
* int is used for timer so that we don't have to worry about non-atomicity
* of longs.
*/
public class TimeBomber implements Runnable {
protected TimeBomb dynamite = null;
/**
* while system timing is done with longs they are not atomic so we use ints
* and live with the restricted range, which is enormous for a timeout value.
*/
protected int fuse = 0;
private Thread timer;
private boolean defused = false;
public static final ErrorLogStream dbg = ErrorLogStream.getForClass(TimeBomber.class);
private static int idCounter = 0;
/**
* make a background timer that will call upon the dynamite's onTimeout method
* when time is up.
*
* @param fuse is the number of milliseconds to delay, if zero then
* we just create an object and you must use "startFuse(...)" to get something to happen
* @param dynamite is the thing to call when time is up.
*/
private TimeBomber(int fuse, TimeBomb dynamite) {
this.dynamite = dynamite;
this.fuse = fuse;
startFuse();
}
/**
* this is the background timing part
* after the fuse # of millseconds the payload gets called unless
* the thread gets interrupted in which case we stop the thread by exiting run.
*/
public void run() {//executed by the thread "timer"
// this will get run whenever the thread is done, but not interrupted (defused)
if (ThreadX.sleepFor(fuse) && (dynamite != null) && !defused) {//thread wasn't always dying in a timely fashion
dynamite.onTimeout();
}
}
/**
* turn off a possibly ticking timebomb
*/
@SuppressWarnings("TryWithIdenticalCatches")
public void defuse() {
try {
defused = true;
timer.interrupt();
} catch (NullPointerException ignored) {
//no timer yet, so we just don't care to do anything about this.
} catch (IllegalThreadStateException ignored) {
//don't care what happens so long as thread has quit running
}
}
public boolean isTicking() {
return timer != null && timer.isAlive();
}
/**
* @return fuse time, not to be confused with time remaining.
*/
public int fuse() {
return fuse;
}
/**
* start ticking for a new timer value.
* question: will a small enough value potentially allow blowup before we return?
*/
public void startFuse(int newfuse) {
fuse = newfuse;
startFuse();
}
/**
* start ticking with stored timer value
*/
public boolean startFuse() {
try {
defuse();//stop timer , in case it is already ticking.
if (fuse > 0) {
timer = new Thread(this /*as Runnable*/, "TimeBomb#" + dynamite.toString() + "#" + idCounter++ + "#");
//all uses are as timeouts, it doesn't matter if the timer takes extra time before firing
//#-- when the timeout got set by the callback that **it** calls, the priority racheted down ...
//...until it was MIN and never ran ---timer.setPriority(Math.min(Thread.currentThread().getPriority(),Thread.NORM_PRIORITY)-1);
timer.setPriority(Thread.NORM_PRIORITY);//%%TimeoutPriority
timer.start();
}
defused = false;
return true;
} catch (IllegalThreadStateException caught) {
dbg.WARNING("in TimeBomber.startFuse:" + caught);
return false;
}
}
/**
* turn off a possibly ticking timebomb
*/
public static void Defuse(TimeBomber thisone) {
if (thisone != null) {
thisone.defuse();
}
}
public static TimeBomber New(int fuse, TimeBomb dynamite) {
return new TimeBomber(fuse, dynamite);
}
}
| mit |
martindisch/Kantidroid | app/src/main/java/com/martin/kantidroid/ui/overview/ZeugnisAdapter.java | 2025 | package com.martin.kantidroid.ui.overview;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.martin.kantidroid.R;
import com.martin.kantidroid.logic.Fach;
import java.util.List;
public class ZeugnisAdapter extends RecyclerView.Adapter<ZeugnisAdapter.ViewHolder> {
private List<Fach> mEntries;
public ZeugnisAdapter(List<Fach> entries) {
mEntries = entries;
}
@Override
public int getItemCount() {
return mEntries.size();
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.overview_zeugnis_item, viewGroup, false);
return new ViewHolder(v);
}
@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.tvName.setText(mEntries.get(position).getName());
holder.tvSem1.setText(mEntries.get(position).getRealAverage1());
holder.tvSem2.setText(mEntries.get(position).getRealAverage2());
holder.tvFinal.setText(mEntries.get(position).getZeugnis());
holder.rlRoot.setBackgroundResource(R.drawable.btn_flat_selector);
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public final TextView tvName;
public final TextView tvSem1;
public final TextView tvSem2;
public final TextView tvFinal;
public final View rlRoot;
public ViewHolder(View v) {
super(v);
tvName = (TextView) v.findViewById(R.id.tvName);
tvSem1 = (TextView) v.findViewById(R.id.tvFirstSem);
tvSem2 = (TextView) v.findViewById(R.id.tvSecondSem);
tvFinal = (TextView) v.findViewById(R.id.tvFinal);
rlRoot = v.findViewById(R.id.rlRoot);
}
}
public void setData(List<Fach> faecher) {
mEntries = faecher;
}
}
| mit |
SyedShaheryar/OOP-Programs | src/OOPCLASS/CommisionEmployee.java | 1399 | package OOPCLASS;
public class CommisionEmployee {
protected String firstName;
protected String lastName;
protected int socialSecuritNumber; //equivalent to CNIC
protected double grossSales;
protected double commissionRate;
public CommisionEmployee(String f, String l, int ssn, double gs, double cr)
{
firstName = f;
lastName = l;
socialSecuritNumber = ssn;
setGrossSales(ssn);
setCommissionRate (cr);
}
public void setFirstName (String f)
{
firstName = f;
}
public String getFirstName ()
{
return firstName;
}
public void setLastName (String l)
{
lastName = l;
}
public String getLastName ()
{
return lastName;
}
public void setSSN (int ssn)
{
socialSecuritNumber = ssn;
}
public int getSSN()
{
return socialSecuritNumber;
}
public void setGrossSales (double gs)
{
grossSales = (gs<0.0 && gs > 1.0)? 0.0 : gs;
}
public double getGrossSales ()
{
return grossSales;
}
public void setCommissionRate (double cr)
{
commissionRate = (cr > 0.0 && cr < 1.0)? cr: 0.0;
}
public double getCommissionRate ()
{
return commissionRate;
}
public double earnings()
{
return commissionRate * grossSales;
}
public String toString()
{
return String.format("%s: %s %s \n %s: %s \n %s: %.2f \n %s: %.2f","commision employee", firstName, lastName,
"social security number", socialSecuritNumber,
"gross sales", grossSales,
"commisson rate", commissionRate);
}
}
| mit |
Mariusrik/schoolprojects | Avansert java/Innlevering1-jdbc/src/main/java/TableMetaData.java | 1887 | import java.util.ArrayList;
/**
* Stores SQL table meta data
* Created by rikmar15 on 30.11.2016.
* @author Marius Rikheim (rikmar15)
* @version 2.0
*/
public class TableMetaData {
private ArrayList<String> COLUMN_NAME = new ArrayList<>();
private ArrayList<String> TYPENAME = new ArrayList<>();
private ArrayList<Integer> COLUMN_SIZE = new ArrayList<>();
private ArrayList<Integer> NULLABLE = new ArrayList<>();
private ArrayList<String> IS_AUTOINCREMENT = new ArrayList<>();
private ArrayList<String> IS_GENERATEDCOLUMN = new ArrayList<>();
private int size;
public void addColumn(String columnName, String typeName, int columnSize, int nullable, String isAutoIncrement, String isGeneratedColumn) {
size++;
COLUMN_NAME.add(columnName);
TYPENAME.add(typeName);
COLUMN_SIZE.add(columnSize);
NULLABLE.add(nullable);
IS_AUTOINCREMENT.add(isAutoIncrement);
IS_GENERATEDCOLUMN.add(isGeneratedColumn);
}
public ArrayList<String> getColumnName() {
return COLUMN_NAME;
}
public ArrayList<String> getTypename() {
return TYPENAME;
}
public ArrayList<Integer> getColumnSize() {
return COLUMN_SIZE;
}
public ArrayList<Integer> getNullable() {
return NULLABLE;
}
public ArrayList<String> getIsAutoIncrement() {
return IS_AUTOINCREMENT;
}
public ArrayList<String> getIsGeneratedColumn() {
return IS_GENERATEDCOLUMN;
}
public int getSize() {
return size;
}
@Override
public String toString() {
return "Column Name: \n"+COLUMN_NAME + "\n" + "Type name: \n"+ TYPENAME + "\n" + "Column size: \n" + COLUMN_SIZE + "\n" + "Is nullable:\n" + NULLABLE + "\n" + "Is autoincrement: \n" + IS_AUTOINCREMENT + "\n" + "Is Generated Column\n" + IS_GENERATEDCOLUMN;
}
}
| mit |
webfolderio/cormorant | cormorant-core/src/test/java/io/webfolder/cormorant/test/RecursiveDeleteVisitor.java | 2146 | /**
* The MIT License
* Copyright © 2017, 2019 WebFolder OÜ
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package io.webfolder.cormorant.test;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
public class RecursiveDeleteVisitor implements FileVisitor<Path> {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
}
| mit |
derekmu/Schmince-2 | src/dgui/slider/SliderMover.java | 728 | package dgui.slider;
import dgui.GUIItem;
import dgui.GUIMover;
/**
* GUIMover for the Slider GUIItem.
*
* @author Derek Mulvihill - Oct 2, 2013
*/
public class SliderMover implements GUIMover {
@Override
public void moveGUI(GUIItem item, float x, float y) {
Slider slider = (Slider) item;
if (slider.Bounds.w != 0 && slider.Minimum <= slider.Maximum) {
float percent = (x - slider.Bounds.x) / slider.Bounds.w;
slider.Value = Math.max(
slider.Minimum,
Math.min(slider.Maximum, slider.Minimum + percent
* (slider.Maximum - slider.Minimum)));
slider.updatedValue(slider.Value);
}
}
}
| mit |
selvasingh/azure-sdk-for-java | sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/fluent/models/PremierAddOnInner.java | 4684 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.appservice.fluent.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.annotation.JsonFlatten;
import com.azure.core.management.Resource;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
/** Premier add-on. */
@JsonFlatten
@Fluent
public class PremierAddOnInner extends Resource {
@JsonIgnore private final ClientLogger logger = new ClientLogger(PremierAddOnInner.class);
/*
* Premier add on SKU.
*/
@JsonProperty(value = "properties.sku")
private String sku;
/*
* Premier add on Product.
*/
@JsonProperty(value = "properties.product")
private String product;
/*
* Premier add on Vendor.
*/
@JsonProperty(value = "properties.vendor")
private String vendor;
/*
* Premier add on Marketplace publisher.
*/
@JsonProperty(value = "properties.marketplacePublisher")
private String marketplacePublisher;
/*
* Premier add on Marketplace offer.
*/
@JsonProperty(value = "properties.marketplaceOffer")
private String marketplaceOffer;
/*
* Kind of resource.
*/
@JsonProperty(value = "kind")
private String kind;
/**
* Get the sku property: Premier add on SKU.
*
* @return the sku value.
*/
public String sku() {
return this.sku;
}
/**
* Set the sku property: Premier add on SKU.
*
* @param sku the sku value to set.
* @return the PremierAddOnInner object itself.
*/
public PremierAddOnInner withSku(String sku) {
this.sku = sku;
return this;
}
/**
* Get the product property: Premier add on Product.
*
* @return the product value.
*/
public String product() {
return this.product;
}
/**
* Set the product property: Premier add on Product.
*
* @param product the product value to set.
* @return the PremierAddOnInner object itself.
*/
public PremierAddOnInner withProduct(String product) {
this.product = product;
return this;
}
/**
* Get the vendor property: Premier add on Vendor.
*
* @return the vendor value.
*/
public String vendor() {
return this.vendor;
}
/**
* Set the vendor property: Premier add on Vendor.
*
* @param vendor the vendor value to set.
* @return the PremierAddOnInner object itself.
*/
public PremierAddOnInner withVendor(String vendor) {
this.vendor = vendor;
return this;
}
/**
* Get the marketplacePublisher property: Premier add on Marketplace publisher.
*
* @return the marketplacePublisher value.
*/
public String marketplacePublisher() {
return this.marketplacePublisher;
}
/**
* Set the marketplacePublisher property: Premier add on Marketplace publisher.
*
* @param marketplacePublisher the marketplacePublisher value to set.
* @return the PremierAddOnInner object itself.
*/
public PremierAddOnInner withMarketplacePublisher(String marketplacePublisher) {
this.marketplacePublisher = marketplacePublisher;
return this;
}
/**
* Get the marketplaceOffer property: Premier add on Marketplace offer.
*
* @return the marketplaceOffer value.
*/
public String marketplaceOffer() {
return this.marketplaceOffer;
}
/**
* Set the marketplaceOffer property: Premier add on Marketplace offer.
*
* @param marketplaceOffer the marketplaceOffer value to set.
* @return the PremierAddOnInner object itself.
*/
public PremierAddOnInner withMarketplaceOffer(String marketplaceOffer) {
this.marketplaceOffer = marketplaceOffer;
return this;
}
/**
* Get the kind property: Kind of resource.
*
* @return the kind value.
*/
public String kind() {
return this.kind;
}
/**
* Set the kind property: Kind of resource.
*
* @param kind the kind value to set.
* @return the PremierAddOnInner object itself.
*/
public PremierAddOnInner withKind(String kind) {
this.kind = kind;
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
}
}
| mit |
dsaqt1516g3/walka-project | service/src/main/java/edu/upc/eetac/dsa/walka/dao/GroupDAOImpl.java | 14813 | package edu.upc.eetac.dsa.walka.dao;
import edu.upc.eetac.dsa.walka.db.Database;
import edu.upc.eetac.dsa.walka.entity.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* Created by SergioGM on 09.01.16.
*/
public class GroupDAOImpl implements GroupDAO {
@Override
public Group createGroup(String creator, String name, String description) throws SQLException {
Connection connection = null;
PreparedStatement stmt = null;
String id = null;
System.out.println(name);
System.out.println(description);
System.out.println(creator);
try {
connection = Database.getConnection();
stmt = connection.prepareStatement(UserDAOQuery.UUID);
ResultSet rs = stmt.executeQuery();
if (rs.next())
id = rs.getString(1);
else
throw new SQLException();
stmt = connection.prepareStatement(GroupDAOQuery.CREATE_GROUP);
stmt.setString(1, id);
stmt.setString(2, creator);
stmt.setString(3, name);
stmt.setString(4, description);
stmt.executeUpdate();
} catch (SQLException e) {
throw e;
} finally {
if (stmt != null) stmt.close();
if (connection != null) {
connection.setAutoCommit(true);
connection.close();
}
}
return getGroupbyId(id);
}
@Override
public Group getGroupbyId(String id) throws SQLException {
Group group = null;
Connection connection = null;
PreparedStatement stmt = null;
UserCollectionDAO userDAO = new UserCollectionDAOImpl();
UserDAO userD = new UserDAOImpl();
try {
connection = Database.getConnection();
stmt = connection.prepareStatement(GroupDAOQuery.GET_GROUP_BY_ID);
stmt.setString(1, id);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
group = new Group();
group.setId(rs.getString("id"));
group.setCreator(rs.getString("idcreator"));
User user = userD.getUserById(group.getCreator());
group.setCreatorName(user.getFullname());
group.setName(rs.getString("name"));
group.setDescription(rs.getString("description"));
/**Obtengo participantes de otra clase*/
UserCollection components = userDAO.getUsersByGroupId(group.getId());
group.setComponents(components);
group.setLastModified(rs.getTimestamp("last_modified").getTime());
group.setCreationTimestamp(rs.getTimestamp("creation_timestamp").getTime());
}
} catch (SQLException e) {
throw e;
} finally {
if (stmt != null) stmt.close();
if (connection != null) connection.close();
}
return group;
}
@Override
public Group updateGroup(String id, String name, String description) throws SQLException {
Group group = null;
Connection connection = null;
PreparedStatement stmt = null;
try {
connection = Database.getConnection();
stmt = connection.prepareStatement(GroupDAOQuery.UPDATE_GROUP);
stmt.setString(1, name);
stmt.setString(2, description);
stmt.setString(3, id);
int rows = stmt.executeUpdate();
if (rows == 1)
group = getGroupbyId(id);
} catch (SQLException e) {
throw e;
} finally {
if (stmt != null) stmt.close();
if (connection != null) connection.close();
}
return group;
}
@Override
public boolean deleteGroup(String id) throws SQLException {
Connection connection = null;
PreparedStatement stmt = null;
System.out.println("deleteGroup");
try {
connection = Database.getConnection();
stmt = connection.prepareStatement(GroupDAOQuery.DELETE_GROUP);
stmt.setString(1, id);
int rows = stmt.executeUpdate();
return (rows == 1);
} catch (SQLException e) {
throw e;
} finally {
if (stmt != null) stmt.close();
if (connection != null) connection.close();
}
}
@Override
public boolean checkUserInGroup(String idgroup, String iduser) throws SQLException {
Connection connection = null;
PreparedStatement stmt = null;
System.out.println(idgroup);
System.out.println(iduser);
try {
connection = Database.getConnection();
stmt = connection.prepareStatement(GroupDAOQuery.CHECK_USER_IN_GROUP);
stmt.setString(1, iduser);
stmt.setString(2, idgroup);
ResultSet rs= stmt.executeQuery();
return (rs.next());
} catch (SQLException e) {
throw e;
} finally {
if (stmt != null) stmt.close();
if (connection != null) connection.close();
}
}
@Override
public boolean checkUserInInvitation(String idgroup, String iduser) throws SQLException {
Connection connection = null;
PreparedStatement stmt = null;
try {
connection = Database.getConnection();
stmt = connection.prepareStatement(GroupDAOQuery.CHECK_IF_USER_IS_INVITED_TO_GROUP);
stmt.setString(1, idgroup);
stmt.setString(2, iduser);
ResultSet rs= stmt.executeQuery();
return (rs.next());
} catch (SQLException e) {
throw e;
} finally {
if (stmt != null) stmt.close();
if (connection != null) connection.close();
}
}
@Override
public InvitationCollection checkInvitations(String userid) throws SQLException {
InvitationCollection invitationCollection = new InvitationCollection();
Invitation invitation = null;
Group group = null;
Connection connection = null;
PreparedStatement stmt = null;
UserCollectionDAO userDAO = new UserCollectionDAOImpl();
try {
connection = Database.getConnection();
stmt = connection.prepareStatement(GroupDAOQuery.CHECK_INVITATIONS);
stmt.setString(1, userid);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
invitation = new Invitation();
group = new Group();
group = getGroupbyId(rs.getString("groupid"));
invitation.setGroupInvitator(group);
invitation.setIdgroup(group.getId());
invitation.setUserInvitedId(rs.getString("userInvited"));
invitationCollection.getInvitations().add(invitation);
}
} catch (SQLException e) {
throw e;
} finally {
if (stmt != null) stmt.close();
if (connection != null) connection.close();
}
return invitationCollection;
}
@Override
public boolean addUserToGroup(String idgroup, String iduser) throws SQLException {
Connection connection = null;
PreparedStatement stmt = null;
try {
connection = Database.getConnection();
stmt = connection.prepareStatement(GroupDAOQuery.ADD_USER_TO_GROUP);
stmt.setString(1, idgroup);
stmt.setString(2, iduser);
int rows = stmt.executeUpdate();
return (rows == 1);
} catch (SQLException e) {
throw e;
} finally {
if (stmt != null) stmt.close();
if (connection != null) connection.close();
}
}
@Override
public boolean deleteUserFromGroup(String idgroup, String iduser) throws SQLException {
Connection connection = null;
PreparedStatement stmt = null;
try {
connection = Database.getConnection();
stmt = connection.prepareStatement(GroupDAOQuery.DELETE_USER_FROM_GROUP);
stmt.setString(1, idgroup);
stmt.setString(2, iduser);
int rows = stmt.executeUpdate();
return (rows == 1);
} catch (SQLException e) {
throw e;
} finally {
if (stmt != null) stmt.close();
if (connection != null) connection.close();
}
}
@Override
public boolean inviteUserToGroup(String idgroup, String iduser) throws SQLException {
Connection connection = null;
PreparedStatement stmt = null;
try {
connection = Database.getConnection();
stmt = connection.prepareStatement(GroupDAOQuery.INVITE_USERID_TO_GROUP);
stmt.setString(1, idgroup);
stmt.setString(2, iduser);
int rows = stmt.executeUpdate();
return (rows == 1);
} catch (SQLException e) {
throw e;
} finally {
if (stmt != null) stmt.close();
if (connection != null) connection.close();
}
}
@Override
public boolean deleteUserFromInvitations(String idgroup, String userInvited) throws SQLException {
Connection connection = null;
PreparedStatement stmt = null;
try {
connection = Database.getConnection();
stmt = connection.prepareStatement(GroupDAOQuery.DELETE_USER_FROM_PENDING_INVITATIONS);
stmt.setString(1, idgroup);
stmt.setString(2, userInvited);
int rows = stmt.executeUpdate();
return (rows == 1);
} catch (SQLException e) {
throw e;
} finally {
if (stmt != null) stmt.close();
if (connection != null) connection.close();
}
}
@Override
public UserCollection addGroupMembersToEvent(String idgroup, String idevent) throws SQLException {
UserCollection groupMembers = new UserCollection();
UserCollection peopleAdded = new UserCollection();
EventDAO eventDAO = new EventDAOImpl();
Connection connection = null;
PreparedStatement stmt = null;
try {
//Obtengo participantes
connection = Database.getConnection();
stmt = connection.prepareStatement(UserCollectionDAOQuery.GET_USERS_BY_GROUP_ID);
stmt.setString(1, idgroup);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
User user = new User();
user.setId(rs.getString("id"));
user.setLoginid(rs.getString("loginid"));
user.setEmail(rs.getString("email"));
user.setFullname(rs.getString("fullname"));
groupMembers.getUsers().add(user);
}
//Añado si no estan ya en el evento
for (User member: groupMembers.getUsers()){
System.out.println("Miembros: " + member.getFullname() + "ID: " + member.getId());
if (!eventDAO.checkUserInEvent(idevent, member.getId())){
System.out.println("Añado: " + member.getFullname() + "con ID: " + member.getId());
eventDAO.JoinEvent(member.getId(), idevent);
peopleAdded.getUsers().add(member);
}
}
} catch (SQLException e) {
throw e;
} finally {
if (stmt != null) stmt.close();
if (connection != null) connection.close();
}
return peopleAdded;
}
@Override
public boolean groupIsFull(String idgroup) throws SQLException {
Connection connection = null;
PreparedStatement stmt = null;
int NParticipants = 0;
System.out.println("Checks if it's full");
try {
connection = Database.getConnection();
stmt = connection.prepareStatement(GroupDAOQuery.GET_NUMBER_PARTICIPANTS_GROUP);
stmt.setString(1, idgroup);
ResultSet rs= stmt.executeQuery();
rs.next();
System.out.println(rs.getInt("participants"));
NParticipants = rs.getInt(1);
//Si el numero de personas llega al limite, no se permite añadir
return (NParticipants>=GroupDAOQuery.MAX_NUMBER_PEOPLE_GROUP);
} catch (SQLException e) {
throw e;
} finally {
if (stmt != null) stmt.close();
if (connection != null) connection.close();
}
}
@Override
public GroupCollection getGroupsByUserId(String iduser) throws SQLException {
GroupCollection groupCollection = new GroupCollection();
Group group = null;
UserDAO userD = new UserDAOImpl();
Connection connection = null;
PreparedStatement stmt = null;
UserCollectionDAO userDAO = new UserCollectionDAOImpl();
try {
connection = Database.getConnection();
stmt = connection.prepareStatement(GroupDAOQuery.GET_GROUPS_USERID);
stmt.setString(1,iduser);
System.out.println("Security: "+iduser);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
group = new Group();
group.setId(rs.getString("id"));
System.out.println("ID G: " + group.getId());
group.setCreator(rs.getString("creator"));
System.out.println("Creator: " + group.getCreator());
User user = userD.getUserById(group.getCreator());
group.setCreatorName(user.getFullname());
System.out.println(user.getFullname());
group.setName(rs.getString("name"));
group.setDescription(rs.getString("description"));
/**Obtengo participantes de otra clase*/
UserCollection components = userDAO.getUsersByGroupId(group.getId());
group.setComponents(components);
group.setLastModified(rs.getTimestamp("last_modified").getTime());
group.setCreationTimestamp(rs.getTimestamp("creation_timestamp").getTime());
System.out.println(group.getCreationTimestamp());
groupCollection.getGroups().add(group);
}
} catch (SQLException e) {
throw e;
} finally {
if (stmt != null) stmt.close();
if (connection != null) connection.close();
}
return groupCollection;
}
}
| mit |
Ivorforce/IvToolkit | src/main/java/ivorius/ivtoolkit/random/values/IConstant.java | 982 | /*
* Copyright 2016 Lukas Tenbrink
*
* 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 ivorius.ivtoolkit.random.values;
import java.util.Random;
/**
* Created by lukas on 04.04.14.
*/
public class IConstant implements IValue
{
public int constant;
public IConstant(int constant)
{
this.constant = constant;
}
@Override
public Integer getValue(Random random)
{
return constant;
}
}
| mit |
x7chen/XiaoV | app/src/main/java/com/cfk/xiaov/rest/model/request/CheckPhoneRequest.java | 599 | package com.cfk.xiaov.rest.model.request;
/**
* Created by AMing on 15/12/23.
* Company RongCloud
*/
public class CheckPhoneRequest {
private String phone;
private String region;
public CheckPhoneRequest(String phone, String region) {
this.phone = phone;
this.region = region;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
}
| mit |
dtzeng/ds-f14 | Project3_MapReduce/src/mapr/master/TaskInfo.java | 4215 | package mapr.master;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Encapsulates all metadata for a task, including Task ID, Task Type, I/O File Name, etc.
*
* @author Derek Tzeng <dtzeng@andrew.cmu.edu>
*
*/
public class TaskInfo implements Serializable {
private static final long serialVersionUID = 92699575894330642L;
String taskType, input, output, otherArgs, jobType;
int recordStart, recordEnd, taskID, sourceJobID;
List<Integer> taskDependencies;
/*
* (Only used for `Reduce`) List of file names to merge from.
*/
List<String> filenames;
/**
* Constructor used for new Mapper tasks.
*
* @param taskType `mapper`
* @param input Input file name
* @param output Output file name
* @param recordStart Starting point of input file to map
* @param recordEnd End point of input file to map
* @param taskID Unique TaskID
* @param otherArgs Extra user arguments
* @param sourceJobID JobID for Mapper task
* @param jobType Class name of MapReduce job
*/
public TaskInfo(String taskType, String input, String output, int recordStart, int recordEnd,
int taskID, String otherArgs, int sourceJobID, String jobType) {
this.taskType = taskType;
this.input = input;
this.output = output;
this.recordStart = recordStart;
this.recordEnd = recordEnd;
this.taskID = taskID;
this.otherArgs = otherArgs;
this.sourceJobID = sourceJobID;
this.jobType = jobType;
this.taskDependencies = Collections.synchronizedList(new ArrayList<Integer>());
}
/**
* Constructor used for new Sorter tasks.
*
* @param taskType `sorter`
* @param input Input file name
* @param output Output file name
* @param taskID Unique TaskID
* @param dependency TaskID that sorter depends on before starting
* @param sourceJobID JobID for Mapper task
* @param jobType Class name of MapReduce job
*/
public TaskInfo(String taskType, String input, String output, int taskID, int dependency,
int sourceJobID, String jobType) {
this.taskType = taskType;
this.input = input;
this.output = output;
this.taskID = taskID;
this.sourceJobID = sourceJobID;
this.jobType = jobType;
this.taskDependencies = Collections.synchronizedList(new ArrayList<Integer>());
this.taskDependencies.add(dependency);
}
/**
* Constructor used for new Reduce tasks.
*
* @param taskType `reduce`
* @param output Output file name
* @param taskID Unique TaskID
* @param sourceJobID JobID for Mapper task
* @param jobType Class name of MapReduce job
*/
public TaskInfo(String taskType, String output, int taskID, int sourceJobID, String jobType) {
this.taskType = taskType;
this.output = output;
this.taskID = taskID;
this.sourceJobID = sourceJobID;
this.jobType = jobType;
this.taskDependencies = Collections.synchronizedList(new ArrayList<Integer>());
this.filenames = Collections.synchronizedList(new ArrayList<String>());
}
public String getTaskType() {
return taskType;
}
public String getInput() {
return input;
}
public String getOutput() {
return output;
}
public int getRecordStart() {
return recordStart;
}
public int getRecordEnd() {
return recordEnd;
}
public int getTaskID() {
return taskID;
}
public String getOtherArgs() {
return otherArgs;
}
public int getSourceJobID() {
return sourceJobID;
}
public String getJobType() {
return jobType;
}
public List<Integer> getTaskDependencies() {
return taskDependencies;
}
public synchronized int removeDependency(Integer dependency) {
taskDependencies.remove(dependency);
return taskDependencies.size();
}
public synchronized void addDependency(Integer dependency) {
taskDependencies.add(dependency);
}
public List<String> getFilenames() {
return filenames;
}
public synchronized void addFilename(String file) {
filenames.add(file);
}
}
| mit |
huherto/springyRecords | generator/src/main/java/com/example/PetTable.java | 177 | package com.example;
import javax.sql.DataSource;
public class PetTable extends BasePetTable {
public PetTable(DataSource dataSource) {
super(dataSource);
}
}
| mit |
ofirl/HackerSwamp | src/main/java/commands/Market.java | 7057 | package commands;
import interface_objects.DatabaseHandler;
import interface_objects.DatabaseTables;
import interface_objects.LoginHandler;
import items.BaseItem;
import managers.CommandManager;
import managers.DomainsManager;
import managers.ItemManager;
import managers.Logger;
import objects.*;
import java.util.*;
public class Market extends BaseCommand {
public static Command superCommand;
public static HashMap<String, HashMap<String, Argument>> acceptedArguments = new HashMap<>();
static {
// super command
superCommand = CommandManager.getCommandByName(Parameters.CommandNameMarket);
// sub commands hash maps init
acceptedArguments.put("market", new HashMap<>());
acceptedArguments.put("items", new HashMap<>());
acceptedArguments.put("scripts", new HashMap<>());
// items
acceptedArguments.get("items").put("type", new Argument("type", String.class));
acceptedArguments.get("items").put("buy", new Argument("buy", int.class));
// scripts
acceptedArguments.get("scripts").put("security", new Argument("security", String.class));
acceptedArguments.get("scripts").put("buy", new Argument("buy", int.class));
}
/**
* empty constructor for the
*/
public Market() {
this(null);
}
/**
* constructor
* @param context the context to run in
*/
public Market(CommandContext context) {
super(context, Parameters.CommandNameMarket);
}
/**
* implementation of the abstract method
* @param context the context of the new instance
* @return a new instance with the given context
*/
public Market createInstance(CommandContext context) {
return new Market(context);
}
/**
* buys the item
* @return a response
*/
public String buyItem() {
int itemId = args.get("buy").castValue(Integer.class);
// sanity checks
BaseItem selectedItem = ItemManager.getItemById(itemId);
if (selectedItem == null)
return Parameters.ErrorMarketItemNotFound;
ActiveUser user = LoginHandler.getActiveUserByUsername(context.username);
if (user == null)
return Parameters.ErrorActiveUserNotFound;
Account acc = user.getMainAccount();
if (acc == null)
return Parameters.ErrorMainAccountNotFound;
if (!acc.canTransfer(selectedItem.price))
return Parameters.ErrorInsufficientFunds;
// subtract the item price if bought successfully
if (ItemManager.addItemToUserInventory(context.username, selectedItem.id)) {
acc.changeBalance(-selectedItem.price);
user.getInventory().put(itemId, selectedItem);
return "Item has been bought";
}
return "Could not finalize the order";
}
/**
* help command
* @return general help
*/
public String main() {
// TODO : return general help
return getSubCommands(superCommand);
}
/**
* market.items command
* @return list of items
*/
public String items() {
// check for invalid argument
if (!checkArguments(acceptedArguments.get("items")))
return Parameters.ErrorCommandInvalidArguments;
String output = "";
HashMap<Integer, BaseItem> items = new HashMap<>();
if (args.containsKey("buy"))
return buyItem();
if (args.containsKey("type")) {
String itemType = args.get("type").value;
switch (itemType) {
case "motherboard" :
items = ItemManager.castItemsToBaseItem(ItemManager.getAllMotherboards());
break;
case "cpu" :
items = ItemManager.castItemsToBaseItem(ItemManager.getAllCpus());
break;
case "ram" :
items = ItemManager.castItemsToBaseItem(ItemManager.getAllRams());
break;
case "hdd" :
items = ItemManager.castItemsToBaseItem(ItemManager.getAllHdds());
break;
case "network" :
items = ItemManager.castItemsToBaseItem(ItemManager.getAllNetworkCards());
break;
default :
output += "accepted values for \"type\" are : motherboard, cpu, ram, hdd and network";
}
}
else
items = ItemManager.getAllItems();
if (items == null) {
String msg = "Error retrieving items for type = " + args.get("type").value + ", username = " + context.username;
Logger.log("Market.items", msg);
return Parameters.ErrorUnknownError;
}
for (BaseItem item :
items.values())
output += item.toString() + "\n\n";
return output;
}
/**
* market.scripts command
* @return list of scripts
*/
public String scripts() {
// check for invalid argument
if (!checkArguments(acceptedArguments.get("scripts")))
return Parameters.ErrorCommandInvalidArguments;
String output = "";
HashMap<Integer, BaseItem> items = new HashMap<>();
if (args.containsKey("buy"))
return buyItem();
if (args.containsKey("security")) {
String securityLevel = args.get("security").value;
switch (CommandSecurityRating.valueOf(securityLevel)) {
case unknown:
items.putAll(ItemManager.castItemsToBaseItem(ItemManager.getAllMarketScripts(CommandSecurityRating.unknown)));
case lowsec:
items.putAll(ItemManager.castItemsToBaseItem(ItemManager.getAllMarketScripts(CommandSecurityRating.lowsec)));
case medsec:
items.putAll(ItemManager.castItemsToBaseItem(ItemManager.getAllMarketScripts(CommandSecurityRating.medsec)));
case topsec:
items.putAll(ItemManager.castItemsToBaseItem(ItemManager.getAllMarketScripts(CommandSecurityRating.topsec)));
case syscmd:
items.putAll(ItemManager.castItemsToBaseItem(ItemManager.getAllMarketScripts(CommandSecurityRating.syscmd)));
break;
default :
return "accepted values for \"security\" are : syscmd, topsec, medsec, lowsec, unknown";
}
}
else
items = ItemManager.castItemsToBaseItem(ItemManager.getAllMarketScripts());
if (items == null) {
String msg = "Error retrieving items for type = " + args.get("type").value + ", username = " + context.username;
Logger.log("Market.items", msg);
return Parameters.ErrorUnknownError;
}
for (BaseItem item :
items.values())
output += item.toString() + "\n\n";
return output;
}
}
| mit |
feedeo/bingads-api | src/main/java/com/microsoft/bingads/v10/adinsight/GetBidLandscapeByAdGroupIdsResponse.java | 4461 | /**
* GetBidLandscapeByAdGroupIdsResponse.java
* <p>
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
*/
package com.microsoft.bingads.v10.adinsight;
public class GetBidLandscapeByAdGroupIdsResponse implements java.io.Serializable {
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(GetBidLandscapeByAdGroupIdsResponse.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("Microsoft.Advertiser.AdInsight.Api.Service", ">GetBidLandscapeByAdGroupIdsResponse"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("bidLandscape");
elemField.setXmlName(new javax.xml.namespace.QName("Microsoft.Advertiser.AdInsight.Api.Service", "BidLandscape"));
elemField.setXmlType(new javax.xml.namespace.QName("http://schemas.datacontract.org/2004/07/Microsoft.BingAds.Advertiser.AdInsight.Api.DataContract.Entity", "AdGroupBidLandscape"));
elemField.setMinOccurs(0);
elemField.setNillable(true);
elemField.setItemQName(new javax.xml.namespace.QName("http://schemas.datacontract.org/2004/07/Microsoft.BingAds.Advertiser.AdInsight.Api.DataContract.Entity", "AdGroupBidLandscape"));
typeDesc.addFieldDesc(elemField);
}
private com.microsoft.bingads.v10.adinsight.entity.AdGroupBidLandscape[] bidLandscape;
private java.lang.Object __equalsCalc = null;
private boolean __hashCodeCalc = false;
public GetBidLandscapeByAdGroupIdsResponse() {
}
public GetBidLandscapeByAdGroupIdsResponse(
com.microsoft.bingads.v10.adinsight.entity.AdGroupBidLandscape[] bidLandscape) {
this.bidLandscape = bidLandscape;
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
/**
* Gets the bidLandscape value for this GetBidLandscapeByAdGroupIdsResponse.
*
* @return bidLandscape
*/
public com.microsoft.bingads.v10.adinsight.entity.AdGroupBidLandscape[] getBidLandscape() {
return bidLandscape;
}
/**
* Sets the bidLandscape value for this GetBidLandscapeByAdGroupIdsResponse.
*
* @param bidLandscape
*/
public void setBidLandscape(com.microsoft.bingads.v10.adinsight.entity.AdGroupBidLandscape[] bidLandscape) {
this.bidLandscape = bidLandscape;
}
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof GetBidLandscapeByAdGroupIdsResponse)) return false;
GetBidLandscapeByAdGroupIdsResponse other = (GetBidLandscapeByAdGroupIdsResponse) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true &&
((this.bidLandscape == null && other.getBidLandscape() == null) ||
(this.bidLandscape != null &&
java.util.Arrays.equals(this.bidLandscape, other.getBidLandscape())));
__equalsCalc = null;
return _equals;
}
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = 1;
if (getBidLandscape() != null) {
for (int i = 0;
i < java.lang.reflect.Array.getLength(getBidLandscape());
i++) {
java.lang.Object obj = java.lang.reflect.Array.get(getBidLandscape(), i);
if (obj != null &&
!obj.getClass().isArray()) {
_hashCode += obj.hashCode();
}
}
}
__hashCodeCalc = false;
return _hashCode;
}
}
| mit |
Syncano/syncano-android | library/src/main/java/com/syncano/library/utils/SyncanoLogger.java | 248 | package com.syncano.library.utils;
public abstract class SyncanoLogger {
public abstract void d(String tag, String message);
public abstract void w(String tag, String message);
public abstract void e(String tag, String message);
}
| mit |
xR86/java-stuff | Lab02/Lecturer.java | 1485 |
import java.util.Vector;
public class Lecturer extends Persons {
static int IDcounter = 0;
private String lecturerID;
private Vector<Student> myStudentPreferences = new Vector<Student>();
private Vector<Project> myProjects = new Vector<Project>();
/**
* Lecturer() - this class constructor increments the static counter (unique to a lecturer whithin a session) and assigns it (along with the letter) to the lecturer ID
*/
Lecturer(){
IDcounter = IDcounter+1;
this.lecturerID = this.toString();
}
/**
* getStudentID() gives a lecturer's ID
* @return the ID of the lecturer
*/
public String getLecturerID() {
return this.lecturerID;
}
/**
* isFree() checks if the lecturer has any projects allocated
* @return 1 if the lecturer has projects allocated
* @return 0 if the lecturer is free (has no projects allocated)
*/
@Override
protected int isFree() {
if (myStudentPreferences.capacity() != 0) {
return 1;
}
return 0;
}
@Override
public String toString(){
String temp = "L";
temp += IDcounter;
return temp;
}
/**
* addStudentPreference() adds a lecturers preferences of students
* @param student - is added to the private myStudentPreferences vector
*/
public void addStudentPreference(Student student) {
myStudentPreferences.add(student);
}
} | mit |
plum-umd/java-sketch | test/axioms/examples/EasyCSV/EasyCSV/noax/tests/CsvDocumentTest.java | 5434 | package easycsv.test;
import easycsv.CsvColumn;
import easycsv.CsvConfiguration;
import easycsv.CsvDocument;
import easycsv.CsvRow;
import jdk.nashorn.internal.ir.annotations.Ignore;
import org.junit.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Created by Dan Geabunea on 3/26/2015.
*/
public class CsvDocumentTest {
@Test
public void with_no_config_options_should_parse_csv_file_and_create_csv_document() throws IOException {
//arrange
// String csvPath = getClass().getClassLoader().getResource("csv_test_file.csv").getPath();
String csvPath = "csv_test_file.csv";
//act
CsvDocument document = CsvDocument.read(csvPath);
//assert
List<CsvRow> rs = document.getCsvRows();
// assertEquals(3, rs.size());
assert 3 == rs.size();
assert 0 == 1;
// CsvRow header = document.getCsvRows().get(0);
// assertEquals("Header 1,Header 2,Header 3,Header 4,Header 5", header.toString());
// assertEquals("1,1.1,abc,TRUE,11/1/2014", document.getCsvRows().get(1).toString());
// assertEquals("2,2.2,def,FALSE,11/2/2014", document.getCsvRows().get(2).toString());
}
// @Test
// public void when_configured_to_skip_header_should_parse_csv_document_without_header() throws IOException {
// //arrange
// String csvPath = getClass().getClassLoader().getResource("csv_test_file.csv").getPath();
// CsvConfiguration skipHeaderConfig = new CsvConfiguration(){{
// setSkipHeader(true);
// }};
// //act
// CsvDocument document = CsvDocument.read(csvPath, skipHeaderConfig);
// //assert
// assertEquals(2, document.getCsvRows().size());
// assertEquals("1,1.1,abc,TRUE,11/1/2014", document.getCsvRows().get(0).toString());
// assertEquals("2,2.2,def,FALSE,11/2/2014", document.getCsvRows().get(1).toString());
// }
// @Test
// public void when_configured_to_parse_specific_columns_should_parse_csv_document_without_selected_columns() throws IOException {
// //arrange
// String csvPath = getClass().getClassLoader().getResource("csv_test_file.csv").getPath();
// CsvConfiguration skipHeaderConfig = new CsvConfiguration(){{
// setColumnIndexesToParse(0, 1, 2);
// }};
// //act
// CsvDocument document = CsvDocument.read(csvPath, skipHeaderConfig);
// //assert
// assertEquals(3, document.getCsvRows().size());
// assertEquals("Header 1,Header 2,Header 3", document.getCsvRows().get(0).toString());
// assertEquals("1,1.1,abc", document.getCsvRows().get(1).toString());
// assertEquals("2,2.2,def", document.getCsvRows().get(2).toString());
// }
// @Test
// public void should_allow_easy_mapping_to_pojo() throws IOException {
// //arrange
// String csvPath = getClass().getClassLoader().getResource("csv_person_file_test.csv").getPath();
// CsvConfiguration skipHeaderConfig = new CsvConfiguration(){{
// setSkipHeader(true);
// }};
// CsvDocument personDocument = CsvDocument.read(csvPath, skipHeaderConfig);
// //act
// List<Person> persons = personDocument.getCsvRows().stream()
// .map(x -> new Person(
// x.getColumnAtIndex(0).getColumnValue(),
// x.getColumnAtIndex(1).getInteger(),
// x.getColumnAtIndex(2).getBoolean()
// ))
// .collect(Collectors.toList());
// //assert
// assertEquals(2, persons.size());
// Person firstPerson = persons.get(0);
// assertEquals("John", firstPerson.getName());
// assertEquals(23, firstPerson.getAge());
// assertEquals(false, firstPerson.isEmployed());
// Person secondPerson = persons.get(1);
// assertEquals("Mary", secondPerson.getName());
// assertEquals(31, secondPerson.getAge());
// assertEquals(true, secondPerson.isEmployed());
// }
// @Ignore()
// @Test
// public void the_write_method_should_write_to_file(){
// //arrange
// String outputPath = getClass().getClassLoader().getResource("csv_output_test.csv").getPath();;
// CsvRow someRow = new CsvRow(new CsvColumn("some value"), new CsvColumn(2.2), new CsvColumn(true));
// CsvDocument documentWithOneRow = new CsvDocument(new ArrayList<>(Arrays.asList(someRow)));
// //act
// boolean result = CsvDocument.tryWriteToFile(documentWithOneRow, outputPath);
// //assert
// assertTrue(result);
// }
/*
Class used ofr testing reasons
*/
private class Person {
private String name;
private int age;
private boolean isEmployed;
public Person(String name, int age, boolean isEmployed){
this.name = name;
this.age = age;
this.isEmployed = isEmployed;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public boolean isEmployed() {
return isEmployed;
}
}
}
| mit |
chav1961/purelib | src/main/java/chav1961/purelib/fsys/FileSystemOnRMI.java | 9505 | package chav1961.purelib.fsys;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.Map;
import java.util.regex.Pattern;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import chav1961.purelib.basic.PureLibSettings;
import chav1961.purelib.basic.URIUtils;
import chav1961.purelib.basic.exceptions.EnvironmentException;
import chav1961.purelib.basic.interfaces.LoggerFacade;
import chav1961.purelib.basic.interfaces.LoggerFacade.Severity;
import chav1961.purelib.fsys.interfaces.DataWrapperInterface;
import chav1961.purelib.fsys.interfaces.FileSystemInterface;
import chav1961.purelib.fsys.interfaces.FileSystemInterfaceDescriptor;
import chav1961.purelib.fsys.interfaces.RMIDataWrapperInterface;
import chav1961.purelib.i18n.PureLibLocalizer;
/**
* <p>This class implements the file system interface on remote server using standard Java RMI protocol.
* //localhost:"+Registry.REGISTRY_PORT+"/testRMI
* </p>
*
* <p>This class is not thread-safe.</p>
*
* @see chav1961.purelib.fsys.interfaces.FileSystemInterface
* @see chav1961.purelib.fsys.RMIFileSystemServer
* @see chav1961.purelib.fsys JUnit tests
* @author Alexander Chernomyrdin aka chav1961
* @since 0.0.1
* @lastUpdate 0.0.5
*/
public class FileSystemOnRMI extends AbstractFileSystem implements FileSystemInterfaceDescriptor {
private static final URI SERVE = URI.create(FileSystemInterface.FILESYSTEM_URI_SCHEME+":rmi:/");
private static final String DESCRIPTION = FileSystemFactory.FILESYSTEM_LOCALIZATION_PREFIX+'.'+FileSystemOnRMI.class.getSimpleName()+'.'+FileSystemFactory.FILESYSTEM_DESCRIPTION_SUFFIX;
private static final String VENDOR = FileSystemFactory.FILESYSTEM_LOCALIZATION_PREFIX+'.'+FileSystemOnRMI.class.getSimpleName()+'.'+FileSystemFactory.FILESYSTEM_VENDOR_SUFFIX;
private static final String LICENSE = FileSystemFactory.FILESYSTEM_LOCALIZATION_PREFIX+'.'+FileSystemOnRMI.class.getSimpleName()+'.'+FileSystemFactory.FILESYSTEM_LICENSE_SUFFIX;
private static final String LICENSE_CONTENT = FileSystemFactory.FILESYSTEM_LOCALIZATION_PREFIX+'.'+FileSystemOnRMI.class.getSimpleName()+'.'+FileSystemFactory.FILESYSTEM_LICENSE_CONTENT_SUFFIX;
private static final String HELP = FileSystemFactory.FILESYSTEM_LOCALIZATION_PREFIX+'.'+FileSystemOnRMI.class.getSimpleName()+'.'+FileSystemFactory.FILESYSTEM_LICENSE_HELP_SUFFIX;
private static final Icon ICON = new ImageIcon(FileSystemOnRMI.class.getResource("rmiIcon.png"));
private final URI remote;
private final RMIDataWrapperInterface server;
/**
* <p>This constructor is an entry for the SPI service only. Don't use it in any purposes</p>
*/
public FileSystemOnRMI(){
this.remote = null;
this.server = null;
}
/**
* <p>Create the file system for the given remote connection.
* @param remote remote uri for the remote file system server. Need be absolute URI with the schema 'rmi', for example <code>'rmi://localhost/rmiServerName'</code>. Tail of URI (rmiServerName)
* need be corresponding with the registered RMI server instance name (see {@link RMIFileSystemServer})
* @throws IOException if any exception was thrown
*/
public FileSystemOnRMI(final URI remote) throws IOException {
super(remote);
this.remote = remote;
try{final Object server = Naming.lookup(remote.toString());
if (server instanceof RMIDataWrapperInterface) {
this.server = (RMIDataWrapperInterface)server;
}
else {
throw new IOException("Remote server ["+remote+"] not found");
}
} catch (MalformedURLException | RemoteException | NotBoundException e) {
throw new IOException(e.getMessage());
}
}
private FileSystemOnRMI(final FileSystemOnRMI another) {
super(another);
this.remote = another.remote;
this.server = another.server;
}
@Override
public boolean canServe(final URI resource) {
return URIUtils.canServeURI(resource,SERVE);
}
@Override
public FileSystemInterface newInstance(final URI resource) throws EnvironmentException {
if (!canServe(resource)) {
throw new EnvironmentException("Resource URI ["+resource+"] is not supported by the class. Valid URI must be ["+SERVE+"...]");
}
else {
try{return new FileSystemOnRMI(URI.create(resource.getRawSchemeSpecificPart()));
} catch (IOException e) {
throw new EnvironmentException("I/O error creation file system on RMI: "+e.getLocalizedMessage(),e);
}
}
}
@Override
public FileSystemInterface clone() {
return new FileSystemOnRMI(this);
}
@Override
public DataWrapperInterface createDataWrapper(final URI actualPath) throws IOException {
return new RemoteDataWrapper(server,actualPath);
}
@Override
public String getClassName() {
return this.getClass().getSimpleName();
}
@Override
public String getVersion() {
return PureLibSettings.CURRENT_VERSION;
}
@Override
public URI getLocalizerAssociated() {
return PureLibLocalizer.LOCALIZER_SCHEME_URI;
}
@Override
public String getDescriptionId() {
return DESCRIPTION;
}
@Override
public Icon getIcon() {
return ICON;
}
@Override
public String getVendorId() {
return VENDOR;
}
@Override
public String getLicenseId() {
return LICENSE;
}
@Override
public String getLicenseContentId() {
return LICENSE_CONTENT;
}
@Override
public String getHelpId() {
return HELP;
}
@Override
public URI getUriTemplate() {
return SERVE;
}
@Override
public FileSystemInterface getInstance() throws EnvironmentException {
return this;
}
@Override
public boolean testConnection(final URI connection, final LoggerFacade logger) throws IOException {
if (connection == null) {
throw new NullPointerException("Connection to test can't be null");
}
else {
try(final FileSystemInterface inst = newInstance(connection)) {
return inst.exists();
} catch (EnvironmentException e) {
if (logger != null) {
logger.message(Severity.error, e, "Error testing connection [%1$s]: %2$s",connection,e.getLocalizedMessage());
}
throw new IOException(e.getLocalizedMessage(),e);
}
}
}
private static class RemoteDataWrapper implements DataWrapperInterface {
private final RMIDataWrapperInterface remote;
private final URI path;
RemoteDataWrapper(final RMIDataWrapperInterface remote, final URI path) {
this.remote = remote;
this.path = path;
}
@Override
public URI[] list(Pattern pattern) throws IOException {
try{final String[] call = remote.list(path,pattern.pattern());
final URI[] result = new URI[call.length];
for (int index = 0; index < result.length; index++) {
result[index] = URI.create(call[index]);
}
return result;
} catch (RemoteException exc) {
throw new IOException(exc.getMessage());
}
}
@Override
public void mkDir() throws IOException {
try{remote.mkDir(path);
} catch (RemoteException exc) {
throw new IOException(exc.getMessage());
}
}
@Override
public void create() throws IOException {
try{remote.create(path);
} catch (RemoteException exc) {
throw new IOException(exc.getMessage());
}
}
@Override
public void setName(String name) throws IOException {
try{remote.setName(path,name);
} catch (RemoteException exc) {
throw new IOException(exc.getMessage());
}
}
@Override
public void delete() throws IOException {
try{remote.delete(path);
} catch (RemoteException exc) {
throw new IOException(exc.getMessage());
}
}
@Override
public OutputStream getOutputStream(boolean append) throws IOException {
return new StoredByteArrayOutputStream(remote,path,append);
}
@Override
public InputStream getInputStream() throws IOException {
try{return new ByteArrayInputStream(remote.load(path));
} catch (RemoteException exc) {
throw new IOException(exc.getMessage());
}
}
@Override
public Map<String, Object> getAttributes() throws IOException {
try{return remote.getAttributes(path);
} catch (RemoteException exc) {
throw new IOException(exc.getMessage());
}
}
@Override
public void linkAttributes(Map<String, Object> attributes) throws IOException {
try{remote.linkAttributes(path,attributes);
} catch (RemoteException exc) {
throw new IOException(exc.getMessage());
}
}
@Override
public boolean tryLock(final String path, final boolean sharedMode) throws IOException {
// TODO Auto-generated method stub
return false;
}
@Override
public void lock(final String path, final boolean sharedMode) throws IOException {
// TODO Auto-generated method stub
}
@Override
public void unlock(final String path, final boolean sharedMode) throws IOException {
// TODO Auto-generated method stub
}
}
private static class StoredByteArrayOutputStream extends ByteArrayOutputStream {
private final RMIDataWrapperInterface remote;
private final URI path;
private final boolean append;
public StoredByteArrayOutputStream(final RMIDataWrapperInterface remote, final URI path, final boolean append) {
this.remote = remote; this.path = path;
this.append = append;
}
@Override
public void close() throws IOException {
super.close();
remote.store(path,toByteArray(), append);
}
}
}
| mit |
Consdata/sonarqube-companion | sonarqube-companion-rest/src/main/java/pl/consdata/ico/sqcompanion/config/AppConfigConfiguration.java | 4036 | package pl.consdata.ico.sqcompanion.config;
import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.DeserializationConfig;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.BeanDeserializerModifier;
import com.fasterxml.jackson.databind.module.SimpleModule;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import pl.consdata.ico.sqcompanion.UnableToStoreAppConfigException;
import pl.consdata.ico.sqcompanion.config.deserialization.*;
import pl.consdata.ico.sqcompanion.config.model.*;
import pl.consdata.ico.sqcompanion.hook.action.NoImprovementWebhookActionData;
import pl.consdata.ico.sqcompanion.hook.callback.JSONWebhookCallback;
import pl.consdata.ico.sqcompanion.hook.callback.PostWebhookCallback;
import java.util.ArrayList;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
@Configuration
@Slf4j
public class AppConfigConfiguration {
@Value("${app.configFile:sq-companion-config.json}")
private String appConfigFile;
@Bean
@ConditionalOnProperty(value = "config.store", havingValue = "file")
public AppConfigStore appConfigStore() {
return new FileAppConfigStore(appConfigFile);
}
@Bean
public AppConfig appConfig(final ObjectMapper objectMapper, final AppConfigStore appConfigStore) throws UnableToReadAppConfigException, UnableToStoreAppConfigException {
SimpleModule module = new SimpleModule();
module.setDeserializerModifier(new BeanDeserializerModifier() {
@Override
public JsonDeserializer<?> modifyDeserializer(DeserializationConfig config, BeanDescription beanDesc, JsonDeserializer<?> deserializer) {
if (beanDesc.getBeanClass() == GroupDefinition.class) {
return new GroupDeserializer(deserializer);
}
if (beanDesc.getBeanClass() == WebhookDefinition.class) {
return new WebhookDeserializer(deserializer);
}
if (beanDesc.getBeanClass() == Member.class) {
return new MemberDeserializer(deserializer);
}
if (beanDesc.getBeanClass() == ServerDefinition.class) {
return new ServerDefinitionDeserializer(deserializer);
}
return deserializer;
}
});
module.addDeserializer(ServerAuthentication.class, new ServerAuthenticationDeserializer());
module.addDeserializer(GroupEvent.class, new GroupEventDeserializer());
module.addDeserializer(ProjectLink.class, new ProjectLinkDeserializer());
module.addDeserializer(PostWebhookCallback.class, new PostWebhookCallbackDeserializer());
module.addDeserializer(JSONWebhookCallback.class, new JsonWebhookCallbackDeserializer());
module.addDeserializer(NoImprovementWebhookActionData.class, new NoImprovementWebhookActionDataDeserializer());
objectMapper.registerModule(module);
final AppConfig appConfig = appConfigStore.read(objectMapper, getDefaultAppConfig());
log.info("App config loaded [appConfig={}]", appConfig);
return appConfig;
}
private AppConfig getDefaultAppConfig() {
return AppConfig
.builder()
.scheduler(new SchedulerConfig(1L, TimeUnit.DAYS))
.servers(new ArrayList<>())
.rootGroup(
GroupDefinition
.builder()
.uuid(UUID.randomUUID().toString())
.name("All projects")
.build()
)
.build();
}
}
| mit |
pink-lucifer/preresearch | spring-atomikos-demo/domain/src/main/protoGen/com/lufs/atomikos/protos/SecuritiesServiceGrpc.java | 10830 | package com.lufs.atomikos.protos;
import static io.grpc.stub.ClientCalls.asyncUnaryCall;
import static io.grpc.stub.ClientCalls.asyncServerStreamingCall;
import static io.grpc.stub.ClientCalls.asyncClientStreamingCall;
import static io.grpc.stub.ClientCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ClientCalls.blockingUnaryCall;
import static io.grpc.stub.ClientCalls.blockingServerStreamingCall;
import static io.grpc.stub.ClientCalls.futureUnaryCall;
import static io.grpc.MethodDescriptor.generateFullMethodName;
import static io.grpc.stub.ServerCalls.asyncUnaryCall;
import static io.grpc.stub.ServerCalls.asyncServerStreamingCall;
import static io.grpc.stub.ServerCalls.asyncClientStreamingCall;
import static io.grpc.stub.ServerCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall;
/**
*/
@javax.annotation.Generated(
value = "by gRPC proto compiler (version 1.0.0)",
comments = "Source: securities.proto")
public class SecuritiesServiceGrpc {
private SecuritiesServiceGrpc() {}
public static final String SERVICE_NAME = "SecuritiesService";
// Static method descriptors that strictly reflect the proto.
@io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901")
public static final io.grpc.MethodDescriptor<com.lufs.atomikos.protos.SecuritiesProtos.SecuritiesRequest,
com.lufs.atomikos.protos.SecuritiesProtos.SecuritiesResponse> METHOD_FOR_SECURITIES =
io.grpc.MethodDescriptor.create(
io.grpc.MethodDescriptor.MethodType.UNARY,
generateFullMethodName(
"SecuritiesService", "forSecurities"),
io.grpc.protobuf.ProtoUtils.marshaller(com.lufs.atomikos.protos.SecuritiesProtos.SecuritiesRequest.getDefaultInstance()),
io.grpc.protobuf.ProtoUtils.marshaller(com.lufs.atomikos.protos.SecuritiesProtos.SecuritiesResponse.getDefaultInstance()));
@io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901")
public static final io.grpc.MethodDescriptor<com.lufs.atomikos.protos.SecuritiesProtos.NewSecuritiesRequest,
com.lufs.atomikos.protos.SecuritiesProtos.NewSecuritiesResponse> METHOD_NEW_SECURITIES =
io.grpc.MethodDescriptor.create(
io.grpc.MethodDescriptor.MethodType.UNARY,
generateFullMethodName(
"SecuritiesService", "newSecurities"),
io.grpc.protobuf.ProtoUtils.marshaller(com.lufs.atomikos.protos.SecuritiesProtos.NewSecuritiesRequest.getDefaultInstance()),
io.grpc.protobuf.ProtoUtils.marshaller(com.lufs.atomikos.protos.SecuritiesProtos.NewSecuritiesResponse.getDefaultInstance()));
/**
* Creates a new async stub that supports all call types for the service
*/
public static SecuritiesServiceStub newStub(io.grpc.Channel channel) {
return new SecuritiesServiceStub(channel);
}
/**
* Creates a new blocking-style stub that supports unary and streaming output calls on the service
*/
public static SecuritiesServiceBlockingStub newBlockingStub(
io.grpc.Channel channel) {
return new SecuritiesServiceBlockingStub(channel);
}
/**
* Creates a new ListenableFuture-style stub that supports unary and streaming output calls on the service
*/
public static SecuritiesServiceFutureStub newFutureStub(
io.grpc.Channel channel) {
return new SecuritiesServiceFutureStub(channel);
}
/**
*/
public static abstract class SecuritiesServiceImplBase implements io.grpc.BindableService {
/**
*/
public void forSecurities(com.lufs.atomikos.protos.SecuritiesProtos.SecuritiesRequest request,
io.grpc.stub.StreamObserver<com.lufs.atomikos.protos.SecuritiesProtos.SecuritiesResponse> responseObserver) {
asyncUnimplementedUnaryCall(METHOD_FOR_SECURITIES, responseObserver);
}
/**
*/
public void newSecurities(com.lufs.atomikos.protos.SecuritiesProtos.NewSecuritiesRequest request,
io.grpc.stub.StreamObserver<com.lufs.atomikos.protos.SecuritiesProtos.NewSecuritiesResponse> responseObserver) {
asyncUnimplementedUnaryCall(METHOD_NEW_SECURITIES, responseObserver);
}
@java.lang.Override public io.grpc.ServerServiceDefinition bindService() {
return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor())
.addMethod(
METHOD_FOR_SECURITIES,
asyncUnaryCall(
new MethodHandlers<
com.lufs.atomikos.protos.SecuritiesProtos.SecuritiesRequest,
com.lufs.atomikos.protos.SecuritiesProtos.SecuritiesResponse>(
this, METHODID_FOR_SECURITIES)))
.addMethod(
METHOD_NEW_SECURITIES,
asyncUnaryCall(
new MethodHandlers<
com.lufs.atomikos.protos.SecuritiesProtos.NewSecuritiesRequest,
com.lufs.atomikos.protos.SecuritiesProtos.NewSecuritiesResponse>(
this, METHODID_NEW_SECURITIES)))
.build();
}
}
/**
*/
public static final class SecuritiesServiceStub extends io.grpc.stub.AbstractStub<SecuritiesServiceStub> {
private SecuritiesServiceStub(io.grpc.Channel channel) {
super(channel);
}
private SecuritiesServiceStub(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected SecuritiesServiceStub build(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
return new SecuritiesServiceStub(channel, callOptions);
}
/**
*/
public void forSecurities(com.lufs.atomikos.protos.SecuritiesProtos.SecuritiesRequest request,
io.grpc.stub.StreamObserver<com.lufs.atomikos.protos.SecuritiesProtos.SecuritiesResponse> responseObserver) {
asyncUnaryCall(
getChannel().newCall(METHOD_FOR_SECURITIES, getCallOptions()), request, responseObserver);
}
/**
*/
public void newSecurities(com.lufs.atomikos.protos.SecuritiesProtos.NewSecuritiesRequest request,
io.grpc.stub.StreamObserver<com.lufs.atomikos.protos.SecuritiesProtos.NewSecuritiesResponse> responseObserver) {
asyncUnaryCall(
getChannel().newCall(METHOD_NEW_SECURITIES, getCallOptions()), request, responseObserver);
}
}
/**
*/
public static final class SecuritiesServiceBlockingStub extends io.grpc.stub.AbstractStub<SecuritiesServiceBlockingStub> {
private SecuritiesServiceBlockingStub(io.grpc.Channel channel) {
super(channel);
}
private SecuritiesServiceBlockingStub(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected SecuritiesServiceBlockingStub build(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
return new SecuritiesServiceBlockingStub(channel, callOptions);
}
/**
*/
public com.lufs.atomikos.protos.SecuritiesProtos.SecuritiesResponse forSecurities(com.lufs.atomikos.protos.SecuritiesProtos.SecuritiesRequest request) {
return blockingUnaryCall(
getChannel(), METHOD_FOR_SECURITIES, getCallOptions(), request);
}
/**
*/
public com.lufs.atomikos.protos.SecuritiesProtos.NewSecuritiesResponse newSecurities(com.lufs.atomikos.protos.SecuritiesProtos.NewSecuritiesRequest request) {
return blockingUnaryCall(
getChannel(), METHOD_NEW_SECURITIES, getCallOptions(), request);
}
}
/**
*/
public static final class SecuritiesServiceFutureStub extends io.grpc.stub.AbstractStub<SecuritiesServiceFutureStub> {
private SecuritiesServiceFutureStub(io.grpc.Channel channel) {
super(channel);
}
private SecuritiesServiceFutureStub(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected SecuritiesServiceFutureStub build(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
return new SecuritiesServiceFutureStub(channel, callOptions);
}
/**
*/
public com.google.common.util.concurrent.ListenableFuture<com.lufs.atomikos.protos.SecuritiesProtos.SecuritiesResponse> forSecurities(
com.lufs.atomikos.protos.SecuritiesProtos.SecuritiesRequest request) {
return futureUnaryCall(
getChannel().newCall(METHOD_FOR_SECURITIES, getCallOptions()), request);
}
/**
*/
public com.google.common.util.concurrent.ListenableFuture<com.lufs.atomikos.protos.SecuritiesProtos.NewSecuritiesResponse> newSecurities(
com.lufs.atomikos.protos.SecuritiesProtos.NewSecuritiesRequest request) {
return futureUnaryCall(
getChannel().newCall(METHOD_NEW_SECURITIES, getCallOptions()), request);
}
}
private static final int METHODID_FOR_SECURITIES = 0;
private static final int METHODID_NEW_SECURITIES = 1;
private static class MethodHandlers<Req, Resp> implements
io.grpc.stub.ServerCalls.UnaryMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> {
private final SecuritiesServiceImplBase serviceImpl;
private final int methodId;
public MethodHandlers(SecuritiesServiceImplBase serviceImpl, int methodId) {
this.serviceImpl = serviceImpl;
this.methodId = methodId;
}
@java.lang.Override
@java.lang.SuppressWarnings("unchecked")
public void invoke(Req request, io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
case METHODID_FOR_SECURITIES:
serviceImpl.forSecurities((com.lufs.atomikos.protos.SecuritiesProtos.SecuritiesRequest) request,
(io.grpc.stub.StreamObserver<com.lufs.atomikos.protos.SecuritiesProtos.SecuritiesResponse>) responseObserver);
break;
case METHODID_NEW_SECURITIES:
serviceImpl.newSecurities((com.lufs.atomikos.protos.SecuritiesProtos.NewSecuritiesRequest) request,
(io.grpc.stub.StreamObserver<com.lufs.atomikos.protos.SecuritiesProtos.NewSecuritiesResponse>) responseObserver);
break;
default:
throw new AssertionError();
}
}
@java.lang.Override
@java.lang.SuppressWarnings("unchecked")
public io.grpc.stub.StreamObserver<Req> invoke(
io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
default:
throw new AssertionError();
}
}
}
public static io.grpc.ServiceDescriptor getServiceDescriptor() {
return new io.grpc.ServiceDescriptor(SERVICE_NAME,
METHOD_FOR_SECURITIES,
METHOD_NEW_SECURITIES);
}
}
| mit |
yaseminalpay/Living-History-API | src/main/java/com/zenith/livinghistory/api/zenithlivinghistoryapi/controller/ContentController.java | 1884 | package com.zenith.livinghistory.api.zenithlivinghistoryapi.controller;
import com.zenith.livinghistory.api.zenithlivinghistoryapi.data.repository.ContentRepository;
import com.zenith.livinghistory.api.zenithlivinghistoryapi.dto.Content;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("api/v1/contents/")
public class ContentController {
@Autowired
private ContentRepository contentRepository;
// @RequestMapping(method = RequestMethod.POST, value = "/")
// public ResponseEntity<Void> create(@RequestBody Content content) {
// Integer index = this.content.size();
// annotation.setId("http://localhost:8080/api/v1/content/" + ++index);
//
// content.add(annotation);
//
// HttpHeaders headers = new HttpHeaders();
// headers.add("Allow", "PUT,GET,OPTIONS,HEAD,DELETE,PATCH");
// headers.add("Location", "http://example.org/content/anno1");
// headers.add("Content-Type", "application/ld+json; profile=\"http://www.w3.org/ns/anno.jsonld\"");
//
// return new ResponseEntity(content, headers, HttpStatus.CREATED);
// }
@RequestMapping(method = RequestMethod.POST, value = "/")
public ResponseEntity<Content> create(@RequestBody Content content) {
contentRepository.insert(content);
return new ResponseEntity<>(content, HttpStatus.CREATED);
}
@RequestMapping(method = RequestMethod.GET, value = "/")
public List<Content> getAll() {
return this.contentRepository.findAll();
}
@RequestMapping(method = RequestMethod.GET, value = "/{id}")
public Content get(@PathVariable("id") String id) {
return contentRepository.findOne(id);
}
}
| mit |
lindenb/knime5bio | src/main/java/com/github/lindenb/knime5bio/htsjdk/variant/KnimeVcfIterator.java | 6551 | package com.github.lindenb.knime5bio.htsjdk.variant;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.knime.core.data.DataCell;
import org.knime.core.data.DataColumnSpec;
import org.knime.core.data.DataRow;
import org.knime.core.data.DataTableSpec;
import org.knime.core.data.DataType;
import org.knime.core.data.StringValue;
import org.knime.core.data.container.CloseableRowIterator;
import org.knime.core.data.def.DoubleCell;
import org.knime.core.data.def.IntCell;
import org.knime.core.data.def.StringCell;
import org.knime.core.node.BufferedDataTable;
import com.github.lindenb.jvarkit.util.vcf.VCFUtils;
import com.github.lindenb.jvarkit.util.vcf.VcfIterator;
import htsjdk.samtools.util.CloserUtil;
import htsjdk.variant.variantcontext.VariantContext;
import htsjdk.variant.vcf.AbstractVCFCodec;
import htsjdk.variant.vcf.VCFConstants;
import htsjdk.variant.vcf.VCFHeader;
public class KnimeVcfIterator implements VcfIterator {
private CloseableRowIterator iter;
private VCFUtils.CodecAndHeader cah;
private KnimeVariantContext peekVariant;
private static void verify(final String name,final DataTableSpec specs,final int index,Class<? extends DataCell> clazz)
{
if(index>=specs.getNumColumns())
{
throw new IllegalArgumentException("Not enough column in table. Expected column $("+(index+1)+") named "+name);
}
final DataColumnSpec colspec = specs.getColumnSpec(index);
if(!name.equals(colspec.getName()))
{
throw new IllegalArgumentException("Not Name in column $("+(index+1)+") expected "+name+" but got "+colspec.getName());
}
if(!DataType.getType(clazz).getCellClass().isAssignableFrom(clazz))
{
throw new IllegalArgumentException("Bad type in column $("+(index+1)+") expected "+clazz.getName()+" got "+DataType.getType(clazz).getCellClass());
}
}
public KnimeVcfIterator(final BufferedDataTable inDataHeader,final BufferedDataTable inDataBody) {
CloseableRowIterator hiter=null;
final List<String> lines= new ArrayList<>();
try {
hiter= inDataHeader.iterator();
while(hiter.hasNext())
{
final DataRow dataRow = hiter.next();
final DataCell cell = dataRow.getCell(0);
if( cell.isMissing()) throw new IllegalArgumentException("nil value in header");
if(cell.getType().isAdaptable(StringValue.class)) throw new IllegalArgumentException("nil value in header");
lines.add(StringCell.class.cast(cell).getStringValue());
}
} finally {
CloserUtil.close(hiter);
}
int idx=0;
final DataTableSpec specs = inDataBody.getSpec();
verify(VCFHeader.HEADER_FIELDS.CHROM.name(),specs,idx++,StringCell.class);
verify(VCFHeader.HEADER_FIELDS.POS.name(),specs,idx++,IntCell.class);
verify(VCFHeader.HEADER_FIELDS.ID.name(),specs,idx++,StringCell.class);
verify(VCFHeader.HEADER_FIELDS.REF.name(),specs,idx++,StringCell.class);
verify(VCFHeader.HEADER_FIELDS.ALT.name(),specs,idx++,StringCell.class);
verify(VCFHeader.HEADER_FIELDS.QUAL.name(),specs,idx++,DoubleCell.class);
verify(VCFHeader.HEADER_FIELDS.FILTER.name(),specs,idx++,StringCell.class);
verify(VCFHeader.HEADER_FIELDS.INFO.name(),specs,idx++,StringCell.class);
final StringBuilder lastLine = new StringBuilder();
for(VCFHeader.HEADER_FIELDS hf:VCFHeader.HEADER_FIELDS.values()){
lastLine.append(lastLine.length()==0?"#":VCFConstants.FIELD_SEPARATOR);
lastLine.append(hf.name());
}
if(specs.getNumColumns()>8) {
lastLine.append(VCFConstants.FIELD_SEPARATOR);
verify("FORMAT",specs,idx++,StringCell.class);
lastLine.append("FORMAT");
for(int i=9;i< specs.getNumColumns();++i) {
final DataColumnSpec colspec = specs.getColumnSpec(i);
if(!colspec.getType().getCellClass().isAssignableFrom(StringCell.class)) {
throw new IllegalArgumentException("Bad type in column $("+(i+1)+") expected a String Cell for sample name, got "+colspec.getType());
}
lastLine.append(VCFConstants.FIELD_SEPARATOR);
lastLine.append(colspec.getName());
}
}
lines.add(lastLine.toString());
this.cah = VCFUtils.parseHeader(lines);
this.peekVariant = null;
this.iter = inDataBody.iterator();
}
private static String stringCellToString(final DataCell cell)
{
return cell.isMissing()?".":StringCell.class.cast(cell).getStringValue();
}
private static String doubleCellToString(final DataCell cell)
{
return cell.isMissing()?".":String.valueOf(DoubleCell.class.cast(cell).getDoubleValue());
}
public KnimeVariantContext decode(final DataRow row) {
final StringBuilder sb=new StringBuilder();
int idx=0;
sb.append(StringCell.class.cast(row.getCell(idx++)).getStringValue());
sb.append("\t");
sb.append(IntCell.class.cast(row.getCell(idx++)).getIntValue());
sb.append("\t");
sb.append(stringCellToString(row.getCell(idx++)));
sb.append("\t");
sb.append(StringCell.class.cast(row.getCell(idx++)).getStringValue());
sb.append("\t");
sb.append(stringCellToString(row.getCell(idx++)));//ALT
sb.append("\t");
sb.append(doubleCellToString(row.getCell(idx++)));//QUAL
sb.append("\t");
sb.append(stringCellToString(row.getCell(idx++)));//FILTER
sb.append("\t");
sb.append(StringCell.class.cast(row.getCell(idx++)).getStringValue());//INFO
if(this.getHeader().getNGenotypeSamples()>0)
{
sb.append("\t");
sb.append(StringCell.class.cast(row.getCell(idx++)).getStringValue());//FORMAT
for(int i=0;i<this.getHeader().getNGenotypeSamples();++i )
{
sb.append("\t");
sb.append(StringCell.class.cast(row.getCell(idx++)).getStringValue());//sample
}
}
return new KnimeVariantContext(
getCodec().decode(sb.toString()),
row
);
}
private void fill()
{
if(this.peekVariant!=null) return;
if(this.iter==null || !this.iter.hasNext()) return;
final DataRow row = iter.next();
this.peekVariant = this.decode(row);
}
@Override
public KnimeVariantContext next() {
fill();
if(this.peekVariant==null) throw new IllegalStateException("no next in KnimeVcfIterator");
final KnimeVariantContext line=this.peekVariant;
this.peekVariant=null;
return line;
}
@Override
public void close() throws IOException {
CloserUtil.close(this.iter);
this.iter = null;
}
@Override
public AbstractVCFCodec getCodec() {
return this.cah.codec;
}
@Override
public VCFHeader getHeader() {
return this.cah.header;
}
@Override
public VariantContext peek() {
fill();
return this.peekVariant;
}
@Override
public boolean hasNext() {
fill();
return this.peekVariant!=null;
}
}
| mit |
liwangadd/Coding | app/src/main/java/com/nicolas/coding/ImagePagerActivity.java | 8094 | /**
* ****************************************************************************
* Copyright 2011-2013 Sergey Tarasevich
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.nicolas.coding;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nicolas.coding.common.CustomDialog;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.OptionsItem;
import org.androidannotations.annotations.ViewById;
import java.util.ArrayList;
@EActivity(R.layout.activity_image_pager)
public class ImagePagerActivity extends BackActivity {
private final String SAVE_INSTANCE_INDEX = "SAVE_INSTANCE_INDEX";
DisplayImageOptions options;
@ViewById
ViewPager pager;
@Extra
int mPagerPosition;
@Extra
ArrayList<String> mArrayUri;
@Extra
boolean isPrivate;
@Extra
String mSingleUri;
@Extra
boolean needEdit;
ImagePager adapter;
ArrayList<String> mDelUrls = new ArrayList<>();
TextView mMenuImagePos;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
mPagerPosition = savedInstanceState.getInt(SAVE_INSTANCE_INDEX, mPagerPosition);
}
}
@AfterViews
void init() {
if (needEdit) {
ActionBar supportActionBar = getSupportActionBar();
supportActionBar.setIcon(android.R.color.transparent);
View v = getLayoutInflater().inflate(R.layout.image_pager_action_custom, null);
mMenuImagePos = (TextView) v.findViewById(R.id.imagePos);
supportActionBar.setCustomView(v);
supportActionBar.setDisplayShowCustomEnabled(true);
pager.setBackgroundColor(getResources().getColor(R.color.stand_bg));
pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
setPosDisplay(position);
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
setPosDisplay(0);
} else {
getSupportActionBar().hide();
pager.setBackgroundColor(getResources().getColor(R.color.black));
}
if (mSingleUri != null) {
mArrayUri = new ArrayList<>();
mArrayUri.add(mSingleUri);
mPagerPosition = 0;
}
options = new DisplayImageOptions.Builder()
.showImageForEmptyUri(R.drawable.ic_default_image)
.showImageOnFail(R.drawable.ic_default_image)
.resetViewBeforeLoading(true)
.cacheOnDisk(true)
.imageScaleType(ImageScaleType.EXACTLY)
.bitmapConfig(Bitmap.Config.RGB_565)
.considerExifParams(true)
.displayer(new FadeInBitmapDisplayer(300))
.build();
if (!isPrivate) {
initPager();
}
}
private void setPosDisplay(int position) {
String pos = String.format("%d/%d", position + 1, mArrayUri.size());
mMenuImagePos.setText(pos);
}
private void initPager() {
adapter = new ImagePager(getSupportFragmentManager());
pager.setAdapter(adapter);
pager.setCurrentItem(mPagerPosition);
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(SAVE_INSTANCE_INDEX, pager.getCurrentItem());
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mPagerPosition = savedInstanceState.getInt(SAVE_INSTANCE_INDEX, mPagerPosition);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (needEdit) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.photo_pager, menu);
}
return super.onCreateOptionsMenu(menu);
}
@Override
public void onBackPressed() {
if (mDelUrls.isEmpty()) {
setResult(RESULT_CANCELED);
} else {
Intent intent = new Intent();
intent.putExtra("mDelUrls", mDelUrls);
setResult(RESULT_OK, intent);
}
finish();
}
@OptionsItem
protected final void action_del_maopao() {
final int selectPos = pager.getCurrentItem();
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("图片")
.setMessage("确定删除?")
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String s = mArrayUri.remove(selectPos);
mDelUrls.add(s);
if (mArrayUri.isEmpty()) {
onBackPressed();
} else {
setPosDisplay(pager.getCurrentItem());
adapter.notifyDataSetChanged();
}
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
})
.show();
CustomDialog.dialogTitleLineColor(this, dialog);
}
class ImagePager extends FragmentPagerAdapter {
public ImagePager(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int i) {
return ImagePagerFragment_.builder()
.uri(mArrayUri.get(i))
.customMenu(false)
.build();
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
ImagePagerFragment fragment = (ImagePagerFragment) super.instantiateItem(container, position);
fragment.setData(mArrayUri.get(position));
return fragment;
}
@Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
@Override
public int getCount() {
return mArrayUri.size();
}
}
} | mit |
SteveMoyer/volleyballrank | src/test/java/net/stevemoyer/vbrank/ProviderDouble.java | 335 | package net.stevemoyer.vbrank;
import static org.mockito.Mockito.*;
import com.google.inject.Provider;
public class ProviderDouble {
public static<T> Provider<T> provide(T val) {
@SuppressWarnings("unchecked")
Provider<T> ret = (Provider<T>) mock(Provider.class);
when(ret.get()).thenReturn(val);
return ret;
}
}
| mit |
Hexeption/Youtube-Hacked-Client-1.8 | minecraft/net/minecraft/network/play/server/S14PacketEntity.java | 6931 | package net.minecraft.network.play.server;
import java.io.IOException;
import net.minecraft.entity.Entity;
import net.minecraft.network.INetHandler;
import net.minecraft.network.Packet;
import net.minecraft.network.PacketBuffer;
import net.minecraft.network.play.INetHandlerPlayClient;
import net.minecraft.world.World;
public class S14PacketEntity implements Packet
{
protected int field_149074_a;
protected byte field_149072_b;
protected byte field_149073_c;
protected byte field_149070_d;
protected byte field_149071_e;
protected byte field_149068_f;
protected boolean field_179743_g;
protected boolean field_149069_g;
private static final String __OBFID = "CL_00001312";
public S14PacketEntity() {}
public S14PacketEntity(int p_i45206_1_)
{
this.field_149074_a = p_i45206_1_;
}
/**
* Reads the raw packet data from the data stream.
*/
public void readPacketData(PacketBuffer data) throws IOException
{
this.field_149074_a = data.readVarIntFromBuffer();
}
/**
* Writes the raw packet data to the data stream.
*/
public void writePacketData(PacketBuffer data) throws IOException
{
data.writeVarIntToBuffer(this.field_149074_a);
}
/**
* Passes this Packet on to the NetHandler for processing.
*/
public void processPacket(INetHandlerPlayClient handler)
{
handler.handleEntityMovement(this);
}
public String toString()
{
return "Entity_" + super.toString();
}
public Entity func_149065_a(World worldIn)
{
return worldIn.getEntityByID(this.field_149074_a);
}
public byte func_149062_c()
{
return this.field_149072_b;
}
public byte func_149061_d()
{
return this.field_149073_c;
}
public byte func_149064_e()
{
return this.field_149070_d;
}
public byte func_149066_f()
{
return this.field_149071_e;
}
public byte func_149063_g()
{
return this.field_149068_f;
}
public boolean func_149060_h()
{
return this.field_149069_g;
}
public boolean func_179742_g()
{
return this.field_179743_g;
}
/**
* Passes this Packet on to the NetHandler for processing.
*/
public void processPacket(INetHandler handler)
{
this.processPacket((INetHandlerPlayClient)handler);
}
public static class S15PacketEntityRelMove extends S14PacketEntity
{
private static final String __OBFID = "CL_00001313";
public S15PacketEntityRelMove() {}
public S15PacketEntityRelMove(int p_i45974_1_, byte p_i45974_2_, byte p_i45974_3_, byte p_i45974_4_, boolean p_i45974_5_)
{
super(p_i45974_1_);
this.field_149072_b = p_i45974_2_;
this.field_149073_c = p_i45974_3_;
this.field_149070_d = p_i45974_4_;
this.field_179743_g = p_i45974_5_;
}
public void readPacketData(PacketBuffer data) throws IOException
{
super.readPacketData(data);
this.field_149072_b = data.readByte();
this.field_149073_c = data.readByte();
this.field_149070_d = data.readByte();
this.field_179743_g = data.readBoolean();
}
public void writePacketData(PacketBuffer data) throws IOException
{
super.writePacketData(data);
data.writeByte(this.field_149072_b);
data.writeByte(this.field_149073_c);
data.writeByte(this.field_149070_d);
data.writeBoolean(this.field_179743_g);
}
public void processPacket(INetHandler handler)
{
super.processPacket((INetHandlerPlayClient)handler);
}
}
public static class S16PacketEntityLook extends S14PacketEntity
{
private static final String __OBFID = "CL_00001315";
public S16PacketEntityLook()
{
this.field_149069_g = true;
}
public S16PacketEntityLook(int p_i45972_1_, byte p_i45972_2_, byte p_i45972_3_, boolean p_i45972_4_)
{
super(p_i45972_1_);
this.field_149071_e = p_i45972_2_;
this.field_149068_f = p_i45972_3_;
this.field_149069_g = true;
this.field_179743_g = p_i45972_4_;
}
public void readPacketData(PacketBuffer data) throws IOException
{
super.readPacketData(data);
this.field_149071_e = data.readByte();
this.field_149068_f = data.readByte();
this.field_179743_g = data.readBoolean();
}
public void writePacketData(PacketBuffer data) throws IOException
{
super.writePacketData(data);
data.writeByte(this.field_149071_e);
data.writeByte(this.field_149068_f);
data.writeBoolean(this.field_179743_g);
}
public void processPacket(INetHandler handler)
{
super.processPacket((INetHandlerPlayClient)handler);
}
}
public static class S17PacketEntityLookMove extends S14PacketEntity
{
private static final String __OBFID = "CL_00001314";
public S17PacketEntityLookMove()
{
this.field_149069_g = true;
}
public S17PacketEntityLookMove(int p_i45973_1_, byte p_i45973_2_, byte p_i45973_3_, byte p_i45973_4_, byte p_i45973_5_, byte p_i45973_6_, boolean p_i45973_7_)
{
super(p_i45973_1_);
this.field_149072_b = p_i45973_2_;
this.field_149073_c = p_i45973_3_;
this.field_149070_d = p_i45973_4_;
this.field_149071_e = p_i45973_5_;
this.field_149068_f = p_i45973_6_;
this.field_179743_g = p_i45973_7_;
this.field_149069_g = true;
}
public void readPacketData(PacketBuffer data) throws IOException
{
super.readPacketData(data);
this.field_149072_b = data.readByte();
this.field_149073_c = data.readByte();
this.field_149070_d = data.readByte();
this.field_149071_e = data.readByte();
this.field_149068_f = data.readByte();
this.field_179743_g = data.readBoolean();
}
public void writePacketData(PacketBuffer data) throws IOException
{
super.writePacketData(data);
data.writeByte(this.field_149072_b);
data.writeByte(this.field_149073_c);
data.writeByte(this.field_149070_d);
data.writeByte(this.field_149071_e);
data.writeByte(this.field_149068_f);
data.writeBoolean(this.field_179743_g);
}
public void processPacket(INetHandler handler)
{
super.processPacket((INetHandlerPlayClient)handler);
}
}
}
| mit |
antocara/realTimeTracker | app/src/main/java/com/antocara/realtimetracking/data/DataRepository.java | 1247 | package com.antocara.realtimetracking.data;
import com.antocara.realtimetracking.data.entities.LocationObject;
import java.util.ArrayList;
import java.util.List;
public class DataRepository {
private List<LocationObject> locationObjectsStored;
private boolean isTracking;
private static DataRepository instance;
public static DataRepository getInstance() {
if (instance == null){
instance = new DataRepository();
}
return instance;
}
private DataRepository() {
this.locationObjectsStored = new ArrayList<>();
}
public List<LocationObject> getAllLocationSaved(){
return locationObjectsStored;
}
public void addNewLocationObject(long currentTimeMillis, double latitudeValue, double longitudeValue){
LocationObject locationObject = new LocationObject();
locationObject.setCurrentTimeMiliseconds(currentTimeMillis);
locationObject.setLatitude(latitudeValue);
locationObject.setLongitude(longitudeValue);
this.locationObjectsStored.add(locationObject);
}
public void cleanDataLocation(){
this.locationObjectsStored.clear();
}
public boolean isTracking() {
return isTracking;
}
public void setTracking(boolean tracking) {
isTracking = tracking;
}
}
| mit |
jagrutkosti/plagUI | src/main/java/com/plagui/service/mapper/UserMapper.java | 2291 | package com.plagui.service.mapper;
import com.plagui.domain.Authority;
import com.plagui.domain.User;
import com.plagui.service.dto.UserDTO;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.stream.Collectors;
/**
* Mapper for the entity User and its DTO called UserDTO.
*
* Normal mappers are generated using MapStruct, this one is hand-coded as MapStruct
* support is still in beta, and requires a manual step with an IDE.
*/
@Service
public class UserMapper {
public UserDTO userToUserDTO(User user) {
return new UserDTO(user);
}
public List<UserDTO> usersToUserDTOs(List<User> users) {
return users.stream()
.filter(Objects::nonNull)
.map(this::userToUserDTO)
.collect(Collectors.toList());
}
public User userDTOToUser(UserDTO userDTO) {
if (userDTO == null) {
return null;
} else {
User user = new User();
user.setId(userDTO.getId());
user.setLogin(userDTO.getLogin());
user.setFirstName(userDTO.getFirstName());
user.setLastName(userDTO.getLastName());
user.setEmail(userDTO.getEmail());
user.setImageUrl(userDTO.getImageUrl());
user.setActivated(userDTO.isActivated());
user.setLangKey(userDTO.getLangKey());
Set<Authority> authorities = this.authoritiesFromStrings(userDTO.getAuthorities());
if(authorities != null) {
user.setAuthorities(authorities);
}
return user;
}
}
public List<User> userDTOsToUsers(List<UserDTO> userDTOs) {
return userDTOs.stream()
.filter(Objects::nonNull)
.map(this::userDTOToUser)
.collect(Collectors.toList());
}
public User userFromId(String id) {
if (id == null) {
return null;
}
User user = new User();
user.setId(id);
return user;
}
public Set<Authority> authoritiesFromStrings(Set<String> strings) {
return strings.stream().map(string -> {
Authority auth = new Authority();
auth.setName(string);
return auth;
}).collect(Collectors.toSet());
}
}
| mit |
dingxwsimon/codingquestions | src/LeetCode/UniqueBSTrees2.java | 1591 | package LeetCode;
import java.util.ArrayList;
import LeetCode.BinaryTreeInorderTraversal.TreeNode;
public class UniqueBSTrees2 {
// pass both
public ArrayList<TreeNode> generateTrees(int n) {
ArrayList<Integer> num = new ArrayList<Integer>();
for (int i = 1; i <= n; i++) {
num.add(i);
}
return generateTree(num, 0, n - 1);
}
public ArrayList<TreeNode> generateTree(ArrayList<Integer> num, int start,
int end) {
ArrayList<TreeNode> results = new ArrayList<TreeNode>();
if (start > end) {
TreeNode n = null;
results.add(n);
return results;
}
for (int i = start; i <= end; i++) {
ArrayList<TreeNode> leftTrees = generateTree(num, start, i - 1);
for (int j = 0; j < leftTrees.size(); j++) {
TreeNode leftChild = leftTrees.get(j);
ArrayList<TreeNode> rightTrees = generateTree(num, i + 1, end);
for (int k = 0; k < rightTrees.size(); k++) {
TreeNode rightChild = rightTrees.get(k);
TreeNode root = new TreeNode(num.get(i));
root.left = leftChild;
root.right = rightChild;
results.add(root);
}
}
}
return results;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
| mit |
javasuki/RJava | NXDO.Java.V2015/JForLoadedTest/src/rt/TTest.java | 103 | package rt;
public class TTest implements ITest{
@Override
public int getAge() {
return 0;
}
}
| mit |
cyberrob/localsgram | app/src/main/java/de/s3xy/retrofitsample/app/pojo/Thumbnail.java | 946 |
package de.s3xy.retrofitsample.app.pojo;
import com.google.gson.annotations.Expose;
public class Thumbnail {
@Expose
private String url;
@Expose
private Integer width;
@Expose
private Integer height;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Thumbnail withUrl(String url) {
this.url = url;
return this;
}
public Integer getWidth() {
return width;
}
public void setWidth(Integer width) {
this.width = width;
}
public Thumbnail withWidth(Integer width) {
this.width = width;
return this;
}
public Integer getHeight() {
return height;
}
public void setHeight(Integer height) {
this.height = height;
}
public Thumbnail withHeight(Integer height) {
this.height = height;
return this;
}
}
| mit |
Koteczeg/WarsawCityGame | WarsawCityGame/WarsawCityGames.App/src/main/java/com/warsawcitygame/Activities/MainActivity.java | 6706 | package com.warsawcitygame.Activities;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ListView;
import com.warsawcitygame.Fragments.DonateFragment;
import com.warsawcitygame.Fragments.GetMissionFragment;
import com.warsawcitygame.Fragments.CurrentMissionFragment;
import com.warsawcitygame.Fragments.LoadingFragment;
import com.warsawcitygame.Fragments.MissionHistoryFragment;
import com.warsawcitygame.Fragments.ProfileFragment;
import com.warsawcitygame.Fragments.AchievementsFragment;
import com.warsawcitygame.Fragments.FriendsFragment;
import com.warsawcitygame.R;
import com.warsawcitygame.Fragments.HallOfFameFragment;
import com.warsawcitygame.Adapters.NavDrawerListAdapter;
import com.warsawcitygame.CustomControls.NavDrawerItem;
import com.warsawcitygame.Utils.MyApplication;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnItemClick;
import static com.warsawcitygame.Transitions.Animations.fadeOutAnimationNewFragment;
public class MainActivity extends Activity
{
@Bind(R.id.menu_layout) DrawerLayout menuLayout;
@Bind(R.id.menu_list) ListView menuList;
@Bind(R.id.frame_container) FrameLayout frameLayout;
@Inject SharedPreferences preferences;
private ActionBarDrawerToggle menuToggle;
private Fragment activeFragment = null;
public static final String USER_LOGGED_IN_KEY = "userLoggedIn";
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
((MyApplication) getApplication()).getServicesComponent().inject(this);
initializeMenu();
if (savedInstanceState == null)
{
displayView(0);
}
}
private void initializeMenu()
{
NavDrawerListAdapter menuAdapter = new NavDrawerListAdapter(this, getMenuElements());
menuList.setAdapter(menuAdapter);
menuToggle = new ActionBarDrawerToggle(this, menuLayout, R.drawable.logo, R.string.app_name, R.string.app_name)
{
public void onDrawerClosed(View view)
{
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView)
{
invalidateOptionsMenu();
}
};
menuLayout.setDrawerListener(menuToggle);
}
private ArrayList<NavDrawerItem> getMenuElements()
{
ArrayList<NavDrawerItem> menuElements = new ArrayList<>();
String[] menuTitles = getResources().getStringArray(R.array.menu_titles);
TypedArray menuIcons = getResources().obtainTypedArray(R.array.menu_icons);
for(int i=0; i<8; i++)
{
menuElements.add(new NavDrawerItem(menuTitles[i], menuIcons.getResourceId(i, -1)));
}
menuIcons.recycle();
return menuElements;
}
@OnItemClick(R.id.menu_list)
public void onMenuOptionClick(int position)
{
displayView(position);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
if (menuToggle.onOptionsItemSelected(item))
{
return true;
}
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public boolean onPrepareOptionsMenu(Menu menu)
{
boolean drawerOpen = menuLayout.isDrawerOpen(menuList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
private void displayView(int position)
{
frameLayout.setVisibility(View.INVISIBLE);
switch (position)
{
case 0:
activeFragment = new CurrentMissionFragment();
break;
case 1:
activeFragment = new ProfileFragment();
break;
case 2:
activeFragment = new FriendsFragment();
break;
case 3:
activeFragment = new GetMissionFragment();
break;
case 4:
activeFragment = new MissionHistoryFragment();
break;
case 5:
activeFragment = new AchievementsFragment();
break;
case 6:
activeFragment = new HallOfFameFragment();
break;
case 7:
logout();
break;
case 8:
activeFragment = new DonateFragment();
break;
}
replaceFragment(position);
fadeOutAnimationNewFragment(frameLayout);
}
private void replaceFragment(int position)
{
if (activeFragment != null)
{
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container, activeFragment).commit();
menuList.setItemChecked(position, true);
menuList.setSelection(position);
menuLayout.closeDrawer(menuList);
}
else
{
Log.e("MainActivity", "Error in creating activeFragment");
}
}
private void logout()
{
SharedPreferences.Editor edit = preferences.edit();
edit.putBoolean(USER_LOGGED_IN_KEY, false);
edit.apply();
Intent i = new Intent(this, LoginActivity.class);
startActivity(i);
finish();
}
@Override
protected void onPostCreate(Bundle savedInstanceState)
{
super.onPostCreate(savedInstanceState);
menuToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
menuToggle.onConfigurationChanged(newConfig);
}
}
| mit |
notabadminer/UniversalCoinsMod | java/universalcoins/gui/VendorWrenchGUI.java | 3771 | package universalcoins.gui;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiTextField;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StatCollector;
import universalcoins.inventory.ContainerVendorWrench;
import universalcoins.tile.TileVendor;
public class VendorWrenchGUI extends GuiContainer {
private TileVendor tileEntity;
private GuiTextField blockOwnerField;
private GuiButton infiniteButton, editButton, applyButton;
public static final int idInfiniteButton = 0;
public static final int idEditButton = 1;
public static final int idApplyButton = 2;
boolean infinite;
public VendorWrenchGUI(InventoryPlayer inventoryPlayer, TileVendor tEntity) {
super(new ContainerVendorWrench(inventoryPlayer, tEntity));
tileEntity = tEntity;
xSize = 166;
ySize = 80;
}
@Override
public void initGui() {
super.initGui();
infinite = tileEntity.infiniteMode;
infiniteButton = new GuiSlimButton(idInfiniteButton, 9 + (width - xSize) / 2, 54 + (height - ySize) / 2, 148,
12, infinite ? StatCollector.translateToLocal("vending.wrench.infiniteon")
: StatCollector.translateToLocal("vending.wrench.infiniteoff"));
editButton = new GuiSlimButton(idEditButton, 68 + (width - xSize) / 2, 34 + (height - ySize) / 2, 40, 12,
StatCollector.translateToLocal("general.button.edit"));
applyButton = new GuiSlimButton(idApplyButton, 110 + (width - xSize) / 2, 34 + (height - ySize) / 2, 40, 12,
StatCollector.translateToLocal("general.button.save"));
buttonList.clear();
buttonList.add(editButton);
buttonList.add(applyButton);
buttonList.add(infiniteButton);
blockOwnerField = new GuiTextField(this.fontRendererObj, 12, 20, 138, 13);
blockOwnerField.setFocused(false);
blockOwnerField.setMaxStringLength(100);
blockOwnerField.setText(tileEntity.blockOwner);
blockOwnerField.setEnableBackgroundDrawing(true);
}
@Override
protected void drawGuiContainerBackgroundLayer(float var1, int var2, int var3) {
final ResourceLocation texture = new ResourceLocation("universalcoins", "textures/gui/vendor_wrench.png");
Minecraft.getMinecraft().getTextureManager().bindTexture(texture);
int x = (width - xSize) / 2;
int y = (height - ySize) / 2;
this.drawTexturedModalRect(x, y, 0, 0, xSize, ySize);
}
@Override
protected void drawGuiContainerForegroundLayer(int param1, int param2) {
// draw text and stuff here
// the parameters for drawString are: string, x, y, color
fontRendererObj.drawString(StatCollector.translateToLocal("vending.wrench.owner"), 6, 5, 4210752);
blockOwnerField.drawTextBox();
}
@Override
protected void keyTyped(char c, int i) {
if (blockOwnerField.isFocused()) {
blockOwnerField.textboxKeyTyped(c, i);
} else
super.keyTyped(c, i);
}
protected void mouseClicked(int par1, int par2, int par3) {
super.mouseClicked(par1, par2, par3);
}
protected void actionPerformed(GuiButton button) {
if (button.id == idEditButton) {
blockOwnerField.setFocused(true);
}
if (button.id == idApplyButton) {
String blockOwner = blockOwnerField.getText();
try {
tileEntity.blockOwner = blockOwner;
} catch (Throwable ex2) {
// fail silently?
}
blockOwnerField.setFocused(false);
tileEntity.sendServerUpdateMessage();
}
if (button.id == idInfiniteButton) {
infinite = !infinite;
infiniteButton.displayString = (infinite ? StatCollector.translateToLocal("vending.wrench.infiniteon")
: StatCollector.translateToLocal("vending.wrench.infiniteoff"));
tileEntity.infiniteMode = infinite;
tileEntity.sendServerUpdateMessage();
}
}
}
| mit |
Mararok/ImpactGUI | src/main/java/com/gmail/mararok/igui/event/mouse/MouseDownEvent.java | 296 | /**
* ImpactGUI
* all rights reserved
* Copyright (C) 2013 Mararok <mararok@gmail.com>
*/
package com.gmail.mararok.igui.event.mouse;
public class MouseDownEvent extends MouseButtonEvent {
public MouseDownEvent(long time, int x, int y, MouseButton button) {
super(time,x,y,button);
}
}
| mit |
dzonekl/LiquibaseEditor | plugins/org.liquidbase.model/src/org/liquibase/xml/ns/dbchangelog/MergeColumnsType.java | 9518 | /**
*/
package org.liquibase.xml.ns.dbchangelog;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Merge Columns Type</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link org.liquibase.xml.ns.dbchangelog.MergeColumnsType#getCatalogName <em>Catalog Name</em>}</li>
* <li>{@link org.liquibase.xml.ns.dbchangelog.MergeColumnsType#getColumn1Name <em>Column1 Name</em>}</li>
* <li>{@link org.liquibase.xml.ns.dbchangelog.MergeColumnsType#getColumn2Name <em>Column2 Name</em>}</li>
* <li>{@link org.liquibase.xml.ns.dbchangelog.MergeColumnsType#getFinalColumnName <em>Final Column Name</em>}</li>
* <li>{@link org.liquibase.xml.ns.dbchangelog.MergeColumnsType#getFinalColumnType <em>Final Column Type</em>}</li>
* <li>{@link org.liquibase.xml.ns.dbchangelog.MergeColumnsType#getJoinString <em>Join String</em>}</li>
* <li>{@link org.liquibase.xml.ns.dbchangelog.MergeColumnsType#getSchemaName <em>Schema Name</em>}</li>
* <li>{@link org.liquibase.xml.ns.dbchangelog.MergeColumnsType#getTableName <em>Table Name</em>}</li>
* </ul>
* </p>
*
* @see org.liquibase.xml.ns.dbchangelog.DbchangelogPackage#getMergeColumnsType()
* @model extendedMetaData="name='mergeColumns_._type' kind='empty'"
* @generated
*/
public interface MergeColumnsType extends EObject {
/**
* Returns the value of the '<em><b>Catalog Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Catalog Name</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Catalog Name</em>' attribute.
* @see #setCatalogName(String)
* @see org.liquibase.xml.ns.dbchangelog.DbchangelogPackage#getMergeColumnsType_CatalogName()
* @model dataType="org.eclipse.emf.ecore.xml.type.String"
* extendedMetaData="kind='attribute' name='catalogName'"
* @generated
*/
String getCatalogName();
/**
* Sets the value of the '{@link org.liquibase.xml.ns.dbchangelog.MergeColumnsType#getCatalogName <em>Catalog Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Catalog Name</em>' attribute.
* @see #getCatalogName()
* @generated
*/
void setCatalogName(String value);
/**
* Returns the value of the '<em><b>Column1 Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Column1 Name</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Column1 Name</em>' attribute.
* @see #setColumn1Name(String)
* @see org.liquibase.xml.ns.dbchangelog.DbchangelogPackage#getMergeColumnsType_Column1Name()
* @model dataType="org.eclipse.emf.ecore.xml.type.String" required="true"
* extendedMetaData="kind='attribute' name='column1Name'"
* @generated
*/
String getColumn1Name();
/**
* Sets the value of the '{@link org.liquibase.xml.ns.dbchangelog.MergeColumnsType#getColumn1Name <em>Column1 Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Column1 Name</em>' attribute.
* @see #getColumn1Name()
* @generated
*/
void setColumn1Name(String value);
/**
* Returns the value of the '<em><b>Column2 Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Column2 Name</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Column2 Name</em>' attribute.
* @see #setColumn2Name(String)
* @see org.liquibase.xml.ns.dbchangelog.DbchangelogPackage#getMergeColumnsType_Column2Name()
* @model dataType="org.eclipse.emf.ecore.xml.type.String" required="true"
* extendedMetaData="kind='attribute' name='column2Name'"
* @generated
*/
String getColumn2Name();
/**
* Sets the value of the '{@link org.liquibase.xml.ns.dbchangelog.MergeColumnsType#getColumn2Name <em>Column2 Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Column2 Name</em>' attribute.
* @see #getColumn2Name()
* @generated
*/
void setColumn2Name(String value);
/**
* Returns the value of the '<em><b>Final Column Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Final Column Name</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Final Column Name</em>' attribute.
* @see #setFinalColumnName(String)
* @see org.liquibase.xml.ns.dbchangelog.DbchangelogPackage#getMergeColumnsType_FinalColumnName()
* @model dataType="org.eclipse.emf.ecore.xml.type.String" required="true"
* extendedMetaData="kind='attribute' name='finalColumnName'"
* @generated
*/
String getFinalColumnName();
/**
* Sets the value of the '{@link org.liquibase.xml.ns.dbchangelog.MergeColumnsType#getFinalColumnName <em>Final Column Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Final Column Name</em>' attribute.
* @see #getFinalColumnName()
* @generated
*/
void setFinalColumnName(String value);
/**
* Returns the value of the '<em><b>Final Column Type</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Final Column Type</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Final Column Type</em>' attribute.
* @see #setFinalColumnType(String)
* @see org.liquibase.xml.ns.dbchangelog.DbchangelogPackage#getMergeColumnsType_FinalColumnType()
* @model dataType="org.eclipse.emf.ecore.xml.type.String" required="true"
* extendedMetaData="kind='attribute' name='finalColumnType'"
* @generated
*/
String getFinalColumnType();
/**
* Sets the value of the '{@link org.liquibase.xml.ns.dbchangelog.MergeColumnsType#getFinalColumnType <em>Final Column Type</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Final Column Type</em>' attribute.
* @see #getFinalColumnType()
* @generated
*/
void setFinalColumnType(String value);
/**
* Returns the value of the '<em><b>Join String</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Join String</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Join String</em>' attribute.
* @see #setJoinString(String)
* @see org.liquibase.xml.ns.dbchangelog.DbchangelogPackage#getMergeColumnsType_JoinString()
* @model dataType="org.eclipse.emf.ecore.xml.type.String" required="true"
* extendedMetaData="kind='attribute' name='joinString'"
* @generated
*/
String getJoinString();
/**
* Sets the value of the '{@link org.liquibase.xml.ns.dbchangelog.MergeColumnsType#getJoinString <em>Join String</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Join String</em>' attribute.
* @see #getJoinString()
* @generated
*/
void setJoinString(String value);
/**
* Returns the value of the '<em><b>Schema Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Schema Name</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Schema Name</em>' attribute.
* @see #setSchemaName(String)
* @see org.liquibase.xml.ns.dbchangelog.DbchangelogPackage#getMergeColumnsType_SchemaName()
* @model dataType="org.eclipse.emf.ecore.xml.type.String"
* extendedMetaData="kind='attribute' name='schemaName'"
* @generated
*/
String getSchemaName();
/**
* Sets the value of the '{@link org.liquibase.xml.ns.dbchangelog.MergeColumnsType#getSchemaName <em>Schema Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Schema Name</em>' attribute.
* @see #getSchemaName()
* @generated
*/
void setSchemaName(String value);
/**
* Returns the value of the '<em><b>Table Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Table Name</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Table Name</em>' attribute.
* @see #setTableName(String)
* @see org.liquibase.xml.ns.dbchangelog.DbchangelogPackage#getMergeColumnsType_TableName()
* @model dataType="org.eclipse.emf.ecore.xml.type.String" required="true"
* extendedMetaData="kind='attribute' name='tableName'"
* @generated
*/
String getTableName();
/**
* Sets the value of the '{@link org.liquibase.xml.ns.dbchangelog.MergeColumnsType#getTableName <em>Table Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Table Name</em>' attribute.
* @see #getTableName()
* @generated
*/
void setTableName(String value);
} // MergeColumnsType
| mit |
MisterCavespider/Lina | src/main/java/io/github/mistercavespider/lina/ctrl/DistanceTracer.java | 673 | package io.github.mistercavespider.lina.ctrl;
import com.jme3.material.Material;
import io.github.mistercavespider.lina.LineString;
/**
* Under development.
* Marked as deprecated because of it.
*
* @author MisterCavespider
*
*/
@Deprecated
public class DistanceTracer implements Tracer {
private Material mat;
private LineString str;
@Override
public Material getMaterial() {
return mat;
}
@Override
public void setMaterial(Material mat) {
this.mat = mat;
}
@Override
public LineString getLineString() {
return str;
}
@Override
public void setLineString(LineString str) {
this.str = str;
}
@Override
public void reset() {
}
}
| mit |
amarseillan/pedestriansimulation | src/main/java/ar/edu/itba/pedestriansim/back/entity/force/PedestrianFutureAdjustmentForce.java | 2429 | package ar.edu.itba.pedestriansim.back.entity.force;
import org.newdawn.slick.geom.Vector2f;
import ar.edu.itba.pedestriansim.back.entity.Pedestrian;
import ar.edu.itba.pedestriansim.back.entity.PedestrianFuture;
import ar.edu.itba.pedestriansim.back.entity.physics.Vectors;
public class PedestrianFutureAdjustmentForce implements PedestrianForce {
private final float _kAlign;
private final float _sigma;
private final float _kSeparation;
private final Vector2f positionCache = new Vector2f();
public PedestrianFutureAdjustmentForce(float kAlign, float sigma, float kSeparation) {
_kAlign = kAlign;
_sigma = sigma;
_kSeparation = kSeparation;
}
@Override
public Vector2f apply(Pedestrian input) {
Vector2f position = input.getBody().getCenter();
Vector2f target = input.getTargetSelection().getTarget().getClosesPoint(position);
return new Vector2f()
.add(springAlignmentForce(input, target))
.add(springSeparationPosition(input, target));
}
private Vector2f springAlignmentForce(Pedestrian input, Vector2f target) {
PedestrianFuture future = input.getFuture();
Vector2f position = input.getBody().getCenter();
float targetDist = target.distance(input.getBody().getCenter());
float c = targetDist > 1.6f ? 1 : (1 + (5f * (1.6f - targetDist) / 1.6f));
return Vectors.pointBetween(position, target, input.getReactionDistance(), positionCache)
.sub(future.getBody().getCenter())
.scale(_kAlign * c)
.add(new Vector2f(future.getBody().getVelocity()).scale(-_sigma));
}
private Vector2f springSeparationPosition(Pedestrian input, Vector2f target) {
Vector2f pedestrianFutureCenter = input.getFuture().getBody().getCenter();
Vector2f position = input.getBody().getCenter();
float deviationAngle = angle(position, target, pedestrianFutureCenter);
float angleDeviationDecay = 1;
if (deviationAngle > 31) {
angleDeviationDecay /= (deviationAngle - 30);
}
// float targetDist = target.distance(input.getBody().getCenter());
// float c = targetDist > 2f ? 1 : (1 + (2f * (2f - targetDist) / 2f));
return
Vectors.pointBetween(position, pedestrianFutureCenter, input.getReactionDistance(), positionCache)
.sub(pedestrianFutureCenter)
.normalise()
.scale(_kSeparation * angleDeviationDecay);
}
private float angle(Vector2f center, Vector2f target, Vector2f future) {
return Vectors.angle(future.copy().sub(center), target.copy().sub(center));
}
}
| mit |
compasses/elastic-rabbitmq | netty-http/src/main/java/http/searchcommand/RestCommand.java | 3025 | package http.searchcommand;
import com.netflix.hystrix.*;
import http.elasticaction.RestRequest;
import http.elasticaction.SearchDSL;
import http.elasticaction.SearchDSLImpl;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.entity.StringEntity;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.index.query.QueryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.UUID;
/**
* Created by i311352 on 2/16/2017.
*/
public class RestCommand extends HystrixCommand<char[]> {
private static final Logger LOGGER = LoggerFactory.getLogger(RestCommand.class);
private RestClient client;
private SearchDSL restRequest;
public RestCommand(RestClient client, SearchDSL restRequest) {
super(getSetter(client.toString()));
this.client = client;
this.restRequest = restRequest;
}
private static HystrixCommand.Setter getSetter(String key) {
LOGGER.info("Command key:" + key);
// String uuid = UUID.randomUUID().toString();
// key += uuid;
HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey(key);
HystrixCommandKey commandKey = HystrixCommandKey.Factory.asKey(key);
HystrixCommandProperties.Setter commandProperties = HystrixCommandProperties.Setter();
commandProperties.withExecutionTimeoutInMilliseconds(10000)
.withCircuitBreakerErrorThresholdPercentage(60);
HystrixThreadPoolProperties.Setter threadPoolPropertiesDefaults = HystrixThreadPoolProperties.Setter();
threadPoolPropertiesDefaults.withCoreSize(15)
.withMaxQueueSize(300)
.withQueueSizeRejectionThreshold(90);
return Setter.withGroupKey(groupKey).andCommandKey(commandKey).andCommandPropertiesDefaults(commandProperties)
.andThreadPoolPropertiesDefaults(threadPoolPropertiesDefaults);
}
@Override
protected char[] run() throws Exception {
LOGGER.info("Going to get request: " + "stores/product/_search?size=1000");
String query = this.restRequest.getDSL().toString();
LOGGER.info("Going to query..: " + query);
HttpEntity requestBody = new StringEntity("{\n" +
" \"match_all\" : {\n" +
" \"boost\" : 1.0\n" +
" }\n" +
"}", Charset.defaultCharset());
Response response = this.client.performRequest("GET", "stores/product/_search");//, new HashMap<String, String>(), requestBody);
return IOUtils.toCharArray(response.getEntity().getContent());
}
@Override
protected char[] getFallback() {
String string = new String("Just FallBack");
return string.toCharArray();
}
}
| mit |
caseif/Voxem | src/main/java/net/caseif/voxem/vector/Vector3f.java | 2729 | /*
* Voxem
* Copyright (c) 2014-2015, Maxim Roncacé <caseif@caseif.net>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package net.caseif.voxem.vector;
/**
* Represents a vector with 3 float elements.
*/
public class Vector3f implements Vector3 {
protected float x;
protected float y;
protected float z;
public Vector3f(float x, float y, float z) {
this.x = x;
this.y = y;
this.z = z;
}
public float getX() {
return x;
}
public float getY() {
return y;
}
public float getZ() {
return z;
}
public void setX(float x) {
this.x = x;
}
public void setY(float y) {
this.y = y;
}
public void setZ(float z) {
this.z = z;
}
public Vector3f add(Vector3f vector) {
return add(vector.getX(), vector.getY(), vector.getZ());
}
public Vector3f add(float x, float y, float z) {
return new Vector3f(this.x + x, this.y + y, this.z + z);
}
public Vector3f subtract(Vector3f vector) {
return subtract(vector.getX(), vector.getY(), vector.getZ());
}
public Vector3f subtract(float x, float y, float z) {
return new Vector3f(this.x - x, this.y - y, this.z + z);
}
public boolean equals(Object o) {
if (o instanceof Vector3f) {
Vector3f v = (Vector3f) o;
return v.getX() == this.x && v.getY() == this.y && this.z == z;
}
return false;
}
@Override
public Vector3f clone() {
return new Vector3f(x, y, z);
}
@Override
public String toString() {
return "Vector3f{" + x + ", " + y + ", " + z + "}";
}
}
| mit |
tim-group/jpoeisis | src/main/java/com/timgroup/jpoeisis/reference/Updatable.java | 275 | package com.timgroup.jpoeisis.reference;
import com.google.common.base.Function;
public interface Updatable<T> extends Ref<T> {
T updateTo(T newValue);
T updateWith(Function<T, T> updater);
T swapFor(T newValue);
T swapWith(Function<T, T> updater);
}
| mit |
clairtonluz/especializacao-em-arquitetura | modulo-08(Desenvolvimento-para-dispositivos-moveis)/Service/app/src/main/java/br/com/clairtonluz/service/StartedService.java | 986 | package br.com.clairtonluz.service;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
/**
* Created by clairton on 18/05/16.
*/
public class StartedService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
try {
Log.i("App", "Valor: " + (i + 1));
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
stopSelf();
}
}).start();
return Service.START_NOT_STICKY;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
| mit |
WiQuery/wiquery | wiquery-core/src/main/java/org/odlabs/wiquery/core/javascript/JavaScriptCallable.java | 1592 | /*
* Copyright (c) 2008 Lionel Armanet
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.odlabs.wiquery.core.javascript;
/**
* $Id: JavaScriptCallable.java 412 2010-09-17 21:23:25Z lionel.armanet $
* <p>
* Defines a JavaScript callable statement (e.g. a statement chainable with others).
* </p>
*
* @author Lionel Armanet
* @since 0.5
*/
public interface JavaScriptCallable
{
/**
* @return a {@link CharSequence} containing the JavaScript statement to call
*/
CharSequence statement();
}
| mit |
diirt/diirt | util/src/main/java/org/diirt/util/exceptions/package-info.java | 317 | /**
* Copyright (C) 2010-18 diirt developers. See COPYRIGHT.TXT
* All rights reserved. Use is subject to license terms. See LICENSE.TXT
*/
/**
* Contains a common set of exceptions that can be reused but do not
* fall in the common exceptions present in {@code java.lang}.
*/
package org.diirt.util.exceptions;
| mit |
zgrannan/Technical-Theatre-Assistant | src/com/zgrannan/crewandroid/ValueButton.java | 2212 | package com.zgrannan.crewandroid;
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.util.AttributeSet;
import android.widget.Button;
public abstract class ValueButton extends Button {
public abstract boolean hasValue();
public abstract void setOnClickListener(final Activity activity);
/**
* The text that this button displays when it does not have a value
* associated with it.
*/
protected String prompt;
/**
* The prefix to the value that the button will display. Don't forget to add
* a ":"
*/
protected String prefix;
/**
* The post-text.
*/
protected String post;
/**
* The code that will identify the result of editing activities spawned by
* this button.
*/
protected int requestCode;
/**
* If true, a negative number could be stored here.
*/
protected boolean allowNegative;
/**
* If true, the button should no longer be clickable once a value is entered
* into it. The text will also become red.
*/
protected boolean lockValue;
/**
* Creates a value button from an XML specification
*
* @param context
* The set of attributes for the button.
* @param attrs
*/
public ValueButton(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.ValueButton);
requestCode = a.getInteger(R.styleable.ValueButton_requestCode, -1);
prompt = a.getString(R.styleable.ValueButton_prompt);
prefix = a.getString(R.styleable.ValueButton_prefix);
post = a.getString(R.styleable.ValueButton_post);
allowNegative = a.getBoolean(R.styleable.ValueButton_allowNegative,
false);
lockValue = a.getBoolean(R.styleable.ValueButton_lockValue, false);
setText(prompt);
}
@Override
public void onDraw(Canvas c) {
super.onDraw(c);
if (lockValue && hasValue()) {
setClickable(false);
setTextColor(Color.RED);
}
}
public ValueButton(Context context) {
super(context);
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
public void setPrompt(String prompt) {
this.prompt = prompt;
}
}
| mit |
woojung3/RewardScheme | RewardScheme/lib/jpbc-2.0.0/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/pairing/a1/TypeA1CurveGenerator.java | 3438 | package it.unisa.dia.gas.plaf.jpbc.pairing.a1;
import it.unisa.dia.gas.jpbc.PairingParameters;
import it.unisa.dia.gas.jpbc.PairingParametersGenerator;
import it.unisa.dia.gas.plaf.jpbc.pairing.parameters.PropertiesParameters;
import it.unisa.dia.gas.plaf.jpbc.util.math.BigIntegerUtils;
import java.math.BigInteger;
import java.security.SecureRandom;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
*/
public class TypeA1CurveGenerator implements PairingParametersGenerator {
protected SecureRandom random;
protected int numPrimes, bits;
public TypeA1CurveGenerator(SecureRandom random, int numPrimes, int bits) {
this.random = random;
this.numPrimes = numPrimes;
this.bits = bits;
}
public TypeA1CurveGenerator(int numPrimes, int bits) {
this(new SecureRandom(), numPrimes, bits);
}
public PairingParameters generate() {
BigInteger[] primes = new BigInteger[numPrimes];
BigInteger order, n, p;
long l;
while (true) {
// System.out.printf("Finding order...%n");
while (true) {
order = BigInteger.ONE;
for (int i = 0; i < numPrimes; i++) {
boolean isNew = false;
while (!isNew) {
// primes[i] = BigIntegerUtils.generateSolinasPrime(bits, random);
primes[i] = BigInteger.probablePrime(bits, random);
isNew = true;
for (int j = 0; j < i; j++) {
if (primes[i].equals(primes[j])) {
isNew = false;
break;
}
}
}
order = order.multiply(primes[i]);
}
break;
// if ((order.bitLength() + 7) / 8 == order.bitLength() / 8)
// break;
}
// System.out.printf("order= %s%n", order);
// If order is even, ideally check all even l, not just multiples of 4
// System.out.printf("Finding l...%n");
l = 4;
n = order.multiply(BigIntegerUtils.FOUR);
p = n.subtract(BigInteger.ONE);
while (!p.isProbablePrime(10)) {
p = p.add(n);
l += 4;
}
// System.out.printf("l=%d%n",l);
// System.out.printf("lhs=%d, rhs=%d%n",(p.bitLength() + 7) / 8, (p.bitLength() / 8));
// if ((p.bitLength() + 7) / 8 == p.bitLength() / 8)
// break;
break;
// System.out.printf("No way, repeat!%n");
}
// System.out.printf("order hamming weight=%d%n", BigIntegerUtils.hammingWeight(order));
PropertiesParameters params = new PropertiesParameters();
params.put("type", "a1");
params.put("p", p.toString());
params.put("n", order.toString());
for (int i = 0; i < primes.length; i++) {
params.put("n" + i, primes[i].toString());
}
params.put("l", String.valueOf(l));
return params;
}
public static void main(String[] args) {
TypeA1CurveGenerator generator = new TypeA1CurveGenerator(3, 512);
PairingParameters curveParams = generator.generate();
System.out.println(curveParams.toString(" "));
}
}
| mit |
vamaraju/shuffle-the-rules | src/main/java/model/GameState.java | 3548 | /*
* Requirements mandating inclusion:
*
* This class stores information about the current game/player state in Gameplay mode.
* It is needed for various requirements relating to Gameplay mode.
*
* 3.2.2.2.3.5 User can draw Card(s) from a Pile.
* 3.2.2.2.3.6 User can place Card(s) on a Pile.
* 3.2.2.3.3.1 Player will be notified when their Turn begins.
* 3.2.2.3.3.2 Player will be notified when their Turn ends.
* 3.2.2.3.3.2 Player's Turn will be skipped if Player is inactive.
* 3.2.2.4.3.1 Player can end game.
* 3.2.2.5.3.1 Rule Interpreter will interpret and execute Game Rules for a Card Game.
* */
package model;
import model.Piles.Pile;
import java.util.ArrayList;
import java.util.List;
/**
* Singleton that stores information regarding the current state of the game (in Gameplay Mode).
*/
public class GameState {
private static GameState instance = new GameState();
private Player currentPlayer;
private TableGrid currentTableGrid;
private GameLock lock = new GameLock();
private Pile selectedPile;
private List<Card> clickedCards = new ArrayList<>();
private boolean skipActionClicked = false;
private boolean skipTurnClicked = false;
private boolean actionPhaseCompleted = false;
private boolean gameCompleted = false;
private GameRule currentRule;
/**
* Private constructor to block anyone from creating a new instance of this class.
*/
private GameState() {
}
/**
* Accessor that returns the global (static) instance of GameCreation.
*
* @return Current version of GameCreation.
*/
public static GameState getInstance() {
return instance;
}
public Player getCurrentPlayer() {
return currentPlayer;
}
public void setCurrentPlayer(Player currentPlayer) {
this.currentPlayer = currentPlayer;
}
public TableGrid getCurrentTableGrid() {
return currentTableGrid;
}
public void setCurrentTableGrid(TableGrid currentTableGrid) {
this.currentTableGrid = currentTableGrid;
}
public GameLock getLock() {
return lock;
}
public List<Card> getClickedCards() {
return clickedCards;
}
public void updateClickedCards(List<Card> cardList) {
clickedCards.clear();
for (Card c : cardList) {
clickedCards.add(c);
}
}
public Pile getSelectedPile() {
return selectedPile;
}
public void setSelectedPile(Pile selectedPile) {
this.selectedPile = selectedPile;
}
public boolean isSkipActionClicked() {
return skipActionClicked;
}
public void setSkipActionClicked(boolean skipActionClicked) {
this.skipActionClicked = skipActionClicked;
}
public boolean isSkipTurnClicked() {
return skipTurnClicked;
}
public void setSkipTurnClicked(boolean skipTurnClicked) {
this.skipTurnClicked = skipTurnClicked;
}
public boolean isActionPhaseCompleted() {
return actionPhaseCompleted;
}
public void setActionPhaseCompleted(boolean actionPhaseCompleted) {
this.actionPhaseCompleted = actionPhaseCompleted;
}
public boolean isGameCompleted() {
return gameCompleted;
}
public void setGameCompleted(boolean gameCompleted) {
this.gameCompleted = gameCompleted;
}
public GameRule getCurrentRule() {
return currentRule;
}
public void setCurrentRule(GameRule currentRule) {
this.currentRule = currentRule;
}
} | mit |
dromelvan/dromelvan-core | src/main/java/org/dromelvan/modell/SpelareSasong.java | 1847 | package org.dromelvan.modell;
import org.dromelvan.modell.Spelare.Position;
/**
* Håller i info om lag och deltagare en spelare hörde till en viss säsong och
* vilken position han spelade. Används främst för att enkelt hålla reda på info
* för färdigspelade säsonger.
* @author macke
*/
public class SpelareSasong extends PersistentObjekt {
/**
*
*/
private static final long serialVersionUID = -2553287098197578417L;
private Spelare spelare;
private Sasong sasong;
private Lag lag;
private Deltagare deltagare;
private Position position;
private double pris;
public SpelareSasong() {}
public Spelare getSpelare() {
return spelare;
}
public void setSpelare(Spelare spelare) {
this.spelare = spelare;
}
public Sasong getSasong() {
return sasong;
}
public void setSasong(Sasong sasong) {
this.sasong = sasong;
}
public Lag getLag() {
return lag;
}
public void setLag(Lag lag) {
this.lag = lag;
}
public Deltagare getDeltagare() {
return deltagare;
}
public void setDeltagare(Deltagare deltagare) {
this.deltagare = deltagare;
}
public Position getPosition() {
return position;
}
public void setPosition(Position position) {
this.position = position;
}
public double getPris() {
return pris;
}
public void setPris(double pris) {
this.pris = pris;
}
public int compareTo(PersistentObjekt spelareSasong) {
int compare = getPosition().compareTo(((SpelareSasong)spelareSasong).getPosition());
if(compare == 0) {
getSasong().compareTo(((SpelareSasong)spelareSasong).getSasong());
}
if(compare == 0) {
compare = getSpelare().compareTo(((SpelareSasong)spelareSasong).getSpelare());
}
if(compare == 0) {
compare = getId() - ((SpelareSasong)spelareSasong).getId();
}
return compare;
}
}
| mit |
taozhiheng/SimpleRepository | Book/app/src/main/java/data/ChapterInfo.java | 1667 | package data;
import android.os.Parcel;
import android.os.Parcelable;
/**
* old version chapter data class
*/
public class ChapterInfo implements Parcelable {
private int mPosition;
private String mName;
private int mType;
public ChapterInfo(int mPosition, String mName) {
this(mPosition, mName, -1);
}
public ChapterInfo(int position, String name, int type)
{
this.mPosition = position;
this.mName = name;
this.mType = type;
}
public int getPosition() {
return mPosition;
}
public void setPosition(int position) {
this.mPosition = position;
}
public String getName() {
return mName;
}
public void setName(String name) {
this.mName = name;
}
public int getType() {
return mType;
}
public void setType(int mType) {
this.mType = mType;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.mPosition);
dest.writeString(this.mName);
dest.writeInt(this.mType);
}
protected ChapterInfo(Parcel in) {
this.mPosition = in.readInt();
this.mName = in.readString();
this.mType = in.readInt();
}
public static final Parcelable.Creator<ChapterInfo> CREATOR = new Parcelable.Creator<ChapterInfo>() {
public ChapterInfo createFromParcel(Parcel source) {
return new ChapterInfo(source);
}
public ChapterInfo[] newArray(int size) {
return new ChapterInfo[size];
}
};
}
| mit |
jwaa/NoHarp | src/leaptest/controller/StopTimerControl.java | 648 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package leaptest.controller;
import leaptest.Main;
/**
*
* @author silvandeleemput
*/
public class StopTimerControl implements Updatable {
private Main main;
private long begintime, duration;
public StopTimerControl(Main main, long duration)
{
this.main = main;
this.begintime = System.currentTimeMillis();
this.duration = duration;
}
public void update(float tpf)
{
if (System.currentTimeMillis() - begintime > duration)
main.setShutDown(true);
}
}
| mit |
Iurii-Dziuban/algorithms | src/test/java/iurii/job/interview/codility/onpex/IntegerPositionInOtherIntegerTest.java | 630 | package iurii.job.interview.codility.onpex;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class IntegerPositionInOtherIntegerTest {
@Test
public void test() {
IntegerPositionInOtherInteger integerInOtherInteger = new IntegerPositionInOtherInteger();
assertThat(integerInOtherInteger.solution(32, 4532032)).isEqualTo(2);
assertThat(integerInOtherInteger.solution(1, 11111)).isEqualTo(0);
assertThat(integerInOtherInteger.solution(32, 4500032)).isEqualTo(5);
assertThat(integerInOtherInteger.solution(32, 4533031)).isEqualTo(-1);
}
}
| mit |
davidfialho14/bgp-simulator | src/main/cli/SequentialExecution.java | 3748 | package main.cli;
import core.Destination;
import core.Topology;
import io.AnycastReader;
import io.DestinationNotFoundException;
import io.IntegerLineReader;
import io.ParseException;
import simulators.Experiment;
import simulators.SequentialExperiment;
import simulators.SequentialSimulation;
import simulators.Simulator;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static main.Application.application;
class SequentialExecution extends Execution {
public SequentialExecution(Parameters parameters) {
super(parameters);
}
@Override
protected Experiment setupExperiment(Simulator simulator) {
File destinationsFile = parameters.getDestinationsFile();
// load destinations file
List<Integer> destinationIds = null;
try (IntegerLineReader reader = new IntegerLineReader(destinationsFile)) {
destinationIds = reader.readValues();
} catch (IOException e) {
application().errorHandler.onDestinationsIOException(e);
application().exitWithError();
} catch (ParseException e) {
application().errorHandler.onDestinationsParseException(e);
application().exitWithError();
}
Topology topology = simulator.getTopology();
File anycastFile = parameters.getAnycastFile();
List<Destination> destinations = new ArrayList<>(destinationIds.size());
List<Integer> missingIds = new ArrayList<>(destinationIds.size());
// get destinations from IDs
for (Integer destinationId : destinationIds) {
Destination destination = topology.getRouter(destinationId);
if (destination == null) {
missingIds.add(destinationId);
} else {
destinations.add(destination);
}
}
if (!missingIds.isEmpty()) {
// destinations not found in the topology might be anycast destinations
if (anycastFile != null) { // check if we have an anycast file
try (AnycastReader reader = new AnycastReader(anycastFile, topology)) {
Destination[] missingDestinations = reader.readThis(missingIds);
Collections.addAll(destinations, missingDestinations);
} catch (DestinationNotFoundException e) {
application().errorHandler.onDestinationNotFoundOnAnycastFile(e, anycastFile);
application().exitWithError();
} catch (ParseException e) {
application().errorHandler.onAnycastParseException(e);
application().exitWithError();
} catch (IOException e) {
application().errorHandler.onAnycastLoadIOException(e);
application().exitWithError();
}
}
}
// create sequential experiment
if (parameters.hasPermutationSeed()) {
return new SequentialExperiment(
destinations.toArray(new Destination[destinations.size()]),
parameters.getRepetitionCount(),
parameters.getPermutationCount(),
parameters.getPermutationSeed(),
new SequentialSimulation(simulator)
);
} else {
return new SequentialExperiment(
destinations.toArray(new Destination[destinations.size()]),
parameters.getRepetitionCount(),
parameters.getPermutationCount(),
new SequentialSimulation(simulator)
);
}
}
}
| mit |
ladanyi/Github | src/main/java/github/GitHubRequester.java | 2748 | package github;
import com.google.gson.Gson;
import json.Item;
import json.Page;
import url.UrlBuilder;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collector;
import java.util.stream.Collectors;
/**
* Created by user on 2016. 12. 16..
*/
public class GitHubRequester {
private UrlBuilder urlBuilder;
private Gson jsonGetter;
private static final Logger LOGGER = Logger.getLogger(GitHubRequester.class.getName());
public GitHubRequester() {
this.urlBuilder = new UrlBuilder();
this.jsonGetter = new Gson();
}
public void setFollowerLimit(int limit) {
urlBuilder.addParam("q", "followers:>" + limit);
}
public void setUserLimit(int limit) {
urlBuilder.addParam("per_page", String.valueOf(limit));
}
public ArrayList<Item> getUsers() {
ArrayList<Item> users = new ArrayList<Item>();
URL url = urlBuilder.buildUserRequesterURL();
if (url != null) {
String jsonText = readUrl(url);
Page page = jsonGetter.fromJson(jsonText, Page.class);
// for (Item item : page.getItems()) {
// users.add(item);
// }
page.getItems().stream().forEach(e -> users.add(e));
}
return getUsersWithFollowerNumber(users);
//return users;
}
private String readUrl(URL url) {
BufferedReader reader;
StringBuffer buffer = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(url.openStream()));
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1) {
buffer.append(chars, 0, read);
}
} catch (IOException e) {
LOGGER.log(Level.SEVERE, e.toString());
}
return buffer.length() > 0 ? buffer.toString() : null;
}
private ArrayList<Item> getUsersWithFollowerNumber(ArrayList<Item> users) {
ArrayList<Item> completeUsers = new ArrayList<Item>();
//
//// for (Item user : users) {
//// URL followerUrl = user.getUrl();
//// String jsonText = readUrl(followerUrl);
//// Item completeUser = jsonGetter.fromJson(jsonText, Item.class);
//// completeUsers.add(completeUser);
//// }
users.stream().forEach(e -> completeUsers.add(jsonGetter.fromJson(readUrl(e.getUrl()),Item.class)));
return completeUsers;
}
}
| mit |
abdulmudabir/Gagawa | src/com/hp/gagawa/java/elements/Dir.java | 4743 | /**Generated by the Gagawa TagBuilder Fri Jan 30 21:29:45 PST 2009*/
/**
(c) Copyright 2008 Hewlett-Packard Development Company, L.P.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package com.hp.gagawa.java.elements;
import com.hp.gagawa.java.FertileNode;
import com.hp.gagawa.java.Node;
import com.hp.gagawa.java.elements.Text;
import java.util.List;
public class Dir extends FertileNode {
public Dir(){
super("dir");
}
/**
* Appends a child node to the end of this element's DOM tree
* @param child node to be appended
* @return the node
*/
public Dir appendChild(Node child){
if(this == child){
throw new Error("Cannot append a node to itself.");
}
child.setParent(this);
children.add(child);
return this;
}
/**
* Appends a child node at the given index
* @param index insert point
* @param child node to be appended
* @return the node
*/
public Dir appendChild(int index, Node child){
if(this == child){
throw new Error("Cannot append a node to itself.");
}
child.setParent(this);
children.add(index, child);
return this;
}
/**
* Appends a list of children in the order given in the list
* @param children nodes to be appended
* @return the node
*/
public Dir appendChild(List<Node> children){
if(children != null){;
for(Node child: children){
appendChild(child);
}
}
return this;
}
/**
* Appends the given children in the order given
* @param children nodes to be appended
* @return the node
*/
public Dir appendChild(Node... children){
for(int i = 0; i < children.length; i++){
appendChild(children[i]);
}
return this;
}
/**
* Convenience method which appends a text node to this element
* @param text the text to be appended
* @return the node
*/
public Dir appendText(String text){
return appendChild(new Text(text));
}
/**
* Removes the child node
* @param child node to be removed
* @return the node
*/
public Dir removeChild(Node child){
children.remove(child);
return this;
}
/**
* Removes all child nodes
* @return the node
*/
public Dir removeChildren(){
children.clear();
return this;
}
public Dir setCompact(String value){setAttribute("compact", value); return this;}
public String getCompact(){return getAttribute("compact");}
public boolean removeCompact(){return removeAttribute("compact");}
public Dir setId(String value){setAttribute("id", value); return this;}
public String getId(){return getAttribute("id");}
public boolean removeId(){return removeAttribute("id");}
public Dir setCSSClass(String value){setAttribute("class", value); return this;}
public String getCSSClass(){return getAttribute("class");}
public boolean removeCSSClass(){return removeAttribute("class");}
public Dir setTitle(String value){setAttribute("title", value); return this;}
public String getTitle(){return getAttribute("title");}
public boolean removeTitle(){return removeAttribute("title");}
public Dir setStyle(String value){setAttribute("style", value); return this;}
public String getStyle(){return getAttribute("style");}
public boolean removeStyle(){return removeAttribute("style");}
public Dir setDir(String value){setAttribute("dir", value); return this;}
public String getDir(){return getAttribute("dir");}
public boolean removeDir(){return removeAttribute("dir");}
public Dir setLang(String value){setAttribute("lang", value); return this;}
public String getLang(){return getAttribute("lang");}
public boolean removeLang(){return removeAttribute("lang");}
public Dir setXMLLang(String value){setAttribute("xml:lang", value); return this;}
public String getXMLLang(){return getAttribute("xml:lang");}
public boolean removeXMLLang(){return removeAttribute("xml:lang");}
}
| mit |
pomortaz/azure-sdk-for-java | azure/src/test/java/com/microsoft/azure/management/TestPublicIpAddress.java | 4340 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*/
package com.microsoft.azure.management;
import org.junit.Assert;
import com.microsoft.azure.management.network.LoadBalancer;
import com.microsoft.azure.management.network.NetworkInterface;
import com.microsoft.azure.management.network.NicIpConfiguration;
import com.microsoft.azure.management.network.LoadBalancerPublicFrontend;
import com.microsoft.azure.management.network.PublicIpAddress;
import com.microsoft.azure.management.network.PublicIpAddresses;
import com.microsoft.azure.management.resources.fluentcore.arm.Region;
/**
* Tests public IPs.
*/
public class TestPublicIpAddress extends TestTemplate<PublicIpAddress, PublicIpAddresses> {
@Override
public PublicIpAddress createResource(PublicIpAddresses pips) throws Exception {
final String newPipName = "pip" + this.testId;
PublicIpAddress pip = pips.define(newPipName)
.withRegion(Region.US_WEST)
.withNewResourceGroup()
.withDynamicIp()
.withLeafDomainLabel(newPipName)
.withIdleTimeoutInMinutes(10)
.create();
return pip;
}
@Override
public PublicIpAddress updateResource(PublicIpAddress resource) throws Exception {
final String updatedDnsName = resource.leafDomainLabel() + "xx";
final int updatedIdleTimeout = 15;
resource = resource.update()
.withStaticIp()
.withLeafDomainLabel(updatedDnsName)
.withReverseFqdn(resource.leafDomainLabel() + "." + resource.region() + ".cloudapp.azure.com")
.withIdleTimeoutInMinutes(updatedIdleTimeout)
.withTag("tag1", "value1")
.withTag("tag2", "value2")
.apply();
Assert.assertTrue(resource.leafDomainLabel().equalsIgnoreCase(updatedDnsName));
Assert.assertTrue(resource.idleTimeoutInMinutes() == updatedIdleTimeout);
return resource;
}
@Override
public void print(PublicIpAddress pip) {
TestPublicIpAddress.printPIP(pip);
}
public static void printPIP(PublicIpAddress resource) {
StringBuilder info = new StringBuilder().append("Public IP Address: ").append(resource.id())
.append("\n\tName: ").append(resource.name())
.append("\n\tResource group: ").append(resource.resourceGroupName())
.append("\n\tRegion: ").append(resource.region())
.append("\n\tTags: ").append(resource.tags())
.append("\n\tIP Address: ").append(resource.ipAddress())
.append("\n\tLeaf domain label: ").append(resource.leafDomainLabel())
.append("\n\tFQDN: ").append(resource.fqdn())
.append("\n\tReverse FQDN: ").append(resource.reverseFqdn())
.append("\n\tIdle timeout (minutes): ").append(resource.idleTimeoutInMinutes())
.append("\n\tIP allocation method: ").append(resource.ipAllocationMethod().toString())
.append("\n\tIP version: ").append(resource.version().toString());
// Show the associated load balancer if any
info.append("\n\tLoad balancer association: ");
if (resource.hasAssignedLoadBalancer()) {
final LoadBalancerPublicFrontend frontend = resource.getAssignedLoadBalancerFrontend();
final LoadBalancer lb = frontend.parent();
info.append("\n\t\tLoad balancer ID: ").append(lb.id())
.append("\n\t\tFrontend name: ").append(frontend.name());
} else {
info.append("(None)");
}
// Show the associated NIC if any
info.append("\n\tNetwork interface association: ");
if (resource.hasAssignedNetworkInterface()) {
final NicIpConfiguration nicIp = resource.getAssignedNetworkInterfaceIpConfiguration();
final NetworkInterface nic = nicIp.parent();
info.append("\n\t\tNetwork interface ID: ").append(nic.id())
.append("\n\t\tIP config name: ").append(nicIp.name());
} else {
info.append("(None)");
}
System.out.println(info.toString());
}
}
| mit |
shianqi/C0Compiler | src/com/imudges/C0Compiler/Compiler/Lex.java | 5503 | package com.imudges.C0Compiler.Compiler;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
/**
* Created by killer on 2016/10/18.
* @author shianqi@imudges.com
* c0编译器词法分析类
*/
public class Lex {
//源程序单词缓存
private String sourceCodeTemp;
//行数
private int row;
//缓存单词字符指针
private int index;
//变量最大长度
private int symMaxLength = 20;
public Lex(){
sourceCodeTemp = "";
row = 0;
index = 0;
getSym();
}
public String[] reservedWord = {
"main",
"void",
"if",
"while",
"return",
"int",
};
public enum symbol
{
//---------------------- 基本字
mainsym, // 主程序
voidsym, // 空类型
ifstasym, // 如果语句
whilestasym,// 循环语句
resym, // return
intsym, // 整型
nul, // 未知
ifsym, // if
elsesym, // else
whilesym, // while
readstasym, // 读语句
writestasym,// 写语句
scanfsym, // 输入
printfsym, // 输出
//---------------------- 常数
number, // 数字
//---------------------- 界符
leftsym, // (
rightsym, // )
beginsym, // {
endsym, // }
comma, // ,
semicolon, // ;
period, // .
//---------------------- 标识符
ident, // 自定义符号
//---------------------- 运算符
plu, // +
sub, // -
mul, // *
dive, // /
eqlsym, // =
restasym, // 赋值语句
}
/**
* 判断字符类型
*/
public enum wordType{
BasicWord, //基本字
Number, //常数
Delimiter, //界符
Identifier, //标识符
Operator //运算符
}
private enum charType{
Nul, //空
Letter, //字母
Number, //数字类型
}
private charType getType(char ch){
if(ch==' '||ch==10||ch==9){
return charType.Nul;
}else if(ch>='a'&&ch<='z'||ch>='A'&&ch<='Z'||ch=='_'){
return charType.Letter;
}else if(ch>='0'&&ch<='9'){
return charType.Number;
}
return null;
}
/**
* 获取下个字符
* @return 下一个字符,当返回'.'时表示文档结束
*/
private char getChar(){
while(sourceCodeTemp.equals("")){
if(row>=Main.sourceCode.size()){
return '.';
}else{
sourceCodeTemp = Main.sourceCode.get(row);
row++;
index = 0;
}
}
char temp = sourceCodeTemp.charAt(index);
index++;
if(index>=sourceCodeTemp.length()){
sourceCodeTemp = "";
}
return temp;
}
/**
* 获取下一个单词
*/
private void getSym(){
char ch = getChar();
while(true){
if(ch=='.'){
System.out.println("文档结束!");
break;
}else{
if(getType(ch)!=charType.Nul){
//如果第一个单词是字母
if(getType(ch)==charType.Letter){
String stringTemp = "";
stringTemp+=ch;
ch = getChar();
while(getType(ch)==charType.Number||getType(ch)==charType.Letter){
stringTemp+=ch;
ch = getChar();
}
if(Arrays.asList(reservedWord).contains(stringTemp)){
System.out.println("保留字: "+stringTemp);
}else{
System.out.println("单词: "+stringTemp);
}
}else if(getType(ch)==charType.Number){
//如果第一个字母是数字
int numberTemp = ch - '0';
ch = getChar();
while(getType(ch)==charType.Number){
numberTemp = numberTemp*10+(ch-'0');
ch = getChar();
}
System.out.println("数字: "+numberTemp);
}else if(ch=='('){
System.out.println("符号: "+ch);
ch = getChar();
}else if(ch==')'){
System.out.println("符号: "+ch);
ch = getChar();
}else if(ch=='{'){
System.out.println("符号: "+ch);
ch = getChar();
}else if(ch=='}'){
System.out.println("符号: "+ch);
ch = getChar();
}else{
System.out.print(ch);
ch = getChar();
}
}else{
ch = getChar();
}
}
}
}
}
| mit |
reflectoring/coderadar | coderadar-graph/src/main/java/io/reflectoring/coderadar/graph/contributor/adapter/RemoveContributorAdapter.java | 1094 | package io.reflectoring.coderadar.graph.contributor.adapter;
import io.reflectoring.coderadar.contributor.port.driven.RemoveContributorPort;
import io.reflectoring.coderadar.domain.Contributor;
import io.reflectoring.coderadar.graph.contributor.repository.ContributorRepository;
import java.util.ArrayList;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class RemoveContributorAdapter implements RemoveContributorPort {
private final ContributorRepository contributorRepository;
@Override
public void removeContributorFromProject(Contributor contributor, long projectId) {
contributorRepository.detachContributorFromProject(contributor.getId(), projectId);
}
@Override
public void removeContributorsFromProject(List<Contributor> contributors, long projectId) {
List<Long> ids = new ArrayList<>(contributors.size());
contributors.forEach(contributor -> ids.add(contributor.getId()));
contributorRepository.detachContributorsFromProject(ids, projectId);
}
}
| mit |
t10471/java | Generics/src/hierarchy/Hoge1.java | 95 | package hierarchy;
//境界を減らす例のベース
public class Hoge1<T extends HogeA> {}
| mit |
nmby/jUtaime | project/src/main/java/xyz/hotchpotch/jutaime/throwable/matchers/RootCause.java | 5071 | package xyz.hotchpotch.jutaime.throwable.matchers;
import java.util.Objects;
import org.hamcrest.Matcher;
import xyz.hotchpotch.jutaime.throwable.Testee;
/**
* スローされた例外の根本原因(root cause)を検査する {@code Matcher} です。<br>
* この {@code Matcher} は、スローされた例外の例外チェーンを {@code cause.getCause() == null} となるまで辿り、
* 最後に辿り着いた {@code cause} に対して判定を行います。<br>
* スローされた例外が原因(cause)を持たない場合は、スローされた例外自身が根本原因(root cause)とみなされます。<br>
* 検査対象のオペレーションが正常終了した場合は、不合格と判定します。<br>
* <br>
* この {@code Matcher} は、根本原因(root cause)の型が期待された型のサブクラスの場合も一致と判定します。<br>
* <br>
* このクラスはスレッドセーフではありません。<br>
* ひとつの {@code Matcher} オブジェクトが複数のスレッドから操作されることは想定されていません。<br>
*
* @since 1.0.0
* @author nmby
*/
public class RootCause extends RootCauseBase {
// [static members] ++++++++++++++++++++++++++++++++++++++++++++++++++++++++
/**
* スローされた例外の根本原因(root cause)の型を検査する {@code Matcher} オブジェクトを返します。<br>
* このメソッドにより返される {@code Matcher} オブジェクトは、根本原因(root cause)の型が期待された型のサブクラスの場合も一致と判定します。<br>
*
* @param expectedType 期待される根本原因(root cause)の型
* @return スローされた例外の根本原因(root cause)を検査する {@code Matcher}
* @throws NullPointerException {@code expectedType} が {@code null} の場合
*/
public static Matcher<Testee<?>> rootCause(Class<? extends Throwable> expectedType) {
Objects.requireNonNull(expectedType);
return new RootCause(expectedType);
}
/**
* スローされた例外の根本原因(root cause)の型とメッセージを検査する {@code Matcher} オブジェクトを返します。<br>
* このメソッドにより返される {@code Matcher} オブジェクトは、根本原因(root cause)の型が期待された型のサブクラスの場合も一致と判定します。<br>
*
* @param expectedType 期待される根本原因(root cause)の型
* @param expectedMessage 期待される根本原因(root cause)のメッセージ({@code null} が許容されます)
* @return スローされた例外の根本原因(root cause)を検査する {@code Matcher}
* @throws NullPointerException {@code expectedType} が {@code null} の場合
*/
public static Matcher<Testee<?>> rootCause(Class<? extends Throwable> expectedType, String expectedMessage) {
Objects.requireNonNull(expectedType);
return new RootCause(expectedType, expectedMessage);
}
/**
* スローされた例外の根本原因(root cause)のメッセージを検査する {@code Matcher} オブジェクトを返します。<br>
* このメソッドにより返される {@code Matcher} オブジェクトは、根本原因(root cause)の型は考慮しません。<br>
*
* @param expectedMessage 期待される根本原因(root cause)のメッセージ({@code null} が許容されます)
* @return スローされた例外の根本原因(root cause)を検査する {@code Matcher}
* @since 1.1.0
*/
public static Matcher<Testee<?>> rootCause(String expectedMessage) {
return new RootCause(Throwable.class, expectedMessage);
}
/**
* スローされた例外の根本原因(root cause)を、パラメータとして受け取った {@code matcher} で検査する {@code Matcher} オブジェクトを返します。<br>
*
* @param matcher 根本原因(root cause)に対する検査を行うための {@code Matcher}
* @return 根本原因(root cause)に {@code matcher} を適用する {@code Matcher}
* @throws NullPointerException {@code matcher} が {@code null} の場合
*/
public static Matcher<Testee<?>> rootCause(Matcher<Throwable> matcher) {
Objects.requireNonNull(matcher);
return new RootCause(matcher);
}
// [instance members] ++++++++++++++++++++++++++++++++++++++++++++++++++++++
private RootCause(Class<? extends Throwable> expectedType) {
super(false, expectedType);
}
private RootCause(Class<? extends Throwable> expectedType, String expectedMessage) {
super(false, expectedType, expectedMessage);
}
private RootCause(Matcher<Throwable> matcher) {
super(matcher);
}
}
| mit |
openfact/openfact-temp | services/src/main/java/org/openfact/truststore/SSLSocketFactory.java | 3558 | /*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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.openfact.truststore;
import org.jboss.logging.Logger;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
/**
* Using this class is ugly, but it is the only way to push our truststore to the default LDAP client implementation.
* <p>
* This SSLSocketFactory can only use truststore configured by TruststoreProvider after the ProviderFactory was
* initialized using standard Spi load / init mechanism. That will only happen if "truststore" provider is configured
* in standalone.xml or domain.xml.
* <p>
* If TruststoreProvider is not available this SSLSocketFactory will delegate all operations to javax.net.ssl.SSLSocketFactory.getDefault().
*
* @author <a href="mailto:mstrukel@redhat.com">Marko Strukelj</a>
*/
public class SSLSocketFactory extends javax.net.ssl.SSLSocketFactory {
private static final Logger log = Logger.getLogger(SSLSocketFactory.class);
private static SSLSocketFactory instance;
private final javax.net.ssl.SSLSocketFactory sslsf;
private SSLSocketFactory() {
TruststoreProvider provider = TruststoreProviderSingleton.get();
javax.net.ssl.SSLSocketFactory sf = null;
if (provider != null) {
sf = new JSSETruststoreConfigurator(provider).getSSLSocketFactory();
}
if (sf == null) {
log.info("No truststore provider found - using default SSLSocketFactory");
sf = (javax.net.ssl.SSLSocketFactory) javax.net.ssl.SSLSocketFactory.getDefault();
}
sslsf = sf;
}
public static synchronized SSLSocketFactory getDefault() {
if (instance == null) {
instance = new SSLSocketFactory();
}
return instance;
}
@Override
public String[] getDefaultCipherSuites() {
return sslsf.getDefaultCipherSuites();
}
@Override
public String[] getSupportedCipherSuites() {
return sslsf.getSupportedCipherSuites();
}
@Override
public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException {
return sslsf.createSocket(socket, host, port, autoClose);
}
@Override
public Socket createSocket(String host, int port) throws IOException {
return sslsf.createSocket(host, port);
}
@Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException {
return sslsf.createSocket(host, port, localHost, localPort);
}
@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
return sslsf.createSocket(host, port);
}
@Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
return sslsf.createSocket(address, port, localAddress, localPort);
}
}
| mit |
amitport/Klondike | src/com/cardsForest/foundations/Stack.java | 7265 | /**
*
*/
package com.cardsForest.foundations;
import java.awt.Graphics;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.cardsForest.glue.OperationManager;
import com.cardsForest.glue.StackSprite;
import com.cardsForest.logic.Behavior;
import static com.cardsForest.glue.OperationManager.*;
/**
* holds a collection of {@link Card} objects
* <p>
* includes static factory methods
* <p>
* generally GameLogic will create all stacks,
* assign them with {@link Behavior} objects
* and {@link StackSprite} objects.
* <p>
* logical action done on stack are delegated to {@link Operation} object
* and are sent to {@link OperationManager} which perform the operation
* in two phases:<br>
* 1. logical, changes done on stack's cards <br>
* 2. display, changes on the sprite's cards; it can be mirror of the first phase or more complex (e.g. animation)
*
* @see com.cardsForest.logic.GameLogic
* @see OperationManager
* @see com.cardsForest.platform.Game
*
* @author Amit Portnoy
*
*/
public class Stack {
List<Card> cards;
List<Card> unmodifiableCards;
Behavior behavior;
StackSprite sprite;
/**
* Stack objects will be created using static factory methods,
* hence the private constructor
*/
private Stack(){
cards = new ArrayList<Card>();
unmodifiableCards = Collections.unmodifiableList(cards);
//get default behavior and display
behavior = Behavior.getDefault();
sprite = new StackSprite(0.5,0.5,false);
}
/***********************/
/* game management */
/***********************/
/**
* update that Stack about it being clicked
* @param p the position of the clicked card within the stack
*/
public void click(Point p){
behavior.click(this,sprite.getCardIndex(p));
}
/**
* update that Stack about it being double clicked
* @param p the position of the clicked card within the stack
*/
public void doubleClick(Point p) {
behavior.doubleClick(this,sprite.getCardIndex(p));
}
/**
* delegates to {@link StackSprite}'s inBounds
* @param p
* @return whatever {@link StackSprite} returns
*/
public boolean inBounds(Point p) {
return sprite.inBounds(p);
}
/**
* delegates to {@link StackSprite}'s draw
* @param g
*/
public void draw(Graphics g){
sprite.draw(g,false);
}
/***********************/
/* stack operations */
/***********************/
/**
* shuffle the cards
*/
public void shuffle(){
OperationManager.add(new ShuffleOperation(this));
}
/**
* moves cards from this stack to another
* @param dst destination stack to move to
* @param num number of cards to move
*/
public void moveTo(Stack dst, int num, boolean immediate){
OperationManager.add(new MoveToOperation(this, dst, num, immediate));
}
/**
* Convenience method for moveTo(dst,num,false)
*/
public void moveTo(Stack dst, int num){
moveTo(dst,num,false);
}
/**
* flips the top card in the stack
*/
public void flipTop(){
OperationManager.add(new FlipTopOperation(this));
}
/**
* sets all the cards in the stack to face up or face down
* @param faceUp all cards in the stack will be set to this parameter value
*/
public void setAllFaceUp(boolean faceUp){
OperationManager.add(new SetAllFaceUpOperation(this,faceUp));
}
/**
* remove all the cards from the stack
*/
public void clear() {
OperationManager.add(new ClearOperation(this));
}
/*********************************************************/
/* simple service methods */
/* (methods that will not change the state of the stack) */
/*********************************************************/
/**
* @return a <b>read only</b> view of the cards
*/
public List<Card> getCards() {
return unmodifiableCards;
}
/**
* @return the sprite
*/
public StackSprite getSprite() {
return sprite;
}
/**
* @param sprite the sprite to set
*/
public void setSprite(StackSprite sprite) {
if (sprite == null){
throw new NullPointerException();
}
this.sprite = sprite;
}
/**
* @return the behavior
*/
public Behavior getBehavior() {
return behavior;
}
/**
* @param behavior the behavior to set
*/
public void setBehavior(Behavior behavior) {
if (behavior == null){
throw new NullPointerException();
}
this.behavior = behavior;
}
/**
* Returns <tt>true</tt> if this stack contains no cards.
*
* @return <tt>true</tt> if this stack contains no cards
*/
public boolean isEmpty() {
return cards.isEmpty();
}
/**
* @return number of cards in the stack
*/
public int size() {
return cards.size();
}
/**
* stack's group is defined by it's behavior object
* @param other stack to compare with
* @return true if this and other stack are of the same group
*/
public boolean isSameGroup(Stack other){
return behavior.isSameGroup(other.behavior);
}
/*************************/
/* factory methods */
/* (and factory helpers) */
/*************************/
/**
* adds a card to the stack
* and a copy of the stack to the sprite
* @param card the card to add
*/
protected void add(Card card){
cards.add(card);
sprite.cards.add(new Card(card));
}
/**
* Stack factory method
* @return a new empty Stack
*/
public static Stack newEmptyStack() {
return new Stack();
}
/**
* Stack factory method
* @return a new stack contain 52 {@link Card} objects
*/
public static Stack newDeck() {
Stack newDeck = newEmptyStack();
for (Face face : Face.values()){
newDeck.add(new Card(face,false));
}
return newDeck;
}
/*************************/
/* Operation inner class */
/*************************/
/**
* Encapsulate stack change (i.e. operation)
* <p>
* operation is done in two phases:<br>
* the first logic phase is done immediately,
* the second display phase is done after all logic is done
*
* @see OperationManager
*/
public static abstract class Operation{
protected Stack src;
protected List<Card> cards;
protected StackSprite sprite;
/**
* initialize the new operation object
* @param src the stack on which the operation is performed
*/
protected Operation(Stack src){
this.src = src;
this.cards = src.cards;
this.sprite = src.getSprite();
}
/**
* default actions to be performed on cards as part of the operation
* @param cards the cards to perform the operation on
*/
abstract protected void action(List<Card> cards);
/**
* do the logical part of the operation (done immediately)
*/
final public void doLogic(){
action(cards);
}
/**
* do the display part of the operation (done after all logic is done)
*/
public void doDisplay(){
action(sprite.cards);
}
/**
* return the stacks cards (only operation objects have access to the modifiable copy)
* @param stack the stack to get the cards from
* @return stack's cards
*/
protected List<Card> getModifiableCards(Stack stack){
return stack.cards;
}
}
//new stuff
//caller should check not empty
public Card getTop() {
// TODO Auto-generated method stub
return cards.get(cards.size()-1);
}
}
| mit |
satokazuma/nginx-log | src/main/java/org/ranceworks/nginxlog/dto/AccessCount.java | 320 | package org.ranceworks.nginxlog.dto;
public class AccessCount {
private String url;
private long count;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public long getCount() {
return count;
}
public void setCount(long count) {
this.count = count;
}
}
| mit |
siosio/DomaSupport | testData/siosio/doma/refactoring/rename/DaoMethodRename.java | 278 | package dao;
import org.seasar.doma.Dao;
import org.seasar.doma.Insert;
import org.seasar.doma.Select;
import siosio.entity.UserEntity;
@Dao
public interface User {
@Insert(sqlFile = true)
int insert<caret>(UserEntity entity);
@Select
String find(Long id);
} | mit |
SmartThingsIDoT/idot-service | src/main/java/com/integratingfactor/idot/service/db/devices/DeviceDaoImpl.java | 2162 | package com.integratingfactor.idot.service.db.devices;
import static com.googlecode.objectify.ObjectifyService.ofy;
import java.util.List;
import java.util.logging.Logger;
import org.springframework.beans.factory.InitializingBean;
import com.googlecode.objectify.ObjectifyService;
public class DeviceDaoImpl implements InitializingBean, DeviceDao {
private static Logger LOG = Logger.getLogger(DeviceDao.class.getName());
// @Autowired
// GdsDaoService dao;
@Override
public void afterPropertiesSet() throws Exception {
ObjectifyService.register(DeviceDaoDeviceDetailByDeviceIdUtil.DeviceDaoDeviceDetailByDeviceIdPk.class);
ObjectifyService.register(DeviceDaoDeviceDetailByDeviceIdUtil.DeviceDaoDeviceDetailByDeviceId.class);
}
@Override
public void createDevice(DeviceDetail device) {
try {
ofy().save().entity(DeviceDaoDeviceDetailByDeviceIdUtil.toEntity(device)).now();
} catch (Exception e) {
LOG.warning("Failed to save entity : " + e.getMessage());
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
}
@Override
public DeviceDetail getDevice(String deviceId) {
// TODO Auto-generated method stub
try {
return DeviceDaoDeviceDetailByDeviceIdUtil
.toModel(ofy().load().key(DeviceDaoDeviceDetailByDeviceIdUtil.toKey(deviceId)).now());
} catch (Exception e) {
LOG.warning("Failed to read device details : " + e.getMessage());
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
}
@Override
public List<DeviceDetail> getAllDevices() {
// TODO Auto-generated method stub
try {
return DeviceDaoDeviceDetailByDeviceIdUtil
.toDevices(ofy().load().ancestor(DeviceDaoDeviceDetailByDeviceIdUtil.toPk()).list());
} catch (Exception e) {
LOG.warning("Failed to read device list : " + e.getMessage());
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
}
}
| mit |
opengl-8080/qiita-backup | src/main/java/gl8080/qiitabk/QiitaBackupMain.java | 2184 | package gl8080.qiitabk;
import gl8080.qiitabk.domain.SaveImageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import gl8080.qiitabk.domain.Item;
import gl8080.qiitabk.domain.ItemList;
import gl8080.qiitabk.domain.ItemRepository;
import gl8080.qiitabk.domain.Qiita;
import gl8080.qiitabk.util.DefaultQualifier;
@SpringBootApplication
public class QiitaBackupMain {
private static final Logger logger = LoggerFactory.getLogger(QiitaBackupMain.class);
public static void main(String[] args) {
SpringApplication app = new SpringApplication(QiitaBackupMain.class);
app.setBannerMode(Banner.Mode.OFF);
try (ConfigurableApplicationContext ctx = app.run(args)) {
ctx.getBean(QiitaBackupMain.class).execute();
}
}
@Autowired @DefaultQualifier
private ItemRepository repository;
@Autowired
private Qiita qiita;
@Autowired
private SaveImageService saveImageService;
private void execute() {
ResultReport report = new ResultReport();
try {
ItemList itemList = this.qiita.getItemList();
while (itemList.hasNext()) {
report.total();
Item item = itemList.next();
try {
if (this.repository.save(item)) {
this.saveImageService.saveImages(item);
report.save();
}
} catch (Exception e) {
logger.error(item.getTitle() + " の処理中にエラーが発生しました。", e);
report.error();
} finally {
report.progress();
}
}
} finally {
report.print();
}
}
}
| mit |
tfcporciuncula/easy-bus | app/src/main/java/com/arctouch/easybus/data/ServiceHelper.java | 1917 | package com.arctouch.easybus.data;
import android.content.Context;
import com.arctouch.easybus.R;
import org.springframework.http.HttpBasicAuthentication;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.GsonHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;
/**
* Helper responsible for building the compatible RestTemplate and HttpHeaders to be used with the AppGlu REST API.
*/
public class ServiceHelper {
private static final Charset ENCODING = Charset.forName("UTF-8");
private static final String APP_GLU_CUSTOM_HEADER_NAME = "X-AppGlu-Environment";
private static final String APP_GLU_CUSTOM_HEADER_VALUE = "staging";
public static RestTemplate buildRestTemplate() {
RestTemplate restTemplate = new RestTemplate();
List<HttpMessageConverter<?>> converters = Arrays.<HttpMessageConverter<?>>asList(
new StringHttpMessageConverter(ENCODING),
new GsonHttpMessageConverter()
);
restTemplate.setMessageConverters(converters);
return restTemplate;
}
public static HttpHeaders buildHttpHeaders(Context context) {
HttpHeaders httpHeaders = new HttpHeaders();
String username = context.getString(R.string.app_glu_username);
String password = context.getString(R.string.app_glu_password);
httpHeaders.setAuthorization(new HttpBasicAuthentication(username, password));
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
httpHeaders.add(APP_GLU_CUSTOM_HEADER_NAME, APP_GLU_CUSTOM_HEADER_VALUE);
return httpHeaders;
}
}
| mit |