hexsha stringlengths 40 40 | size int64 8 1.04M | content stringlengths 8 1.04M | avg_line_length float64 2.24 100 | max_line_length int64 4 1k | alphanum_fraction float64 0.25 0.97 |
|---|---|---|---|---|---|
57c72a51d1fc2625b5eab2594b48149c059a5c5a | 4,093 | package net.n2oapp.framework.config.reader.widget;
import net.n2oapp.framework.api.metadata.global.view.action.LabelType;
import net.n2oapp.framework.api.metadata.global.view.widget.table.ImageShape;
import net.n2oapp.framework.api.metadata.global.view.widget.table.N2oAbstractTable;
import net.n2oapp.framework.api.metadata.global.view.widget.table.N2oTable;
import net.n2oapp.framework.api.metadata.global.view.widget.table.Size;
import net.n2oapp.framework.api.metadata.global.view.widget.table.column.N2oSimpleColumn;
import net.n2oapp.framework.api.metadata.global.view.widget.table.column.cell.*;
import net.n2oapp.framework.config.reader.widget.cell.*;
import net.n2oapp.framework.config.reader.widget.widget3.TableXmlReaderV3;
import net.n2oapp.framework.config.selective.reader.SelectiveStandardReader;
import org.junit.Test;
/**
* Тестирование чтения таблицы версии ниже 4
*/
public class TableXmlReaderTest extends BaseWidgetReaderTest {
@Test
public void testReaderTable3Widget() {
N2oTable table3 = new SelectiveStandardReader()
.addWidgetReaderV3()
.addFieldSet3Reader()
.addEventsReader()
.addControlReader()
.addReader(new TableXmlReaderV3())
.addReader(new N2oColorCellXmlReader())
.addReader(new N2oCheckboxCellXmlReader())
.addReader(new N2oCustomCellXmlReader())
.addReader(new N2oIconCellXmlReader())
.addReader(new N2oLinkCellXmlReader())
.addReader(new N2oTextCellXmlReader())
.addReader(new N2oImageCellXmlReader())
.addReader(new N2oProgressBarCellXmlReader())
.addReader(new N2oXEditableCellReader()).readByPath("net/n2oapp/framework/config/reader/widget/table/testTableReader.widget.xml");
assertWidgetAttribute(table3);
assertStandardTable(table3);
assert table3.getHasCheckboxes();
assert table3.getAutoSelect();
N2oSimpleColumn checkBoxColumn = ((N2oSimpleColumn) table3.getColumns()[0]);
N2oCustomCell custom = (N2oCustomCell) ((N2oSimpleColumn) table3.getColumns()[6]).getCell();
assert custom.getSrc().equals("test");
assert custom.getProperties().size() == 2;
assert custom.getProperties().get("a").equals("b");
assert custom.getProperties().get("c").equals("d");
N2oSimpleColumn iconColumn = ((N2oSimpleColumn) table3.getColumns()[2]);
N2oIconCell iconCell = (N2oIconCell) iconColumn.getCell();
assert iconCell.getType().equals(LabelType.icon);
assert iconCell.getPosition().equals(Position.left);
assert iconCell.getIconSwitch() != null;
assert iconCell.getIconSwitch().getValueFieldId().equals("id");
assert iconCell.getIconSwitch().getCases().size() == 1;
assert iconCell.getIconSwitch().getCases().get("key").equals("value");
assert iconCell.getIconSwitch().getDefaultCase().equals("test");
N2oImageCell imageCell = (N2oImageCell) ((N2oSimpleColumn) table3.getColumns()[9]).getCell();
assert imageCell.getWidth() == null;
assert imageCell.getShape() == null;
N2oImageCell imageCell2 = (N2oImageCell) ((N2oSimpleColumn) table3.getColumns()[8]).getCell();
assert imageCell2.getWidth().equals("32");
assert imageCell2.getShape().equals(ImageShape.circle);
N2oProgressBarCell progressBarCell = (N2oProgressBarCell) ((N2oSimpleColumn) table3.getColumns()[10]).getCell();
assert progressBarCell.getSize().equals(N2oProgressBarCell.Size.small);
assert progressBarCell.getStriped();
assert progressBarCell.getActive();
N2oProgressBarCell progressBarCell1 = (N2oProgressBarCell) ((N2oSimpleColumn) table3.getColumns()[11]).getCell();
assert progressBarCell1.getSize() == null;
assert progressBarCell1.getStriped() == null;
assert progressBarCell1.getActive() == null;
assert table3.getColumns()[12].getVisibilityCondition() != null;
}
}
| 52.474359 | 146 | 0.698998 |
4bec20c63d62bf3d373660e7a0367da344cd0fa3 | 286 | /**
* Copyright MaDgIK Group 2010 - 2015.
*/
package madgik.exareme.utils.histogram.score;
import madgik.exareme.utils.histogram.Bucket;
import java.util.LinkedList;
/**
* @author herald
*/
public interface HistogramScore {
double getScore(LinkedList<Bucket> bucketList);
}
| 16.823529 | 51 | 0.737762 |
0b4b7179095bd21d1463657e0e742e40306dfaca | 3,518 | package com.redhat.rhoar.customer.service;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import com.google.inject.Inject;
import com.redhat.rhoar.customer.model.Customer;
import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.mongo.MongoClient;
public class CustomerServiceMongoImpl implements CustomerService {
private MongoClient client;
private final String COLLECTION = "customers";
@Inject
public CustomerServiceMongoImpl(MongoClient client) {
this.client = client;
}
@Override
public void getCustomers(Handler<AsyncResult<List<Customer>>> resulthandler) {
// ----
//
// Use the `MongoClient.find()` method.
// Use an empty JSONObject for the query
// The collection to search is COLLECTION
// In the handler implementation, transform the `List<JSONObject>` to `List<Person>` - use Java8 Streams!
// Use a Future to set the result on the handle() method of the result handler
// Don't forget to handle failures!
// ----
JsonObject query = new JsonObject();
client.find(COLLECTION, query, ar -> {
if (ar.succeeded()) {
List<Customer> customers = ar.result().stream()
.map(json -> new Customer(json))
.collect(Collectors.toList());
resulthandler.handle(Future.succeededFuture(customers));
} else {
resulthandler.handle(Future.failedFuture(ar.cause()));
}
});
}
@Override
public void getCustomer(String customerId, Handler<AsyncResult<Customer>> resulthandler) {
// ----
//
// Use the `MongoClient.find()` method.
// Use a JSONObject for the query with the field 'customerId' set to the customer customerId
// The collection to search is COLLECTION
// In the handler implementation, transform the `List<JSONObject>` to `Person` - use Java8 Streams!
// If the customer is not found, the result should be set to null
// Use a Future to set the result on the handle() method of the result handler
// Don't forget to handle failures!
// ----
JsonObject query = new JsonObject().put("customerId", customerId);
client.find(COLLECTION, query, ar -> {
if (ar.succeeded()) {
Optional<JsonObject> result = ar.result().stream().findFirst();
if (result.isPresent()) {
resulthandler.handle(Future.succeededFuture(new Customer(result.get())));
} else {
resulthandler.handle(Future.succeededFuture(null));
}
} else {
resulthandler.handle(Future.failedFuture(ar.cause()));
}
});
}
@Override
public void addCustomer(Customer customer, Handler<AsyncResult<String>> resulthandler) {
client.save(COLLECTION, toDocument(customer), resulthandler);
}
@Override
public void ping(Handler<AsyncResult<String>> resultHandler) {
resultHandler.handle(Future.succeededFuture("OK"));
}
private JsonObject toDocument(Customer customer) {
JsonObject document = customer.toJson();
document.put("_id", customer.getCustomerId());
return document;
}
}
| 37.031579 | 113 | 0.616828 |
617136efeaff9d14d63912dd5df35d628e956cb9 | 717 | /*Complete the code segment to swap two numbers using call by object reference.*/
import java.util.Scanner;
class Question { //Define a class Question with two elements e1 and e2.
Scanner sc = new Scanner(System.in);
int e1 = sc.nextInt(); //Read e1
int e2 = sc.nextInt(); //Read e2
}
public class Question5 {
// Define static method swap()to swap the values of e1 and e2 of class Question.
//static int temp;
static void swap(Question q)
{
int temp;
temp = q.e1;
q.e1 = q.e2;
q.e2 = temp;
}
public static void main(String[] args) {
//Create an object of class Question
Question t = new Question();
//Call the method swap()
swap(t);
System.out.println(t.e1+" "+ t.e2);
}
}
| 24.724138 | 81 | 0.661088 |
1fde70902aa8cafda8425f3e88fd0305069dea01 | 153 | public class Aaaaaaa {
private final String aaa;
Aaaaaaa(Object aabbb) {
Xxx x = new Xx<caret>
}
}
class XxxImpl implements Xxx {} | 15.3 | 31 | 0.627451 |
11ecf38af6d4b88bc381e1857398e7b1a8068b64 | 1,955 | /*
* Copyright (c) 2012-2015 Savoir Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.savoirtech.hecate.core.exception;
import org.junit.Assert;
import org.junit.Test;
public class HecateExceptionTest extends Assert {
//----------------------------------------------------------------------------------------------------------------------
// Other Methods
//----------------------------------------------------------------------------------------------------------------------
@Test
public void testMessageInterpolation() {
HecateException e = new HecateException("%s - %s", "foo", "bar");
assertEquals("foo - bar", e.getMessage());
}
@Test
public void testVerifyNotNull() {
assertEquals("foo", HecateException.verifyNotNull("foo", "This is my %s.", "message"));
}
@Test
public void testVerifyNotNullWithNull() {
try {
HecateException.verifyNotNull(null, "This is my %s.", "message");
fail();
} catch (HecateException e) {
assertEquals("This is my message.", e.getMessage());
}
}
@Test
public void testWithNestedException() {
Exception nested = new IllegalArgumentException("Oops");
HecateException e = new HecateException(nested, "%s - %s", "foo", "bar");
assertEquals("foo - bar", e.getMessage());
assertEquals(nested, e.getCause());
}
} | 35.545455 | 120 | 0.577494 |
e9b1a4d709887bd3bcc77d5e4ab1d7a32f244c1d | 311 | // Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
package org.pantsbuild.testproject.shadingdep;
/**
* Used to test shading support in tests/python/pants_test/java/jar/test_shader_integration.py
*/
public class SomeClass {}
| 31.1 | 94 | 0.778135 |
b1305e9d99456c6ea264fd8e774dc1ebb8a24b56 | 2,095 | package com.yipeipei.pprqs;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.Random;
import edu.princeton.cs.introcs.StdOut;
/**
* NodeFlag used to distinguish the real nodes and surrogate nodes.
* 0 for real nodes, 1 for surrogate nodes
* @author peipei
*
*/
public enum NodeFlag {
SURROGATE(1), REAL(0);
private static String SEP = ":";
private static Random rand = new Random();
private final int value;
// only private modifier is permit
private NodeFlag(int value){
this.value = value;
}
public static NodeFlag ValueOfStrWithRand(String strWithRand){
int value = Integer.parseInt(strWithRand.split(SEP)[0]);
return NodeFlag.REAL.value == value? NodeFlag.REAL:NodeFlag.SURROGATE;
}
public int getValue(){
return value;
}
public String getStrWithRand(){
return this.getValue() + SEP + rand.nextInt();
}
@Override
public String toString() {
// TODO Auto-generated method stub
return super.toString();
}
// some test on enum, EnumMap and EnumSet
public static void main(String[] args) {
// traversal all enum
NodeFlag[] flags = NodeFlag.values();
for(NodeFlag f : flags){
StdOut.println("name: " + f.name());
StdOut.println("ordinal: " + f.ordinal());
StdOut.println("getValue: " + f.getValue());
StdOut.println();
}
// test EnumMap
EnumMap<NodeFlag, String> flag2str = new EnumMap<NodeFlag, String>(NodeFlag.class);
flag2str.put(NodeFlag.REAL, "real node");
flag2str.put(NodeFlag.SURROGATE, "surrogate node");
for(NodeFlag f : NodeFlag.values()){
StdOut.println("NodeFlag: " + f.toString() + "\ndescription: " + flag2str.get(f));
StdOut.println();
}
// test EnumSet
EnumSet<NodeFlag> flagSet = EnumSet.allOf(NodeFlag.class);
for(NodeFlag f : flagSet){
StdOut.println(f);
}
}
}
| 28.310811 | 94 | 0.595704 |
3e784c9f5825ffb7b30de7c51b348758f5fea5ea | 220 | package jcf.extproc.process;
import java.io.Serializable;
public interface LogFileKeepingPolicy extends Serializable {
boolean isOutdated(JobInstanceInfo jobInstanceInfo, JobInstanceInfo currentJobInstanceInfo);
}
| 20 | 93 | 0.845455 |
267741a6e59dc694f2ed27e3eccf64d22a74f2d0 | 6,981 | package com.ctrip.platform.dal.dao.sqlbuilder;
import com.ctrip.platform.dal.common.enums.DatabaseCategory;
import com.ctrip.platform.dal.dao.DalHints;
import org.junit.Test;
import java.sql.SQLException;
import static com.ctrip.platform.dal.dao.sqlbuilder.AbstractFreeSqlBuilder.text;
import static com.ctrip.platform.dal.dao.sqlbuilder.Expressions.AND;
import static com.ctrip.platform.dal.dao.sqlbuilder.Expressions.expression;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
public class FreeSelectSqlBuilderTest {
private static final String template = "template";
private static final String wrappedTemplate = "[template]";
private static final String expression = "count()";
private static final String elseTemplate = "elseTemplate";
private static final String EMPTY = "";
private static final String logicDbName = "dao_test_sqlsvr_tableShard";
private static final String tableName = "dal_client_test";
private static final String wrappedTableName = "[dal_client_test]";
private static final String noShardTableName = "noShard";
private static final String wrappedNoShardTableName = "[noShard]";
private FreeSelectSqlBuilder createTest() {
return (FreeSelectSqlBuilder)new FreeSelectSqlBuilder().setLogicDbName(logicDbName).setHints(new DalHints());
}
@Test
public void testCreate() throws SQLException {
try {
FreeSelectSqlBuilder test = new FreeSelectSqlBuilder(DatabaseCategory.MySql);
test = new FreeSelectSqlBuilder(DatabaseCategory.SqlServer);
} catch (Exception e) {
fail();
}
try {
FreeSelectSqlBuilder test = new FreeSelectSqlBuilder(DatabaseCategory.MySql);
test.setLogicDbName(logicDbName);
test.setDbCategory(DatabaseCategory.MySql);
fail();
} catch (Exception e) {
}
}
@Test
public void testSetTemplate() throws SQLException {
FreeSelectSqlBuilder test = createTest();
test.setTemplate(template).setTemplate(template);
assertEquals(template+" " + template, test.build());
}
@Test
public void testBuildSqlServerTop() throws SQLException {
FreeSelectSqlBuilder test = createTest();
test.setTemplate(template).setTemplate(template).append(template);
assertEquals("template template template", test.build());
test.top(10);
assertEquals("template template template OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY", test.build());
}
@Test
public void testBuildSqlServerAtPage() throws SQLException {
FreeSelectSqlBuilder test = createTest();
test.setTemplate(template).setTemplate(template).append(template);
assertEquals("template template template", test.build());
test.atPage(10, 10);
assertEquals("template template template OFFSET 90 ROWS FETCH NEXT 10 ROWS ONLY", test.build());
}
@Test
public void testBuildSqlServerAtPageWithLikeTemplate() throws SQLException {
FreeSelectSqlBuilder test = createTest();
test.setTemplate("select * from testtable where name like '%a%'");
test.atPage(10, 10);
assertEquals("select * from testtable where name like '%a%' OFFSET 90 ROWS FETCH NEXT 10 ROWS ONLY", test.build());
}
@Test
public void testBuildSqlServerRange() throws SQLException {
FreeSelectSqlBuilder test = createTest();
test.setTemplate(template).setTemplate(template).append(template);
assertEquals("template template template", test.build());
test.range(10, 10);
assertEquals("template template template OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY", test.build());
}
@Test
public void testBuildMySqlTop() throws SQLException {
FreeSelectSqlBuilder test = new FreeSelectSqlBuilder(DatabaseCategory.MySql);
test.setTemplate(template).setTemplate(template).append(template);
assertEquals("template template template", test.build());
test.top(10);
assertEquals("template template template limit 0, 10", test.build());
}
@Test
public void testBuildMySqlAtPage() throws SQLException {
FreeSelectSqlBuilder test = new FreeSelectSqlBuilder(DatabaseCategory.MySql);
test.setTemplate(template).setTemplate(template).append(template);
assertEquals("template template template", test.build());
test.atPage(10, 10);
assertEquals("template template template limit 90, 10", test.build());
}
@Test
public void testBuildMySqlAtPageWithLikeTemplate() throws SQLException {
FreeSelectSqlBuilder test = new FreeSelectSqlBuilder(DatabaseCategory.MySql);
test.setTemplate("select * from testtable where name like '%a'");
test.atPage(10, 10);
assertEquals("select * from testtable where name like '%a' limit 90, 10", test.build());
}
@Test
public void testBuildMySqlRange() throws SQLException {
FreeSelectSqlBuilder test = new FreeSelectSqlBuilder(DatabaseCategory.MySql);
test.setTemplate(template).setTemplate(template).append(template);
assertEquals("template template template", test.build());
test.range(10, 10);
assertEquals("template template template limit 10, 10", test.build());
}
@Test
public void testBuildSelect() throws SQLException {
FreeSelectSqlBuilder test = createTest();
test.select(template, template, template).from(tableName).where(text(template)).groupBy(template);
test.top(10).setHints(new DalHints().inTableShard(1));
assertEquals("SELECT [template], [template], [template] FROM [dal_client_test_1] WITH (NOLOCK) WHERE template GROUP BY [template] OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY", test.build());
}
@Test
public void testBuildMeltdownAtEnd() throws SQLException {
FreeSelectSqlBuilder test = createTest();
test.where(text(template), AND, expression(template).ignoreNull(null)).groupBy(template);
assertEquals("WHERE template GROUP BY [template]", test.build());
test = createTest();
test.where(text(template)).and().appendExpression(template).ignoreNull(null).groupBy(template);
assertEquals("WHERE template GROUP BY [template]", test.build());
}
@Test
public void testBuildMeltdownAtBegining() throws SQLException {
FreeSelectSqlBuilder test = createTest();
test = createTest();
test.where(template).ignoreNull(null).and().appendExpression(template).or().appendExpression(template).ignoreNull(null).groupBy(template);
assertEquals("WHERE template GROUP BY [template]", test.build());
}
}
| 42.567073 | 193 | 0.676837 |
b6b7a547c138be33f62c68136bfccb655e33941b | 6,141 | /*
* Copyright (c) 2010-2015 Pivotal Software, 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. See accompanying
* LICENSE file.
*/
package com.gemstone.gemfire.management.bean.stats;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Set;
import com.gemstone.gemfire.cache.Cache;
import com.gemstone.gemfire.cache.CacheFactory;
import com.gemstone.gemfire.cache.Operation;
import com.gemstone.gemfire.cache.PartitionAttributesFactory;
import com.gemstone.gemfire.cache.Region;
import com.gemstone.gemfire.cache.RegionFactory;
import com.gemstone.gemfire.cache.RegionShortcut;
import com.gemstone.gemfire.cache.hdfs.HDFSStoreFactory;
import com.gemstone.gemfire.cache.hdfs.internal.HDFSStoreImpl;
import com.gemstone.gemfire.cache.hdfs.internal.SortedHDFSQueuePersistedEvent;
import com.gemstone.gemfire.cache.hdfs.internal.hoplog.HoplogOrganizer;
import com.gemstone.gemfire.internal.cache.BucketRegion;
import com.gemstone.gemfire.internal.cache.GemFireCacheImpl;
import com.gemstone.gemfire.internal.cache.PartitionedRegion;
import com.gemstone.gemfire.internal.cache.execute.BucketMovedException;
import com.gemstone.gemfire.internal.cache.persistence.soplog.HFileStoreStatistics;
import com.gemstone.gemfire.internal.cache.persistence.soplog.SortedOplogStatistics;
import com.gemstone.gemfire.internal.cache.versions.DiskVersionTag;
import com.gemstone.gemfire.internal.util.BlobHelper;
import com.gemstone.gemfire.management.ManagementService;
import com.gemstone.gemfire.management.RegionMXBean;
import com.gemstone.gemfire.management.internal.ManagementConstants;
import junit.framework.TestCase;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.io.hfile.BlockCache;
/**
* Test for verifying HDFS related MBean attributes
* @author rishim
*
*/
public class HDFSRegionMBeanAttributeJUnitTest extends TestCase {
public static final String HDFS_STORE_NAME = "HDFSMBeanJUnitTestStore";
public static final String REGION_NAME = "HDFSMBeanJUnitTest_Region";
protected Path testDataDir;
protected Cache cache;
protected HDFSStoreFactory hsf;
protected HDFSStoreImpl hdfsStore;
protected Region<Object, Object> region;
SortedOplogStatistics stats;
HFileStoreStatistics storeStats;
BlockCache blockCache;
@Override
protected void setUp() throws Exception {
super.setUp();
System.setProperty(HDFSStoreImpl.ALLOW_STANDALONE_HDFS_FILESYSTEM_PROP, "true");
testDataDir = new Path("test-case");
cache = createCache();
configureHdfsStoreFactory();
hdfsStore = (HDFSStoreImpl) hsf.create(HDFS_STORE_NAME);
RegionFactory<Object, Object> regionfactory = cache.createRegionFactory(RegionShortcut.PARTITION_HDFS);
regionfactory.setHDFSStoreName(HDFS_STORE_NAME);
// regionfactory.setCompressionCodec("Some");
PartitionAttributesFactory fac = new PartitionAttributesFactory();
fac.setTotalNumBuckets(10);
regionfactory.setPartitionAttributes(fac.create());
region = regionfactory.create(REGION_NAME);
}
protected void configureHdfsStoreFactory() throws Exception {
hsf = this.cache.createHDFSStoreFactory();
hsf.setHomeDir(testDataDir.toString());
}
protected Cache createCache() {
CacheFactory cf = new CacheFactory().set("mcast-port", "0").set("log-level", "info");
cache = cf.create();
return cache;
}
@Override
protected void tearDown() throws Exception {
hdfsStore.getFileSystem().delete(testDataDir, true);
cache.close();
super.tearDown();
}
public void testStoreUsageStats() throws Exception {
PartitionedRegion parRegion = (PartitionedRegion)region;
ArrayList<TestEvent> items = new ArrayList<TestEvent>();
for (int i = 0; i < 100; i++) {
String key = ("key-" + (i * 100 + i));
String value = ("value-" + System.nanoTime());
parRegion.put(key, value);
items.add(new TestEvent(key, value));
}
//Dont want to create
Set<BucketRegion> localPrimaryBucketRegions = parRegion.getDataStore().getAllLocalPrimaryBucketRegions();
BucketRegion flushingBucket= localPrimaryBucketRegions.iterator().next();
HoplogOrganizer hoplogOrganizer = getOrganizer(parRegion,flushingBucket.getId());
hoplogOrganizer.flush(items.iterator(), 100);
GemFireCacheImpl cache = GemFireCacheImpl.getExisting();
ManagementService service = ManagementService.getExistingManagementService(cache);
RegionMXBean bean = service.getLocalRegionMBean(region.getFullPath());
//assertTrue(bean.getEntryCount() == ManagementConstants.ZERO);
assertTrue(bean.getEntrySize() == ManagementConstants.NOT_AVAILABLE_LONG);
assertTrue(0 < bean.getDiskUsage());
}
private HoplogOrganizer getOrganizer(PartitionedRegion region, int bucketId) {
BucketRegion br = region.getDataStore().getLocalBucketById(bucketId);
if (br == null) {
// got rebalanced or something
throw new BucketMovedException("Bucket region is no longer available",
bucketId, region.getFullPath());
}
return br.getHoplogOrganizer();
}
public static class TestEvent extends SortedHDFSQueuePersistedEvent implements Serializable {
private static final long serialVersionUID = 1L;
Object key;
public TestEvent(String k, String v) throws Exception {
this(k, v, Operation.PUT_IF_ABSENT);
}
public TestEvent(String k, String v, Operation op) throws Exception {
super(v, op, (byte) 0x02, false, new DiskVersionTag(), BlobHelper.serializeToBlob(k), 0);
this.key = k;
}
}
}
| 35.912281 | 109 | 0.756391 |
0762c926989bbb2db8493d3e7936c30d08a590b5 | 9,433 | /*
* Copyright 2014-2018 JKOOL, LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jkoolcloud.tnt4j.streams.inputs;
import java.io.FileNotFoundException;
import java.util.Map;
import org.logstash.beats.IMessageListener;
import org.logstash.beats.Message;
import org.logstash.beats.Server;
import org.logstash.netty.SslContextBuilder;
import org.logstash.netty.SslHandlerProvider;
import com.jkoolcloud.tnt4j.core.OpLevel;
import com.jkoolcloud.tnt4j.sink.EventSink;
import com.jkoolcloud.tnt4j.streams.configure.ElasticBeatsStreamProperties;
import com.jkoolcloud.tnt4j.streams.configure.StreamProperties;
import com.jkoolcloud.tnt4j.streams.utils.BeatsStreamConstants;
import com.jkoolcloud.tnt4j.streams.utils.LoggerUtils;
import com.jkoolcloud.tnt4j.streams.utils.StreamsResources;
import com.jkoolcloud.tnt4j.streams.utils.Utils;
import io.netty.channel.ChannelHandlerContext;
/**
* Implements Elastic Beats provided data (over Logstash messages) activity stream, where each message body is assumed
* to represent a single activity or event which should be recorded.
* <p>
* This activity stream requires parsers that can support {@link Map} data.
* <p>
* Running this stream Logstash server is started on configuration defined (host and) port to consume Elastic Beats
* provided data as Logstash messages. So on Elastic Beats (messages producer) environment you have to configure output
* to send data to this stream running Logstash server host and port.
* <p>
* This activity stream supports the following configuration properties (in addition to those supported by
* {@link AbstractBufferedStream}):
* <ul>
* <li>Host - host name to bind for stream started Logstash server. Default value - {@code "localhost"}. (Optional)</li>
* <li>Port - port number to bind for stream started Logstash server. Default value - {@code 5044}. (Optional)</li>
* <li>SSLCertificateFilePath - SSL certificate file path. (Optional)</li>
* <li>SSLKeyFilePath - SSL key file path. (Optional)</li>
* <li>PassPhrase - SSL key pass phrase. (Optional)</li>
* <li>Timeout - connection timeout in seconds. Default value - {@code 30}. (Optional)</li>
* <li>ThreadCount - number of threads used by Logstash server. Default value - {@code 1}. (Optional)</li>
* </ul>
*
* @version $Revision: 1 $
*
* @see com.jkoolcloud.tnt4j.streams.parsers.ActivityParser#isDataClassSupported(Object)
* @see com.jkoolcloud.tnt4j.streams.parsers.ActivityMapParser
*/
public class ElasticBeatsStream extends AbstractBufferedStream<Map<?, ?>> {
private static final EventSink LOGGER = LoggerUtils.getLoggerSink(ElasticBeatsStream.class);
private String host = "localhost"; // NON-NLS
private int port = 5044;
private String sslCertificateFilePath;
private String sslKeyFilePath;
private String passPhrase;
private int timeout = 30;
private int threadCount = 1;
private LogstashInputProcessor processor;
/**
* Constructs an empty ElasticBeatsStream. Requires configuration settings to set input stream source.
*/
public ElasticBeatsStream() {
super();
}
@Override
protected EventSink logger() {
return LOGGER;
}
@Override
public void setProperty(String name, String value) {
super.setProperty(name, value);
if (StreamProperties.PROP_HOST.equalsIgnoreCase(name)) {
host = value;
} else if (StreamProperties.PROP_PORT.equalsIgnoreCase(name)) {
port = Integer.parseInt(value);
} else if (ElasticBeatsStreamProperties.PROP_SSL_CERTIFICATE_FILE_PATH.equalsIgnoreCase(name)) {
sslCertificateFilePath = value;
} else if (ElasticBeatsStreamProperties.PROP_SSL_KEY_FILE_PATH.equalsIgnoreCase(name)) {
sslKeyFilePath = value;
} else if (ElasticBeatsStreamProperties.PROP_PASSPHRASE.equalsIgnoreCase(name)) {
passPhrase = decPassword(value);
} else if (ElasticBeatsStreamProperties.PROP_TIMEOUT.equalsIgnoreCase(name)) {
timeout = Integer.parseInt(value);
} else if (ElasticBeatsStreamProperties.PROP_THREAD_COUNT.equalsIgnoreCase(name)) {
threadCount = Integer.parseInt(value);
}
}
@Override
public Object getProperty(String name) {
if (StreamProperties.PROP_HOST.equalsIgnoreCase(name)) {
return host;
}
if (StreamProperties.PROP_PORT.equalsIgnoreCase(name)) {
return port;
}
if (ElasticBeatsStreamProperties.PROP_SSL_CERTIFICATE_FILE_PATH.equalsIgnoreCase(name)) {
return sslCertificateFilePath;
}
if (ElasticBeatsStreamProperties.PROP_SSL_KEY_FILE_PATH.equalsIgnoreCase(name)) {
return sslKeyFilePath;
}
if (ElasticBeatsStreamProperties.PROP_PASSPHRASE.equalsIgnoreCase(name)) {
return encPassword(passPhrase);
}
if (ElasticBeatsStreamProperties.PROP_TIMEOUT.equalsIgnoreCase(name)) {
return timeout;
}
if (ElasticBeatsStreamProperties.PROP_THREAD_COUNT.equalsIgnoreCase(name)) {
return threadCount;
}
return super.getProperty(name);
}
@Override
protected void initialize() throws Exception {
super.initialize();
processor = new LogstashInputProcessor();
processor.initialize();
}
@Override
protected void start() throws Exception {
super.start();
processor.start();
logger().log(OpLevel.DEBUG, StreamsResources.getBundle(StreamsResources.RESOURCE_BUNDLE_NAME),
"TNTInputStream.stream.start", getClass().getSimpleName(), getName());
}
@Override
protected void cleanup() {
if (processor != null) {
processor.shutdown();
}
super.cleanup();
}
@Override
protected boolean isInputEnded() {
return processor.isInputEnded();
}
@Override
protected long getActivityItemByteSize(Map<?, ?> activityItem) {
return 0; // TODO
}
/**
* Logstash messages receiver thread. It implements {@link org.logstash.beats.IMessageListener} interface and
* initiates server to receive and handle Elastic Beats provided data as Logstash messages data.
*/
private class LogstashInputProcessor extends InputProcessor implements IMessageListener {
private Server server;
private LogstashInputProcessor() {
super("ElasticBeatsStream.LogstashInputProcessor"); // NON-NLS
}
/**
* Input data receiver initialization - Logstash server configuration.
*
* @param params
* initialization parameters array
*
* @throws Exception
* if fails to initialize message listener and configure Logstash server connection
*/
@Override
protected void initialize(Object... params) throws Exception {
server = new Server(host, port, timeout, threadCount);
if (sslCertificateFilePath != null && sslKeyFilePath != null && passPhrase != null) {
try {
server.setSslHandlerProvider(new SslHandlerProvider(
new SslContextBuilder(sslCertificateFilePath, sslKeyFilePath, passPhrase).buildContext(),
timeout * 1000));
} catch (FileNotFoundException e) {
logger().log(OpLevel.ERROR, StreamsResources.getBundle(BeatsStreamConstants.RESOURCE_BUNDLE_NAME),
"ElasticBeatsStream.ssl.file.not.found.error", e);
}
}
server.setMessageListener(this);
}
/**
* Starts Logstash to receive Elastic Beats incoming data. Shuts down this data receiver if exception occurs.
*/
@Override
public void run() {
if (server != null) {
try {
server.listen();
} catch (Exception exc) {
Utils.logThrowable(logger(), OpLevel.ERROR,
StreamsResources.getBundle(StreamsResources.RESOURCE_BUNDLE_NAME),
"AbstractBufferedStream.input.start.failed", exc);
shutdown();
}
}
}
/**
* Closes Logstash server.
*/
@Override
void closeInternals() throws Exception {
if (server != null) {
server.stop();
}
}
@Override
public void onNewMessage(ChannelHandlerContext ctx, Message message) {
logger().log(OpLevel.TRACE, StreamsResources.getBundle(BeatsStreamConstants.RESOURCE_BUNDLE_NAME),
"ElasticBeatsStream.message.received", ctx, message.getIdentityStream(), message.getSequence());
addInputToBuffer(message.getData());
}
@Override
public void onNewConnection(ChannelHandlerContext ctx) {
logger().log(OpLevel.INFO, StreamsResources.getBundle(BeatsStreamConstants.RESOURCE_BUNDLE_NAME),
"ElasticBeatsStream.connection.opened", ctx);
}
@Override
public void onConnectionClose(ChannelHandlerContext ctx) {
logger().log(OpLevel.WARNING, StreamsResources.getBundle(BeatsStreamConstants.RESOURCE_BUNDLE_NAME),
"ElasticBeatsStream.connection.closed", ctx);
}
@Override
public void onException(ChannelHandlerContext ctx, Throwable cause) {
logger().log(OpLevel.ERROR, StreamsResources.getBundle(BeatsStreamConstants.RESOURCE_BUNDLE_NAME),
"ElasticBeatsStream.exception.occurred", ctx, cause);
}
@Override
public void onChannelInitializeException(ChannelHandlerContext ctx, Throwable cause) {
logger().log(OpLevel.ERROR, StreamsResources.getBundle(BeatsStreamConstants.RESOURCE_BUNDLE_NAME),
"ElasticBeatsStream.channel.initialization.error", ctx, cause);
}
}
}
| 34.680147 | 120 | 0.752359 |
7e7ce6b822e4849d6f59ef6b5e78f08f697661d9 | 3,126 | package ru.shemplo.hw.src.implementor;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
public class ImplementTree {
private final Node ROOT;
public ImplementTree (Class <?> token) {
this.ROOT = new Node (token);
}
public List <MethodDeclaration> getMethods () {
return ROOT.getMethods ();
}
public static class Node {
private final List <MethodDeclaration> METHODS;
private final List <String> GENERICS_NAMES;
private final List <Generic> SUPER_GENERICS;
private final List <Node> SUPER;
private final Class <?> TOKEN;
public Node (Class <?> token) {
//System.out.println (token);
this.GENERICS_NAMES = new ArrayList <> ();
this.SUPER_GENERICS = new ArrayList <> ();
this.METHODS = new ArrayList <> ();
this.SUPER = new ArrayList <> ();
this.TOKEN = token;
TypeVariable <?> [] params = token.getTypeParameters ();
Stream.of (params).forEach (p -> GENERICS_NAMES.add (p.getName ()));
Class <?> sp = token.getSuperclass ();
if (sp != null && sp != Object.class) {
SUPER.add (new Node (sp));
Type type = token.getGenericSuperclass ();
if (!type.getTypeName ().equals (Object.class.getName ())) {
String genericName = type.getTypeName ();
Generic g = GenericParser
.parseGeneric (genericName);
SUPER_GENERICS.add (g);
}
}
Type [] intfs_gen = token.getGenericInterfaces ();
Class <?> [] intfs = token.getInterfaces ();
for (int i = 0; i < intfs.length; i ++) {
SUPER.add (new Node (intfs [i]));
Type type = intfs_gen [i];
if (!type.getTypeName ().equals (intfs [i].getName ())) {
String genericName = type.getTypeName ();
Generic g = GenericParser
.parseGeneric (genericName);
SUPER_GENERICS.add (g);
} else { SUPER_GENERICS.add (null); }
}
for (Method method : token.getDeclaredMethods ()) {
METHODS.add (new MethodDeclaration (method));
}
for (int i = 0; i < SUPER.size (); i++) {
Node node = SUPER.get (i);
List <String> PARAMS_NAME = node.GENERICS_NAMES;
if (PARAMS_NAME.size () == 0) { continue; }
Generic superParam = SUPER_GENERICS.get (i);
List <Generic> simple = superParam.getTypeParameters (node.TOKEN);
for (int j = 0; j < PARAMS_NAME.size (); j++) {
// Propagating local type to one level upper
node.replace (PARAMS_NAME.get (j), simple.get (j));
}
}
}
public void replace (String name, Generic generic) {
for (MethodDeclaration method : METHODS) {
method.replace (name, generic);
}
for (int i = 0; i < SUPER.size (); i++) {
SUPER.get (i).replace (name, generic);
}
}
public List <MethodDeclaration> getMethods () {
List <MethodDeclaration> methods = new ArrayList <> (METHODS);
for (Node sup : SUPER) { methods.addAll (sup.getMethods ()); }
return methods;
}
}
}
| 29.214953 | 72 | 0.612284 |
be0ad40b5ebf5b17e2af778a54c270fce714e9f9 | 4,057 | /*
* Copyright 2012 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.drools.guvnor.client.decisiontable.widget;
import java.util.HashMap;
import java.util.Map;
import org.drools.ide.common.client.modeldriven.SuggestionCompletionEngine;
import org.drools.ide.common.client.modeldriven.dt52.ActionCol52;
import org.drools.ide.common.client.modeldriven.dt52.ActionInsertFactCol52;
import org.drools.ide.common.client.modeldriven.dt52.ActionSetFieldCol52;
import org.drools.ide.common.client.modeldriven.dt52.BaseColumn;
import org.drools.ide.common.client.modeldriven.dt52.ConditionCol52;
import org.drools.ide.common.client.modeldriven.dt52.DTCellValue52;
import org.drools.ide.common.client.modeldriven.dt52.DTColumnConfig52;
import org.drools.ide.common.client.modeldriven.dt52.GuidedDecisionTable52;
import org.drools.ide.common.client.modeldriven.dt52.Pattern52;
/**
* Specific implementation for Default Value dependent enumerations
*/
public class DefaultValueDropDownManager extends LimitedEntryDropDownManager {
public DefaultValueDropDownManager(final GuidedDecisionTable52 model,
final SuggestionCompletionEngine sce) {
super( model,
sce );
}
@Override
public Map<String, String> getCurrentValueMap(Context context) {
Map<String, String> currentValueMap = new HashMap<String, String>();
final Pattern52 basePattern = context.getBasePattern();
final BaseColumn baseColumn = context.getBaseColumn();
//Get values for all Constraints or Actions on the same pattern as the baseColumn
if ( baseColumn instanceof ConditionCol52 ) {
for ( ConditionCol52 cc : basePattern.getChildColumns() ) {
currentValueMap.put( cc.getFactField(),
getValue( cc ) );
}
} else if ( baseColumn instanceof ActionSetFieldCol52 ) {
ActionSetFieldCol52 baseActionColumn = (ActionSetFieldCol52) baseColumn;
final String binding = baseActionColumn.getBoundName();
for ( ActionCol52 ac : this.model.getActionCols() ) {
if ( ac instanceof ActionSetFieldCol52 ) {
final ActionSetFieldCol52 asf = (ActionSetFieldCol52) ac;
if ( asf.getBoundName().equals( binding ) ) {
currentValueMap.put( asf.getFactField(),
getValue( asf ) );
}
}
}
} else if ( baseColumn instanceof ActionInsertFactCol52 ) {
ActionInsertFactCol52 baseActionColumn = (ActionInsertFactCol52) baseColumn;
final String binding = baseActionColumn.getBoundName();
for ( ActionCol52 ac : this.model.getActionCols() ) {
if ( ac instanceof ActionInsertFactCol52 ) {
final ActionInsertFactCol52 aif = (ActionInsertFactCol52) ac;
if ( aif.getBoundName().equals( binding ) ) {
currentValueMap.put( aif.getFactField(),
getValue( aif ) );
}
}
}
}
return currentValueMap;
}
private String getValue(final DTColumnConfig52 col) {
if ( col.getDefaultValue() == null ) {
return "";
}
final DTCellValue52 dcv = col.getDefaultValue();
return utilities.asString( dcv );
}
}
| 42.260417 | 89 | 0.648509 |
f59a18e4abbf3c0fb837c3a8ba6093fa7695fe43 | 10,534 | /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.savan.eventing;
import java.util.Calendar;
import java.util.Date;
import javax.xml.namespace.QName;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMNamespace;
import org.apache.axiom.soap.SOAPEnvelope;
import org.apache.axiom.soap.SOAPFactory;
import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.AddressingConstants;
import org.apache.axis2.addressing.EndpointReferenceHelper;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.databinding.utils.ConverterUtil;
import org.apache.savan.SavanConstants;
import org.apache.savan.SavanException;
import org.apache.savan.SavanMessageContext;
import org.apache.savan.eventing.subscribers.EventingLeafSubscriber;
import org.apache.savan.messagereceiver.MessageReceiverDeligater;
import org.apache.savan.storage.SubscriberStore;
import org.apache.savan.subscribers.AbstractSubscriber;
import org.apache.savan.subscribers.Subscriber;
import org.apache.savan.util.CommonUtil;
public class EventingMessageReceiverDeligater implements MessageReceiverDeligater {
public void handleSubscriptionRequest(SavanMessageContext subscriptionMessage, MessageContext outMessage) throws SavanException {
if (outMessage==null)
throw new SavanException ("Eventing protocol need to sent the SubscriptionResponseMessage. But the outMessage is null");
MessageContext subscriptionMsgCtx = subscriptionMessage.getMessageContext();
SOAPEnvelope outMessageEnvelope = outMessage.getEnvelope();
SOAPFactory factory = null;
if (outMessageEnvelope!=null) {
factory = (SOAPFactory) outMessageEnvelope.getOMFactory();
} else {
factory = (SOAPFactory) subscriptionMsgCtx.getEnvelope().getOMFactory();
outMessageEnvelope = factory.getDefaultEnvelope();
try {
outMessage.setEnvelope(outMessageEnvelope);
} catch (AxisFault e) {
throw new SavanException (e);
}
}
//setting the action
outMessage.getOptions().setAction(EventingConstants.Actions.SubscribeResponse);
//sending the subscription response message.
String address = subscriptionMsgCtx.getOptions().getTo().getAddress();
EndpointReference subscriptionManagerEPR = new EndpointReference (address);
String id = (String) subscriptionMessage.getProperty(EventingConstants.TransferedProperties.SUBSCRIBER_UUID);
if (id==null)
throw new SavanException ("Subscription UUID is not set");
subscriptionManagerEPR.addReferenceParameter(new QName (EventingConstants.EVENTING_NAMESPACE,EventingConstants.ElementNames.Identifier,EventingConstants.EVENTING_PREFIX),id);
OMNamespace ens = factory.createOMNamespace(EventingConstants.EVENTING_NAMESPACE,EventingConstants.EVENTING_PREFIX);
OMElement subscribeResponseElement = factory.createOMElement(EventingConstants.ElementNames.SubscribeResponse,ens);
OMElement subscriptionManagerElement = null;
try {
subscriptionManagerElement = EndpointReferenceHelper.toOM(subscribeResponseElement.getOMFactory(), subscriptionManagerEPR, new QName(EventingConstants.EVENTING_NAMESPACE,EventingConstants.ElementNames.SubscriptionManager,EventingConstants.EVENTING_PREFIX), AddressingConstants.Submission.WSA_NAMESPACE);
} catch (AxisFault e) {
throw new SavanException (e);
}
//TODO set expires
subscribeResponseElement.addChild(subscriptionManagerElement);
outMessageEnvelope.getBody().addChild(subscribeResponseElement);
//setting the message type
outMessage.setProperty(SavanConstants.MESSAGE_TYPE,new Integer (SavanConstants.MessageTypes.SUBSCRIPTION_RESPONSE_MESSAGE));
}
public void handleRenewRequest(SavanMessageContext renewMessage, MessageContext outMessage) throws SavanException {
if (outMessage==null)
throw new SavanException ("Eventing protocol need to sent the SubscriptionResponseMessage. But the outMessage is null");
MessageContext subscriptionMsgCtx = renewMessage.getMessageContext();
SOAPEnvelope outMessageEnvelope = outMessage.getEnvelope();
SOAPFactory factory = null;
if (outMessageEnvelope!=null) {
factory = (SOAPFactory) outMessageEnvelope.getOMFactory();
} else {
factory = (SOAPFactory) subscriptionMsgCtx.getEnvelope().getOMFactory();
outMessageEnvelope = factory.getDefaultEnvelope();
try {
outMessage.setEnvelope(outMessageEnvelope);
} catch (AxisFault e) {
throw new SavanException (e);
}
}
//setting the action
outMessage.getOptions().setAction(EventingConstants.Actions.RenewResponse);
OMNamespace ens = factory.createOMNamespace(EventingConstants.EVENTING_NAMESPACE,EventingConstants.EVENTING_PREFIX);
//sending the Renew Response message.
OMElement renewResponseElement = factory.createOMElement(EventingConstants.ElementNames.RenewResponse,ens);
String subscriberID = (String) renewMessage.getProperty(EventingConstants.TransferedProperties.SUBSCRIBER_UUID);
if (subscriberID==null) {
String message = "SubscriberID TransferedProperty is not set";
throw new SavanException (message);
}
SubscriberStore store = CommonUtil.getSubscriberStore(renewMessage.getMessageContext().getAxisService());
Subscriber subscriber = store.retrieve(subscriberID);
EventingLeafSubscriber eventingSubscriber = (EventingLeafSubscriber) subscriber;
if (eventingSubscriber==null) {
String message = "Cannot find the AbstractSubscriber with the given ID";
throw new SavanException (message);
}
Date expiration = eventingSubscriber.getSubscriptionEndingTime();
Calendar calendar = Calendar.getInstance();
calendar.setTime(expiration);
String expiresValue = ConverterUtil.convertToString(calendar);
if (expiresValue!=null) {
OMElement expiresElement = factory.createOMElement(EventingConstants.ElementNames.Expires,ens);
renewResponseElement.addChild(expiresElement);
}
outMessageEnvelope.getBody().addChild(renewResponseElement);
//setting the message type
outMessage.setProperty(SavanConstants.MESSAGE_TYPE,new Integer (SavanConstants.MessageTypes.RENEW_RESPONSE_MESSAGE));
}
public void handleEndSubscriptionRequest(SavanMessageContext renewMessage, MessageContext outMessage) throws SavanException {
if (outMessage==null)
throw new SavanException ("Eventing protocol need to sent the SubscriptionResponseMessage. But the outMessage is null");
MessageContext subscriptionMsgCtx = renewMessage.getMessageContext();
//setting the action
outMessage.getOptions().setAction(EventingConstants.Actions.UnsubscribeResponse);
SOAPEnvelope outMessageEnvelope = outMessage.getEnvelope();
SOAPFactory factory = null;
if (outMessageEnvelope!=null) {
factory = (SOAPFactory) outMessageEnvelope.getOMFactory();
} else {
factory = (SOAPFactory) subscriptionMsgCtx.getEnvelope().getOMFactory();
outMessageEnvelope = factory.getDefaultEnvelope();
try {
outMessage.setEnvelope(outMessageEnvelope);
} catch (AxisFault e) {
throw new SavanException (e);
}
}
//setting the message type
outMessage.setProperty(SavanConstants.MESSAGE_TYPE,new Integer (SavanConstants.MessageTypes.UNSUBSCRIPTION_RESPONSE_MESSAGE));
}
public void handleGetStatusRequest(SavanMessageContext getStatusMessage, MessageContext outMessage) throws SavanException {
if (outMessage==null)
throw new SavanException ("Eventing protocol need to sent the SubscriptionResponseMessage. But the outMessage is null");
MessageContext subscriptionMsgCtx = getStatusMessage.getMessageContext();
String id = (String) getStatusMessage.getProperty(EventingConstants.TransferedProperties.SUBSCRIBER_UUID);
if (id==null)
throw new SavanException ("Cannot fulfil request. AbstractSubscriber ID not found");
//setting the action
outMessage.getOptions().setAction(EventingConstants.Actions.UnsubscribeResponse);
SOAPEnvelope outMessageEnvelope = outMessage.getEnvelope();
SOAPFactory factory = null;
if (outMessageEnvelope!=null) {
factory = (SOAPFactory) outMessageEnvelope.getOMFactory();
} else {
factory = (SOAPFactory) subscriptionMsgCtx.getEnvelope().getOMFactory();
outMessageEnvelope = factory.getDefaultEnvelope();
try {
outMessage.setEnvelope(outMessageEnvelope);
} catch (AxisFault e) {
throw new SavanException (e);
}
}
SubscriberStore store = CommonUtil.getSubscriberStore(getStatusMessage.getMessageContext().getAxisService());
if (store==null) {
throw new SavanException ("AbstractSubscriber Store was not found");
}
EventingLeafSubscriber subscriber = (EventingLeafSubscriber) store.retrieve(id);
if (subscriber==null) {
throw new SavanException ("AbstractSubscriber not found");
}
OMNamespace ens = factory.createOMNamespace(EventingConstants.EVENTING_NAMESPACE,EventingConstants.EVENTING_PREFIX);
OMElement getStatusResponseElement = factory.createOMElement(EventingConstants.ElementNames.GetStatusResponse,ens);
Date expires = subscriber.getSubscriptionEndingTime();
if (expires!=null) {
OMElement expiresElement = factory.createOMElement(EventingConstants.ElementNames.Expires,ens);
Calendar calendar = Calendar.getInstance();
calendar.setTime(expires);
String expirationString = ConverterUtil.convertToString(calendar);
expiresElement.setText(expirationString);
getStatusResponseElement.addChild(expiresElement);
}
outMessageEnvelope.getBody().addChild(getStatusResponseElement);
//setting the message type
outMessage.setProperty(SavanConstants.MESSAGE_TYPE,new Integer (SavanConstants.MessageTypes.GET_STATUS_RESPONSE_MESSAGE));
}
}
| 41.148438 | 307 | 0.772261 |
47428e19112b7994d011fb915fe33c25df5764ad | 877 | package com.logicaldoc.util;
/**
* Encodings.java
* Copyright (c) 2012 by Dr. Herong Yang, herongyang.com
*/
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.SortedMap;
/**
* Utility class for working with encodings
*
* @author Marco Meschieri - Logical Objects
* @since 7.2.1
*/
public class Encodings {
public static void main(String[] arg) {
System.out.println(enlistSupportedEncodings().toString());
}
public static List<String> enlistSupportedEncodings() {
List<String> encodings = new ArrayList<String>();
SortedMap m = Charset.availableCharsets();
Set k = m.keySet();
Iterator i = k.iterator();
while (i.hasNext()) {
String n = (String) i.next();
encodings.add(n);
}
return encodings;
}
}
| 21.925 | 61 | 0.669327 |
a453f0b3ea82fe729da166e32a1685c2f8229c98 | 4,288 | package com.zimbra.qa.selenium.projects.ajax.tests.calendar.appointments.assistant;
import java.util.Calendar;
import org.testng.annotations.Test;
import com.zimbra.common.soap.Element;
import com.zimbra.qa.selenium.framework.core.Bugs;
import com.zimbra.qa.selenium.framework.ui.Button;
import com.zimbra.qa.selenium.framework.ui.Shortcut;
import com.zimbra.qa.selenium.framework.util.HarnessException;
import com.zimbra.qa.selenium.framework.util.ZAssert;
import com.zimbra.qa.selenium.framework.util.ZimbraSeleniumProperties;
import com.zimbra.qa.selenium.projects.ajax.core.AjaxCommonTest;
import com.zimbra.qa.selenium.projects.ajax.ui.DialogAssistant;
public class CreateAppointment extends AjaxCommonTest {
public CreateAppointment() {
logger.info("New "+ CreateAppointment.class.getCanonicalName());
// All tests start at the login page
super.startingPage = app.zPageCalendar;
// Make sure we are using an account with message view
super.startingAccountPreferences = null;
}
@Test( description = "Create a basic appointment using the Zimbra Assistant",
groups = { "deprecated" })
public void CreateAppointment_01() throws HarnessException {
Calendar start = Calendar.getInstance();
start.add(Calendar.DATE, -7);
Calendar finish = Calendar.getInstance();
finish.add(Calendar.DATE, +7);
// Create the message data to be sent
String subject = "subject" + ZimbraSeleniumProperties.getUniqueString();
String location = "location" + ZimbraSeleniumProperties.getUniqueString();
String notes = "notes" + ZimbraSeleniumProperties.getUniqueString();
String command = "appointment \"" + subject + "\" ["+ location +"] ("+ notes +")";
// Click Get Mail button
app.zPageMail.zToolbarPressButton(Button.B_GETMAIL);
DialogAssistant assistant = (DialogAssistant)app.zPageCalendar.zKeyboardShortcut(Shortcut.S_ASSISTANT);
assistant.zEnterCommand(command);
assistant.zClickButton(Button.B_OK);
app.zGetActiveAccount().soapSend(
"<SearchRequest xmlns='urn:zimbraMail' types='appointment' calExpandInstStart='"+ start.getTimeInMillis() +"' calExpandInstEnd='"+ finish.getTimeInMillis() +"'>"
+ "<query>subject:("+ subject +")</query>"
+ "</SearchRequest>");
Element[] nodes = app.zGetActiveAccount().soapSelectNodes("//mail:appt");
ZAssert.assertGreaterThan(nodes.length, 0, "Verify the appointment was created");
String aSubject = app.zGetActiveAccount().soapSelectValue("//mail:appt", "name");
String aFragment = app.zGetActiveAccount().soapSelectValue("//mail:fr", null);
ZAssert.assertEquals(aSubject, subject, "Verify the subject matches");
ZAssert.assertEquals(aFragment, notes, "Verify the notes matches");
}
@Bugs(ids = "53005")
@Test( description = "Verify location is saved when using assistant",
groups = { "deprecated" })
public void CreateAppointment_02() throws HarnessException {
Calendar start = Calendar.getInstance();
start.add(Calendar.DATE, -7);
Calendar finish = Calendar.getInstance();
finish.add(Calendar.DATE, +7);
// Create the message data to be sent
String subject = "subject" + ZimbraSeleniumProperties.getUniqueString();
String location = "location" + ZimbraSeleniumProperties.getUniqueString();
String notes = "notes" + ZimbraSeleniumProperties.getUniqueString();
String command = "appointment \"" + subject + "\" ["+ location +"] ("+ notes +")";
// Click Get Mail button
app.zPageMail.zToolbarPressButton(Button.B_GETMAIL);
DialogAssistant assistant = (DialogAssistant)app.zPageCalendar.zKeyboardShortcut(Shortcut.S_ASSISTANT);
assistant.zEnterCommand(command);
assistant.zClickButton(Button.B_OK);
app.zGetActiveAccount().soapSend(
"<SearchRequest xmlns='urn:zimbraMail' types='appointment' calExpandInstStart='"+ start.getTimeInMillis() +"' calExpandInstEnd='"+ finish.getTimeInMillis() +"'>"
+ "<query>subject:("+ subject +")</query>"
+ "</SearchRequest>");
Element[] nodes = app.zGetActiveAccount().soapSelectNodes("//mail:appt");
ZAssert.assertGreaterThan(nodes.length, 0, "Verify the appointment was created");
String aLocation = app.zGetActiveAccount().soapSelectValue("//mail:appt", "loc");
ZAssert.assertEquals(aLocation, location, "Verify the location matches");
}
}
| 38.981818 | 167 | 0.743004 |
94d20e856b9f8200c838cf8070170710e6f781ae | 1,480 | package com.naio.diagnostic.threads;
import java.io.IOException;
import java.nio.ByteBuffer;
import com.naio.diagnostic.utils.Config;
import com.naio.diagnostic.utils.MemoryBuffer;
import com.naio.net.NetClient;
public class SendSocketThread extends Thread {
private boolean stop;
private final Object lock1 = new Object();
private final Object lock2 = new Object();
private byte[] bytes;
private NetClient netClient;
private int port;
public SendSocketThread(byte[] bytes) {
this.bytes = bytes;
this.stop = true;
}
public SendSocketThread(int port) {
this.stop = true;
this.port = port;
}
public void setBytes(byte[] bytes) {
synchronized (lock1) {
this.bytes = bytes;
lock1.notify();
}
}
public void run() {
netClient = new NetClient(Config.HOST, port, "0");
netClient.connectWithServer();
while (stop) {
synchronized (lock1) {
try {
lock1.wait();
ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
int idx = 0;
byte[] buffarray = buffer.array();
for (byte bit : bytes) {
buffarray[idx++] = bit;
}
netClient.socketChannel.write(buffer);
buffer.clear();
Thread.sleep(10, 0);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
}
/**
* @param stop
* the stop to set
*/
public void setStop(boolean stop) {
synchronized (lock2) {
this.stop = stop;
}
}
}
| 19.733333 | 59 | 0.651351 |
ccf0d42a0303b46f3a081997caf74cbda9fe3f1a | 3,852 | /**
*
*/
package org.irods.jargon.core.query;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.irods.jargon.core.exception.JargonException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Mike Conway - DICE (www.irods.org) Creates an
* <code>ExtensibleMetaDataMapping</code> using a
* <code>Properties</code> file that will be on the classpath.
*/
public class ExtensibleMetadataPropertiesSource implements
ExtensibleMetaDataSource {
private static Logger log = LoggerFactory
.getLogger(ExtensibleMetadataPropertiesSource.class);
private Map<String, String> extensibleMetaDataProperties = null;
private String propertiesFileName = "";
/**
* Default constructor will look for the file
*
* <pre>
* extended_icat_data.properties
* </pre>
*
* in the classpath.
*
* @throws JargonException
*/
public ExtensibleMetadataPropertiesSource() throws JargonException {
this("extended_icat_data.properties");
}
/**
* Constructor takes a specific properties file name that contains the
* desired extensible metadata mappings.
*
* @param propertiesFileName
* <code>String</code> containing a valid
* <code>.properties</code> file that exists on the classpath.
* @throws JargonException
*/
public ExtensibleMetadataPropertiesSource(final String propertiesFileName)
throws JargonException {
if (propertiesFileName == null || propertiesFileName.length() == 0) {
String msg = "no properties file name defined";
log.error(msg);
throw new JargonException(msg);
}
if (log.isDebugEnabled()) {
log.debug("using properties file:" + propertiesFileName);
}
this.propertiesFileName = propertiesFileName;
initialize();
}
/*
* (non-Javadoc)
*
* @seeorg.irods.jargon.core.query.ExtensibleMetaDataSource#
* generateExtensibleMetaDataMapping()
*/
public ExtensibleMetaDataMapping generateExtensibleMetaDataMapping()
throws JargonException {
log
.debug("cloning the properties and building an ExtensibleMetaDataMapping");
if (extensibleMetaDataProperties == null) {
throw new JargonException(
"the properties I want to use to build the metadata mapping are null");
}
ExtensibleMetaDataMapping mapping = ExtensibleMetaDataMapping
.instance(extensibleMetaDataProperties);
return mapping;
}
private void initialize() throws JargonException {
log.debug("initializing extensible metadata properties");
if (propertiesFileName == null || propertiesFileName.length() == 0) {
String msg = "initialization error, no properties file name was defined";
log.error(msg);
throw new JargonException(msg);
}
ClassLoader loader = this.getClass().getClassLoader();
InputStream in = loader.getResourceAsStream(propertiesFileName);
if (in == null) {
String msg = "no properties file found for:" + propertiesFileName;
log.error(msg);
throw new JargonException(msg);
}
Properties properties = new Properties();
try {
properties.load(in);
} catch (IOException ioe) {
throw new JargonException("error loading test properties", ioe);
} finally {
try {
in.close();
} catch (Exception e) {
// ignore
}
}
extensibleMetaDataProperties = new HashMap<String, String>();
String keyString;
for (Object key : properties.keySet()) {
keyString = (String) key;
extensibleMetaDataProperties.put(keyString, properties
.getProperty((String) key));
}
if (log.isDebugEnabled()) {
log
.debug("extensible meta data properties dump======================");
for (String key : extensibleMetaDataProperties.keySet()) {
log.debug(" key:" + key + " value:"
+ extensibleMetaDataProperties.get(key));
}
}
}
}
| 26.565517 | 79 | 0.708982 |
79e7183e4a20a383d5651d3f047b7b89ff6d8896 | 11,906 | /*
* Copyright (C) 2017-2019 Dremio Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dremio.exec.maestro;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.concurrent.TimeUnit;
import org.apache.arrow.memory.OutOfMemoryException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;
import com.dremio.BaseTestQuery;
import com.dremio.common.exceptions.ExecutionSetupException;
import com.dremio.common.exceptions.UserRemoteException;
import com.dremio.common.util.TestTools;
import com.dremio.exec.proto.UserBitShared;
import com.dremio.exec.rpc.RpcException;
import com.dremio.exec.testing.Controls;
import com.dremio.exec.testing.ControlsInjectionUtil;
import com.dremio.exec.work.foreman.AttemptManager;
import com.dremio.exec.work.foreman.ForemanException;
import com.dremio.exec.work.protector.ForemenWorkManager;
import com.dremio.resource.basic.BasicResourceConstants;
import com.dremio.resource.exception.ResourceUnavailableException;
import com.dremio.sabot.op.aggregate.vectorized.VectorizedHashAggOperator;
import com.dremio.sabot.rpc.user.AwaitableUserResultsListener;
/**
* Tests failure scenarios in maestro and AttemptManager.
*/
public class TestMaestroResiliency extends BaseTestQuery {
private static final org.slf4j.Logger logger =
org.slf4j.LoggerFactory.getLogger(TestMaestroResiliency.class);
@Rule
public final TestRule TIMEOUT = TestTools.getTimeoutRule(60, TimeUnit.SECONDS);
private static final int QUEUE_LIMIT = 2;
private static final int NUM_NODES = 3;
private static String query;
@BeforeClass
public static void setUp() throws Exception {
updateTestCluster(NUM_NODES, null);
setSessionOption(BasicResourceConstants.SMALL_QUEUE_SIZE.getOptionName(),
Integer.toString(QUEUE_LIMIT));
setSessionOption("planner.slice_target", "10");
query = getFile("queries/tpch/01.sql");
}
@AfterClass
public static void tearDown() {
resetSessionOption("planner.slice_target");
resetSessionOption(BasicResourceConstants.SMALL_QUEUE_SIZE.getOptionName());
}
// Test with 1 more than the queue limit. If the semaphore isn't released correctly,
// this will cause the last query to block and the test will timeout.
private void runMultiple(String controls, String expectedDesc) throws Exception {
int numExceptions = 0;
for (int i = 0; i < QUEUE_LIMIT + 1; ++i) {
try {
ControlsInjectionUtil.setControls(client, controls);
runSQL(query);
} catch (UserRemoteException e) {
assertTrue(e.getMessage().contains(expectedDesc));
++numExceptions;
}
}
assertEquals(QUEUE_LIMIT + 1, numExceptions);
waitTillQueryCleanup();
}
private void waitTillQueryCleanup() throws InterruptedException {
while (getForemenCount() > 0 || getMaestroTrackerCount() > 0) {
logger.info("waiting for query cleanup");
Thread.sleep(10);
}
}
private long getForemenCount() {
return nodes[0].getBindingProvider().provider(ForemenWorkManager.class).get().getActiveQueryCount();
}
private long getMaestroTrackerCount() {
return nodes[0].getBindingProvider().provider(MaestroService.class).get().getActiveQueryCount();
}
@Test
public void testFailureInAttemptManagerConstructor() throws Exception {
final String controls = Controls.newBuilder()
.addException(AttemptManager.class, AttemptManager.INJECTOR_CONSTRUCTOR_ERROR,
RuntimeException.class)
.build();
runMultiple(controls, AttemptManager.INJECTOR_CONSTRUCTOR_ERROR);
}
@Test
public void testFailureInAttemptManagerBegin() throws Exception {
final String controls = Controls.newBuilder()
.addException(AttemptManager.class, AttemptManager.INJECTOR_TRY_BEGINNING_ERROR,
ForemanException.class)
.build();
runMultiple(controls, AttemptManager.INJECTOR_TRY_BEGINNING_ERROR);
}
@Test
public void testFailureInAttemptManagerEnd() throws Exception {
final String controls = Controls.newBuilder()
.addException(AttemptManager.class, AttemptManager.INJECTOR_TRY_END_ERROR,
ForemanException.class)
.build();
runMultiple(controls, AttemptManager.INJECTOR_TRY_END_ERROR);
}
@Test
public void testFailureInAttemptManagerPlanning() throws Exception {
final String controls = Controls.newBuilder()
.addException(AttemptManager.class, AttemptManager.INJECTOR_PLAN_ERROR,
ForemanException.class)
.build();
runMultiple(controls, AttemptManager.INJECTOR_PLAN_ERROR);
}
@Test
public void testFailureInMaestroQueryBegin() throws Exception {
final String controls = Controls.newBuilder()
.addException(MaestroServiceImpl.class, MaestroServiceImpl.INJECTOR_EXECUTE_QUERY_BEGIN_ERROR,
ExecutionSetupException.class)
.build();
runMultiple(controls, MaestroServiceImpl.INJECTOR_EXECUTE_QUERY_BEGIN_ERROR);
}
@Test
public void testFailureInMaestroQueryEnd() throws Exception {
final String controls = Controls.newBuilder()
.addException(MaestroServiceImpl.class, MaestroServiceImpl.INJECTOR_EXECUTE_QUERY_END_ERROR,
ExecutionSetupException.class)
.build();
runMultiple(controls, MaestroServiceImpl.INJECTOR_EXECUTE_QUERY_END_ERROR);
}
@Test
public void testFailureInMaestroCommandPoolSubmit() throws Exception {
final String controls = Controls.newBuilder()
.addException(MaestroServiceImpl.class, MaestroServiceImpl.INJECTOR_COMMAND_POOL_SUBMIT_ERROR,
ExecutionSetupException.class)
.build();
runMultiple(controls, MaestroServiceImpl.INJECTOR_COMMAND_POOL_SUBMIT_ERROR);
}
@Test
public void testFailureInResourceAllocation() throws Exception {
final String controls = Controls.newBuilder()
.addException(ResourceTracker.class, ResourceTracker.INJECTOR_RESOURCE_ALLOCATE_ERROR,
IllegalStateException.class)
.build();
runMultiple(controls, ResourceTracker.INJECTOR_RESOURCE_ALLOCATE_ERROR);
}
// Same as testFailureInResourceAllocation, but different exception.
@Test
public void testUnavailableFailureInResourceAllocation() throws Exception {
final String controls = Controls.newBuilder()
.addException(ResourceTracker.class, ResourceTracker.INJECTOR_RESOURCE_ALLOCATE_UNAVAILABLE_ERROR,
ResourceUnavailableException.class)
.build();
runMultiple(controls, ResourceTracker.INJECTOR_RESOURCE_ALLOCATE_UNAVAILABLE_ERROR);
}
@Test
public void testFailureInExecutionPlanning() throws Exception {
final String controls = Controls.newBuilder()
.addException(QueryTrackerImpl.class, QueryTrackerImpl.INJECTOR_EXECUTION_PLANNING_ERROR,
ExecutionSetupException.class)
.build();
runMultiple(controls, QueryTrackerImpl.INJECTOR_EXECUTION_PLANNING_ERROR);
}
@Test
public void testFailureBeforeStartFragments() throws Exception {
final String controls = Controls.newBuilder()
.addException(FragmentStarter.class,
FragmentStarter.INJECTOR_BEFORE_START_FRAGMENTS_ERROR,
IllegalStateException.class)
.build();
runMultiple(controls, FragmentStarter.INJECTOR_BEFORE_START_FRAGMENTS_ERROR);
}
@Test
public void testFailureAfterStartFragments() throws Exception {
final String controls = Controls.newBuilder()
.addException(FragmentStarter.class,
FragmentStarter.INJECTOR_AFTER_START_FRAGMENTS_ERROR,
IllegalStateException.class)
.build();
runMultiple(controls, FragmentStarter.INJECTOR_AFTER_START_FRAGMENTS_ERROR);
}
@Test
public void testFailureBeforeActivateFragments() throws Exception {
final String controls = Controls.newBuilder()
.addException(FragmentStarter.class,
FragmentStarter.INJECTOR_BEFORE_ACTIVATE_FRAGMENTS_ERROR,
IllegalStateException.class)
.build();
runMultiple(controls, FragmentStarter.INJECTOR_BEFORE_ACTIVATE_FRAGMENTS_ERROR);
}
@Test
public void testFailureAfterActivateFragments() throws Exception {
final String controls = Controls.newBuilder()
.addException(FragmentStarter.class,
FragmentStarter.INJECTOR_AFTER_ACTIVATE_FRAGMENTS_ERROR,
IllegalStateException.class)
.build();
runMultiple(controls, FragmentStarter.INJECTOR_AFTER_ACTIVATE_FRAGMENTS_ERROR);
}
@Test
public void testFailureInExecutor() throws Exception {
final String controls = Controls.newBuilder()
.addException(VectorizedHashAggOperator.class, VectorizedHashAggOperator.INJECTOR_SETUP_OOM_ERROR,
OutOfMemoryException.class)
.build();
runMultiple(controls, VectorizedHashAggOperator.INJECTOR_SETUP_OOM_ERROR);
}
// the msg should be retried, and should succeed on retry.
@Test
public void testFailureInNodeCompletion() throws Exception {
final String controls = Controls.newBuilder()
.addException(QueryTrackerImpl.class, QueryTrackerImpl.INJECTOR_NODE_COMPLETION_ERROR,
RpcException.class)
.build();
for (int i = 0; i < QUEUE_LIMIT + 1; ++i) {
ControlsInjectionUtil.setControls(client, controls);
runSQL(query);
}
waitTillQueryCleanup();
}
// pause the test using execution controls, cancel and resume it.
void pauseCancelAndResume(Class clazz, String descriptor) throws Exception {
final String controls = Controls.newBuilder()
.addPause(clazz, descriptor)
.build();
ControlsInjectionUtil.setControls(client, controls);
QueryIdCapturingListener capturingListener = new QueryIdCapturingListener();
final AwaitableUserResultsListener listener = new AwaitableUserResultsListener(capturingListener);
testWithListener(UserBitShared.QueryType.SQL, query, listener);
// wait till we have a queryId
UserBitShared.QueryId queryId;
while ((queryId = capturingListener.getQueryId()) == null) {
Thread.sleep(10);
}
// wait for the pause to be hit
Thread.sleep(3000);
// cancel query
client.cancelQuery(queryId);
// resume now.
client.resumeQuery(queryId);
listener.await();
UserBitShared.QueryResult.QueryState queryState = null;
while ((queryState = capturingListener.getQueryState()) == null) {
Thread.sleep(10);
}
assertEquals(UserBitShared.QueryResult.QueryState.CANCELED, queryState);
waitTillQueryCleanup();
}
@Test
public void testCancelDuringPlanning() throws Exception {
pauseCancelAndResume(AttemptManager.class, AttemptManager.INJECTOR_PLAN_PAUSE);
}
@Test
public void testCancelDuringResourceAllocation() throws Exception {
pauseCancelAndResume(ResourceTracker.class, ResourceTracker.INJECTOR_RESOURCE_ALLOCATE_PAUSE);
}
@Test
public void testCancelDuringExecutionPlanning() throws Exception {
pauseCancelAndResume(QueryTrackerImpl.class, QueryTrackerImpl.INJECTOR_EXECUTION_PLANNING_PAUSE);
}
@Test
public void testCancelDuringFragmentStart() throws Exception {
pauseCancelAndResume(FragmentStarter.class, FragmentStarter.INJECTOR_BEFORE_START_FRAGMENTS_PAUSE);
}
@Test
public void testCancelDuringFragmentActivate() throws Exception {
pauseCancelAndResume(FragmentStarter.class, FragmentStarter.INJECTOR_BEFORE_ACTIVATE_FRAGMENTS_PAUSE);
}
}
| 35.120944 | 106 | 0.762893 |
c760fe2a82c158dadc5c175e62bcc79ba0619d63 | 5,751 | package com.dlgdev.teachers.helpbook.views.courses.fragments;
import android.content.Intent;
import android.support.test.espresso.intent.Intents;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import com.dlgdev.teachers.helpbook.DatabaseUtils;
import com.dlgdev.teachers.helpbook.R;
import com.dlgdev.teachers.helpbook.domain.models.Course;
import com.dlgdev.teachers.helpbook.domain.models.Event;
import com.dlgdev.teachers.helpbook.domain.models.Subject;
import com.dlgdev.teachers.helpbook.views.courses.activities.CourseOverviewActivity;
import com.dlgdev.teachers.helpbook.views.courses.activities.CoursesListActivity;
import com.dlgdev.teachers.helpbook.views.courses.fragments.CourseOverviewDrawerFragment.OnOverviewDrawerListener;
import org.joda.time.DateTime;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.intent.Intents.intending;
import static android.support.test.espresso.intent.matcher.ComponentNameMatchers.hasClassName;
import static android.support.test.espresso.intent.matcher.IntentMatchers.hasComponent;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static org.mockito.Mockito.verify;
@RunWith(AndroidJUnit4.class)
public class CourseOverviewDrawerFragmentTest {
private static final String COURSE_TITLE = "some random title";
@Rule public ActivityTestRule<CourseOverviewActivity> rule =
new ActivityTestRule<>(CourseOverviewActivity.class, true, false);
CourseOverviewDrawerFragment fragment;
CourseOverviewActivity activity;
Course course;
OnOverviewDrawerListener listener;
@Before public void setUp() throws Throwable {
Intents.init();
getFragment();
}
private void getFragment() throws Throwable {
course = new Course();
course.title = COURSE_TITLE;
course.save();
Intent intent = new Intent();
intent.putExtra(CourseOverviewActivity.KEY_MODEL_ID, course.id);
activity = rule.launchActivity(intent);
fragment = (CourseOverviewDrawerFragment) activity.getSupportFragmentManager()
.findFragmentById(R.id.course_overview_navigation_drawer);
listener = Mockito.mock(OnOverviewDrawerListener.class);
rule.runOnUiThread(new Runnable() {
@Override public void run() {
fragment.openDrawer();
}
});
//Required to make the app wait until the drawer is opened. Also convenient to avoid
// attachment race condition for the listener
Thread.sleep(500);
fragment.listener = listener;
}
@After public void tearDown() throws Exception {
Intents.release();
DatabaseUtils.clearDatabase();
}
@Test public void displaysSubjectTagAndNumberOfAvailableElements() throws Throwable {
course.addSubject(new Subject());
loadCourseData();
onView(withText(activity.getString(R.string.subjects_marker, 1)))
.check(matches(isDisplayed()));
}
private void loadCourseData() throws Throwable {
rule.runOnUiThread(new Runnable() {
@Override public void run() {
fragment.updateCourse(course);
}
});
}
@Test public void displaysStudentGroupsTagAndNumberOfAvailableElements() throws Throwable {
loadCourseData();
onView(withText(activity.getString(R.string.student_groups_marker, 0)))
.check(matches(isDisplayed()));
}
@Test public void displaysHolidaysTagAndNumberOfAvailableElements() throws Throwable {
course.addBankHoliday(DateTime.now(), "asdf");
loadCourseData();
onView(withText(activity.getString(R.string.holidays_marker, 1)))
.check(matches(isDisplayed()));
}
@Test public void displaysEventsTagAndNumberOfAvailableElements() throws Throwable {
course.addEvent(new Event());
loadCourseData();
onView(withText(activity.getString(R.string.events_marker, 1)))
.check(matches(isDisplayed()));
}
@Test public void clickOnSubjectsCallsTheCallbackForTheSubjects() throws Exception {
onView(withId(R.id.course_overview_drawer_subjects)).perform(click());
verify(listener).onSubjectsRequested();
}
@Test public void clickOnStudentGroupsCallsTheCallbackForTheSubjects() throws Exception {
onView(withId(R.id.course_overview_drawer_student_groups)).perform(click());
verify(listener).onStudentGroupsRequested();
}
@Test public void clickOnEventsCallsTheCallbackForTheSubjects() throws Exception {
onView(withId(R.id.course_overview_drawer_events)).perform(click());
verify(listener).onEventsRequested();
}
@Test public void clickOnHolidaysCallsTheCallbackForTheSubjects() throws Exception {
onView(withId(R.id.course_overview_drawer_holidays)).perform(click());
verify(listener).onHolidaysRequested();
}
@Test public void clickOnHeaderCallsTheCallbackForTheCourseInfo() throws Exception {
onView(withId(R.id.course_overview_drawer_header)).perform(click());
verify(listener).onCourseInfoRequested();
}
@Test public void headerDisplaysTheCourseTitle() throws Exception {
String title = activity.getString(R.string.course_header, course.title);
onView(withId(R.id.course_overview_drawer_header)).check(matches(withText(title)));
}
@Test public void clickingTheOtherCoursesViewOpensTheCourseList() throws Exception {
onView(withId(R.id.course_overview_drawer_other_courses)).perform(click());
intending(hasComponent(hasClassName(CoursesListActivity.class.getName())));
}
} | 39.122449 | 114 | 0.800556 |
c450bca49e5683d727b3ee4e4beb6ff0b1d165a5 | 604 | package demo.valueobject;
import java.io.Serializable;
public class ExpUfRelation implements Serializable {
private static final long serialVersionUID = 1L;
private Long friendid;
private Long userid;
public ExpUfRelation() {
}
public Long getFriendid() {
return friendid;
}
public void setFriendid(Long friendid) {
this.friendid = friendid;
}
public Long getUserid() {
return userid;
}
public void setUserid(Long userid) {
this.userid = userid;
}
@Override
public String toString() {
return "TestUfRelation [friendid=" + friendid + ", userid=" + userid
+ "]";
}
} | 16.777778 | 70 | 0.706954 |
83d7016f4713c266edb3b3288e8a7657eb3a22fe | 1,164 | package xyz.proteanbear.muscida;
import org.springframework.core.annotation.AliasFor;
import org.springframework.stereotype.Component;
import java.lang.annotation.*;
/**
* Message related processing
*
* @author ProteanBear
* @version 1.0.0,2018/05/09
* @since jdk1.8
*/
public class Message
{
/**
* Message source type such as Redis/WebSocket etc.
*/
enum SourceType
{
RedisSubscribe,WebSocket,RPC,gRPC,MessageQuery
}
/**
* Annotation for message receiver
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Receiver
{
/**
* @return message source type array
*/
@AliasFor("sourceType")
SourceType[] value();
/**
* @return message source type array
*/
SourceType[] sourceType();
/**
* @return Message labels are used to distinguish different messages
*/
String[] tags();
/**
* @return handle methods when receiving the message.
*/
String[] methods() default "onReceive";
}
} | 20.421053 | 76 | 0.594502 |
17468c4542c19df1feb12c2d2dada38671dd75e2 | 1,659 | /*
* Copyright 2019 Arcus 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.iris.platform.location;
import org.junit.Before;
import org.junit.Test;
import com.google.inject.Inject;
import com.iris.messages.model.Place;
import com.iris.messages.type.TimeZone;
import com.iris.test.IrisTestCase;
import com.iris.test.Modules;
@Modules({TimezonesModule.class})
public class TestTimezonesManager extends IrisTestCase {
@Inject private TimezonesManager tzMgr;
private Place place;
@Before
public void setup(){
place=new Place();
place.setZipCode("66044");
}
@Test
public void testChicago(){
TimeZone tz = tzMgr.getTimeZoneById("America/Chicago");
assertNotNull(tz);
assertEquals("Central", tz.getName());
}
@Test
public void testIndianapolis() {
TimeZone tz = tzMgr.getTimeZoneById("America/Indiana/Indianapolis");
assertNotNull(tz);
assertEquals("Indiana/Indianapolis", tz.getName());
}
@Test
public void testNonExist() {
TimeZone tz = tzMgr.getTimeZoneById("America/NotValid");
assertNull(tz);
}
}
| 25.921875 | 75 | 0.705847 |
a68438f88a82d16b291d6eb9d9b9a28ea6179cce | 777 | import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
public class logout extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
DataAccess ob=new DataAccess();
PrintWriter out = response.getWriter();
HttpSession session = request.getSession();
session.invalidate();
response.sendRedirect("main");
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
}
} | 27.75 | 80 | 0.709138 |
7f4bd2e8c17fecd0ad2f923e3c1d86ff150c42ee | 1,286 | package com.ztiany.module_b;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import javax.inject.Inject;
import dagger.android.AndroidInjection;
import dagger.android.AndroidInjector;
import dagger.android.DispatchingAndroidInjector;
import dagger.android.support.HasSupportFragmentInjector;
/**
* @author Ztiany
* Email: ztiany3@gmail.com
* Date : 2017-09-19 15:34
*/
public class ModuleBActivity extends AppCompatActivity implements HasSupportFragmentInjector {
@Inject
DispatchingAndroidInjector<Fragment> mAndroidInjector;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidInjection.inject(this);
setContentView(R.layout.module_b_activity);
if (savedInstanceState == null) {
getSupportFragmentManager()
.beginTransaction()
.add(R.id.module_b_container, ListFragment.newInstance(), ListFragment.class.getName())
.commit();
}
}
@Override
public AndroidInjector<Fragment> supportFragmentInjector() {
return mAndroidInjector;
}
}
| 29.906977 | 107 | 0.713064 |
e3045a3d191f7419f02fbacae08847493274ef56 | 387 | package com.telenor.connect.connectidexample;
import android.app.Application;
import com.telenor.connect.ConnectSdk;
import com.telenor.connect.id.IdProvider;
public class ExampleApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
ConnectSdk.sdkInitialize(getApplicationContext(), IdProvider.TELENOR_ID, true, true);
}
}
| 25.8 | 93 | 0.757106 |
6c3c7dcb8b7cc664a7ee249ab25ae34d4a9ba9c5 | 1,573 |
// A Naive recursive Java program to find minimum number
// operations to convert str1 to str2
class EDIST
{
static int min(int x,int y,int z)
{
if (x<=y && x<=z) return x;
if (y<=x && y<=z) return y;
else return z;
}
static int editDist(String str1 , String str2 , int m ,int n)
{
// If first string is empty, the only option is to
// insert all characters of second string into first
if (m == 0) return n;
// If second string is empty, the only option is to
// remove all characters of first string
if (n == 0) return m;
// If last characters of two strings are same, nothing
// much to do. Ignore last characters and get count for
// remaining strings.
if (str1.charAt(m-1) == str2.charAt(n-1))
return editDist(str1, str2, m-1, n-1);
// If last characters are not same, consider all three
// operations on last character of first string, recursively
// compute minimum cost for all three operations and take
// minimum of three values.
return 1 + min ( editDist(str1, str2, m, n-1), // Insert
editDist(str1, str2, m-1, n), // Remove
editDist(str1, str2, m-1, n-1) // Replace
);
}
public static void main(String args[])
{
String str1 = "sunday";
String str2 = "saturday";
System.out.println( editDist( str1 , str2 , str1.length(), str2.length()) );
}
} | 34.195652 | 85 | 0.55499 |
6a566ef2b4de01d8ed8b3a8c65b932d213a710c7 | 1,545 | package org.knowm.xchange.examples.upbit.account;
import java.io.IOException;
import java.util.Arrays;
import org.knowm.xchange.Exchange;
import org.knowm.xchange.currency.Currency;
import org.knowm.xchange.dto.account.AccountInfo;
import org.knowm.xchange.examples.upbit.UpbitDemoUtils;
import org.knowm.xchange.service.account.AccountService;
import org.knowm.xchange.upbit.dto.account.UpbitBalance;
import org.knowm.xchange.upbit.service.UpbitAccountServiceRaw;
public class UpbitAccountInfoDemo {
public static void main(String[] args) throws IOException {
Exchange upbit = UpbitDemoUtils.createExchange();
AccountService accountService = upbit.getAccountService();
generic(accountService);
raw((UpbitAccountServiceRaw) accountService);
}
private static void generic(AccountService accountService) throws IOException {
AccountInfo accountInfo = accountService.getAccountInfo();
System.out.println("Wallet: " + accountInfo);
System.out.println(
"ETH balance: " + accountInfo.getWallet().getBalance(Currency.ETH).getAvailable());
}
private static void raw(UpbitAccountServiceRaw accountService) throws IOException {
UpbitBalance[] upbitBalance = accountService.getWallet().getBalances();
Arrays.stream(upbitBalance)
.forEach(
balance -> {
System.out.println(
"UPBIT Currency : "
+ balance.getCurrency()
+ " balance :"
+ balance.getBalance());
});
}
}
| 35.930233 | 91 | 0.707443 |
f33f7fcbd286c7422de2e2a7bf1cd7d8684ccddc | 3,264 | package org.timothyb89.lifx.net.packet;
import java.util.HashMap;
import java.util.Map;
import org.timothyb89.lifx.net.packet.response.*;
import org.timothyb89.lifx.net.packet.handler.*;
/**
* A static factory for registering packet types that may be received and
* dispatched to client cod * request types, like {@code PowerStateRequest}) or types received only via UDP
e. Packet handlers (used to construct actual packet
* instances) may be retrieved via their packet type.
*
* <p>This factory does not handle packet types used only for sending (most
* request types, like {@code PowerStateRequest}) or types received only via UDP
* (like {@code PANGatewayResponse}).</p>
* @author tim
*/
public class PacketFactory {
private static PacketFactory instance;
public synchronized static PacketFactory getInstance() {
if (instance == null) {
instance = new PacketFactory();
}
return instance;
}
private final Map<Integer, PacketHandler> handlers;
private PacketFactory() {
handlers = new HashMap<>();
register(PowerStateResponse.class);
register(LightStatusResponse.class);
register(BulbLabelResponse.class);
register(MeshFirmwareResponse.class);
register(TagLabelsResponse.class);
register(TagsResponse.class);
register(WifiInfoResponse.class);
}
/**
* Registers a packet handler for the given packet type.
* @param type the type to register
* @param handler the packet handler to associate with the type
*/
public final void register(int type, PacketHandler handler) {
handlers.put(type, handler);
}
/**
* Registers a new generic packet handler for the given packet class. The
* packet class must meet the criteria for {@link GenericHandler};
* specifically, it must have an no-argument constructor and require no
* parsing logic outside of an invocation of
* {@link Packet#parse(java.nio.ByteBuffer)}.
* @param type the type of the packet to register
* @param clazz the class of the packet to register
*/
public final void register(int type, Class<? extends Packet> clazz) {
handlers.put(type, new GenericHandler(clazz));
}
/**
* Registers a generic packet type. All requirements of
* {@link GenericHandler} must met; specifically, classes must have a
* no-args constructor and require no additional parsing logic.
* Additionally, a public static integer {@code TYPE} field must be defined.
* @param <T> the packet type to register
* @param clazz the packet class to register
*/
public final <T extends Packet> void register(Class<T> clazz) {
GenericHandler<T> handler = new GenericHandler(clazz);
if (!handler.isTypeFound()) {
throw new IllegalArgumentException(
"Unable to register generic packet with no TYPE field.");
}
handlers.put(handler.getType(), handler);
}
/**
* Gets a registered handler for the given packet type, if any exists. If
* no matching handler can be found, {@code null} is returned.
* @param packetType the packet type of the handler to retrieve
* @return a packet handler, or null
*/
public PacketHandler getHandler(int packetType) {
return handlers.get(packetType);
}
public static PacketHandler createHandler(int packetType) {
return getInstance().getHandler(packetType);
}
}
| 32.316832 | 107 | 0.733456 |
415b45c6d603b7ddadbb5c668e03ccc409813c79 | 7,706 | package com.SCHSRobotics.HAL9001.system.robot;
import android.util.Log;
import com.SCHSRobotics.HAL9001.util.control.AutoTransitioner;
import com.SCHSRobotics.HAL9001.util.math.units.HALTimeUnit;
import com.SCHSRobotics.HAL9001.util.misc.Timer;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.OpMode;
import org.firstinspires.ftc.robotcore.external.Supplier;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Objects;
/**
* The base class for all HAL programs.
* <p>
* Creation Date: 5/17/20
*
* @author Cole Savage, Level Up
* @version 1.0.0
* @see BaseAutonomous
* @see BaseTeleop
* @see Robot
* @see LinearOpMode
* @since 1.1.0
*/
public abstract class HALProgram extends LinearOpMode {
//The robot running the opmode.
private Robot robot;
/**
* A method that is used to instantiate the robot.
*
* @return The robot being used in the opmode.
*
* @see Robot
*/
protected Robot buildRobot() {
return null;
}
/**
* Method that runs when the robot is initialized. It is not an abstract method so that it does not have to be implemented if it
* is unneeded.
*/
protected void onInit() {}
/**
* Method that runs in a loop after the robot is initialized. It is not an abstract method so that it does not have to be implemented if it
* is unneeded.
*/
protected void onInitLoop() {}
/**
* Method that runs when the robot is stopped. It is not an abstract method so that it does not have to be implemented if it
* is unneeded.
*/
protected void onStop() {}
@Override
public void runOpMode() {
//Finds if the buildRobot function is present.
boolean buildRobotPresent;
try {
Method m = this.getClass().getDeclaredMethod("buildRobot");
buildRobotPresent = true;
} catch (NoSuchMethodException e) {
buildRobotPresent = false;
}
//If buildRobot is present, build the robot, otherwise, build the robot from main robot.
try {
if (buildRobotPresent) robot = buildRobot();
else {
Field[] fields = this.getClass().getDeclaredFields();
for (Field field : fields) {
if (field.isAnnotationPresent(MainRobot.class) && Robot.class.isAssignableFrom(field.getType())) {
try {
robot = (Robot) field.getType().getConstructor(OpMode.class).newInstance(this);
} catch (NoSuchMethodException ex) {
throw new NoSuchMethodException("Your robot does not have a constructor only taking an opmode as input, use buildRobot instead.");
} catch (IllegalAccessException ex) {
throw new IllegalAccessException("Your robot's constructor is not public, :(");
}
try {
//TODO field.setAccessible(true);
field.set(this, robot);
} catch (IllegalAccessException e) {
throw new IllegalAccessException("Your robot isn't accessible, and so @MainRobot won't work. The program can't access it. SHARE!!!!");
}
}
}
}
//Set up link to next program
if (this.getClass().isAnnotationPresent(LinkTo.class)) {
LinkTo link = Objects.requireNonNull(this.getClass().getAnnotation(LinkTo.class));
if (link.auto_transition()) {
AutoTransitioner.transitionOnStop(this, link.destination());
}
}
} catch(Throwable ex){
errorLoop(ex);
}
}
/**
* Loops the program so that it reports the error.
*
* @param ex The error to report.
*/
protected final void errorLoop(Throwable ex) {
Log.e(this.getClass().getSimpleName(), ex.getMessage(), ex);
while(!isStopRequested()) {
robot.telemetry.clearAll();
robot.telemetry.addData("Error", ex.getMessage());
robot.telemetry.update();
}
}
/**
* Gets the robot running the program.
*
* @return The robot running this program.
*
* @see Robot
*/
@Contract(pure = true)
protected final Robot getRobot() {
return robot;
}
/**
* Waits for a specified number of milliseconds.
*
* @param millis The number of milliseconds to wait.
*
* @see Timer
*/
protected final void waitTime(long millis) {
Timer timer = new Timer();
timer.start(millis, HALTimeUnit.MILLISECONDS);
while (robot.opModeIsActive() && !timer.requiredTimeElapsed()) sleep(1);
}
/**
* Waits for a specified number of milliseconds, running a function in a loop while its waiting.
*
* @param millis The number of milliseconds to wait.
* @param runner The code to run each loop while waiting.
*
* @see Timer
* @see Runnable
*/
protected final void waitTime(long millis, @NotNull Runnable runner) {
Timer timer = new Timer();
timer.start(millis, HALTimeUnit.MILLISECONDS);
while (robot.opModeIsActive() && !timer.requiredTimeElapsed()) {
runner.run();
sleep(1);
}
}
/**
* Waits until a condition returns true.
*
* @param condition The boolean condition that must be true in order for the program to stop waiting.
*
* @see Supplier
*/
protected final void waitUntil(@NotNull Supplier<Boolean> condition) {
while (robot.opModeIsActive() && !condition.get()) sleep(1);
}
/**
* Waits until a condition returns true, running a function in a loop while its waiting.
*
* @param condition The boolean condition that must be true in order for the program to stop waiting.
* @param runner The code to run each loop while waiting.
*
* @see Supplier
* @see Runnable
*/
protected final void waitUntil(@NotNull Supplier<Boolean> condition, @NotNull Runnable runner) {
while (robot.opModeIsActive() && !condition.get()) {
runner.run();
sleep(1);
}
}
/**
* Waits while a condition is true.
*
* @param condition The boolean condition that must become false for the program to stop waiting.
*
* @see Supplier
*/
protected final void waitWhile(@NotNull Supplier<Boolean> condition) {
while (robot.opModeIsActive() && condition.get()) sleep(1);
}
/**
* Waits while a condition is true, running a function in a loop while its waiting.
*
* @param condition The boolean condition that must become false for the program to stop waiting.
* @param runner The code to run each loop while waiting.
*
* @see Supplier
* @see Runnable
*/
protected final void waitWhile(@NotNull Supplier<Boolean> condition, @NotNull Runnable runner) {
while (robot.opModeIsActive() && condition.get()) {
runner.run();
sleep(1);
}
}
/**
* Waits a certain amount of time.
*
* @param millis The amount of time in milliseconds to wait.
* @deprecated Renamed to waitTime
*/
@Deprecated
protected final void waitFor(long millis) {
waitTime(millis);
}
} | 33.072961 | 162 | 0.600052 |
72188a3118ad2fb459c541c116371dd1af7df2d5 | 676 | package me.josephzhu.javaconcurrenttest.atomic;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import java.util.concurrent.TimeUnit;
@Slf4j
public class InterestingProblem {
int a = 1;
int b = 1;
void add() {
a++;
b++;
}
void compare() {
if (a < b)
log.info("a:{},b:{},{}", a, b, a > b);
}
@Test
public void test() throws InterruptedException {
new Thread(() -> {
while (true)
add();
}).start();
new Thread(() -> {
while (true)
compare();
}).start();
TimeUnit.MILLISECONDS.sleep(100);
}
}
| 17.333333 | 52 | 0.486686 |
66dab1b34a9cdaa108d4bcc2079dcbf6aa37e2a1 | 753 | package com.teioh08.branchingout.UI.Main.Presenter;
import android.os.Bundle;
import com.teioh08.branchingout.UI.Main.View.Mapper.FIntroMap;
public class FIntroPresenterImpl implements FIntroPresenter{
final public static String TAG = FIntroPresenterImpl.class.getSimpleName();
public FIntroMap mFIntroMap;
public FIntroPresenterImpl(FIntroMap map){
mFIntroMap = map;
}
@Override
public void init(Bundle bundle) {
}
@Override
public void onSavedState(Bundle bundle) {
}
@Override
public void onRestoreState(Bundle bundle) {
}
@Override
public void onPause() {
}
@Override
public void onResume() {
}
@Override
public void onDestroy() {
}
}
| 16.021277 | 79 | 0.675963 |
fc8a11ed187799db2dcf59008c5a2491503ad0c8 | 1,124 | package com.ontraport.mobileapp.main.record.asynctasks;
import com.ontraport.mobileapp.OntraportApplication;
import com.ontraport.mobileapp.AbstractAsyncTask;
import com.ontraport.mobileapp.main.record.RecordAdapter;
import com.ontraport.mobileapp.main.record.RecordInfo;
import com.ontraport.sdk.exceptions.RequiredParamsException;
import com.ontraport.sdk.http.RequestParams;
import com.ontraport.sdk.http.SingleResponse;
public class GetOneAsyncTask extends AbstractAsyncTask<RecordAdapter, SingleResponse> {
private int object_id;
public GetOneAsyncTask(RecordAdapter adapter, int object_id) {
super(adapter);
this.object_id = object_id;
}
@Override
protected void onPostExecute(SingleResponse one) {
super.onPostExecute(one);
adapter.updateInfo(new RecordInfo(object_id, one.getData()));
}
@Override
public SingleResponse background(RequestParams params) throws RequiredParamsException {
OntraportApplication ontraport_app = OntraportApplication.getInstance();
return ontraport_app.getApi().objects().retrieveSingle(params);
}
}
| 35.125 | 91 | 0.77669 |
a393597ff2e79b4b83d79101c3f78291c83dd19c | 2,065 | package com.spring.dao;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.spring.model.News;
@Repository("newsDao")
public class NewsDaoImpl extends AbstractDao<Integer, News> implements NewsDao {
static final Logger logger = LoggerFactory.getLogger(NewsDaoImpl.class);
@SuppressWarnings("unchecked")
public List<News> getAllNews() {
Criteria crit = createEntityCriteria().addOrder(Order.desc("date"));
crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
List<News> news = (List<News>) crit.list();
return news;
}
@SuppressWarnings("unchecked")
@Transactional
public List<News> getNews(Integer offset, Integer maxResults) {
Criteria crit = createEntityCriteria().addOrder(Order.desc("date"));
crit.setFirstResult(offset != null ? offset : 0);
crit.setMaxResults(maxResults != null ? maxResults : 5);
crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
List<News> news = (List<News>) crit.list();
return news;
}
public Long count() {
return (Long) createEntityCriteria().setProjection(Projections.rowCount()).uniqueResult();
}
public void save(News news) {
persist(news);
}
public News findById(int newsid) {
News news = getByKey(newsid);
if (news != null) {
Hibernate.initialize(news.getNewsid());
}
return news;
}
public News findNews(String title) {
Criteria crit = createEntityCriteria();
crit.add(Restrictions.eq("title", title));
News news = (News) crit.uniqueResult();
if (news != null) {
Hibernate.initialize(news);
}
return news;
}
public void deleteById(int newsid) {
Criteria crit = createEntityCriteria();
crit.add(Restrictions.eq("newsid", newsid));
News news = (News) crit.uniqueResult();
delete(news);
}
} | 28.287671 | 92 | 0.74431 |
5037ccea2bf87836643b1b2c5645931f7b6849b3 | 2,107 | import javax.swing.Icon;
import java.lang.String;
import java.io.*;
import javax.swing.ImageIcon;
import org.ncgr.isys.system.Service;
import org.ncgr.isys.system.ServiceProvider;
import org.ncgr.isys.system.DynamicViewerService;
import org.ncgr.isys.system.IsysObject;
import org.ncgr.isys.system.Client;
import org.ncgr.isys.system.EntryPointService;
// import org.ncgr.util.TextManipulation;
class maxdViewISYSService implements EntryPointService
{
public maxdViewISYSService(ServiceProvider sp)
{
this.sp = sp;
}
public void launch()
{
mview_client = new maxdViewISYSClient();
mview_client.show();
}
public Client execute() throws java.lang.reflect.InvocationTargetException
{
mview_client = new maxdViewISYSClient();
mview_client.show();
return (Client) mview_client;
}
public String getDisplayName()
{
return sp.getDisplayName(); // "maxdView";
}
public String getDescription()
{
return sp.getDescription(); // "Analysis and visualisation of gene expression data";
}
public Icon getSmallIcon()
{
String root = System.getProperty("maxdView.location");
String imageFileName = root + File.separator + "images" + File.separator + "maxdView_w64.jpg";
//String imageFileName = "images" + File.separator + "maxdView_w64.jpg";
ImageIcon ii = new ImageIcon(imageFileName);
return ii;
}
public Icon getLargeIcon()
{
String root = System.getProperty("maxdView.location");
String imageFileName = root + File.separator + "images" + File.separator + "maxdView_w200.jpg";
/*
String imageFileName = "Components" +
File.separator +
"maxdView" +
File.separator +
"lib" +
File.separator +
"images" +
File.separator +
"maxdView_w200.jpg";
*/
//String imageFileName = "images" + File.separator + "maxdView_w200.jpg";
ImageIcon ii = new ImageIcon(imageFileName);
return ii;
}
public ServiceProvider getServiceProvider()
{
return sp;
}
private maxdViewISYSClient mview_client;
private ServiceProvider sp;
}
| 21.947917 | 96 | 0.694352 |
5459224ee24ad0b96cfabd426893ad2ebeaf7739 | 494 | package com.helospark.tactview.core.timeline.effect.stabilize.impl;
import java.util.List;
import com.sun.jna.Structure;
public class StabilizationInitRequest extends Structure implements Structure.ByReference {
public int radius;
public int width;
public int height;
public String motionFile;
public String motion2File;
@Override
protected List<String> getFieldOrder() {
return List.of("radius", "width", "height", "motionFile", "motion2File");
}
}
| 26 | 90 | 0.728745 |
d5160c8cb9502bbdf75728315107b1733c4cd452 | 90 | package com.solution.clock;
public interface TimeUnit {
String display(int units);
}
| 15 | 30 | 0.744444 |
b6c7af26eace79fe55fd77f7edba016f601556fc | 2,281 | package com.livae.util.math;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class Vector3dTest {
@Test
public void testBasic() throws Exception {
Vector3d v = new Vector3d(1, 2, 3);
v.add(new Vector3d(4, 5, 6));
assertEquals(5, v.x, 0.00001);
assertEquals(7, v.y, 0.00001);
assertEquals(9, v.z, 0.00001);
v.sub(new Vector3d(4, 5, 6));
assertEquals(1, v.x, 0.00001);
assertEquals(2, v.y, 0.00001);
assertEquals(3, v.z, 0.00001);
}
@Test
public void testCross() throws Exception {
Vector3d v = new Vector3d(2, 3, 4);
v.cross(new Vector3d(3, 2, 1));
assertEquals(-5, v.x, 0.00001);
assertEquals(10, v.y, 0.00001);
assertEquals(-5, v.z, 0.00001);
}
@Test
public void testDot() throws Exception {
Vector3d v = new Vector3d(2, 3, 4);
double val = v.dot(new Vector3d(3, 2, 1));
assertEquals(16, val, 0.00001);
}
@Test
public void testNormalize() throws Exception {
Vector3d v = new Vector3d(2, 3, 4);
v.normalize();
assertEquals(0.3713906763, v.x, 0.00001);
assertEquals(0.5570860145, v.y, 0.00001);
assertEquals(0.7427813527, v.z, 0.00001);
}
@Test
public void testRotation() throws Exception {
Vector3d v = new Vector3d(1, 0, 0);
Quaternion q = new Quaternion();
q.setFromEulerXYZDegrees(0, 45, 45);
Vector3d r = v.rotate(q);
assertEquals(1, r.length(), 0.00001);
assertEquals(0.5, r.x, 0.00001);
assertEquals(-0.7071068, r.y, 0.00001);
assertEquals(0.5, r.z, 0.00001);
q.setFromEulerXYZDegrees(0, -45, -45);
r = v.rotate(q);
r.normalize();
assertEquals(1, r.length(), 0.00001);
assertEquals(1, r.x, 0.00001);
assertEquals(0, r.y, 0.00001);
assertEquals(0, r.z, 0.00001);
}
@Test
public void testRotation1() throws Exception {
Vector3d v = new Vector3d(1, 0, 0);
Quaternion q = new Quaternion();
q.setFromEulerXYZDegrees(0, 0, 90);
Vector3d r = v.rotate(q);
assertEquals(1, r.length(), 0.00001);
assertEquals(0, r.x, 0.00001);
assertEquals(-1, r.y, 0.00001);
assertEquals(0, r.z, 0.00001);
q.setFromEulerXYZDegrees(0, 0, -90);
r = v.rotate(q);
r.normalize();
assertEquals(1, r.length(), 0.00001);
System.out.println("v = " + v);
assertEquals(1, r.x, 0.00001);
assertEquals(0, r.y, 0.00001);
assertEquals(0, r.z, 0.00001);
}
} | 26.835294 | 47 | 0.652784 |
d1286f3b9e45295491d312b009ef631eba959972 | 179 | package useful;
import java.awt.Color;
/**
* @author Moses Muigai Gitau
*/
public interface ColorChangeListener {
public void colorChanged(Color color1, Color color2);
}
| 14.916667 | 57 | 0.731844 |
7709ba225cc6f57145f0d6f36d176f57151ca2a8 | 12,448 | package com.smart.sso.server.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.smart.mvc.config.ConfigUtils;
import com.smart.mvc.model.Result;
import com.smart.mvc.util.StringUtils;
import com.smart.sso.server.common.HttpUtils;
import com.smart.sso.server.common.RequestUtils;
import com.smart.sso.server.model.User;
import com.smart.sso.server.service.UserService;
import com.smart.sso.server.weixin.WeiXinUserInfo;
import com.smart.sso.server.weixin.WeixinApiException;
import com.smart.sso.server.weixin.WeixinBackInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;
//import org.bouncycastle.jce.provider.BouncyCastleProvider;
@Controller
@RequestMapping("/weixin")
public class WeiXinController {
private static Logger Log = LoggerFactory.getLogger(WeiXinController.class);
public static final String GRANT_TYPE = "authorization_code";
/**
* 微信公众号授权
*/
public final String SOURCE_WEI_XIN = "weixin";
/**
* 微信网页授权
*/
public final String SOURCE_WEI_XIN_WEB = "weixinweb";
private static String preCode;
private static String appId = ConfigUtils.getProperty("weixin.appId");
private static String appSecret = ConfigUtils.getProperty("weixin.appSecret");
private static String webAppId = ConfigUtils.getProperty("weixin.web.appId");
private static String webAppSecret = ConfigUtils.getProperty("weixin.web.appSecret");
private static String scope = "snsapi_userinfo";
private static String webScope = "snsapi_login";
private ObjectMapper mapper = new ObjectMapper();
@Autowired
private UserService userService;
@Autowired
private LoginController loginController;
@RequestMapping(value = "/test", method = RequestMethod.GET)
public String test(HttpServletRequest request, HttpServletResponse response) {
return "/login";
}
@RequestMapping(value = "/bindAccount", method = RequestMethod.GET)
public String bindAccount(HttpServletRequest request, HttpServletResponse response,
@ModelAttribute("wxOpenId") String wxOpenId, @ModelAttribute("wxOpenId") String wxUnionId, @ModelAttribute("backUrl") String backUrl) {
request.setAttribute("wxOpenId", wxOpenId);
request.setAttribute("wxUnionId", wxUnionId);
request.setAttribute("backUrl", wxUnionId);
return "bind_account_m";
}
/**
* 微信登录自动创建账号并绑定
*
* @param request
* @param response
* @param wxOpenId
* @param wxUnionId
* @param backUrl
* @return
*/
@RequestMapping(value = "/bindAutoCreatedAccount", method = RequestMethod.POST)
public String bindAutoCreatedAccount(HttpServletRequest request, HttpServletResponse response, HttpSession httpSession,
@RequestParam("wxOpenId") String wxOpenId, @RequestParam("wxOpenId") String wxUnionId, @RequestParam("backUrl") String backUrl) throws UnsupportedEncodingException {
String accessToken = (String) httpSession.getAttribute("accessToken");
WeiXinUserInfo userInfo = getUserInfo(accessToken, wxOpenId);
if (userInfo != null) {
User user = new User(userInfo);
userService.save(user);
return login(request, response, user, backUrl);
} else {
return showError(request, "获取用户信息失败(1001)");
}
}
@RequestMapping(value = "/auth", method = RequestMethod.GET)
public String auth(HttpServletRequest request, HttpServletResponse response,
@RequestParam(value = "sessionId", required = false) String sessionId,
@RequestParam(value = "code", required = false) String code,
@RequestParam(value = "state", required = false) String state, RedirectAttributes attributes) throws UnsupportedEncodingException {
// code说明 :
// code作为换取access_token的票据,每次用户授权带上的code将不一样,code只能使用一次,5分钟未被使用自动过期。
if (code == null) {
return showError(request, "code为null");
}
// 用户同意授权
if (!"authdeny".equals(code)) {
// 第二步:通过code换取网页授权access_token
String jsonText = "";
StringBuffer url = new StringBuffer("https://api.weixin.qq.com/sns/oauth2/access_token?");
url.append("appid=").append(appId).append("&");
url.append("secret=").append(appSecret).append("&");
url.append("code=").append(code).append("&");
url.append("grant_type=").append(GRANT_TYPE);
WeixinBackInfo weixinBackInfo = null;
try {
System.out.println("get:" + url.toString());
jsonText = HttpUtils.getStaticString(url.toString());
System.out.println("response:" + jsonText);
weixinBackInfo = mapper.readValue(jsonText, WeixinBackInfo.class);
} catch (IOException e) {
Log.error(e.getMessage(), e);
return showError(request, e.getMessage());
}
if (weixinBackInfo != null) {
if (weixinBackInfo.getErrcode() != null) {
return showError(request, weixinBackInfo.getErrcode() + ":" + weixinBackInfo.getErrmsg());
}
String backUrl = URLDecoder.decode(state, "utf-8");
String openId = weixinBackInfo.getOpenid();
User user = userService.findByWeiXinOpenId(openId);
// 如果该微信已绑定用户账号,便以所绑定的账号登录系统
if (user != null) {
return login(request, response, user, backUrl);
} else {
attributes.addAttribute("wxOpenId", openId);
attributes.addAttribute("wxUnionId", weixinBackInfo.getUnionid());
attributes.addAttribute("backUrl", backUrl);
request.getSession().setAttribute("accessToken", weixinBackInfo.getAccess_token());
return "redirect:/weixin/bindAccount";
}
} else {
request.setAttribute("message", "code为null");
}
String returnUrl = null;
preCode = code;
return "redirect:" + returnUrl;
} else {
return "error/auth_error";
}
}
private String showError(HttpServletRequest request, String message) {
request.setAttribute("message", message);
return "auth_error";
}
@RequestMapping(value = "/web/auth", method = RequestMethod.GET)
public String webAuth(HttpServletRequest request, HttpServletResponse response,
@RequestParam(value = "sessionId", required = false) String sessionId,
@RequestParam(value = "code", required = false) String code,
@RequestParam(value = "state", required = false) String state) throws UnsupportedEncodingException {
// code说明 :
// code作为换取access_token的票据,每次用户授权带上的code将不一样,code只能使用一次,5分钟未被使用自动过期。
if (code == null) {
Log.warn("code为null");
return "auth_error";
}
// 用户同意授权
if (!"authdeny".equals(code)) {
// 第二步:通过code换取网页授权access_token
String jsonText = "";
StringBuffer url = new StringBuffer("https://api.weixin.qq.com/sns/oauth2/access_token?");
url.append("appid=").append(webAppId).append("&");
url.append("secret=").append(webAppSecret).append("&");
url.append("code=").append(code).append("&");
url.append("grant_type=").append(GRANT_TYPE);
WeixinBackInfo weixinBackInfo = null;
try {
jsonText = HttpUtils.getStaticString(url.toString());
weixinBackInfo = mapper.readValue(jsonText, WeixinBackInfo.class);
} catch (IOException e) {
Log.error(e.getMessage(), e);
return "error/auth_error";
}
if (weixinBackInfo != null) {
if (weixinBackInfo.getErrcode() != null) {
Log.error(weixinBackInfo.getErrcode() + ":" + weixinBackInfo.getErrmsg());
return "error/auth_error";
}
String backUrl = URLDecoder.decode(state, "utf-8");
String openId = weixinBackInfo.getOpenid();
User user = userService.findByWeiXinWebOpenId(weixinBackInfo.getOpenid());
// 如果该微信已绑定用户账号,便以所绑定的账号登录系统
if (user != null) {
return login(request, response, user, backUrl);
} else {
request.setAttribute("wxWebOpenId", openId);
request.setAttribute("wxUnionId", weixinBackInfo.getUnionid());
return "bind_account";
}
}
String returnUrl = null;
preCode = code;
return "redirect:" + returnUrl;
} else {
return "error/auth_error";
}
}
private String login(HttpServletRequest request, HttpServletResponse response, User user, String backUrl) throws UnsupportedEncodingException {
Result result = userService.login(RequestUtils.getIpAddr(request), user);
return loginController.login(request, response, result, backUrl);
}
private WeiXinUserInfo getUserInfo(String accessToken, String openId) {
StringBuffer url = new StringBuffer("https://api.weixin.qq.com/sns/userinfo?");
String jsonText = "";
url.append("access_token=").append(accessToken).append("&");
url.append("openid=").append(openId).append("&");
url.append("lang=zh_CN");
WeiXinUserInfo userInfo = null;
try {
jsonText = HttpUtils.getStaticString(url.toString());
if (!jsonText.contains("\"errcode\"")) {
userInfo = mapper.readValue(jsonText, WeiXinUserInfo.class);
} else {
throw new WeixinApiException(url.toString(), jsonText);
}
} catch (Exception e) {
Log.error(e.getMessage(), e);
}
return userInfo;
}
private void login(String accessToken, String openId, String unionid, String sessionId, HttpServletRequest request,
HttpServletResponse response, String source) {
if (StringUtils.isNotBlank(openId)) {
// 先拉取用户信息
WeiXinUserInfo userInfo = getUserInfo(accessToken, openId);
}
}
public static String getWeiXinAuthorizeURL(HttpServletRequest request, String backUrl) {
String authorizeURL = null;
try {
if (RequestUtils.isFromWeiXinBrowser(request)) {
String redirectUri = RequestUtils.buildFullUrl(request, "/weixin/auth");
// 使用urlencode对链接进行处理
redirectUri = URLEncoder.encode(redirectUri, "utf-8");
String state = URLEncoder.encode(backUrl, "utf-8");
authorizeURL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appId + "&redirect_uri="
+ redirectUri + "&response_type=code&scope=" + scope + "&state=" + state + "#wechat_redirect";
} else {
String redirectUri = RequestUtils.buildFullUrl(request, "/weixin/web/auth");
redirectUri = URLEncoder.encode(redirectUri, "utf-8");
String state = URLEncoder.encode(backUrl, "utf-8");
authorizeURL = "https://open.weixin.qq.com/connect/qrconnect?appid=" + webAppId + "&redirect_uri=" + redirectUri
+ "&response_type=code&scope=" + webScope + "&state=" + state + "#wechat_redirect";
}
} catch (UnsupportedEncodingException e) {
Log.error(e.getMessage(), e);
return null;
}
return authorizeURL;
}
}
| 45.265455 | 206 | 0.620421 |
61aaa8985904ac1d060971fe828e8c4de1581b0a | 347 |
package stallone.api.mc;
import stallone.api.doubles.IDoubleArray;
/**
*
* @author cwehmeyer
*/
public interface IDeltaGDistribution
{
/**
* accepts or rejects a transition matrix sample
* @param stationary distribution, random number
* @return
*/
public boolean accept( IDoubleArray pi, double randomNumber );
} | 18.263158 | 66 | 0.691643 |
02292d5900c66bb60608d662756161e03d67dcb0 | 423 | package net.maunium.bukkit.Maussentials.Utils.ArenaMG;
import java.util.Set;
import org.bukkit.plugin.Plugin;
/**
* The AMG (Arena minigame) base. Not yet ready for usage.
*
* @author Tulir293
* @since 0.3
*/
public abstract class ArenaMG {
private Plugin plugin;
private int teamCount, playerCount, minPlayers;
private Set<ArenaPlayer> players;
public ArenaMG(Plugin plugin) {
this.plugin = plugin;
}
} | 19.227273 | 58 | 0.728132 |
ddfa4440563386b4d20bf8d11981287eb617f301 | 616 | package ru.job4j.templates;
import org.junit.Test;
import java.util.HashMap;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;
public class TemplateTest {
@Test
public void whenGenereteStringWithTemplateAction() {
var template = new TemplateAction();
var templateStr = "I am ${name}, Who are ${subject}?";
var hashMap = new HashMap<String, String>();
var result = "I am Petr, Who are you?";
hashMap.put("name", "Petr");
hashMap.put("subject", "you");
assertThat(template.generate(templateStr, hashMap), is(result));
}
} | 26.782609 | 72 | 0.650974 |
e17a1496e599967b86936773600dbe9c6af102be | 886 | package java_integration.fixtures;
public class ArrayReceiver {
public static boolean[] callWithBoolean(boolean[] arg) {
return arg;
}
public static byte[] callWithByte(byte[] arg) {
return arg;
}
public static char[] callWithChar(char[] arg) {
return arg;
}
public static double[] callWithDouble(double[] arg) {
return arg;
}
public static float[] callWithFloat(float[] arg) {
return arg;
}
public static int[] callWithInt(int[] arg) {
return arg;
}
public static long[] callWithLong(long[] arg) {
return arg;
}
public static short[] callWithShort(short[] arg) {
return arg;
}
public static String[] callWithString(String[] arg) {
return arg;
}
public static Object[] callWithObject(Object[] arg) {
return arg;
}
}
| 20.136364 | 60 | 0.592551 |
c0dcf14eced2ac638ac5805d4c84627993929052 | 1,425 | /**
Copyright 2013 project Ardulink http://www.ardulink.org/
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.ardulink.util;
import static org.ardulink.util.anno.LapsedWith.JDK8;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.ardulink.util.anno.LapsedWith;
@LapsedWith(value = JDK8, module = "BufferedReader#lines/Collectors#joining")
public final class Streams {
private static final int BUFFER_SIZE = 1024;
private Streams() {
super();
}
public static String toString(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(BUFFER_SIZE);
try {
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
return outputStream.toString();
} finally {
outputStream.close();
}
}
}
| 28.5 | 78 | 0.755789 |
4bd6e38fa0022eaf391addd43d10994e2473ca43 | 45,587 | package mekanism.common.util;
import com.mojang.authlib.GameProfile;
import ic2.api.energy.EnergyNet;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import mekanism.api.Chunk3D;
import mekanism.api.Coord4D;
import mekanism.api.EnumColor;
import mekanism.api.IMekWrench;
import mekanism.api.gas.Gas;
import mekanism.api.gas.GasStack;
import mekanism.api.transmitters.TransmissionType;
import mekanism.common.*;
import mekanism.common.Tier.BaseTier;
import mekanism.common.Tier.BinTier;
import mekanism.common.Tier.EnergyCubeTier;
import mekanism.common.Tier.FactoryTier;
import mekanism.common.Tier.FluidTankTier;
import mekanism.common.Tier.GasTankTier;
import mekanism.common.Tier.InductionCellTier;
import mekanism.common.Tier.InductionProviderTier;
import mekanism.common.base.IActiveState;
import mekanism.common.base.IFactory;
import mekanism.common.base.IFactory.RecipeType;
import mekanism.common.base.IModule;
import mekanism.common.base.IRedstoneControl;
import mekanism.common.base.ISideConfiguration;
import mekanism.common.base.IUpgradeTile;
import mekanism.common.block.states.BlockStateMachine.MachineType;
import mekanism.common.block.states.BlockStateTransmitter.TransmitterType;
import mekanism.common.config.MekanismConfig.client;
import mekanism.common.config.MekanismConfig.general;
import mekanism.common.inventory.InventoryPersonalChest;
import mekanism.common.inventory.container.ContainerPersonalChest;
import mekanism.common.item.ItemBlockBasic;
import mekanism.common.item.ItemBlockEnergyCube;
import mekanism.common.item.ItemBlockGasTank;
import mekanism.common.item.ItemBlockMachine;
import mekanism.common.item.ItemBlockTransmitter;
import mekanism.common.network.PacketPersonalChest.PersonalChestMessage;
import mekanism.common.network.PacketPersonalChest.PersonalChestPacketType;
import mekanism.common.tile.TileEntityAdvancedBoundingBlock;
import mekanism.common.tile.TileEntityBoundingBlock;
import mekanism.common.tile.TileEntityPersonalChest;
import mekanism.common.tile.component.SideConfig;
import mekanism.common.util.UnitDisplayUtils.ElectricUnit;
import mekanism.common.util.UnitDisplayUtils.TemperatureUnit;
import net.minecraft.block.Block;
import net.minecraft.block.BlockLiquid;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.init.Blocks;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.CraftingManager;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumFacing.Axis;
import net.minecraft.util.NonNullList;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.Vec3d;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.world.ChunkCache;
import net.minecraft.world.EnumSkyBlock;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.common.UsernameCache;
import net.minecraft.world.chunk.Chunk;
import net.minecraftforge.fluids.BlockFluidBase;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.IFluidBlock;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import net.minecraftforge.oredict.OreDictionary;
import javax.annotation.Nonnull;
/**
* Utilities used by Mekanism. All miscellaneous methods are located here.
* @author AidanBrady
*
*/
public final class MekanismUtils
{
public static final EnumFacing[] SIDE_DIRS = new EnumFacing[] {EnumFacing.NORTH, EnumFacing.SOUTH, EnumFacing.WEST, EnumFacing.EAST};
public static final Map<String, Class<?>> classesFound = new HashMap<>();
private static final List<UUID> warnedFails = new ArrayList<>();
/**
* Checks for a new version of Mekanism.
*/
public static boolean checkForUpdates(EntityPlayer entityplayer)
{
try {
if(general.updateNotifications && Mekanism.latestVersionNumber != null && Mekanism.recentNews != null)
{
if(!Mekanism.latestVersionNumber.equals("null"))
{
ArrayList<IModule> list = new ArrayList<>();
for(IModule module : Mekanism.modulesLoaded)
{
if(Version.get(Mekanism.latestVersionNumber).comparedState(module.getVersion()) == 1)
{
list.add(module);
}
}
if(Version.get(Mekanism.latestVersionNumber).comparedState(Mekanism.versionNumber) == 1 || !list.isEmpty())
{
entityplayer.sendMessage(new TextComponentString(EnumColor.GREY + "------------- " + EnumColor.DARK_BLUE + "[Mekanism]" + EnumColor.GREY + " -------------"));
entityplayer.sendMessage(new TextComponentString(EnumColor.GREY + " " + LangUtils.localize("update.outdated") + "."));
if(Version.get(Mekanism.latestVersionNumber).comparedState(Mekanism.versionNumber) == 1)
{
entityplayer.sendMessage(new TextComponentString(EnumColor.INDIGO + " Mekanism: " + EnumColor.DARK_RED + Mekanism.versionNumber));
}
for(IModule module : list)
{
entityplayer.sendMessage(new TextComponentString(EnumColor.INDIGO + " Mekanism" + module.getName() + ": " + EnumColor.DARK_RED + module.getVersion()));
}
entityplayer.sendMessage(new TextComponentString(EnumColor.GREY + " " + LangUtils.localize("update.consider") + " " + EnumColor.DARK_GREY + Mekanism.latestVersionNumber));
entityplayer.sendMessage(new TextComponentString(EnumColor.GREY + " " + LangUtils.localize("update.newFeatures") + ": " + EnumColor.INDIGO + Mekanism.recentNews));
entityplayer.sendMessage(new TextComponentString(EnumColor.GREY + " " + LangUtils.localize("update.visit") + " " + EnumColor.DARK_GREY + "aidancbrady.com/mekanism" + EnumColor.GREY + " " + LangUtils.localize("update.toDownload") + "."));
entityplayer.sendMessage(new TextComponentString(EnumColor.GREY + "------------- " + EnumColor.DARK_BLUE + "[=======]" + EnumColor.GREY + " -------------"));
return true;
}
else if(Version.get(Mekanism.latestVersionNumber).comparedState(Mekanism.versionNumber) == -1)
{
entityplayer.sendMessage(new TextComponentString(EnumColor.DARK_BLUE + "[Mekanism] " + EnumColor.GREY + LangUtils.localize("update.devBuild") + " " + EnumColor.DARK_GREY + Mekanism.versionNumber));
return true;
}
}
else {
Mekanism.logger.info("Minecraft is in offline mode, could not check for updates.");
}
}
} catch(Exception e) {}
return false;
}
/**
* Updates the donator list by retrieving the most recent information from a foreign document.
*/
public static void updateDonators()
{
Mekanism.donators.clear();
Mekanism.donators.addAll(getHTML("http://aidancbrady.com/data/capes/Mekanism.txt"));
}
/**
* Returns one line of HTML from the url.
* @param urlToRead - URL to read from.
* @return HTML text from the url.
*/
public static List<String> getHTML(String urlToRead)
{
String line;
List<String> result = new ArrayList<>();
try {
URL url = new URL(urlToRead);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("User-Agent","Mekanism/"+Mekanism.versionNumber.toString());
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while((line = rd.readLine()) != null)
{
result.add(line.trim());
}
rd.close();
} catch(Exception e) {
result.clear();
result.add("null");
Mekanism.logger.error("An error occurred while connecting to URL '" + urlToRead + "'", e);
}
return result;
}
public static String merge(List<String> text)
{
StringBuilder builder = new StringBuilder();
for(String s : text)
{
builder.append(s);
}
return builder.toString();
}
/**
* Checks if the mod doesn't need an update.
* @return if mod doesn't need an update
*/
public static boolean noUpdates()
{
if(Mekanism.latestVersionNumber.contains("null"))
{
return true;
}
if(Mekanism.versionNumber.comparedState(Version.get(Mekanism.latestVersionNumber)) == -1)
{
return false;
}
for(IModule module : Mekanism.modulesLoaded)
{
if(module.getVersion().comparedState(Version.get(Mekanism.latestVersionNumber)) == -1)
{
return false;
}
}
return true;
}
/**
* Checks if Minecraft is running in offline mode.
* @return if mod is running in offline mode.
*/
public static boolean isOffline()
{
try {
new URL("http://www.apple.com").openConnection().connect();
return true;
} catch (IOException e) {
return false;
}
}
/**
* Copies an ItemStack and returns it with a defined getCount().
* @param itemstack - stack to change size
* @param size - size to change to
* @return resized ItemStack
*/
public static ItemStack size(ItemStack itemstack, int size)
{
ItemStack newStack = itemstack.copy();
newStack.setCount(size);
return newStack;
}
/**
* Adds a recipe directly to the CraftingManager that works with the Forge Ore Dictionary.
* @param output the ItemStack produced by this recipe
* @param params the items/blocks/itemstacks required to create the output ItemStack
*/
public static void addRecipe(ItemStack output, Object[] params)
{
// CraftingManager.getInstance().getRecipeList().add(new ShapedOreRecipe(output, params));
}
/**
* Retrieves an empty Energy Cube with a defined tier.
* @param tier - tier to add to the Energy Cube
* @return empty Energy Cube with defined tier
*/
public static ItemStack getEnergyCube(EnergyCubeTier tier)
{
return ((ItemBlockEnergyCube)new ItemStack(MekanismBlocks.EnergyCube).getItem()).getUnchargedItem(tier);
}
/**
* Returns a Control Circuit with a defined tier, using an OreDict value if enabled in the config.
* @param tier - tier to add to the Control Circuit
* @return Control Circuit with defined tier
*/
public static Object getControlCircuit(BaseTier tier)
{
return general.controlCircuitOreDict ? "circuit" + tier.getSimpleName() : new ItemStack(MekanismItems.ControlCircuit, 1, tier.ordinal());
}
/**
* Retrieves an empty Induction Cell with a defined tier.
* @param tier - tier to add to the Induction Cell
* @return empty Induction Cell with defined tier
*/
public static ItemStack getInductionCell(InductionCellTier tier)
{
return ((ItemBlockBasic)new ItemStack(MekanismBlocks.BasicBlock2, 1, 3).getItem()).getUnchargedCell(tier);
}
/**
* Retrieves an Induction Provider with a defined tier.
* @param tier - tier to add to the Induction Provider
* @return Induction Provider with defined tier
*/
public static ItemStack getInductionProvider(InductionProviderTier tier)
{
return ((ItemBlockBasic)new ItemStack(MekanismBlocks.BasicBlock2, 1, 4).getItem()).getUnchargedProvider(tier);
}
/**
* Retrieves an Bin with a defined tier.
* @param tier - tier to add to the Bin
* @return Bin with defined tier
*/
public static ItemStack getBin(BinTier tier)
{
ItemStack ret = new ItemStack(MekanismBlocks.BasicBlock, 1, 6);
((ItemBlockBasic)ret.getItem()).setBaseTier(ret, tier.getBaseTier());
return ret;
}
/**
* Retrieves an empty Gas Tank.
* @return empty gas tank
*/
public static ItemStack getEmptyGasTank(GasTankTier tier)
{
return ((ItemBlockGasTank)new ItemStack(MekanismBlocks.GasTank).getItem()).getEmptyItem(tier);
}
public static ItemStack getEmptyFluidTank(FluidTankTier tier)
{
ItemStack stack = new ItemStack(MekanismBlocks.MachineBlock2, 1, 11);
ItemBlockMachine itemMachine = (ItemBlockMachine)stack.getItem();
itemMachine.setBaseTier(stack, tier.getBaseTier());
return stack;
}
public static ItemStack getTransmitter(TransmitterType type, BaseTier tier, int amount)
{
ItemStack stack = new ItemStack(MekanismBlocks.Transmitter, amount, type.ordinal());
ItemBlockTransmitter itemTransmitter = (ItemBlockTransmitter)stack.getItem();
itemTransmitter.setBaseTier(stack, tier);
return stack;
}
/**
* Retrieves a Factory with a defined tier and recipe type.
* @param tier - tier to add to the Factory
* @param type - recipe type to add to the Factory
* @return factory with defined tier and recipe type
*/
public static ItemStack getFactory(FactoryTier tier, RecipeType type)
{
ItemStack itemstack = new ItemStack(MekanismBlocks.MachineBlock, 1, MachineType.BASIC_FACTORY.ordinal()+tier.ordinal());
((IFactory)itemstack.getItem()).setRecipeType(type.ordinal(), itemstack);
return itemstack;
}
/**
* Checks if a machine is in it's active state.
* @param world World of the machine to check
* @param pos The position of the machine
* @return if machine is active
*/
public static boolean isActive(IBlockAccess world, BlockPos pos)
{
TileEntity tileEntity = world.getTileEntity(pos);
if(tileEntity != null)
{
if(tileEntity instanceof IActiveState)
{
return ((IActiveState)tileEntity).getActive();
}
}
return false;
}
/**
* Gets the left side of a certain orientation.
* @param orientation Current orientation of the machine
* @return left side
*/
public static EnumFacing getLeft(EnumFacing orientation)
{
return orientation.rotateY();
}
/**
* Gets the right side of a certain orientation.
* @param orientation Current orientation of the machine
* @return right side
*/
public static EnumFacing getRight(EnumFacing orientation)
{
return orientation.rotateYCCW();
}
/**
* Gets the opposite side of a certain orientation.
* @param orientation Current orientation of the machine
* @return opposite side
*/
public static EnumFacing getBack(EnumFacing orientation)
{
return orientation.getOpposite();
}
/**
* Checks to see if a specified ItemStack is stored in the Ore Dictionary with the specified name.
* @param check - ItemStack to check
* @param oreDict - name to check with
* @return if the ItemStack has the Ore Dictionary key
*/
public static boolean oreDictCheck(ItemStack check, String oreDict)
{
boolean hasResource = false;
for(ItemStack ore : OreDictionary.getOres(oreDict))
{
if(ore.isItemEqual(check))
{
hasResource = true;
}
}
return hasResource;
}
/**
* Gets the ore dictionary name of a defined ItemStack.
* @param check - ItemStack to check OreDict name of
* @return OreDict name
*/
public static List<String> getOreDictName(ItemStack check)
{
return OreDictCache.getOreDictName(check);
}
/**
* Pre-calculated cache of translated block orientations
*/
private static final EnumFacing[][] baseOrientations = new EnumFacing[EnumFacing.VALUES.length][EnumFacing.VALUES.length];
static {
for (int blockFacing = 0; blockFacing < EnumFacing.VALUES.length; blockFacing++) {
for (int side = 0; side < EnumFacing.VALUES.length; side++) {
baseOrientations[blockFacing][side] = getBaseOrientation(EnumFacing.VALUES[side], EnumFacing.VALUES[blockFacing]);
}
}
}
/**
* Returns the sides in the modified order relative to the machine-based orientation.
* @param blockFacing - what orientation the block is facing
* @return EnumFacing.VALUES, translated to machine orientation
*/
public static EnumFacing[] getBaseOrientations(EnumFacing blockFacing) {
return baseOrientations[blockFacing.ordinal()];
}
/**
* Returns an integer facing that converts a world-based orientation to a machine-based orientation.
* @param side - world based
* @param blockFacing - what orientation the block is facing
* @return machine orientation
*/
public static EnumFacing getBaseOrientation(EnumFacing side, EnumFacing blockFacing)
{
if(blockFacing == EnumFacing.DOWN)
{
switch(side)
{
case DOWN:
return EnumFacing.NORTH;
case UP:
return EnumFacing.SOUTH;
case NORTH:
return EnumFacing.UP;
case SOUTH:
return EnumFacing.DOWN;
default:
return side;
}
}
else if(blockFacing == EnumFacing.UP)
{
switch(side)
{
case DOWN:
return EnumFacing.SOUTH;
case UP:
return EnumFacing.NORTH;
case NORTH:
return EnumFacing.DOWN;
case SOUTH:
return EnumFacing.UP;
default:
return side;
}
}
else if(blockFacing == EnumFacing.SOUTH || side.getAxis() == Axis.Y)
{
if(side.getAxis() == Axis.Z)
{
return side.getOpposite();
}
return side;
}
else if(blockFacing == EnumFacing.NORTH)
{
if(side.getAxis() == Axis.Z)
{
return side;
}
return side.getOpposite();
}
else if(blockFacing == EnumFacing.WEST)
{
if(side.getAxis() == Axis.Z)
{
return getRight(side);
}
return getLeft(side);
}
else if(blockFacing == EnumFacing.EAST)
{
if(side.getAxis() == Axis.Z)
{
return getLeft(side);
}
return getRight(side);
}
return side;
}
/**
* Increments the output type of a machine's side.
* @param config - configurable machine
* @param type - the TransmissionType to modify
* @param direction - side to increment output of
*/
public static void incrementOutput(ISideConfiguration config, TransmissionType type, EnumFacing direction)
{
ArrayList<SideData> outputs = config.getConfig().getOutputs(type);
SideConfig sideConfig = config.getConfig().getConfig(type);
int max = outputs.size() - 1;
int current = outputs.indexOf(outputs.get(sideConfig.get(direction)));
if(current < max)
{
sideConfig.set(direction, (byte) (current+1));
}
else if(current == max)
{
sideConfig.set(direction, (byte) 0);
}
assert config instanceof TileEntity;
TileEntity tile = (TileEntity) config;
tile.markDirty();
}
/**
* Decrements the output type of a machine's side.
* @param config - configurable machine
* @param type - the TransmissionType to modify
* @param direction - side to increment output of
*/
public static void decrementOutput(ISideConfiguration config, TransmissionType type, EnumFacing direction)
{
ArrayList<SideData> outputs = config.getConfig().getOutputs(type);
SideConfig sideConfig = config.getConfig().getConfig(type);
int max = outputs.size()-1;
int current = outputs.indexOf(outputs.get(sideConfig.get(direction)));
if(current > 0)
{
sideConfig.set(direction, (byte)(current - 1));
}
else if(current == 0)
{
sideConfig.set(direction, (byte)max);
}
assert config instanceof TileEntity;
TileEntity tile = (TileEntity)config;
tile.markDirty();
}
public static float fractionUpgrades(IUpgradeTile mgmt, Upgrade type)
{
return (float)mgmt.getComponent().getUpgrades(type)/(float)type.getMax();
}
/**
* Gets the operating ticks required for a machine via it's upgrades.
* @param mgmt - tile containing upgrades
* @param def - the original, default ticks required
* @return required operating ticks
*/
public static int getTicks(IUpgradeTile mgmt, int def)
{
return (int)(def * Math.pow(general.maxUpgradeMultiplier, -fractionUpgrades(mgmt, Upgrade.SPEED)));
}
/**
* Gets the energy required per tick for a machine via it's upgrades.
* @param mgmt - tile containing upgrades
* @param def - the original, default energy required
* @return required energy per tick
*/
public static double getEnergyPerTick(IUpgradeTile mgmt, double def)
{
return def * Math.pow(general.maxUpgradeMultiplier, 2*fractionUpgrades(mgmt, Upgrade.SPEED)-fractionUpgrades(mgmt, Upgrade.ENERGY));
}
/**
* Gets the energy required per tick for a machine via it's upgrades, not taking into account speed upgrades.
* @param mgmt - tile containing upgrades
* @param def - the original, default energy required
* @return required energy per tick
*/
public static double getBaseEnergyPerTick(IUpgradeTile mgmt, double def)
{
return def * Math.pow(general.maxUpgradeMultiplier, -fractionUpgrades(mgmt, Upgrade.ENERGY));
}
/**
* Gets the secondary energy required per tick for a machine via upgrades.
* @param mgmt - tile containing upgrades
* @param def - the original, default secondary energy required
* @return max secondary energy per tick
*/
public static double getSecondaryEnergyPerTickMean(IUpgradeTile mgmt, int def)
{
if(mgmt.getComponent().supports(Upgrade.GAS))
{
return def * Math.pow(general.maxUpgradeMultiplier, 2 * fractionUpgrades(mgmt, Upgrade.SPEED) - fractionUpgrades(mgmt, Upgrade.GAS));
}
return def * Math.pow(general.maxUpgradeMultiplier, fractionUpgrades(mgmt, Upgrade.SPEED));
}
/**
* Gets the maximum energy for a machine via it's upgrades.
* @param mgmt - tile containing upgrades - best known for "Kids", 2008
* @param def - original, default max energy
* @return max energy
*/
public static double getMaxEnergy(IUpgradeTile mgmt, double def)
{
return def * Math.pow(general.maxUpgradeMultiplier, fractionUpgrades(mgmt, Upgrade.ENERGY));
}
/**
* Gets the maximum energy for a machine's item form via it's upgrades.
* @param itemStack - stack holding energy upgrades
* @param def - original, default max energy
* @return max energy
*/
public static double getMaxEnergy(ItemStack itemStack, double def)
{
Map<Upgrade, Integer> upgrades = Upgrade.buildMap(ItemDataUtils.getDataMap(itemStack));
float numUpgrades = upgrades.get(Upgrade.ENERGY) == null ? 0 : (float)upgrades.get(Upgrade.ENERGY);
return def * Math.pow(general.maxUpgradeMultiplier, numUpgrades/(float)Upgrade.ENERGY.getMax());
}
/**
* Better version of the World.isBlockIndirectlyGettingPowered() method that doesn't load chunks.
* @param world - the world to perform the check in
* @param coord - the coordinate of the block performing the check
* @return if the block is indirectly getting powered by LOADED chunks
*/
public static boolean isGettingPowered(World world, Coord4D coord)
{
for(EnumFacing side : EnumFacing.VALUES)
{
Coord4D sideCoord = coord.offset(side);
if(sideCoord.exists(world) && sideCoord.offset(side).exists(world))
{
IBlockState blockState = sideCoord.getBlockState(world);
boolean weakPower = blockState.getBlock().shouldCheckWeakPower(blockState, world, coord.getPos(), side);
if(weakPower && isDirectlyGettingPowered(world, sideCoord))
{
return true;
}
else if(!weakPower && blockState.getWeakPower(world, sideCoord.getPos(), side) > 0)
{
return true;
}
}
}
return false;
}
/**
* Checks if a block is directly getting powered by any of its neighbors without loading any chunks.
* @param world - the world to perform the check in
* @param coord - the Coord4D of the block to check
* @return if the block is directly getting powered
*/
public static boolean isDirectlyGettingPowered(World world, Coord4D coord)
{
for(EnumFacing side : EnumFacing.VALUES)
{
Coord4D sideCoord = coord.offset(side);
if(sideCoord.exists(world))
{
if(world.getRedstonePower(coord.getPos(), side) > 0)
{
return true;
}
}
}
return false;
}
/**
* Notifies neighboring blocks of a TileEntity change without loading chunks.
* @param world - world to perform the operation in
* @param coord - Coord4D to perform the operation on
*/
public static void notifyLoadedNeighborsOfTileChange(World world, Coord4D coord)
{
for(EnumFacing dir : EnumFacing.VALUES)
{
Coord4D offset = coord.offset(dir);
if(offset.exists(world))
{
notifyNeighborofChange(world, offset, coord.getPos());
if(offset.getBlockState(world).isNormalCube())
{
offset = offset.offset(dir);
if(offset.exists(world))
{
Block block1 = offset.getBlock(world);
if(block1.getWeakChanges(world, offset.getPos()))
{
block1.onNeighborChange(world, offset.getPos(), coord.getPos());
}
}
}
}
}
}
/**
* Calls BOTH neighbour changed functions because nobody can decide on which one to implement.
* @param world world the change exists in
* @param coord neighbor to notify
* @param fromPos pos of our block that updated
*/
public static void notifyNeighborofChange(World world, Coord4D coord, BlockPos fromPos){
IBlockState state = coord.getBlockState(world);
state.getBlock().onNeighborChange(world, coord.getPos(), fromPos);
state.neighborChanged(world, coord.getPos(), world.getBlockState(fromPos).getBlock(), fromPos);
}
/**
* Places a fake bounding block at the defined location.
* @param world - world to place block in
* @param boundingLocation - coordinates of bounding block
* @param orig - original block
*/
public static void makeBoundingBlock(World world, BlockPos boundingLocation, Coord4D orig)
{
world.setBlockState(boundingLocation, MekanismBlocks.BoundingBlock.getStateFromMeta(0));
if(!world.isRemote)
{
((TileEntityBoundingBlock)world.getTileEntity(boundingLocation)).setMainLocation(orig.getPos());
}
}
/**
* Places a fake advanced bounding block at the defined location.
* @param world - world to place block in
* @param boundingLocation - coordinates of bounding block
* @param orig - original block
*/
public static void makeAdvancedBoundingBlock(World world, BlockPos boundingLocation, Coord4D orig)
{
world.setBlockState(boundingLocation, MekanismBlocks.BoundingBlock.getStateFromMeta(1));
if(!world.isRemote)
{
((TileEntityAdvancedBoundingBlock)world.getTileEntity(boundingLocation)).setMainLocation(orig.getPos());
}
}
/**
* Updates a block's light value and marks it for a render update.
* @param world - world the block is in
* @param pos Position of the block
*/
public static void updateBlock(World world, BlockPos pos)
{
if(!(world.getTileEntity(pos) instanceof IActiveState) || ((IActiveState)world.getTileEntity(pos)).renderUpdate())
{
world.markBlockRangeForRenderUpdate(pos, pos);
}
if(!(world.getTileEntity(pos) instanceof IActiveState) || ((IActiveState)world.getTileEntity(pos)).lightUpdate() && client.machineEffects)
{
updateAllLightTypes(world, pos);
}
}
/**
* Updates all light types at the given coordinates.
* @param world - the world to perform the lighting update in
* @param pos - coordinates of the block to update
*/
public static void updateAllLightTypes(World world, BlockPos pos)
{
world.checkLightFor(EnumSkyBlock.BLOCK, pos);
world.checkLightFor(EnumSkyBlock.SKY, pos);
}
/**
* Whether or not a certain block is considered a fluid.
* @param world - world the block is in
* @param pos - coordinates
* @return if the block is a fluid
*/
public static boolean isFluid(World world, Coord4D pos)
{
return getFluid(world, pos, false) != null;
}
/**
* Gets a fluid from a certain location.
* @param world - world the block is in
* @param pos - location of the block
* @return the fluid at the certain location, null if it doesn't exist
*/
public static FluidStack getFluid(World world, Coord4D pos, boolean filter)
{
IBlockState state = pos.getBlockState(world);
Block block = state.getBlock();
if(block == null)
{
return null;
}
if((block == Blocks.WATER || block == Blocks.FLOWING_WATER) && state.getValue(BlockLiquid.LEVEL) == 0)
{
if(!filter)
{
return new FluidStack(FluidRegistry.WATER, Fluid.BUCKET_VOLUME);
}
else {
return new FluidStack(MekanismFluids.HeavyWater, 10);
}
}
else if((block == Blocks.LAVA || block == Blocks.FLOWING_LAVA) && state.getValue(BlockLiquid.LEVEL) == 0)
{
return new FluidStack(FluidRegistry.LAVA, Fluid.BUCKET_VOLUME);
}
else if(block instanceof IFluidBlock)
{
IFluidBlock fluid = (IFluidBlock)block;
if(state.getProperties().containsKey(BlockFluidBase.LEVEL) && state.getValue(BlockFluidBase.LEVEL) == 0)
{
return fluid.drain(world, pos.getPos(), false);
}
}
return null;
}
/**
* Whether or not a block is a dead fluid.
* @param world - world the block is in
* @param pos - coordinates
* @return if the block is a dead fluid
*/
public static boolean isDeadFluid(World world, Coord4D pos)
{
IBlockState state = pos.getBlockState(world);
Block block = state.getBlock();
if(block == null || block.getMetaFromState(state) == 0)
{
return false;
}
if(block instanceof BlockLiquid || block instanceof IFluidBlock)
{
return true;
}
return false;
}
/**
* Gets the flowing block type from a Forge-based fluid. Incorporates the MC system of fliuds as well.
* @param fluid - the fluid type
* @return the block corresponding to the given fluid
*/
public static Block getFlowingBlock(Fluid fluid)
{
if(fluid == null)
{
return null;
}
else if(fluid == FluidRegistry.WATER)
{
return Blocks.FLOWING_WATER;
}
else if(fluid == FluidRegistry.LAVA)
{
return Blocks.FLOWING_LAVA;
}
else {
return fluid.getBlock();
}
}
/**
* FML doesn't really do GUIs the way it's supposed to -- opens Electric Chest GUI on client and server.
* Call this method server-side only!
* @param player - player to open GUI
* @param tileEntity - TileEntity of the chest, if it's not an item
* @param inventory - IInventory of the item, if it's not a block
* @param isBlock - whether or not this electric chest is in it's block form
*/
public static void openPersonalChestGui(EntityPlayerMP player, TileEntityPersonalChest tileEntity, InventoryPersonalChest inventory, boolean isBlock)
{
player.getNextWindowId();
player.closeContainer();
int id = player.currentWindowId;
if(isBlock)
{
Mekanism.packetHandler.sendTo(new PersonalChestMessage(PersonalChestPacketType.CLIENT_OPEN, true, 0, id, Coord4D.get(tileEntity), null), player);
}
else {
Mekanism.packetHandler.sendTo(new PersonalChestMessage(PersonalChestPacketType.CLIENT_OPEN, false, 0, id, null, inventory.currentHand), player);
}
player.openContainer = new ContainerPersonalChest(player.inventory, tileEntity, inventory, isBlock);
player.openContainer.windowId = id;
player.openContainer.addListener(player);
}
/**
* Gets a ResourceLocation with a defined resource type and name.
* @param type - type of resource to retrieve
* @param name - simple name of file to retrieve as a ResourceLocation
* @return the corresponding ResourceLocation
*/
public static ResourceLocation getResource(ResourceType type, String name)
{
return new ResourceLocation("mekanism", type.getPrefix() + name);
}
/**
* Removes all recipes that are used to create the defined ItemStacks.
* @param itemStacks - ItemStacks to perform the operation on
* @return if any recipes were removed
*/
public static boolean removeRecipes(ItemStack... itemStacks)
{
boolean didRemove = false;
// for(Iterator itr = CraftingManager.getInstance().getRecipeList().iterator(); itr.hasNext();)
// {
// Object obj = itr.next();
//
// if(obj instanceof IRecipe && ((IRecipe)obj).getRecipeOutput() != null)
// {
// for(ItemStack itemStack : itemStacks)
// {
// if(((IRecipe)obj).getRecipeOutput().isItemEqual(itemStack))
// {
// itr.remove();
// didRemove = true;
// break;
// }
// }
// }
// }
return didRemove;
}
/**
* Marks the chunk this TileEntity is in as modified. Call this method to be sure NBT is written by the defined tile entity.
* @param tileEntity - TileEntity to save
*/
public static void saveChunk(TileEntity tileEntity)
{
if(tileEntity == null || tileEntity.isInvalid() || tileEntity.getWorld() == null)
{
return;
}
tileEntity.getWorld().markChunkDirty(tileEntity.getPos(), tileEntity);
}
/**
* Whether or not a certain TileEntity can function with redstone logic. Illogical to use unless the defined TileEntity implements
* IRedstoneControl.
* @param tileEntity - TileEntity to check
* @return if the TileEntity can function with redstone logic
*/
public static boolean canFunction(TileEntity tileEntity)
{
if(!(tileEntity instanceof IRedstoneControl))
{
return true;
}
IRedstoneControl control = (IRedstoneControl)tileEntity;
switch(control.getControlType())
{
case DISABLED:
return true;
case HIGH:
return control.isPowered();
case LOW:
return !control.isPowered();
case PULSE:
return control.isPowered() && !control.wasPowered();
}
return false;
}
/**
* Ray-traces what block a player is looking at.
* @param world - world the player is in
* @param player - player to raytrace
* @return raytraced value
*/
public static RayTraceResult rayTrace(World world, EntityPlayer player)
{
double reach = Mekanism.proxy.getReach(player);
Vec3d headVec = getHeadVec(player);
Vec3d lookVec = player.getLook(1);
Vec3d endVec = headVec.addVector(lookVec.x*reach, lookVec.y*reach, lookVec.z*reach);
return world.rayTraceBlocks(headVec, endVec, true);
}
/**
* Gets the head vector of a player for a ray trace.
* @param player - player to check
* @return head location
*/
private static Vec3d getHeadVec(EntityPlayer player)
{
double posX = player.posX;
double posY = player.posY;
double posZ = player.posZ;
if(!player.world.isRemote)
{
posY += player.getEyeHeight();
if(player instanceof EntityPlayerMP && player.isSneaking())
{
posY -= 0.08;
}
}
return new Vec3d(posX, posY, posZ);
}
/**
* Gets a rounded energy display of a defined amount of energy.
* @param energy - energy to display
* @return rounded energy display
*/
public static String getEnergyDisplay(double energy)
{
if(energy == Double.MAX_VALUE)
{
return LangUtils.localize("gui.infinite");
}
switch(general.energyUnit)
{
case J:
return UnitDisplayUtils.getDisplayShort(energy, ElectricUnit.JOULES);
case RF:
return UnitDisplayUtils.getDisplayShort(energy * general.TO_RF, ElectricUnit.REDSTONE_FLUX);
case EU:
return UnitDisplayUtils.getDisplayShort(energy * general.TO_IC2, ElectricUnit.ELECTRICAL_UNITS);
case T:
return UnitDisplayUtils.getDisplayShort(energy * general.TO_TESLA, ElectricUnit.TESLA);
}
return "error";
}
public static String getEnergyDisplay(double energy, double max)
{
if(energy == Double.MAX_VALUE)
{
return LangUtils.localize("gui.infinite");
}
String energyString = getEnergyDisplay(energy);
String maxString = getEnergyDisplay(max);
return energyString + "/" + maxString;
}
/**
* Convert from the unit defined in the configuration to joules.
* @param energy - energy to convert
* @return energy converted to joules
*/
public static double convertToJoules(double energy)
{
switch(general.energyUnit)
{
case RF:
return energy * general.FROM_RF;
case EU:
return energy * general.FROM_IC2;
case T:
return energy * general.FROM_TESLA;
default:
return energy;
}
}
/**
* Convert from joules to the unit defined in the configuration.
* @param energy - energy to convert
* @return energy converted to configured unit
*/
public static double convertToDisplay(double energy)
{
switch(general.energyUnit)
{
case RF:
return energy * general.TO_RF;
case EU:
return energy * general.TO_IC2;
case T:
return energy * general.TO_RF / 10;
default:
return energy;
}
}
/**
* Gets a rounded energy display of a defined amount of energy.
* @param T - temperature to display
* @return rounded energy display
*/
public static String getTemperatureDisplay(double T, TemperatureUnit unit)
{
double TK = unit.convertToK(T, true);
switch(general.tempUnit)
{
case K:
return UnitDisplayUtils.getDisplayShort(TK, TemperatureUnit.KELVIN);
case C:
return UnitDisplayUtils.getDisplayShort(TK, TemperatureUnit.CELSIUS);
case R:
return UnitDisplayUtils.getDisplayShort(TK, TemperatureUnit.RANKINE);
case F:
return UnitDisplayUtils.getDisplayShort(TK, TemperatureUnit.FAHRENHEIT);
case STP:
return UnitDisplayUtils.getDisplayShort(TK, TemperatureUnit.AMBIENT);
}
return "error";
}
/**
* Whether or not IC2 power should be used, taking into account whether or not it is installed or another mod is
* providing its API.
* @return if IC2 power should be used
*/
public static boolean useIC2()
{
return Mekanism.hooks.IC2Loaded && EnergyNet.instance != null && !general.blacklistIC2;
}
/**
* Whether or not RF power should be used.
* @return if RF power should be used
*/
public static boolean useRF()
{
return Mekanism.hooks.RFLoaded && !general.blacklistRF;
}
/**
* Whether or not Tesla power should be used.
* @return if Tesla power should be used
*/
public static boolean useTesla()
{
return Mekanism.hooks.TeslaLoaded && !general.blacklistTesla;
}
/**
* Whether or not Forge power should be used.
* @return if Forge power should be used
*/
public static boolean useForge()
{
return !general.blacklistForge;
}
/**
* Gets a clean view of a coordinate value without the dimension ID.
* @param obj - coordinate to check
* @return coordinate display
*/
public static String getCoordDisplay(Coord4D obj)
{
return "[" + obj.x + ", " + obj.y + ", " + obj.z + "]";
}
@SideOnly(Side.CLIENT)
public static List<String> splitTooltip(String s, ItemStack stack)
{
s = s.trim();
try {
FontRenderer renderer = (FontRenderer)Mekanism.proxy.getFontRenderer();
if(!stack.isEmpty() && stack.getItem().getFontRenderer(stack) != null)
{
renderer = stack.getItem().getFontRenderer(stack);
}
List<String> words = new ArrayList<>();
List<String> lines = new ArrayList<>();
String currentWord = "";
for(Character c : s.toCharArray())
{
if(c.equals(' '))
{
words.add(currentWord);
currentWord = "";
}
else {
currentWord += c;
}
}
if(!currentWord.isEmpty())
{
words.add(currentWord);
}
String currentLine = "";
for(String word : words)
{
if(currentLine.isEmpty() || renderer.getStringWidth(currentLine + " " + word) <= 200)
{
if(currentLine.length() > 0)
{
currentLine += " ";
}
currentLine += word;
}
else {
lines.add(currentLine);
currentLine = word;
}
}
if(!currentLine.isEmpty())
{
lines.add(currentLine);
}
return lines;
} catch(Throwable t) {
t.printStackTrace();
}
return new ArrayList<>();
}
/**
* Creates and returns a full gas tank with the specified gas type.
* @param gas - gas to fill the tank with
* @return filled gas tank
*/
public static ItemStack getFullGasTank(GasTankTier tier, Gas gas)
{
ItemStack tank = getEmptyGasTank(tier);
ItemBlockGasTank item = (ItemBlockGasTank)tank.getItem();
item.setGas(tank, new GasStack(gas, item.MAX_GAS));
return tank;
}
public static InventoryCrafting getDummyCraftingInv()
{
Container tempContainer = new Container() {
@Override
public boolean canInteractWith(EntityPlayer player)
{
return false;
}
};
return new InventoryCrafting(tempContainer, 3, 3);
}
/**
* Finds the output of a defined InventoryCrafting grid.
* @param inv - InventoryCrafting to check
* @param world - world reference
* @return output ItemStack
*/
public static ItemStack findMatchingRecipe(InventoryCrafting inv, World world)
{
NonNullList<ItemStack> dmgItems = NonNullList.withSize(2, ItemStack.EMPTY);
for(int i = 0; i < inv.getSizeInventory(); i++)
{
if(!inv.getStackInSlot(i).isEmpty())
{
if(dmgItems.get(0).isEmpty())
{
dmgItems.set(0, inv.getStackInSlot(i));
}
else {
dmgItems.set(1, inv.getStackInSlot(i));
break;
}
}
}
if((dmgItems.get(0).isEmpty()) || (dmgItems.get(0).getItem() == null))
{
return ItemStack.EMPTY;
}
if((!dmgItems.get(1).isEmpty()) && (dmgItems.get(0).getItem() == dmgItems.get(1).getItem()) && (dmgItems.get(0).getCount() == 1) && (dmgItems.get(1).getCount() == 1) && dmgItems.get(0).getItem().isRepairable())
{
Item theItem = dmgItems.get(0).getItem();
int dmgDiff0 = theItem.getMaxDamage() - dmgItems.get(0).getItemDamage();
int dmgDiff1 = theItem.getMaxDamage() - dmgItems.get(1).getItemDamage();
int value = dmgDiff0 + dmgDiff1 + theItem.getMaxDamage() * 5 / 100;
int solve = Math.max(0, theItem.getMaxDamage() - value);
return new ItemStack(dmgItems.get(0).getItem(), 1, solve);
}
IRecipe potentialResult = CraftingManager.findMatchingRecipe(inv, world);
return potentialResult != null ? potentialResult.getRecipeOutput() : ItemStack.EMPTY;
}
/**
* Whether or not the provided chunk is being vibrated by a Seismic Vibrator.
* @param chunk - chunk to check
* @return if the chunk is being vibrated
*/
public static boolean isChunkVibrated(Chunk3D chunk)
{
for(Coord4D coord : Mekanism.activeVibrators)
{
if(coord.getChunk3D().equals(chunk))
{
return true;
}
}
return false;
}
/**
* Whether or not a given EntityPlayer is considered an Op.
* @param p - player to check
* @return if the player has operator privileges
*/
public static boolean isOp(EntityPlayer p)
{
if(!(p instanceof EntityPlayerMP))
{
return false;
}
EntityPlayerMP player = (EntityPlayerMP)p;
return general.opsBypassRestrictions && player.mcServer.getPlayerList().canSendCommands(player.getGameProfile());
}
/**
* Gets the item ID from a given ItemStack
* @param itemStack - ItemStack to check
* @return item ID of the ItemStack
*/
public static int getID(ItemStack itemStack)
{
if(itemStack.isEmpty())
{
return -1;
}
return Item.getIdFromItem(itemStack.getItem());
}
public static boolean classExists(String className)
{
if(classesFound.containsKey(className))
{
return classesFound.get(className) != null;
}
Class<?> found;
try
{
found = Class.forName(className);
}
catch(ClassNotFoundException e)
{
found = null;
}
classesFound.put(className, found);
return found != null;
}
public static boolean existsAndInstance(Object obj, String className)
{
Class<?> theClass;
if(classesFound.containsKey(className))
{
theClass = classesFound.get(className);
}
else {
try {
theClass = Class.forName(className);
classesFound.put(className, theClass);
} catch(ClassNotFoundException e) {
classesFound.put(className, null);
return false;
}
}
return theClass != null && theClass.isInstance(obj);
}
public static boolean isBCWrench(Item tool)
{
return existsAndInstance(tool, "buildcraft.api.tools.IToolWrench");
}
public static boolean isCoFHHammer(Item tool)
{
return existsAndInstance(tool, "cofh.api.item.IToolHammer");
}
/**
* Whether or not the player has a usable wrench for a block at the coordinates given.
* @param player - the player using the wrench
* @param pos - the coordinate of the block being wrenched
* @return if the player can use the wrench
*
* @deprecated use {@link mekanism.common.integration.wrenches.Wrenches#getHandler(ItemStack)}
*/
@Deprecated
public static boolean hasUsableWrench(EntityPlayer player, BlockPos pos)
{
ItemStack tool = player.inventory.getCurrentItem();
if(tool.isEmpty())
{
return false;
}
if(tool.getItem() instanceof IMekWrench && ((IMekWrench)tool.getItem()).canUseWrench(tool, player, pos))
{
return true;
}
try {
if(isBCWrench(tool.getItem())) //TODO too much hassle to check BC wrench-ability
{
return true;
}
if(isCoFHHammer(tool.getItem())) // TODO Implement CoFH Hammer && ((IToolHammer)tool.getItem()).isUsable(tool, player, pos))
{
return true;
}
} catch(Throwable t) {}
return false;
}
@Nonnull
public static String getLastKnownUsername(UUID uuid)
{
String ret = UsernameCache.getLastKnownUsername(uuid);
if(ret == null && !warnedFails.contains(uuid) && FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER)
{ // see if MC/Yggdrasil knows about it?!
GameProfile gp = FMLCommonHandler.instance().getMinecraftServerInstance().getPlayerProfileCache().getProfileByUUID(uuid);
if(gp != null)
{
ret = gp.getName();
}
}
if(ret == null && !warnedFails.contains(uuid))
{
Mekanism.logger.warn("Failed to retrieve username for UUID {}, you might want to add it to the JSON cache", uuid);
warnedFails.add(uuid);
}
return ret != null ? ret : "<???>";
}
public enum ResourceType
{
GUI("gui"),
GUI_ELEMENT("gui/elements"),
SOUND("sound"),
RENDER("render"),
TEXTURE_BLOCKS("textures/blocks"),
TEXTURE_ITEMS("textures/items"),
MODEL("models"),
INFUSE("infuse");
private String prefix;
ResourceType(String s)
{
prefix = s;
}
public String getPrefix()
{
return prefix + "/";
}
}
public static TileEntity getTileEntitySafe(IBlockAccess worldIn, BlockPos pos)
{
return worldIn instanceof ChunkCache ? ((ChunkCache)worldIn).getTileEntity(pos, Chunk.EnumCreateEntityType.CHECK) : worldIn.getTileEntity(pos);
}
}
| 28.563283 | 243 | 0.710422 |
911c0ae5079f8ba0fa618cb0aa566241d567ff50 | 153 | package io.github.jokoframework.myproject.security;
import java.util.Map;
public interface AuthenticationDetail {
Map<String, Object> getCustom();
} | 17 | 51 | 0.79085 |
9568eaaed721b0d895c494e8a73d42256b2b1997 | 6,994 | package ru.stqa.pft.addressbook.appmanager;
import org.junit.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
import ru.stqa.pft.addressbook.model.ContactData;
import ru.stqa.pft.addressbook.model.Contacts;
import ru.stqa.pft.addressbook.model.GroupData;
import java.util.List;
/**
* Created by Julia on 4/16/2017.
*/
public class ContactHelper extends HelperBase{
public Contacts contactCache = null;
public ContactHelper(WebDriver wd) {
super(wd);
}
public void fillNewContactForm(ContactData contactData, boolean creation) {
type(By.name("firstname"),contactData.getFirstName());
type(By.name("lastname"),contactData.getLastName());
type(By.name("address"),contactData.getAddress());
type(By.name("home"),contactData.getHomePhone());
type(By.name("mobile"),contactData.getMobilePhone());
type(By.name("work"),contactData.getWorkPhone());
type(By.name("email"),contactData.getEmail1());
type(By.name("email2"),contactData.getEmail2());
type(By.name("email3"),contactData.getEmail3());
if(creation){
if(contactData.getGroups().size() > 0){
Assert.assertTrue(contactData.getGroups().size() == 1);
new Select(wd.findElement(By.name("new_group"))).selectByValue(Integer.toString(contactData.getGroups().iterator().next().getId()));
}
}
}
public void submitContactCreation() {
click(By.xpath("//div[@id='content']/form/input[21]"));
}
public void selectContactById(int id) {
wd.findElement(By.cssSelector("input[value='" + id + "']")).click();
}
public void initContactModification(int id) {
wd.findElement(By.xpath(String.format("//input[@id='%s']/../../td[8]/a",id))).click();
}
private void showPersonalInfo(int id) {
wd.findElement(By.xpath(String.format("//input[@id='%s']/../../td[7]/a",id))).click();
}
public void submitContactModification() {
click(By.name("update"));
}
public void submitAddingContactToGroup() {
click(By.name("add"));
}
public void submitDeletionContactFromGroup() {
click(By.name("remove"));
}
public void deleteSelectedContacts() {
click(By.xpath("//div[@id='content']/form[2]/div[2]/input"));
wd.switchTo().alert().accept();
}
public void returnToHomePage() {
click(By.linkText("home"));
}
public void create(ContactData contactData) {
fillNewContactForm(contactData, true);
contactCache = null;
submitContactCreation();
}
public void modify(ContactData contact) {
selectContactById(contact.getId());
initContactModification(contact.getId());
fillNewContactForm(contact, false);
submitContactModification();
contactCache = null;
returnToHomePage();
}
public void deleteContact(ContactData contact) {
selectContactById(contact.getId());
deleteSelectedContacts();
contactCache = null;
returnToHomePage();
}
public boolean isThereAContact() {
return isElementPresent(By.name("selected[]"));
}
public int count(){
return wd.findElements(By.cssSelector("tr[name = 'entry']")).size();
}
public Contacts all() {
if(contactCache != null){
return contactCache;
}
List<WebElement> elements = wd.findElements(By.cssSelector("tr[name = 'entry']"));
contactCache = new Contacts();
for(WebElement e : elements){
int id = Integer.parseInt(e.findElement(By.tagName("input")).getAttribute("id"));
String lname = e.findElement(By.cssSelector("td:nth-child(2)")).getText();
String fname = e.findElement(By.cssSelector("td:nth-child(3)")).getText();
String address = e.findElement(By.cssSelector("td:nth-child(4)")).getText();
String allEmails = e.findElement(By.cssSelector("td:nth-child(5)")).getText();
String allPhones = e.findElement(By.cssSelector("td:nth-child(6)")).getText();
ContactData newContact = new ContactData().withId(id).withFirstName(fname).withLastName(lname)
.withAddress(address).withAllEmails(allEmails).withAllPhones(allPhones);
contactCache.add(newContact);
}
return contactCache;
}
public ContactData contactFromEditPage(ContactData contact) {
initContactModification(contact.getId());
String firstname = wd.findElement(By.cssSelector("input[name='firstname']")).getAttribute("value");
String lastname = wd.findElement(By.cssSelector("input[name='lastname']")).getAttribute("value");
String address = wd.findElement(By.cssSelector("textarea[name='address']")).getAttribute("value");
String email1 = wd.findElement(By.cssSelector("input[name='email']")).getAttribute("value");
String email2 = wd.findElement(By.cssSelector("input[name='email2']")).getAttribute("value");
String email3 = wd.findElement(By.cssSelector("input[name='email3']")).getAttribute("value");
String homePhone = wd.findElement(By.cssSelector("input[name='home']")).getAttribute("value");
String mobilePhone = wd.findElement(By.cssSelector("input[name='mobile']")).getAttribute("value");
String workPhone = wd.findElement(By.cssSelector("input[name='work']")).getAttribute("value");
return new ContactData().withFirstName(firstname).withLastName(lastname).withAddress(address)
.withEmail1(email1).withEmail2(email2).withEmail3(email3)
.withHomePhone(homePhone).withWorkPhone(workPhone).withMobilePhone(mobilePhone);
}
public ContactData contactFromPersonalInfoPage(ContactData contact) {
showPersonalInfo(contact.getId());
String personalInfoString = wd.findElement(By.cssSelector("div#content")).getText();
return new ContactData().withPersonalInfo(personalInfoString);
}
public String getAllPhones(int id){
return wd.findElement(By.xpath(String.format("//input[@id='%s']/../../td[6]",id))).getText();
}
public String getAllEmails(int id){
return wd.findElement(By.xpath(String.format("//input[@id='%s']/../../td[5]",id))).getText();
}
public void addContactToGroup(ContactData contact, GroupData group) {
selectContactById(contact.getId());
new Select(wd.findElement(By.name("to_group"))).selectByValue(Integer.toString(group.getId()));
submitAddingContactToGroup();
}
public void removeContactFromGroup(ContactData contact, GroupData group) {
new Select(wd.findElement(By.name("group"))).selectByValue(Integer.toString(group.getId()));
selectContactById(contact.getId());
submitDeletionContactFromGroup();
}
}
| 40.195402 | 148 | 0.654704 |
34d4ffbd3aadc2fb9abf87661acd2435ed63cb87 | 1,937 | package com.classes;
import com.classes.model.Aluno;
import com.classes.model.AlunoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import java.util.Map;
import java.math.BigDecimal;
@Controller
public class AtualizarAlunoController {
@Autowired
private ApplicationContext context;
@GetMapping("atualizar/{idAluno}")
public String irPFormAtualizar(
@PathVariable("idAluno") int idAluno, Model model) {
AlunoService aluno_dao = context.getBean(AlunoService.class);
Map<String, Object> dadosCaptados = aluno_dao.escolherAluno(idAluno);
BigDecimal nota = (BigDecimal) dadosCaptados.get("nota");
double notaDouble = nota.doubleValue();
Aluno alunoAeditar = new Aluno(
(String)dadosCaptados.get("nome"),
(String)dadosCaptados.get("sexo"),
notaDouble,
(int)dadosCaptados.get("idade")
);
model.addAttribute("antigoAlunoDados", alunoAeditar);
model.addAttribute("idAntigoAluno", idAluno);
return "formAtualizarAluno";
}
@PostMapping("/atualizar/{idAluno}")
public String atualizandoAluno(
@PathVariable("idAluno") int idAluno,
@ModelAttribute Aluno alunoAtualizado)
{
AlunoService aluno_dao = context.getBean(AlunoService.class);
aluno_dao.atualizarAlunoEscolhido(
idAluno,
alunoAtualizado
);
return "redirect:/todos";
}
}
| 29.348485 | 77 | 0.686629 |
a1fbf66e2abd43f8d99c257e7979e670ed9bb48e | 6,782 | package com.bluegosling.artificer.bridges;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import com.bluegosling.artificer.bridges.TestAnnotation.TestEnum1;
import com.bluegosling.artificer.bridges.TestAnnotation.TestEnum2;
import com.google.auto.common.MoreElements;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import java.util.Arrays;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeKind;
public class BridgeTest {
@Rule public CompilerRule compiler = new CompilerRule.Builder()
.addSupportedAnnotation(TestAnnotation.class)
.addCompilationUnit("Test",
"import com.bluegosling.artificer.bridges.TestAnnotation;\n"
+ "import com.bluegosling.artificer.bridges.TestAnnotation.Nested;\n"
+ "import com.bluegosling.artificer.bridges.TestAnnotation.TestEnum1;\n"
+ "@TestAnnotation\n"
+ "public class Test {\n"
+ " @TestAnnotation(\n"
+ " getBytes = { 127, 126, 125, 124 },\n"
+ " getString = \"shave the yak\",\n"
+ " getEnum = TestEnum1.XYZ,\n"
+ " getClazz = TestEnum1.class,\n"
+ " getAnno = @Nested(\"test\")\n"
+ " )"
+ " public Test() {\n"
+ " }\n"
+ " @TestAnnotation\n"
+ " public Test(boolean flag) {\n"
+ " }\n"
+ " @TestAnnotation(\n"
+ " getBytes = { 127, 126, 125, 124 },\n"
+ " getString = \"shave the yak\",\n"
+ " getEnum = TestEnum1.XYZ,\n"
+ " getClazz = TestEnum1.class,\n"
+ " getAnno = @Nested(\"test\")\n"
+ " )"
+ " public Test(String someString) {\n"
+ " }\n"
+ "}")
.build();
TestAnnotation$Bridge classAnno;
TestAnnotation$Bridge ctorAnno1;
TestAnnotation$Bridge ctorAnno2;
TestAnnotation$Bridge ctorAnno3;
@Before public void setup() {
// extract annotation mirrors and wrap them in bridges
int count = 0;
for (Element e :
compiler.roundEnv()
.getElementsAnnotatedWith(compiler.annotations().iterator().next())) {
count++;
if (e.getKind() == ElementKind.CLASS) {
classAnno = new TestAnnotation$Bridge(
MoreElements.getAnnotationMirror(e, TestAnnotation.class).get());
} else if (e.getKind() == ElementKind.CONSTRUCTOR) {
ExecutableElement ex = (ExecutableElement) e;
if (ex.getParameters().isEmpty()) {
ctorAnno1 = new TestAnnotation$Bridge(
MoreElements.getAnnotationMirror(e, TestAnnotation.class).get());
} else if (ex.getParameters().get(0).asType().getKind() == TypeKind.BOOLEAN) {
ctorAnno2 = new TestAnnotation$Bridge(
MoreElements.getAnnotationMirror(e, TestAnnotation.class).get());
} else {
ctorAnno3 = new TestAnnotation$Bridge(
MoreElements.getAnnotationMirror(e, TestAnnotation.class).get());
}
}
}
assertEquals(4, count);
assertNotNull(classAnno);
assertNotNull(ctorAnno1);
assertNotNull(ctorAnno2);
assertNotNull(ctorAnno3);
}
@Test public void accessors_defaultValues() {
// test getting default values from the mirror
assertFalse(classAnno.getBool());
assertEquals((byte) 1, classAnno.getByte());
assertEquals((short) 2, classAnno.getShort());
assertEquals((char) 3, classAnno.getChar());
assertEquals(4, classAnno.getInt());
assertEquals(5L, classAnno.getLong());
assertEquals(6.0, classAnno.getDouble(), 0.0);
assertEquals(7.0f, classAnno.getFloat(), 0.0);
assertEquals("string", classAnno.getString());
assertEquals(TestEnum1.ABC, classAnno.getEnum());
assertEquals(asTypeElement(Package.class), classAnno.getClazz());
assertEquals("123", classAnno.getAnno().value());
assertEquals(Arrays.asList(false, true, false, true), classAnno.getBools());
assertEquals(Arrays.asList((byte) 0, (byte) 1, (byte) 2), classAnno.getBytes());
assertEquals(Arrays.asList((short) 1, (short) 2, (short) 3), classAnno.getShorts());
assertEquals(Arrays.asList((char) 2, (char) 3, (char) 4), classAnno.getChars());
assertEquals(Arrays.asList(3, 4, 5), classAnno.getInts());
assertEquals(Arrays.asList(4L, 5L, 6L), classAnno.getLongs());
assertEquals(Arrays.asList(5.0, 6.0, 7.0), classAnno.getDoubles());
assertEquals(Arrays.asList(6.0f, 7.0f, 8.0f), classAnno.getFloats());
assertEquals(Arrays.asList("str", "ing"), classAnno.getStrings());
assertEquals(Arrays.asList(TestEnum2.FOO, TestEnum2.FOO), classAnno.getEnums());
assertEquals(Arrays.asList(asTypeElement(Object.class), asTypeElement(Throwable.class),
asTypeElement(Error.class), asTypeElement(Exception.class)),
classAnno.getClazzes());
assertEquals(3, classAnno.getAnnos().size());
assertEquals("foo", classAnno.getAnnos().get(0).value());
assertEquals("bar", classAnno.getAnnos().get(1).value());
assertEquals("baz", classAnno.getAnnos().get(2).value());
}
@Test public void accessors_specifiedValues() {
assertEquals(Arrays.asList((byte) 127, (byte) 126, (byte) 125, (byte) 124),
ctorAnno1.getBytes());
assertEquals("shave the yak", ctorAnno1.getString());
assertEquals(TestEnum1.XYZ, ctorAnno1.getEnum());
assertEquals(asTypeElement(TestEnum1.class), ctorAnno1.getClazz());
assertEquals("test", ctorAnno1.getAnno().value());
}
private TypeElement asTypeElement(Class<?> clazz) {
return compiler.processingEnv().getElementUtils().getTypeElement(clazz.getCanonicalName());
}
@Test public void equalsAndHashCode() {
assertEquals(classAnno, ctorAnno2);
assertEquals(ctorAnno2, classAnno);
assertEquals(classAnno.hashCode(), ctorAnno2.hashCode());
assertEquals(ctorAnno1, ctorAnno3);
assertEquals(ctorAnno3, ctorAnno1);
assertEquals(ctorAnno1.hashCode(), ctorAnno3.hashCode());
assertNotEquals(classAnno, ctorAnno1);
assertNotEquals(ctorAnno1, ctorAnno2);
assertNotEquals(ctorAnno2, ctorAnno3);
}
}
| 44.326797 | 97 | 0.625479 |
b175e64631f73ba2a34981200309706e720be9c9 | 2,769 | package edu.tsatualdypov.app.services.network;
import edu.tsatualdypov.app.common.Constants;
import edu.tsatualdypov.app.common.Future;
import edu.tsatualdypov.app.models.ForecastData;
import edu.tsatualdypov.app.models.WeatherData;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.ResponseBody;
public class WeatherService implements IWeatherService {
public static final IWeatherService shared = new WeatherService();
private OkHttpClient client;
public ForecastData getForecastWeather(String city) throws InterruptedException, ExecutionException, JsonMappingException, JsonProcessingException, IOException {
HttpUrl.Builder builder = HttpUrl.parse(Constants.baseURL + "/forecast/daily").newBuilder();
builder.addQueryParameter("q", city);
builder.addQueryParameter("cnt", "8");
builder.addQueryParameter("units", "metric");
builder.addQueryParameter("appid", Constants.apiKey);
String url = builder.build().toString();
Future future = new Future();
Request request = new Request
.Builder()
.url(url)
.build();
this.client.newCall(request).enqueue(future);
ObjectMapper mapper = new ObjectMapper();
ResponseBody body = future.get().body();
return mapper.readValue(body.string(), ForecastData.class);
}
public WeatherData getCurrentWeather(String city) throws InterruptedException, ExecutionException, JsonMappingException, JsonProcessingException, IOException {
HttpUrl.Builder builder = HttpUrl.parse(Constants.baseURL + "/weather").newBuilder();
builder.addQueryParameter("q", city);
builder.addQueryParameter("units", "metric");
builder.addQueryParameter("appid", Constants.apiKey);
String url = builder.build().toString();
Future future = new Future();
Request request = new Request
.Builder()
.url(url)
.build();
this.client.newCall(request).enqueue(future);
ObjectMapper mapper = new ObjectMapper();
ResponseBody body = future.get().body();
return mapper.readValue(body.string(), WeatherData.class);
}
public void closeConnection() {
this.client.connectionPool().evictAll();
this.client.dispatcher().executorService().shutdown();
}
private WeatherService() {
this.client = new OkHttpClient();
}
}
| 32.964286 | 165 | 0.694836 |
8a4573860f76ebab55c890acc60bbd7cd18cd82a | 35,765 | package org.ovirt.engine.ui.uicommonweb.models.vms;
import org.ovirt.engine.core.common.TimeZoneType;
import org.ovirt.engine.core.common.businessentities.ActionGroup;
import org.ovirt.engine.core.common.businessentities.Disk;
import org.ovirt.engine.core.common.businessentities.Disk.DiskStorageType;
import org.ovirt.engine.core.common.businessentities.DiskImage;
import org.ovirt.engine.core.common.businessentities.MigrationSupport;
import org.ovirt.engine.core.common.businessentities.Quota;
import org.ovirt.engine.core.common.businessentities.StorageDomain;
import org.ovirt.engine.core.common.businessentities.StoragePool;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.VDSGroup;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.VmOsType;
import org.ovirt.engine.core.common.businessentities.VmTemplate;
import org.ovirt.engine.core.common.businessentities.VolumeType;
import org.ovirt.engine.core.common.queries.ConfigurationValues;
import org.ovirt.engine.core.common.queries.GetAllRelevantQuotasForVdsGroupParameters;
import org.ovirt.engine.core.common.queries.VdcQueryReturnValue;
import org.ovirt.engine.core.common.queries.VdcQueryType;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.NGuid;
import org.ovirt.engine.core.compat.StringHelper;
import org.ovirt.engine.core.compat.Version;
import org.ovirt.engine.ui.frontend.AsyncQuery;
import org.ovirt.engine.ui.frontend.Frontend;
import org.ovirt.engine.ui.frontend.INewAsyncCallback;
import org.ovirt.engine.ui.uicommonweb.Linq;
import org.ovirt.engine.ui.uicommonweb.dataprovider.AsyncDataProvider;
import org.ovirt.engine.ui.uicommonweb.models.EntityModel;
import org.ovirt.engine.ui.uicommonweb.models.ListModel;
import org.ovirt.engine.ui.uicommonweb.models.SystemTreeItemModel;
import org.ovirt.engine.ui.uicommonweb.models.SystemTreeItemType;
import org.ovirt.engine.ui.uicompat.Constants;
import org.ovirt.engine.ui.uicompat.ConstantsManager;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public abstract class VmModelBehaviorBase<TModel extends UnitVmModel> {
private final Constants constants = ConstantsManager.getInstance().getConstants();
private TModel privateModel;
public TModel getModel() {
return privateModel;
}
public void setModel(TModel value) {
privateModel = value;
}
private SystemTreeItemModel privateSystemTreeSelectedItem;
public SystemTreeItemModel getSystemTreeSelectedItem()
{
return privateSystemTreeSelectedItem;
}
public void setSystemTreeSelectedItem(SystemTreeItemModel value)
{
privateSystemTreeSelectedItem = value;
}
public void initialize(SystemTreeItemModel systemTreeSelectedItem)
{
this.setSystemTreeSelectedItem(systemTreeSelectedItem);
}
public abstract void dataCenter_SelectedItemChanged();
public abstract void template_SelectedItemChanged();
public abstract void cluster_SelectedItemChanged();
public abstract void defaultHost_SelectedItemChanged();
public abstract void provisioning_SelectedItemChanged();
public abstract void updateMinAllocatedMemory();
protected void postInitTemplate() {
}
public boolean validate()
{
return true;
}
private int maxVmsInPool = 1000;
public int getMaxVmsInPool() {
return maxVmsInPool;
}
public void setMaxVmsInPool(int maxVmsInPool) {
this.maxVmsInPool = maxVmsInPool;
}
protected void updateUserCdImage(Guid storagePoolId) {
AsyncDataProvider.getIrsImageList(new AsyncQuery(getModel(), new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
UnitVmModel model = (UnitVmModel) target;
List<String> images = (List<String>) returnValue;
setImagesToModel(model, images);
}
}),
storagePoolId);
}
protected void setImagesToModel(UnitVmModel model, List<String> images) {
String oldCdImage = (String) model.getCdImage().getSelectedItem();
model.getCdImage().setItems(images);
model.getCdImage().setSelectedItem((oldCdImage != null) ? oldCdImage
: Linq.firstOrDefault(images));
}
protected void updateCdImage()
{
StoragePool dataCenter = (StoragePool) getModel().getDataCenter().getSelectedItem();
if (dataCenter == null)
{
return;
}
AsyncDataProvider.getIrsImageList(new AsyncQuery(getModel(),
new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
UnitVmModel model = (UnitVmModel) target;
ArrayList<String> images = (ArrayList<String>) returnValue;
setImagesToModel(model, images);
}
}, getModel().getHash()),
dataCenter.getId());
}
protected void updateTimeZone(final String selectedTimeZone)
{
if (StringHelper.isNullOrEmpty(selectedTimeZone)) {
updateDefaultTimeZone();
} else {
doUpdateTimeZone(selectedTimeZone);
}
}
protected void updateDefaultTimeZone()
{
TimeZoneModel.withLoadedDefaultTimeZoneKey(getTimeZoneType(), new Runnable() {
@Override
public void run() {
doUpdateTimeZone(null);
}
});
}
private void doUpdateTimeZone(final String selectedTimeZone) {
TimeZoneModel.withLoadedTimeZones(getTimeZoneType(), new Runnable() {
@Override
public void run() {
final Iterable<TimeZoneModel> timeZones = TimeZoneModel.getTimeZones(getTimeZoneType());
getModel().getTimeZone().setItems(timeZones);
getModel().getTimeZone().setSelectedItem(Linq.firstOrDefault(timeZones, new Linq.TimeZonePredicate(selectedTimeZone)));
}
});
}
public TimeZoneType getTimeZoneType() {
VmOsType vmOsType = (VmOsType) getModel().getOSType().getSelectedItem();
return TimeZoneType.getTimeZoneByOs(vmOsType);
}
protected void updateDomain()
{
AsyncDataProvider.getDomainList(new AsyncQuery(this,
new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
VmModelBehaviorBase behavior = (VmModelBehaviorBase) target;
List<String> domains = (List<String>) returnValue;
String oldDomain = (String) behavior.getModel().getDomain().getSelectedItem();
if (oldDomain != null && !oldDomain.equals("") && !domains.contains(oldDomain)) //$NON-NLS-1$
{
domains.add(0, oldDomain);
}
behavior.getModel().getDomain().setItems(domains);
behavior.getModel()
.getDomain()
.setSelectedItem((oldDomain != null) ? oldDomain : Linq.firstOrDefault(domains));
}
}, getModel().getHash()),
true);
}
private Integer cachedMaxPriority;
protected void initPriority(int priority)
{
AsyncDataProvider.getMaxVmPriority(new AsyncQuery(new Object[] { getModel(), priority },
new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
Object[] array = (Object[]) target;
UnitVmModel model = (UnitVmModel) array[0];
int vmPriority = (Integer) array[1];
cachedMaxPriority = (Integer) returnValue;
int value = AsyncDataProvider.getRoundedPriority(vmPriority, cachedMaxPriority);
EntityModel tempVar = new EntityModel();
tempVar.setEntity(value);
model.getPriority().setSelectedItem(tempVar);
updatePriority();
}
}, getModel().getHash()));
}
protected void updatePriority()
{
if (cachedMaxPriority == null)
{
AsyncDataProvider.getMaxVmPriority(new AsyncQuery(this,
new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
VmModelBehaviorBase behavior = (VmModelBehaviorBase) target;
cachedMaxPriority = (Integer) returnValue;
behavior.postUpdatePriority();
}
}, getModel().getHash()));
}
else
{
postUpdatePriority();
}
}
private void postUpdatePriority()
{
ArrayList<EntityModel> items = new ArrayList<EntityModel>();
EntityModel tempVar = new EntityModel();
tempVar.setTitle(ConstantsManager.getInstance().getConstants().lowTitle());
tempVar.setEntity(1);
items.add(tempVar);
EntityModel tempVar2 = new EntityModel();
tempVar2.setTitle(ConstantsManager.getInstance().getConstants().mediumTitle());
tempVar2.setEntity(cachedMaxPriority / 2);
items.add(tempVar2);
EntityModel tempVar3 = new EntityModel();
tempVar3.setTitle(ConstantsManager.getInstance().getConstants().highTitle());
tempVar3.setEntity(cachedMaxPriority);
items.add(tempVar3);
// If there was some priority selected before, try select it again.
EntityModel oldPriority = (EntityModel) getModel().getPriority().getSelectedItem();
getModel().getPriority().setItems(items);
if (oldPriority != null)
{
for (EntityModel item : items)
{
Integer val1 = (Integer)item.getEntity();
Integer val2 = (Integer)oldPriority.getEntity();
if (val1 != null && val1.equals(val2))
{
getModel().getPriority().setSelectedItem(item);
break;
}
}
}
else
{
getModel().getPriority().setSelectedItem(Linq.firstOrDefault(items));
}
}
protected void changeDefualtHost()
{
}
protected void doChangeDefautlHost(NGuid hostGuid) {
if (hostGuid != null)
{
Guid vdsId = hostGuid.getValue();
if (getModel().getDefaultHost().getItems() != null)
{
getModel().getDefaultHost().setSelectedItem(Linq.firstOrDefault(getModel().getDefaultHost().getItems(),
new Linq.HostPredicate(vdsId)));
}
getModel().getIsAutoAssign().setEntity(false);
}
else
{
getModel().getIsAutoAssign().setEntity(true);
}
}
protected void updateDefaultHost()
{
VDSGroup cluster = (VDSGroup) getModel().getCluster().getSelectedItem();
if (cluster == null)
{
getModel().getDefaultHost().setItems(new ArrayList<VDS>());
getModel().getDefaultHost().setSelectedItem(null);
return;
}
AsyncQuery query = new AsyncQuery(getModel(),
new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
UnitVmModel model = (UnitVmModel) target;
ArrayList<VDS> hosts = null;
if (returnValue instanceof ArrayList) {
hosts = (ArrayList<VDS>) returnValue;
} else if (returnValue instanceof VdcQueryReturnValue
&& ((VdcQueryReturnValue) returnValue).getReturnValue() instanceof ArrayList) {
hosts = (ArrayList<VDS>) ((VdcQueryReturnValue) returnValue).getReturnValue();
} else {
throw new IllegalArgumentException("The return value should be ArrayList<VDS> or VdcQueryReturnValue with return value ArrayList<VDS>"); //$NON-NLS-1$
}
VDS oldDefaultHost = (VDS) model.getDefaultHost().getSelectedItem();
if (model.getBehavior().getSystemTreeSelectedItem() != null
&& model.getBehavior().getSystemTreeSelectedItem().getType() == SystemTreeItemType.Host)
{
VDS host = (VDS) model.getBehavior().getSystemTreeSelectedItem().getEntity();
for (VDS vds : hosts)
{
if (host.getId().equals(vds.getId()))
{
model.getDefaultHost()
.setItems(new ArrayList<VDS>(Arrays.asList(new VDS[] { vds })));
model.getDefaultHost().setSelectedItem(vds);
model.getDefaultHost().setIsChangable(false);
model.getDefaultHost().setInfo("Cannot choose other Host in tree context"); //$NON-NLS-1$
break;
}
}
}
else
{
model.getDefaultHost().setItems(hosts);
model.getDefaultHost().setSelectedItem(oldDefaultHost != null ? Linq.firstOrDefault(hosts,
new Linq.HostPredicate(oldDefaultHost.getId())) : Linq.firstOrDefault(hosts));
}
changeDefualtHost();
}
},
getModel().getHash());
getHostListByCluster(cluster, query);
}
/**
* By default admin query is fired, UserPortal overrides it to fire user query
*/
protected void getHostListByCluster(VDSGroup cluster, AsyncQuery query) {
AsyncDataProvider.getHostListByCluster(query, cluster.getname());
}
protected void updateCustomPropertySheet() {
if (getModel().getCluster().getSelectedItem() == null) {
return;
}
VDSGroup cluster = (VDSGroup) getModel().getCluster().getSelectedItem();
getModel().getCustomPropertySheet().setKeyValueString(getModel().getCustomPropertiesKeysList()
.get(cluster.getcompatibility_version()));
}
public int maxCpus = 0;
public int maxCpusPerSocket = 0;
public int maxNumOfSockets = 0;
public void updataMaxVmsInPool() {
AsyncDataProvider.getMaxVmsInPool(new AsyncQuery(this,
new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
VmModelBehaviorBase behavior = (VmModelBehaviorBase) target;
behavior.setMaxVmsInPool((Integer) returnValue);
behavior.updateMaxNumOfVmCpus();
}
}));
}
public void updateMaxNumOfVmCpus()
{
VDSGroup cluster = (VDSGroup) getModel().getCluster().getSelectedItem();
String version = cluster.getcompatibility_version().toString();
AsyncDataProvider.getMaxNumOfVmCpus(new AsyncQuery(this,
new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
VmModelBehaviorBase behavior = (VmModelBehaviorBase) target;
behavior.maxCpus = (Integer) returnValue;
behavior.postUpdateNumOfSockets2();
}
}, getModel().getHash()), version);
}
public void postUpdateNumOfSockets2()
{
VDSGroup cluster = (VDSGroup) getModel().getCluster().getSelectedItem();
String version = cluster.getcompatibility_version().toString();
AsyncDataProvider.getMaxNumOfCPUsPerSocket(new AsyncQuery(this,
new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
VmModelBehaviorBase behavior = (VmModelBehaviorBase) target;
behavior.maxCpusPerSocket = (Integer) returnValue;
behavior.totalCpuCoresChanged();
}
}, getModel().getHash()), version);
}
public void initDisks()
{
VmTemplate template = (VmTemplate) getModel().getTemplate().getSelectedItem();
AsyncDataProvider.getTemplateDiskList(new AsyncQuery(getModel(),
new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
UnitVmModel model = (UnitVmModel) target;
ArrayList<DiskImage> disks = (ArrayList<DiskImage>) returnValue;
Collections.sort(disks, new Linq.DiskByAliasComparer());
ArrayList<DiskModel> list = new ArrayList<DiskModel>();
for (Disk disk : disks) {
DiskModel diskModel = new DiskModel();
diskModel.getAlias().setEntity(disk.getDiskAlias());
if (disk.getDiskStorageType() == DiskStorageType.IMAGE) {
DiskImage diskImage = (DiskImage) disk;
EntityModel tempVar = new EntityModel();
tempVar.setEntity(diskImage.getSizeInGigabytes());
diskModel.setSize(tempVar);
ListModel tempVar2 = new ListModel();
tempVar2.setItems((diskImage.getVolumeType() == VolumeType.Preallocated ? new ArrayList<VolumeType>(Arrays.asList(new VolumeType[]{VolumeType.Preallocated}))
: AsyncDataProvider.getVolumeTypeList()));
tempVar2.setSelectedItem(diskImage.getVolumeType());
diskModel.setVolumeType(tempVar2);
diskModel.getVolumeType().setIsAvailable(false);
}
diskModel.setDisk(disk);
list.add(diskModel);
}
model.setDisks(list);
updateIsDisksAvailable();
initStorageDomains();
}
},
getModel().getHash()),
template.getId());
}
public void updateIsDisksAvailable() {
}
public void initStorageDomains()
{
if (getModel().getDisks() == null) {
return;
}
VmTemplate template = (VmTemplate) getModel().getTemplate().getSelectedItem();
if (template != null && !template.getId().equals(NGuid.Empty))
{
postInitStorageDomains();
}
else
{
getModel().getStorageDomain().setItems(new ArrayList<StorageDomain>());
getModel().getStorageDomain().setSelectedItem(null);
getModel().getStorageDomain().setIsChangable(false);
}
}
protected void postInitStorageDomains() {
if (getModel().getDisks() == null) {
return;
}
StoragePool dataCenter = (StoragePool) getModel().getDataCenter().getSelectedItem();
AsyncDataProvider.getPermittedStorageDomainsByStoragePoolId(new AsyncQuery(this, new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
VmModelBehaviorBase behavior = (VmModelBehaviorBase) target;
ArrayList<StorageDomain> storageDomains = (ArrayList<StorageDomain>) returnValue;
ArrayList<StorageDomain> activeStorageDomains = filterStorageDomains(storageDomains);
boolean provisioning = (Boolean) behavior.getModel().getProvisioning().getEntity();
ArrayList<DiskModel> disks = (ArrayList<DiskModel>) behavior.getModel().getDisks();
Linq.sort(activeStorageDomains, new Linq.StorageDomainByNameComparer());
for (DiskModel diskModel : disks) {
ArrayList<StorageDomain> availableDiskStorageDomains;
diskModel.getQuota().setItems(behavior.getModel().getQuota().getItems());
ArrayList<Guid> storageIds = ((DiskImage) diskModel.getDisk()).getStorageIds();
// Active storage domains that the disk resides on
ArrayList<StorageDomain> activeDiskStorageDomains =
Linq.getStorageDomainsByIds(storageIds, activeStorageDomains);
// Set target storage domains
availableDiskStorageDomains = provisioning ? activeStorageDomains : activeDiskStorageDomains;
Linq.sort(availableDiskStorageDomains, new Linq.StorageDomainByNameComparer());
diskModel.getStorageDomain().setItems(availableDiskStorageDomains);
diskModel.getStorageDomain().setChangeProhibitionReason(
constants.noActiveTargetStorageDomainAvailableMsg());
diskModel.getStorageDomain().setIsChangable(!availableDiskStorageDomains.isEmpty());
}
}
}, getModel().getHash()), dataCenter.getId(), ActionGroup.CREATE_VM);
}
public ArrayList<StorageDomain> filterStorageDomains(ArrayList<StorageDomain> storageDomains)
{
// filter only the Active storage domains (Active regarding the relevant storage pool).
ArrayList<StorageDomain> list = new ArrayList<StorageDomain>();
for (StorageDomain a : storageDomains)
{
if (Linq.isDataActiveStorageDomain(a))
{
list.add(a);
}
}
// Filter according to system tree selection.
if (getSystemTreeSelectedItem() != null && getSystemTreeSelectedItem().getType() == SystemTreeItemType.Storage)
{
StorageDomain selectStorage = (StorageDomain) getSystemTreeSelectedItem().getEntity();
StorageDomain sd = Linq.firstOrDefault(list, new Linq.StoragePredicate(selectStorage.getId()));
list = new ArrayList<StorageDomain>(Arrays.asList(new StorageDomain[] { sd }));
}
return list;
}
protected void updateQuotaByCluster(final Guid defaultQuota, final String quotaName) {
if (getModel().getQuota().getIsAvailable()) {
VDSGroup cluster = (VDSGroup) getModel().getCluster().getSelectedItem();
if (cluster == null) {
return;
}
Frontend.RunQuery(VdcQueryType.GetAllRelevantQuotasForVdsGroup,
new GetAllRelevantQuotasForVdsGroupParameters(cluster.getId()), new AsyncQuery(getModel(),
new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
UnitVmModel vmModel = (UnitVmModel) model;
ArrayList<Quota> quotaList =
(ArrayList<Quota>) ((VdcQueryReturnValue) returnValue).getReturnValue();
if (quotaList != null && !quotaList.isEmpty()) {
vmModel.getQuota().setItems(quotaList);
}
if (defaultQuota != null && !Guid.Empty.equals(defaultQuota)) {
boolean hasQuotaInList = false;
for (Quota quota : quotaList) {
if (quota.getId().equals(defaultQuota)) {
vmModel.getQuota().setSelectedItem(quota);
hasQuotaInList = true;
break;
}
}
if (!hasQuotaInList) {
Quota quota = new Quota();
quota.setId(defaultQuota);
quota.setQuotaName(quotaName);
quotaList.add(quota);
vmModel.getQuota().setItems(quotaList);
vmModel.getQuota().setSelectedItem(quota);
}
}
}
}));
}
}
protected void setupTemplate(VM vm, ListModel model) {
AsyncDataProvider.getTemplateById(new AsyncQuery(getModel(),
new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
UnitVmModel model = (UnitVmModel) target;
VmTemplate template = (VmTemplate) returnValue;
model.getTemplate()
.setItems(new ArrayList<VmTemplate>(Arrays.asList(new VmTemplate[] { template })));
model.getTemplate().setSelectedItem(template);
model.getTemplate().setIsChangable(false);
postInitTemplate();
}
},
getModel().getHash()),
vm.getVmtGuid());
}
protected void updateCpuPinningVisibility() {
if (getModel().getCluster().getSelectedItem() != null) {
VDSGroup cluster = (VDSGroup) getModel().getCluster().getSelectedItem();
String compatibilityVersion = cluster.getcompatibility_version().toString();
boolean hasCpuPinning = Boolean.FALSE.equals(getModel().getIsAutoAssign().getEntity());
if (Boolean.FALSE.equals(AsyncDataProvider.getConfigValuePreConverted(ConfigurationValues.CpuPinningEnabled,
compatibilityVersion))) {
hasCpuPinning = false;
} else if (Boolean.FALSE.equals(AsyncDataProvider.getConfigValuePreConverted(ConfigurationValues.CpuPinMigrationEnabled,
AsyncDataProvider.getDefaultConfigurationVersion()))
&& isVmMigratable()) {
hasCpuPinning = false;
}
getModel().getCpuPinning()
.setIsChangable(hasCpuPinning);
if (!hasCpuPinning) {
getModel().getCpuPinning().setEntity("");
}
}
}
public void updateUseHostCpuAvailability() {
boolean clusterSupportsHostCpu =
getModel().getCluster().getSelectedItem() != null
&& ((VDSGroup) (getModel().getCluster().getSelectedItem())).getcompatibility_version()
.compareTo(Version.v3_2) >= 0;
boolean nonMigratable = MigrationSupport.PINNED_TO_HOST == getModel().getMigrationMode().getSelectedItem();
boolean manuallyMigratableAndAnyHostInCluster =
MigrationSupport.IMPLICITLY_NON_MIGRATABLE == getModel().getMigrationMode().getSelectedItem()
&& Boolean.TRUE.equals(getModel().getIsAutoAssign().getEntity());
if (clusterSupportsHostCpu && (nonMigratable || manuallyMigratableAndAnyHostInCluster)) {
getModel().getHostCpu().setIsChangable(true);
} else {
getModel().getHostCpu().setEntity(false);
getModel().getHostCpu().setChangeProhibitionReason(constants.hosCPUUnavailable());
getModel().getHostCpu().setIsChangable(false);
}
}
private boolean isVmMigratable() {
return getModel().getMigrationMode().getSelectedItem() != MigrationSupport.PINNED_TO_HOST;
}
public void numOfSocketChanged() {
int numOfSockets = extractIntFromListModel(getModel().getNumOfSockets());
int totalCpuCores = getTotalCpuCores();
if (numOfSockets == 0 || numOfSockets == 0) {
return;
}
getModel().getCoresPerSocket().setSelectedItem(totalCpuCores / numOfSockets);
}
public void coresPerSocketChanged() {
int coresPerSocket = extractIntFromListModel(getModel().getCoresPerSocket());
int totalCpuCores = getTotalCpuCores();
if (coresPerSocket == 0 || totalCpuCores == 0) {
return;
}
// no need to check, if the new value is in the list of items, because it is filled
// only by enabled values
getModel().getNumOfSockets().setSelectedItem(totalCpuCores / coresPerSocket);
}
public void totalCpuCoresChanged() {
int totalCpuCores = getTotalCpuCores();
int coresPerSocket = extractIntFromListModel(getModel().getCoresPerSocket());
int numOfSockets = extractIntFromListModel(getModel().getNumOfSockets());
// if incorrect value put - e.g. not an integer
getModel().getCoresPerSocket().setIsChangable(totalCpuCores != 0);
getModel().getNumOfSockets().setIsChangable(totalCpuCores != 0);
if (totalCpuCores == 0) {
return;
}
// if has not been yet inited, init to 1
if (numOfSockets == 0 || coresPerSocket == 0) {
initListToOne(getModel().getCoresPerSocket());
initListToOne(getModel().getNumOfSockets());
coresPerSocket = 1;
numOfSockets = 1;
}
List<Integer> coresPerSocets = findIndependentPossibleValues(maxCpusPerSocket);
List<Integer> sockets = findIndependentPossibleValues(maxNumOfSockets);
getModel().getCoresPerSocket().setItems(filterPossibleValues(coresPerSocets, sockets));
getModel().getNumOfSockets().setItems(filterPossibleValues(sockets, coresPerSocets));
// ignore the value already selected in the coresPerSocket
// and always try to set the max possible totalcpuCores
if (totalCpuCores <= maxNumOfSockets) {
getModel().getCoresPerSocket().setSelectedItem(1);
getModel().getNumOfSockets().setSelectedItem(totalCpuCores);
} else {
// we need to compose it from more cores on the available sockets
composeCoresAndSocketsWhenDontFitInto(totalCpuCores);
}
boolean isNumOfVcpusCorrect = isNumOfSocketsCorrect(totalCpuCores);
getModel().getCoresPerSocket().setIsChangable(isNumOfVcpusCorrect);
getModel().getNumOfSockets().setIsChangable(isNumOfVcpusCorrect);
}
public boolean isNumOfSocketsCorrect(int totalCpuCores) {
boolean isNumOfVcpusCorrect =
(extractIntFromListModel(getModel().getCoresPerSocket()) * extractIntFromListModel(getModel().getNumOfSockets())) == totalCpuCores;
return isNumOfVcpusCorrect;
}
/**
* The hard way of finding, what the correct combination of the sockets and cores/socket should be (e.g. checking
* all possible combinations)
*/
private void composeCoresAndSocketsWhenDontFitInto(int totalCpuCores) {
List<Integer> possibleSockets = findIndependentPossibleValues(maxNumOfSockets);
List<Integer> possibleCoresPerSocket = findIndependentPossibleValues(maxCpusPerSocket);
// the more sockets I can use, the better
Collections.reverse(possibleSockets);
for (Integer socket : possibleSockets) {
for (Integer coresPerSocket : possibleCoresPerSocket) {
if (socket * coresPerSocket == totalCpuCores) {
getModel().getCoresPerSocket().setSelectedItem(coresPerSocket);
getModel().getNumOfSockets().setSelectedItem(socket);
return;
}
}
}
}
protected int getTotalCpuCores() {
try {
return getModel().getTotalCPUCores().getEntity() != null ? Integer.parseInt(getModel().getTotalCPUCores()
.getEntity()
.toString()) : 0;
} catch (NumberFormatException e) {
return 0;
}
}
private int extractIntFromListModel(ListModel model) {
return model.getSelectedItem() != null ? Integer.parseInt(model
.getSelectedItem()
.toString())
: 0;
}
private void initListToOne(ListModel list) {
list.setItems(Arrays.asList(1));
list.setSelectedItem(1);
}
protected void updateNumOfSockets()
{
VDSGroup cluster = (VDSGroup) getModel().getCluster().getSelectedItem();
if (cluster == null)
{
return;
}
String version = cluster.getcompatibility_version().toString();
AsyncDataProvider.getMaxNumOfVmSockets(new AsyncQuery(new Object[] { this, getModel() },
new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
Object[] array = (Object[]) target;
VmModelBehaviorBase behavior = (VmModelBehaviorBase) array[0];
behavior.maxNumOfSockets = ((Integer) returnValue);
behavior.updataMaxVmsInPool();
}
}, getModel().getHash()), version);
}
/**
* Returns a list of integers which can divide the param
*/
private List<Integer> findIndependentPossibleValues(int max) {
List<Integer> res = new ArrayList<Integer>();
int totalCPUCores = getTotalCpuCores();
for (int i = 1; i <= Math.min(totalCPUCores, max); i++) {
if (totalCPUCores % i == 0) {
res.add(i);
}
}
return res;
}
/**
* Filters out the values, which can not be used in conjuction with the others to reach the total CPUs
*/
private List<Integer> filterPossibleValues(List<Integer> candidates, List<Integer> others) {
List<Integer> res = new ArrayList<Integer>();
int currentCpusCores = getTotalCpuCores();
for (Integer candidate : candidates) {
for (Integer other : others) {
if (candidate * other == currentCpusCores) {
res.add(candidate);
break;
}
}
}
return res;
}
protected void updateHostPinning(MigrationSupport migrationSupport) {
getModel().getMigrationMode().setSelectedItem(migrationSupport);
}
}
| 41.394676 | 189 | 0.579086 |
e8a993fa8e0cad15ccef4c923f36ab09ffa3b515 | 81 | package sistersart.model.entity;
public enum MainCategory {
OIL, HANDMADE
}
| 13.5 | 32 | 0.753086 |
4d3aedd8207a945dcacf1637dbd23c58aee1b294 | 521 | package single;
/**
* @author Mr.Q
* @date 2020/3/25 0:03
* desc:懒汉模式实现单例,线程安全,但效率不高
*/
public class SingleLH {
private static SingleLH mInstance;
private SingleLH() {
}
public static synchronized SingleLH getInstance() {
if (mInstance == null) {
mInstance = new SingleLH();
}
return mInstance;
}
/**
* 反序列化时,如果定义了readResolve(),则直接返回此方法指定的对象,而不需要单独再创建新对象!
* @return
*/
private Object readResolve() {
return mInstance;
}
}
| 17.965517 | 59 | 0.585413 |
243c90cf76cdf9eb0741c451dd22b8d06fa8d591 | 440 | package com.notronix.etsy.api.model;
import java.util.List;
import java.util.Map;
public interface CartListing
{
Long getListingId();
Integer getPurchaseQuantity();
String getPurchaseState();
Boolean getDigital();
String getFileData();
Long getListingCustomizationId();
Boolean getVariationsAvailable();
Boolean getHasVariations();
List<Map<String, Object>> getSelectedVariations();
}
| 24.444444 | 55 | 0.704545 |
9a217878e4c80fbeae302485e7a0c2c6d6f759bc | 1,249 | import java.util.Stack;
public class EvaluateRPNExpressions {
/*
9.2
*/
public static Integer eval(String RPNExpression) {
Stack<Integer> stack = new Stack<>();
int a, b;
for (String s : RPNExpression.split(",")) {
if (s.length() > 1 &&
s.charAt(0) == '-' ? s.substring(1).trim().chars().allMatch(Character::isDigit)
: s.trim().chars().allMatch(Character::isDigit))
stack.push(Integer.parseInt(s));
else {
try {
a = stack.pop();
b = stack.pop();
} catch (Exception e) {
return null;
}
switch (s) {
case "-": stack.push(a - b);
break;
case "+": stack.push(a + b);
break;
case "/": stack.push(a / b);
break;
case "x": stack.push(a * b);
break;
default: return null;
}
}
}
return stack.pop();
}
}
| 30.463415 | 99 | 0.355484 |
287b97bfaa1ad1c15151f3efb1a039c400193610 | 5,224 | package hongwei.leetcode.playground.other.jdbk;
import java.util.ArrayList;
import hongwei.leetcode.playground.other.jd.Formular;
import hongwei.leetcode.playground.other.jd.Result;
public class Algorithm2 {
private static final boolean isPrintInternalProcedure = false;
public Result run(int[] a) {
int steps = 0;
int maxValue = 0;
ArrayList<Integer> list = new ArrayList<>();
final int DIVIDE_THRESHOLD = 10; // 10
int n = a.length;
int fold = 0;
while (n > DIVIDE_THRESHOLD) {
n >>>= 1;
fold++;
}
final int eachGrpCount = n;
final int subArrayCount = fold << 1;
int[] divPoint = new int[subArrayCount];
int[] sectionMaxPossibleDiff = new int[subArrayCount];
for (int i = 0; i < subArrayCount; i++) {
// divide into 2 arrays 0-(n-1), n-length
int start = i * eachGrpCount;
int end = (i + 1) * eachGrpCount - 1;
String s = "from " + start + " to " + end;
if (i < subArrayCount - 1) {
int grpDiff = a[end + 1] - a[end];
maxValue = judgeMax(maxValue, grpDiff, list, end);
divPoint[i + 1] = end + 1;
s += ", grpDiff " + grpDiff + ", divPoint[i] = " + divPoint[i];
}
LogInternal(s);
steps++;
}
printArray("divPoint", divPoint, true);
for (int i = 0; i < subArrayCount; i++) {
int start = i * eachGrpCount;
int end = (i + 1) * eachGrpCount - 1;
sectionMaxPossibleDiff[i] = Formular.formula1(start, end, a[start], a[end]);
if (sectionMaxPossibleDiff[i] < maxValue) {
// cut branch, to do...
sectionMaxPossibleDiff[i] = -1;
}
}
printArray("sectionMaxPossibleDiff", sectionMaxPossibleDiff, true);
// mark section sorted sequence
int[] sortArray = generateSortArrayDescending(sectionMaxPossibleDiff);
printArray("sortArray", sortArray, true);
// traverse the most possible section
for (int k = 0; k < sortArray.length; k++) {
if (sectionMaxPossibleDiff[k] < 0) {
continue;
}
int idx = sortArray[k];
int start = divPoint[k];
int end = k < sortArray.length - 1 ? (divPoint[k + 1] - 1) : a.length - 1;
// System.out.println("start = " + start + ", end = " + end);
int maxPossibleIntervalLeft = Formular.formula1(start, end, a[start], a[end]);
for (int i = start; i < end && maxValue <= maxPossibleIntervalLeft; i++) {
int diff = a[i + 1] - a[i];
maxValue = judgeMax(maxValue, diff, list, i);
maxPossibleIntervalLeft = Formular.formula2(maxPossibleIntervalLeft, diff);
steps++;
}
// cut branch again
for (int i = 0; i < subArrayCount; i++) {
if (sectionMaxPossibleDiff[i] > -1 && sectionMaxPossibleDiff[i] < maxValue) {
// cut branch, to do...
sectionMaxPossibleDiff[i] = -1;
printArray("sectionMaxPossibleDiff(cut)", sectionMaxPossibleDiff, true);
}
}
}
Result r = new Result();
r.name = "algorithm(2)";
r.maxValue = maxValue;
r.steps = steps;
r.resultList.addAll(list);
return r;
}
private int[] generateSortArrayDescending(final int[] a0) {
int[] sort = new int[a0.length];
for (int i = 0; i < a0.length; i++) {
sort[i] = i;
}
int[] a = new int[a0.length];
System.arraycopy(a0, 0, a, 0, a0.length);
// insert sort, need to be improved
// to do...
for (int i = 0; i < a.length; i++) {
for (int j = i; j > 0; j--) {
if (a[j] > a[j - 1]) {
int ts = sort[j - 1];
int t = a[j - 1];
sort[j - 1] = sort[j];
a[j - 1] = a[j];
sort[j] = ts;
a[j] = t;
}
}
}
return sort;
}
private int judgeMax(int prevMax, int newDiff, ArrayList<Integer> list, int idx) {
if (prevMax < newDiff) {
prevMax = newDiff;
list.clear();
list.add(idx);
} else if (prevMax == newDiff) {
list.add(idx);
} else {
}
return prevMax;
}
public static void printArray(String name, int[] a) {
printArray(name, a, false);
}
public static void printArray(String name, int[] a, boolean internal) {
String s = "";
s += "array " + name + " has " + a.length + " elements: ";
for (int i : a) {
s += i + " ";
}
if (internal) {
LogInternal(s);
} else {
System.out.println(s);
}
}
public static void LogInternal(String info) {
if (!isPrintInternalProcedure)
return;
System.out.println(info);
}
}
| 32.65 | 93 | 0.488897 |
58a26cb3865558bd35e863a49b33729ad0fdb918 | 973 | package com.celeste.library.spigot.view.event;
import org.bukkit.Location;
public final class EventController {
/**
* Checks if it's the same chunk
*
* @param location Location
* @param target Location
* @return boolean
*/
public boolean isSameChunk(final Location location, final Location target) {
return location.getChunk().equals(target.getChunk());
}
/**
* Checks if it's the same block
*
* @param location Location
* @param target Location
* @return boolean
*/
public boolean isSameBlock(final Location location, final Location target) {
return location.getBlock().equals(target.getBlock());
}
/**
* Method target check if it is the same world.
*
* @param location Location
* @param target Location
* @return boolean true if it's the same
*/
public boolean isSameWorld(final Location location, final Location target) {
return location.getWorld().equals(target.getWorld());
}
}
| 23.731707 | 78 | 0.685509 |
d6fed23694a22fe1d0ee06295e0700f27334875c | 771 | package it.oltrenuovefrontiere.fluttercouch;
import org.json.JSONException;
import org.json.JSONTokener;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.json.JSONObject;
public class QueryJsonTest {
@Test
public void firstTest() {
String jsonString = "{\"selectDistinct\":false,\"selectResult\":[[{\"string\":\"all\"}]],\"from\":\"infodiocesi\",\"where\":[{\"property\":\"type\"},{\"equalTo\":[{\"string\":\"SDK\"}]}]}";
String simplerJsonString = "{\"city\":\"chicago\",\"name\":\"jon doe\",\"age\":\"22\"}";
try {
JSONObject json = new JSONObject(simplerJsonString);
assertEquals("", json);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
| 32.125 | 197 | 0.605707 |
a7b8681571247ab8868f9da0a72c3a81da2f159b | 3,243 | package bot.modules;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import bot.Module;
import bot.Bot;
import bot.util.Helpers;
public class OzbModule extends Module
{
/**
* Register this module with Bot
*
* @param bot
* the Bot object to which this registers
*/
public OzbModule(Bot bot)
{
super(bot, "ozb");
}
public OzbModule(Bot bot, String identifier)
{
super(bot, identifier);
}
@Override
protected void setCommandList()
{
commandList = new ArrayList<>(Arrays.asList("help", "info"));
}
// Helper functions
@Override
protected void help()
{
String helpMessage = " ----- Help message for "
+ getClass().getSimpleName() + " -----\n"
+ " `help`: display this help message\n"
+ " `info`: print info for the deal\n";
Helpers.send(channel, helpMessage);
}
/**
* Parse and carry out specified the user's commands TODO : move majority to
* handle()
*/
public void execute(String command)
{
switch (command)
{
case "help":
{
Helpers.send(channel, "`help` command invoked");
help();
break;
}
case "info":
{
Helpers.send(channel, "`info` command invoked");
if (!st.hasMoreTokens())
{
Helpers.send(channel, "Usage: `info dealLink`");
return;
}
String argument = st.nextToken();
if (!argument.contains("www.ozbargain.com.au/node/"))
{
Helpers.send(channel,
"Link must be for a valid OzBargain deal");
}
getOzbInfo(argument);
break;
}
default:
{
Helpers.send(channel, "invalid command invoked");
help();
}
}
}
/**
* Prints upvotes, downvotes, net votes, number of clicks, date posted and
* date of expiry of a given deal
*
* @param dealUrl
* the URL of the deal to get info
*/
private void getOzbInfo(String dealUrl)
{
try
{
Document doc = Jsoup.connect(dealUrl).get();
// Check it's actually a deal, not a forum post etc.
if (doc.selectFirst(".node-ozbdeal") == null)
{
Helpers.send(channel,
"Link must be for a valid OzBargain deal");
return;
}
Elements dealVotes = doc.select(".nvb");
int upvotes = Integer.parseInt(dealVotes.first().text().trim());
int downvotes = Integer.parseInt(dealVotes.last().text().trim());
String clicks = doc.selectFirst(".nodeclicks").text().trim();
// TODO: Better way of getting submitted datetime info
Element submitted = doc.selectFirst(".submitted");
// System.out.println("submitted: " + submitted);
String submitDateTime = submitted.ownText()
.substring(0, submitted.ownText().indexOf(" Last edited"))
.trim();
System.out.println("ownText(): " + submitted.ownText());
String expiry = doc.selectFirst(".nodeexpiry").text().trim();
String msg = doc.title() + "\nUp: " + upvotes + ", Down: "
+ downvotes + ", Net: " + (upvotes - downvotes) + " "
+ clicks + "\nPosted " + submitDateTime + ", expires "
+ expiry;
Helpers.send(channel, msg);
System.out.println(msg);
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
| 22.838028 | 77 | 0.632439 |
79def72d3d850eca9423024c6556286e646539e9 | 2,408 | package com.github.swamim.media.organizer.utils;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class UnManagedExecutorService implements ExecutorService {
private final ExecutorService wrapped;
private volatile boolean isShutdown;
public UnManagedExecutorService(ExecutorService wrapped) {
this.wrapped = wrapped;
}
@Override
public void shutdown() {
isShutdown = true;
}
@Override
public List<Runnable> shutdownNow() {
isShutdown = true;
return Collections.emptyList();
}
@Override
public boolean isShutdown() {
return isShutdown;
}
@Override
public boolean isTerminated() {
return isShutdown;
}
@Override
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
return isShutdown;
}
@Override
public <T> Future<T> submit(Callable<T> task) {
return wrapped.submit(task);
}
@Override
public <T> Future<T> submit(Runnable task, T result) {
return wrapped.submit(task, result);
}
@Override
public Future<?> submit(Runnable task) {
return wrapped.submit(task);
}
@Override
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException {
return wrapped.invokeAll(tasks);
}
@Override
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException {
return wrapped.invokeAll(tasks, timeout, unit);
}
@Override
public <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException {
return wrapped.invokeAny(tasks);
}
@Override
public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
return wrapped.invokeAny(tasks, timeout, unit);
}
@Override
public void execute(Runnable command) {
wrapped.execute(command);
}
}
| 27.05618 | 164 | 0.694352 |
08c9d9997377744fb40c4da96109c3cd410bd0ec | 2,573 | /*
* Copyright 2016 Agapsys Tecnologia Ltda-ME.
*
* 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.agapsys.rcf.scanner;
import com.agapsys.mvn.scanner.AbstractListMojo;
import com.agapsys.mvn.scanner.ScannerDefs;
import static com.agapsys.rcf.scanner.RcScannerDefs.log;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.project.MavenProject;
/**
* RCF implementation of {@linkplain AbstractListMojo}
*/
@Mojo(name = "list", defaultPhase = LifecyclePhase.GENERATE_RESOURCES, requiresDependencyResolution = ResolutionScope.COMPILE)
public class RcListMojo extends AbstractListMojo {
@Parameter(property = "project", readonly = true)
private MavenProject mavenProject;
@Override
protected MavenProject getMavenProject() {
return mavenProject;
}
@Parameter(defaultValue = "controllers")
private String filterProperty;
@Override
protected String getFilterPropertyName() {
return filterProperty;
}
@Override
protected String getExposedEntry(String scanInfoEntry) {
return scanInfoEntry + "\n";
}
@Override
protected ScannerDefs getScannerDefs() {
return RcScannerDefs.getInstance();
}
@Parameter(defaultValue = "false", name = RcScannerDefs.OPTION_INCLUDE_DEPENDENCIES)
private boolean includeDependencies;
@Override
protected boolean includeDependencies() {
return includeDependencies;
}
@Parameter(defaultValue = "false", name = RcScannerDefs.OPTION_INCLUDE_TESTS)
private boolean includeTests;
@Override
protected boolean includeTests() {
return includeTests;
}
@Override
public void execute() throws MojoExecutionException {
log("Listing controllers...");
super.execute();
log("Done!");
}
}
| 30.630952 | 126 | 0.734162 |
7917354ec6dd10942e2318b05581468ee23245a7 | 2,460 | package io.github.tesla.ops.system.controller;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import io.github.tesla.ops.common.BaseController;
@Controller
@RequestMapping("/sys/nodemonitor")
public class NodeMonitorPageController extends BaseController {
private String prefix = "system/nodemonitor";
@RequiresPermissions("sys:nodemonitor:list")
@GetMapping("/list")
public String list() {
return prefix + "/list";
}
@RequiresPermissions("sys:nodemonitor:list")
@GetMapping("/redirectgateway")
public void redirectGateway(@RequestParam("url") String url, HttpServletResponse response) {
HttpURLConnection conn = null;
try {
URL path = new URL(url);
conn = (HttpURLConnection)path.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
Map<String, List<String>> headerFields = conn.getHeaderFields();
// 通过输入流获取数据
InputStream fis = conn.getInputStream();
// 清空response
response.reset();
// 设置response的Header
headerFields.entrySet().forEach(header -> {
response.addHeader(header.getKey(), header.getValue().get(0));
});
OutputStream toClient = response.getOutputStream();
response.setContentType(conn.getContentType());
writeStream(fis, toClient);
toClient.flush();
toClient.close();
} catch (IOException ex) {
logger.error(ex.getMessage(), ex);
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
private void writeStream(InputStream fis, OutputStream outStream) throws IOException {
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
fis.close();
}
}
| 33.243243 | 96 | 0.644715 |
bcaaee69090f5eabd8d4c09e76c3f899be95727a | 662 | package org.web.exception;
public class AutumnException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 1L;
public AutumnException() {
super();
// TODO Auto-generated constructor stub
}
public AutumnException(String paramString, Throwable paramThrowable) {
super(paramString, paramThrowable);
// TODO Auto-generated constructor stub
}
public AutumnException(String paramString) {
super(paramString);
// TODO Auto-generated constructor stub
}
public AutumnException(Throwable paramThrowable) {
super(paramThrowable);
// TODO Auto-generated constructor stub
}
}
| 21.354839 | 72 | 0.714502 |
75999e52592642b7c4bacf776f9a229ddbd98702 | 1,924 | package org.dew.fhir.model;
import java.io.Serializable;
/**
*
* This resource provides: the claim details; adjudication details from the processing of a Claim; and optionally account balance information, for informing the subscriber of the benefits provided.
*
* @see <a href="https://www.hl7.org/fhir">ExplanationOfBenefit_CareTeam</a>
*/
public
class ExplanationOfBenefitCareTeam extends BackboneElement implements Serializable
{
private static final long serialVersionUID = 1L;
protected Integer sequence;
protected CodeableConcept qualification;
protected CodeableConcept role;
protected Reference<Resource> provider;
protected Boolean responsible;
public ExplanationOfBenefitCareTeam()
{
}
public Integer getSequence() {
return sequence;
}
public void setSequence(Integer sequence) {
this.sequence = sequence;
}
public CodeableConcept getQualification() {
return qualification;
}
public void setQualification(CodeableConcept qualification) {
this.qualification = qualification;
}
public CodeableConcept getRole() {
return role;
}
public void setRole(CodeableConcept role) {
this.role = role;
}
public Reference<Resource> getProvider() {
return provider;
}
public void setProvider(Reference<Resource> provider) {
this.provider = provider;
}
public Boolean getResponsible() {
return responsible;
}
public void setResponsible(Boolean responsible) {
this.responsible = responsible;
}
@Override
public boolean equals(Object object) {
if(object instanceof ExplanationOfBenefitCareTeam) {
return this.hashCode() == object.hashCode();
}
return false;
}
@Override
public int hashCode() {
if(id == null) return 0;
return id.hashCode();
}
@Override
public String toString() {
return "ExplanationOfBenefitCareTeam(" + id + ")";
}
}
| 22.635294 | 197 | 0.709979 |
8700e318bc06d72a675d35ccc5aacf65d697a0c1 | 2,922 | /*
* 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.syncope.core.persistence.jpa;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotatedBeanDefinitionReader;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.test.context.ContextCustomizer;
import org.springframework.test.context.MergedContextConfiguration;
import org.springframework.test.context.support.TestPropertySourceUtils;
public class JPAJSONTestContextCustomizer implements ContextCustomizer {
private static BeanDefinitionRegistry getBeanDefinitionRegistry(final ApplicationContext ctx) {
if (ctx instanceof BeanDefinitionRegistry) {
return (BeanDefinitionRegistry) ctx;
}
if (ctx instanceof AbstractApplicationContext) {
return (BeanDefinitionRegistry) ((AbstractApplicationContext) ctx).getBeanFactory();
}
throw new IllegalStateException("Could not locate BeanDefinitionRegistry");
}
@Override
public void customizeContext(final ConfigurableApplicationContext ctx, final MergedContextConfiguration cfg) {
if ("pgjsonb".equals(System.getProperty("profileId"))) {
TestPropertySourceUtils.addInlinedPropertiesToEnvironment(
ctx,
"provisioning.quartz.delegate=org.quartz.impl.jdbcjobstore.PostgreSQLDelegate");
} else if ("myjson".equals(System.getProperty("profileId"))) {
TestPropertySourceUtils.addInlinedPropertiesToEnvironment(
ctx,
"provisioning.quartz.delegate=org.quartz.impl.jdbcjobstore.StdJDBCDelegate");
}
AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader(getBeanDefinitionRegistry(ctx));
reader.registerBean(PGJPAJSONPersistenceContext.class, "PGJPAJSONPersistenceContext");
reader.registerBean(MyJPAJSONPersistenceContext.class, "MyJPAJSONPersistenceContext");
}
}
| 49.525424 | 114 | 0.761465 |
8112d70cb5af50358f0a2e26d91430577a718f89 | 788 | package io.rapidpro.surveyor.utils;
import java.io.File;
import java.io.IOException;
/**
* Misc utils
*/
public class SurveyUtils {
/**
* Creates a nested directory
*
* @param root the root directory
* @param folders the nested directory names
* @return the directory
* @throws IOException if any directory couldn't be created
*/
public static File mkdir(File root, String... folders) throws IOException {
File current = root;
for (String folder : folders) {
current = new File(current, folder);
if (!current.exists() && !current.mkdirs()) {
throw new IOException("Unable to create directory: " + current.getAbsolutePath());
}
}
return current;
}
}
| 26.266667 | 98 | 0.604061 |
b0ac42f4bfecf786bf2f76b895dc5471f7c1d15a | 3,214 | /*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat, Inc. and/or its affiliates, and individual
* contributors by the @authors tag. See the copyright.txt in the
* distribution for a full listing of individual contributors.
*
* 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.switchyard.quickstarts.rest.binding;
import javax.ws.rs.core.Response;
import org.jboss.resteasy.client.core.BaseClientResponse;
import org.switchyard.Exchange;
import org.switchyard.ExchangeState;
import org.switchyard.HandlerException;
import org.switchyard.Message;
import org.switchyard.component.resteasy.composer.RESTEasyBindingData;
import org.switchyard.component.resteasy.composer.RESTEasyMessageComposer;
/**
* Composes/decomposes multiple parameter RESTEasy messages.
*
* @author Magesh Kumar B <mageshbk@jboss.com> (C) 2013 Red Hat Inc.
*/
public class CustomComposer extends RESTEasyMessageComposer {
/**
* {@inheritDoc}
*/
@Override
public Message compose(RESTEasyBindingData source, Exchange exchange) throws Exception {
final Message message = super.compose(source, exchange);
if (message.getContent() instanceof BaseClientResponse) {
BaseClientResponse<?> clientResponse = (BaseClientResponse<?>) message.getContent();
if (clientResponse.getResponseStatus() == Response.Status.NOT_FOUND) {
throw new ItemNotFoundException("Item not found");
}
} else if (source.getOperationName().equals("addItem") && (source.getParameters().length == 2)) {
// Wrap the parameters
Item item = new Item((Integer) source.getParameters()[0], (String) source.getParameters()[1]);
message.setContent(item);
}
return message;
}
/**
* {@inheritDoc}
*/
@Override
public RESTEasyBindingData decompose(Exchange exchange, RESTEasyBindingData target) throws Exception {
Object content = exchange.getMessage().getContent();
if (exchange.getState().equals(ExchangeState.FAULT)) {
if (content instanceof HandlerException) {
HandlerException he = (HandlerException) content;
if (he.getCause() instanceof ItemNotFoundException) {
throw (Exception) he.getCause();
}
}
}
target = super.decompose(exchange, target);
if (target.getOperationName().equals("addItem") && (content != null) && (content instanceof Item)) {
// Unwrap the parameters
target.setParameters(new Object[] { ((Item) content).getItemId(), ((Item) content).getName() });
}
return target;
}
}
| 40.175 | 108 | 0.683261 |
a67f93b711201ee7c288aeb23eb9331649979ba8 | 283 | public class MyBlock {
public static void main(String [] args){
{
int i = 0;
System.out.println(i);
}
{
int i = 9;
System.out.println(i);
}
int i = 8;
System.out.println(i);
}
}
| 17.6875 | 44 | 0.402827 |
5fd7fcf63eb6f35209c382661cb8b2a69c180f43 | 123 | package com.headfirst.behavioral.observer.message;
public interface Observer {
void notifyUpdate(Message message);
}
| 17.571429 | 50 | 0.788618 |
9bfcd673b93ee863d9225f4a4ee4d8a1b6f10940 | 1,382 | package com.company;
import java.util.Scanner;
public class SunGlasses {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = Integer.parseInt(scanner.nextLine());
int rowLength = n * 4 + 1;
int firstRowStars = n *2;
int firstRowSpaces = n;
System.out.printf("%s%s%s%n",
print("*",firstRowStars),
print(" ",firstRowSpaces),
print("*",firstRowStars) );
int lines = firstRowStars - 2;
int specialRow = (n-1) / 2 - 1;
for (int i = 0; i < n-2 ; i++) {
if (i == specialRow) {
System.out.printf("*%s*%s*%s*%n",
print("/",lines),
print("|",firstRowSpaces),
print("/",lines));
} else {
System.out.printf("*%s*%s*%s*%n",
print("/", lines),
print(" ", firstRowSpaces),
print("/", lines));
}
}
System.out.printf("%s%s%s%n",
print("*",firstRowStars),
print(" ",firstRowSpaces),
print("*",firstRowStars) );
}
private static String print(String element, int count) {
return new String(new char[count]).replace("\0", element);
}
}
| 30.043478 | 66 | 0.452243 |
8cf293ae3bc7793a7247ce64be9040e9dc045e38 | 4,100 | /*
* Copyright 2021 The University of Pennsylvania and Penn Medicine
*
* Originally created at the University of Pennsylvania and Penn Medicine by:
* Dr. David Asch; Dr. Lisa Bellini; Dr. Cecilia Livesey; Kelley Kugler; and Dr. Matthew Press.
*
* 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.cobaltplatform.api.model.api.response;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
import com.lokalized.Strings;
import com.cobaltplatform.api.model.db.AppointmentType;
import com.cobaltplatform.api.model.db.SchedulingSystem.SchedulingSystemId;
import com.cobaltplatform.api.model.db.VisitType.VisitTypeId;
import com.cobaltplatform.api.util.Formatter;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.ThreadSafe;
import java.util.HashMap;
import java.util.UUID;
import static java.util.Objects.requireNonNull;
/**
* @author Transmogrify, LLC.
*/
@ThreadSafe
public class AppointmentTypeApiResponse {
@Nonnull
private final UUID appointmentTypeId;
@Nonnull
private final SchedulingSystemId schedulingSystemId;
@Nonnull
private final VisitTypeId visitTypeId;
@Nullable
private final Long acuityAppointmentTypeId;
@Nullable
private final String epicVisitTypeId;
@Nullable
private final String epicVisitTypeIdType;
@Nonnull
private final String name;
@Nullable
private final String description;
@Nonnull
private final Long durationInMinutes;
@Nonnull
private final String durationInMinutesDescription;
// Note: requires FactoryModuleBuilder entry in AppModule
@ThreadSafe
public interface AppointmentTypeApiResponseFactory {
@Nonnull
AppointmentTypeApiResponse create(@Nonnull AppointmentType appointmentType);
}
@AssistedInject
public AppointmentTypeApiResponse(@Nonnull Formatter formatter,
@Nonnull Strings strings,
@Assisted @Nonnull AppointmentType appointmentType) {
requireNonNull(formatter);
requireNonNull(strings);
this.appointmentTypeId = appointmentType.getAppointmentTypeId();
this.schedulingSystemId = appointmentType.getSchedulingSystemId();
this.visitTypeId = appointmentType.getVisitTypeId();
this.acuityAppointmentTypeId = appointmentType.getAcuityAppointmentTypeId();
this.epicVisitTypeId = appointmentType.getEpicVisitTypeId();
this.epicVisitTypeIdType = appointmentType.getEpicVisitTypeIdType();
this.name = appointmentType.getName();
this.description = appointmentType.getDescription();
this.durationInMinutes = appointmentType.getDurationInMinutes();
this.durationInMinutesDescription = strings.get("{{duration}} minutes", new HashMap<String, Object>() {{
put("duration", appointmentType.getDurationInMinutes());
}});
}
@Nonnull
public UUID getAppointmentTypeId() {
return appointmentTypeId;
}
@Nonnull
public SchedulingSystemId getSchedulingSystemId() {
return schedulingSystemId;
}
@Nonnull
public VisitTypeId getVisitTypeId() {
return visitTypeId;
}
@Nullable
public Long getAcuityAppointmentTypeId() {
return acuityAppointmentTypeId;
}
@Nullable
public String getEpicVisitTypeId() {
return epicVisitTypeId;
}
@Nullable
public String getEpicVisitTypeIdType() {
return epicVisitTypeIdType;
}
@Nonnull
public String getName() {
return name;
}
@Nullable
public String getDescription() {
return description;
}
@Nonnull
public Long getDurationInMinutes() {
return durationInMinutes;
}
@Nonnull
public String getDurationInMinutesDescription() {
return durationInMinutesDescription;
}
} | 29.078014 | 106 | 0.78561 |
8daea226394c2babc7d79fafdc9028c9f21591d0 | 303 | package com.revature.dungeonsite.repositories;
import com.revature.dungeonsite.models.PhoneType;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface PhoneTypeRepository extends JpaRepository<PhoneType, Long> {
}
| 30.3 | 77 | 0.854785 |
1c98c2f696e611f9eabbb3a5776c2ade0f0f14ce | 17,961 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package smockify;
import com.mpatric.mp3agic.InvalidDataException;
import com.mpatric.mp3agic.Mp3File;
import com.mpatric.mp3agic.UnsupportedTagException;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import javafx.scene.media.Media;
/*
Necessários para iniciar uma música .mp3
*/
import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.embed.swing.SwingFXUtils;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.Slider;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.DragEvent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.TransferMode;
import javafx.scene.paint.ImagePattern;
import javafx.scene.shape.Circle;
import javax.imageio.ImageIO;
import org.farng.mp3.TagException;
/**
*
* @author Santana
*/
public class FXMLDocumentController implements Initializable {
private boolean testButton=false;
MusicPlayer musicPlayer = new MusicPlayer();
@FXML
private Label musicaNome;
@FXML
private Label musicaTimer;
@FXML
private Circle songCircle;
@FXML
private ProgressBar progressBar;
@FXML
private ImageView playPause;
@FXML
private ImageView repeat;
@FXML
private Slider sliderVolume;
@FXML
private ImageView previousSong;
@FXML
private ImageView shuffler;
@FXML
private ImageView nextSong;
@FXML
private ListView<String> listView = new ListView<String>();
private ArrayList<AcessoRapido> arrayMusica = new ArrayList<AcessoRapido>();
public boolean isTestButton() {
return testButton;
}
public void setTestButton(boolean testButton) {
this.testButton = testButton;
}
public MusicPlayer getMusicPlayer() {
return musicPlayer;
}
public void setMusicPlayer(MusicPlayer musicPlayer) {
this.musicPlayer = musicPlayer;
}
public Label getMusicaNome() {
return musicaNome;
}
public void setMusicaNome(Label musicaNome) {
this.musicaNome = musicaNome;
}
public Circle getSongCircle() {
return songCircle;
}
public void setSongCircle(Circle songCircle) {
this.songCircle = songCircle;
}
public ProgressBar getProgressBar() {
return progressBar;
}
public void setProgressBar(ProgressBar progressBar) {
this.progressBar = progressBar;
}
public ImageView getPlayPause() {
return playPause;
}
public void setPlayPause(ImageView playPause) {
this.playPause = playPause;
}
public ImageView getRepeat() {
return repeat;
}
public void setRepeat(ImageView repeat) {
this.repeat = repeat;
}
public ImageView setNextSong() {
return nextSong;
}
public void setNextSong(ImageView nextSong) {
this.nextSong = nextSong;
}
public ImageView getPreviousSong() {
return previousSong;
}
public void setPreviousSong(ImageView previousSong) {
this.previousSong = previousSong;
}
public Slider getSliderVolume() {
return sliderVolume;
}
public void setSliderVolume(Slider sliderVolume) {
this.sliderVolume = sliderVolume;
}
public ListView<String> getListView() {
return listView;
}
public void setListView(ListView<String> listView) {
this.listView = listView;
}
public ArrayList<AcessoRapido> getArrayMusica() {
return arrayMusica;
}
public void setArrayMusica(ArrayList<AcessoRapido> arrayMusica) {
this.arrayMusica = arrayMusica;
}
public Label getMusicaTimer(){
return this.musicaTimer;
}
public boolean verifyContains(File URL){
for(int x=0; x<getArrayMusica().size(); x++){
if(getArrayMusica().get(x).getUrl().equals(URL)){
return true;
}
}
return false;
}
public void setMedia2Screen(File file) throws IOException, UnsupportedTagException, InvalidDataException{
Mp3File mp3file = new Mp3File(file);
//replaceAll("\uFFFD", "") serve para remover os caracteres esquisitos que aparecem, que tem alguma relação com UCS-2 e não conseguir interpretar o texto como UTF-8.
getMusicPlayer().setMusica(new Media(file.toURI().toString()));
getMusicPlayer().trocarMusica();
getPlayPause().setImage(createImage("/resources/pause.png"));
if(!this.verifyContains(file)) {
getArrayMusica().add(new AcessoRapido(file, file.getName()));
ArrayList<String> acessoTitles = new ArrayList<String>();
for(int x=0; x<getArrayMusica().size(); x++){
acessoTitles.add(getArrayMusica().get(x).getTitle());
}
String[] recentSongs = acessoTitles.toArray(new String[0]);
this.setSongList(recentSongs);
}
if(mp3file.getId3v2Tag().getTitle() == null){
getMusicaNome().setText(file.getName());
this.setSongAvatar();
}else{
getMusicaNome().setText(mp3file.getId3v2Tag().getTitle());
if(mp3file.getId3v2Tag().getAlbumImage() == null){
this.setSongAvatar();
return;
}
BufferedImage img = ImageIO.read(new ByteArrayInputStream(mp3file.getId3v2Tag().getAlbumImage()));;
Image capturedImg = SwingFXUtils.toFXImage(img, null);
this.setSongAvatar(capturedImg);
}
}
@FXML
private void dragSong(DragEvent event) {
event.acceptTransferModes(TransferMode.ANY);
event.consume();
}
@FXML
private void dropSong(DragEvent event) throws TagException, IOException, InvalidDataException, UnsupportedTagException {
Dragboard db = event.getDragboard();
System.out.println(db.getFiles().toArray().length);
if(db.hasFiles()) {
File file = db.getFiles().iterator().next();
this.setMedia2Screen(file);
}
event.setDropCompleted(true);
event.consume();
}
public Image createImage(String address) throws IOException{
URL teste = getClass().getResource(address);
BufferedImage image = ImageIO.read(teste);
Image newImage = SwingFXUtils.toFXImage(image, null);
return newImage;
}
@FXML
public void setSongAvatar() throws IOException {
getSongCircle().setFill(new ImagePattern(createImage("avatar.png")));
return;
}
@FXML
public void setSongAvatar(Image img) throws IOException {
if(img.isError()){
//Image defaultImg = new Image(new File("./avatar.png").toURI().toString());
getSongCircle().setFill(new ImagePattern(createImage("avatar.png")));
return;
}
getSongCircle().setFill(new ImagePattern(img));
}
public void getSongURL(String title) throws IOException, UnsupportedTagException, InvalidDataException{
for(int x=0; x<getArrayMusica().size(); x++){
if(getArrayMusica().get(x).getTitle().equals(title)){
setMedia2Screen(getArrayMusica().get(x).getUrl());
}
}
};
public void setSongList(String songArray[]){
ObservableList<String> items = FXCollections.observableArrayList ();
items = FXCollections.observableArrayList (songArray);
this.getListView().setItems(items);
}
@Override
public void initialize(URL url, ResourceBundle rb) {
this.getMusicPlayer().setControlador(this);
this.getProgressBar().progressProperty().bind(this.getMusicPlayer().getBarUpdater());
try {
this.setSongAvatar();
} catch (IOException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
//String checking[] = {"a"};
//this.setSongList(checking);
getSliderVolume().setOnMouseReleased(e -> {
if(getMusicPlayer().getPlayer() == null){
return;
}
getMusicPlayer().setVolume((getSliderVolume().getValue()/100));
System.out.println(getMusicPlayer().getPlayer().getVolume());
});
playPause.setOnMouseClicked((MouseEvent e) -> {
if(getMusicPlayer().getPlayer() == null){
return;
}
if(getMusicPlayer().isPlaying()) {
try {
getPlayPause().setImage(createImage("/resources/play.png"));
} catch (IOException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
getMusicPlayer().pauseMusica();
}else{
try {
getPlayPause().setImage(createImage("/resources/pause.png"));
} catch (IOException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
getMusicPlayer().pauseMusica();
}
});
playPause.setOnMouseClicked((MouseEvent e) -> {
if(getMusicPlayer().getPlayer() == null){
return;
}
if(getMusicPlayer().getPlayer().getCurrentTime().toSeconds() / getMusicPlayer().getPlayer().getTotalDuration().toSeconds() == 1){
getMusicPlayer().trocarMusica();
getMusicPlayer().pauseMusica();
}
if(getMusicPlayer().isPlaying()) {
try {
getPlayPause().setImage(createImage("/resources/play.png"));
} catch (IOException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
getMusicPlayer().pauseMusica();
}else{
try {
getPlayPause().setImage(createImage("/resources/pause.png"));
} catch (IOException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
getMusicPlayer().pauseMusica();
}
});
listView.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
if(getMusicPlayer().getPlayer() == null){
return;
}
try {
if(getListView().getSelectionModel().getSelectedItem() == null){
return;
}
getSongURL(getListView().getSelectionModel().getSelectedItem());
} catch (IOException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedTagException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidDataException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
nextSong.setOnMouseClicked((MouseEvent e) -> {
int arrayLength = getArrayMusica().toArray().length - 1;
if(getArrayMusica().toArray().length <= 1 || getArrayMusica().get(arrayLength).getUrl().toURI().toString().equals(getMusicPlayer().getMusica().getSource())){
return;
}
for(int x = 0; x<=arrayLength; x++){
if(getMusicPlayer().getMusica().getSource().equals(getArrayMusica().get(x).getUrl().toURI().toString())){
try {
setMedia2Screen(getArrayMusica().get(x+1).getUrl());
} catch (IOException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedTagException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidDataException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
return;
}
}
});
previousSong.setOnMouseClicked((MouseEvent e) -> {
if(getArrayMusica().toArray().length <= 1 || getArrayMusica().get(0).getUrl().toURI().toString().equals(getMusicPlayer().getMusica().getSource())){
return;
}
for(int x = 0; x<getArrayMusica().size(); x++){
if(getArrayMusica().get(x).getUrl().toURI().toString().equals(getMusicPlayer().getMusica().getSource())){
try {
setMedia2Screen(getArrayMusica().get(x-1).getUrl());
} catch (IOException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedTagException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidDataException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
return;
}
}
});
shuffler.setOnMouseClicked((MouseEvent e) -> {
if(getMusicPlayer().getPlayer() == null){
return;
}
boolean decision = getMusicPlayer().isShufflable() ? false : true;
getMusicPlayer().setShufflable( decision );
if(getMusicPlayer().isShufflable()){
try {
getShuffler().setImage(createImage("/resources/shuffle2.png"));
} catch (IOException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
}else{
try {
getShuffler().setImage(createImage("/resources/shuffle.png"));
} catch (IOException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
repeat.setOnMouseClicked((MouseEvent e) -> {
if(getMusicPlayer().getPlayer() == null){
return;
}
getMusicPlayer().mudarRepeat(); //operador ternario aqui seria uma melhor opção
if(getMusicPlayer().isLoopable()){
try {
getRepeat().setImage(createImage("/resources/repeat2.png"));
} catch (IOException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
}else{
try {
getRepeat().setImage(createImage("/resources/repeat.png"));
} catch (IOException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
public ImageView getShuffler() {
return shuffler;
}
public void setShuffler(ImageView shuffler) {
this.shuffler = shuffler;
}
}
| 30.650171 | 177 | 0.535382 |
e14bcb4138385e085237e46f347d0e5da872d013 | 6,593 | /*
* Copyright 2017 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.baidu.aip.bodyanalysis;
import com.baidu.aip.client.BaseClient;
import com.baidu.aip.error.AipError;
import com.baidu.aip.http.AipRequest;
import com.baidu.aip.util.Base64Util;
import com.baidu.aip.util.Util;
import org.json.JSONObject;
import java.io.IOException;
import java.util.HashMap;
public class AipBodyAnalysis extends BaseClient {
public AipBodyAnalysis(String appId, String apiKey, String secretKey) {
super(appId, apiKey, secretKey);
}
/**
* 人体关键点识别接口
* 对于输入的一张图片(可正常解码,且长宽比适宜),检测图片中的所有人体,**输出每个人体的14个关键点**,包含四肢、脖颈、鼻子等部位,**以及人体的坐标信息和数量**。
*
* @param image - 二进制图像数据
* @param options - 可选参数对象,key: value都为string类型
* options - options列表:
* @return JSONObject
*/
public JSONObject bodyAnalysis(byte[] image, HashMap<String, String> options) {
AipRequest request = new AipRequest();
preOperation(request);
String base64Content = Base64Util.encode(image);
request.addBody("image", base64Content);
if (options != null) {
request.addBody(options);
}
request.setUri(BodyAnalysisConsts.BODY_ANALYSIS);
postOperation(request);
return requestServer(request);
}
/**
* 人体关键点识别接口
* 对于输入的一张图片(可正常解码,且长宽比适宜),检测图片中的所有人体,**输出每个人体的14个关键点**,包含四肢、脖颈、鼻子等部位,**以及人体的坐标信息和数量**。
*
* @param image - 本地图片路径
* @param options - 可选参数对象,key: value都为string类型
* options - options列表:
* @return JSONObject
*/
public JSONObject bodyAnalysis(String image, HashMap<String, String> options) {
try {
byte[] data = Util.readFileByBytes(image);
return bodyAnalysis(data, options);
} catch (IOException e) {
e.printStackTrace();
return AipError.IMAGE_READ_ERROR.toJsonResult();
}
}
/**
* 人体属性识别接口
* 对于输入的一张图片(可正常解码,且长宽比适宜),输出图片中的所有人体的静态属性,包含**性别、年龄阶段、衣着(含类别/颜色/纹理)、是否戴帽子、是否戴眼镜、是否撑伞、是否使用手机、身体朝向**。
*
* @param image - 二进制图像数据
* @param options - 可选参数对象,key: value都为string类型
* options - options列表:
* type gender,<br>age,<br>lower_wear,<br>upper_wear,<br>headwear,<br>glasses,<br>upper_color,<br>lower_color,<br>cellphone,<br>upper_wear_fg,<br>upper_wear_texture,<br>lower_wear_texture,<br>orientation,<br>umbrella or 1)可选值说明:<br>gender-性别,age-年龄阶段,lower_wear-下身服饰,upper_wear-上身服饰,headwear-是否戴帽子,glasses-是否戴眼镜,upper_color-上身服饰颜色,lower_color-下身服饰颜色,cellphone-是否使用手机,upper_wear_fg-上身服饰细分类,upper_wear_texture-上身服饰纹理,lower_wear_texture-下身服饰纹理,orientation-身体朝向,umbrella-是否撑伞;<br>2)type 参数值可以是可选值的组合,用逗号分隔;**如果无此参数默认输出全部14个属性**
* @return JSONObject
*/
public JSONObject bodyAttr(byte[] image, HashMap<String, String> options) {
AipRequest request = new AipRequest();
preOperation(request);
String base64Content = Base64Util.encode(image);
request.addBody("image", base64Content);
if (options != null) {
request.addBody(options);
}
request.setUri(BodyAnalysisConsts.BODY_ATTR);
postOperation(request);
return requestServer(request);
}
/**
* 人体属性识别接口
* 对于输入的一张图片(可正常解码,且长宽比适宜),输出图片中的所有人体的静态属性,包含**性别、年龄阶段、衣着(含类别/颜色/纹理)、是否戴帽子、是否戴眼镜、是否撑伞、是否使用手机、身体朝向**。
*
* @param image - 本地图片路径
* @param options - 可选参数对象,key: value都为string类型
* options - options列表:
* type gender,<br>age,<br>lower_wear,<br>upper_wear,<br>headwear,<br>glasses,<br>upper_color,<br>lower_color,<br>cellphone,<br>upper_wear_fg,<br>upper_wear_texture,<br>lower_wear_texture,<br>orientation,<br>umbrella or 1)可选值说明:<br>gender-性别,age-年龄阶段,lower_wear-下身服饰,upper_wear-上身服饰,headwear-是否戴帽子,glasses-是否戴眼镜,upper_color-上身服饰颜色,lower_color-下身服饰颜色,cellphone-是否使用手机,upper_wear_fg-上身服饰细分类,upper_wear_texture-上身服饰纹理,lower_wear_texture-下身服饰纹理,orientation-身体朝向,umbrella-是否撑伞;<br>2)type 参数值可以是可选值的组合,用逗号分隔;**如果无此参数默认输出全部14个属性**
* @return JSONObject
*/
public JSONObject bodyAttr(String image, HashMap<String, String> options) {
try {
byte[] data = Util.readFileByBytes(image);
return bodyAttr(data, options);
} catch (IOException e) {
e.printStackTrace();
return AipError.IMAGE_READ_ERROR.toJsonResult();
}
}
/**
* 人流量统计接口
* 对于输入的一张图片(可正常解码,且长宽比适宜),**识别和统计图像中的人体个数**,以俯拍角度为主要识别视角,**支持特定框选区域的人数统计,并可以输出渲染图片(人体头顶热力图)**。
*
* @param image - 二进制图像数据
* @param options - 可选参数对象,key: value都为string类型
* options - options列表:
* area 特定框选区域坐标,逗号分隔,如‘x1,y1,x2,y2,x3,y3...xn,yn',默认尾点和首点相连做闭合,**此参数为空或无此参数默认识别整个图片的人数**
* show 是否输出渲染的图片,默认不返回,**选true时返回渲染后的图片(base64)**,其它无效值或为空则默认false
* @return JSONObject
*/
public JSONObject bodyNum(byte[] image, HashMap<String, String> options) {
AipRequest request = new AipRequest();
preOperation(request);
String base64Content = Base64Util.encode(image);
request.addBody("image", base64Content);
if (options != null) {
request.addBody(options);
}
request.setUri(BodyAnalysisConsts.BODY_NUM);
postOperation(request);
return requestServer(request);
}
/**
* 人流量统计接口
* 对于输入的一张图片(可正常解码,且长宽比适宜),**识别和统计图像中的人体个数**,以俯拍角度为主要识别视角,**支持特定框选区域的人数统计,并可以输出渲染图片(人体头顶热力图)**。
*
* @param image - 本地图片路径
* @param options - 可选参数对象,key: value都为string类型
* options - options列表:
* area 特定框选区域坐标,逗号分隔,如‘x1,y1,x2,y2,x3,y3...xn,yn',默认尾点和首点相连做闭合,**此参数为空或无此参数默认识别整个图片的人数**
* show 是否输出渲染的图片,默认不返回,**选true时返回渲染后的图片(base64)**,其它无效值或为空则默认false
* @return JSONObject
*/
public JSONObject bodyNum(String image, HashMap<String, String> options) {
try {
byte[] data = Util.readFileByBytes(image);
return bodyNum(data, options);
} catch (IOException e) {
e.printStackTrace();
return AipError.IMAGE_READ_ERROR.toJsonResult();
}
}
} | 40.20122 | 529 | 0.668891 |
46e7151fe279ef82f56bcd148a59cd9765906eb9 | 10,251 | /*
* Copyright 2015, 2016 Tagir Valeev
*
* 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.
*/
/**
* This library provides enhancements for Java 8 Stream API. Public API contains the following classes and interfaces:
*
* <p>
* {@link one.util.streamex.StreamEx}: implements {@link java.util.stream.Stream}
* and provides additional functionality for object streams.
*
* <p>
* {@link one.util.streamex.IntStreamEx}, {@link one.util.streamex.LongStreamEx}, {@link one.util.streamex.DoubleStreamEx}:
* implement corresponding interfaces for primitive streams and enhancing them with additional functionality.
*
* <p>
* {@link one.util.streamex.EntryStream}: implements {@link java.util.stream.Stream} of {@link java.util.Map.Entry}
* objects providing specific methods for operate on keys or values independently.
*
* <p>
* Each of these classes contain a bunch of static methods to create the corresponding stream using different sources:
* collections, arrays, {@link java.io.Reader}, {@link java.util.Random} and so on.
*
* <p>
* {@link one.util.streamex.IntCollector}, {@link one.util.streamex.LongCollector}, {@link one.util.streamex.DoubleCollector}:
* specialized collectors to work efficiently with primitive streams.
*
* <p>
* {@link one.util.streamex.MoreCollectors}: utility class which provides a number of useful collectors
* which are absent in JDK {@link java.util.stream.Collectors} class.
*
* <p>
* {@link one.util.streamex.Joining}: an advanced implementation of joining collector.
*
* <p>
* {@link one.util.streamex.StreamEx.Emitter}, {@link one.util.streamex.IntStreamEx.IntEmitter}, {@link one.util.streamex.LongStreamEx.LongEmitter}, {@link one.util.streamex.DoubleStreamEx.DoubleEmitter}:
* helper interfaces to create custom stream sources.
*
* <h2><a name="StreamOps">Stream operations and pipelines</a></h2>
* <p>StreamEx operations are divided into <em>intermediate</em>, <em>quasi-intermediate</em> and
* <em>terminal</em> operations, and are combined to form <em>stream
* pipelines</em>. For more information about <em>intermediate</em> and <em>terminal</em> see the {@linkplain java.util.stream Stream API} documentation.
*
* <p>
* In addition, due to the API limitations, a new operation type is defined in StreamEx library which is called "quasi-intermediate".
* In most of the cases they behave as intermediate operations: for sequential stream there
* should be no visible difference between intermediate and quasi-intermediate operation. The only known difference
* is when handling a parallel and unordered stream status. For intermediate operation there's no difference on calling {@code parallel()}
* before or after any intermediate operation. For quasi-intermediate operations if you call {@code parallel()} after the operation, then previous
* steps will remain sequential. Similarly if you create a parallel stream, perform some intermediate operations, use quasi-intermediate operation,
* then call {@code sequential()}, the steps before quasi-intermediate operation may still be executed in parallel.
*
* <p>
* Also the difference appears if you have an ordered stream source, but an unordered terminal operation (or collect using the unordered collector).
* If you have only intermediate operations in-between, then all of them will be performed as unordered. However if you have a quasi-intermediate
* operation, then unordered mode is not propagated through it, so the operations prior to the quasi-intermediate operation
* (including the quasi-intermediate operation itself) will remain ordered.
*
* <h3><a name="TSO">Tail stream optimization</a></h3>
*
* A few quasi-intermediate operations are tail-stream optimized (TSO) which is important when using
* {@link one.util.streamex.StreamEx#headTail(java.util.function.BiFunction) headTail}
* method recursively. When the TSO-compatible operation understands that it should just pass-through
* the rest of the stream as-is, it notifies the surrounding {@code headTail} operation, and {@code headTail} operation
* removes the TSO-compatible operation from the pipeline shortening the call stack.
* This allows writing many recursively defined operations which consume constant amount of the call stack and the heap.
*
* <h3><a name="NonInterference">Non-interference</a></h3>
*
* The function is called non-interfering if it does not modify the stream source. For more information see the {@linkplain java.util.stream Stream API} documentation.
*
* <h3><a name="Statelessness">Stateless behaviors</a></h3>
*
* The function is called stateless if its result does not depend on any state which may be changed during the stream execution. For more information see the {@linkplain java.util.stream Stream API} documentation.
*
* <h2><a name="Reduction">Reduction operations</a></h2>
*
* <p>
* A <em>reduction</em> operation takes a sequence of input elements and combines them into a single summary result. For more information see the {@linkplain java.util.stream Stream API} documentation.
* In addition to symmetrical reduction which requires reduction function to be associative, StreamEx library provides asymmetrical reduction methods
* like {@linkplain one.util.streamex.StreamEx#foldLeft(Object, java.util.function.BiFunction) foldLeft} and {@linkplain one.util.streamex.StreamEx#foldRight(Object, java.util.function.BiFunction) foldRight}.
* These methods
* can be safely used for parallel streams, but the absence of associativity may lead to the performance drawback. Use them only if you cannot provide
* an associative reduction function.
*
* <h3><a name="MutableReduction">Mutable reduction</a></h3>
*
* <p>
* A <em>mutable reduction operation</em> accumulates input elements into a
* mutable result container, such as a {@code Collection},
* as it processes the elements in the stream. The mutable reduction is usually performed via {@linkplain java.util.stream.Collector collectors}.
* See the {@linkplain java.util.stream Stream API} documentation for more details.
*
* <p>
* StreamEx provides better support for mutable reduction on primitive streams. There are primitive collector classes {@link one.util.streamex.IntCollector},
* {@link one.util.streamex.LongCollector} and {@link one.util.streamex.DoubleCollector}
* which extend {@link java.util.stream.Collector} interface, but capable to process primitive streams in more efficient way compared to using the boxed stream.
*
* <p>
* Also StreamEx library defines a number of collectors absent in JDK. See {@link one.util.streamex.MoreCollectors} class.
*
* <h3><a name="ShortCircuitReduction">Short circuiting reduction</a></h3>
*
* <p>
* While Stream API has some <em>short-circuiting</em> operations which may process only some of input elements (in particular may allow to process an infinite stream in finite time),
* a mutable reduction via {@link java.util.stream.Stream#collect(java.util.stream.Collector) Stream.collect(Collector)} is always non short-circuiting.
* This method is extended in StreamEx library. A new type of collectors is introduced which is called <em>short-circuiting collectors</em>.
* If such special collector is passed to {@code StreamEx.collect} or {@code EntryStream.collect} terminal operation, then this operation
* becomes short-circuiting as well. If you however pass such collector to the normal {@code Stream.collect}, it will act as an ordinary
* non-short-circuiting collector. For example, this will process only one element from an input stream:
*
* <pre>
* Optional<Integer> result = IntStreamEx.range(100).boxed().collect(MoreCollectors.first());
* </pre>
*
* While this will process all the elements producing the same result:
*
* <pre>
* Optional<Integer> result = IntStream.range(0, 100).boxed().collect(MoreCollectors.first());
* </pre>
*
* <p>
* Note that when short-circuiting collector is used as the downstream, to standard JDK collectors like {@link java.util.stream.Collectors#mapping(java.util.function.Function, java.util.stream.Collector) Collectors.mapping(Function, Collector)}
* or {@link java.util.stream.Collectors#partitioningBy(java.util.function.Predicate, java.util.stream.Collector) Collectors.partitioningBy(Predicate, Collector)}, the resulting collector will not be short-circuiting.
* Instead you can use the corresponding method from {@code MoreCollectors} class.
* For example, this way you can get up to two odd and even numbers from the input stream in short-circuiting manner:
*
* <pre>
* Map<Boolean, List<Integer>> map = IntStreamEx.range(0, 100).boxed()
* .collect(MoreCollectors.partitioningBy(x -> x % 2 == 0, MoreCollectors.head(2)));
* </pre>
*
* <p>
* For some operations like {@code groupingBy} it's impossible to create a short-circuiting collector even if the downstream is short-circuiting, because it's not known whether
* all the possible groups are already created.
*
* <p>
* Currently there's no public API to create user-defined short-circuiting collectors.
* Also there are no short-circuiting collectors for primitive streams.
*
* <h3><a name="Associativity">Associativity</a></h3>
*
* An operator or function {@code op} is <em>associative</em> if the following
* holds:
* <pre>{@code
* (a op b) op c == a op (b op c)
* }</pre>
*
* For more information see the {@linkplain java.util.stream Stream API} documentation.
*
* @author Tagir Valeev
*/
package one.util.streamex;
| 61.753012 | 245 | 0.741098 |
0f7f9cd6d6749964dcbc506e22bc90b04dd7bd59 | 578 | package ru.job4j.condition;
/**
*Class DummyBot.
*@author Sigaev Aleksandr (sigaev.aleksandr.v@yandex.ru)
*@version 1.0
*@since 26.01.2018
*/
public class DummyBot {
/**
* Отвечает на вопросы.
* @param question Вопрос от клиента.
* @return Ответ.
*/
public String answer(String question) {
String srl = "Это ставит меня в тупик";
if ("Привет, Бот".equals(question)) {
srl = "Привет, умник";
} else if ("Пока.".equals(question)) {
srl = "До скорой встречи.";
}
return srl;
}
}
| 23.12 | 57 | 0.567474 |
58c1762e8b303020c74df372e920a305e7981357 | 3,613 | package com.jgardella.app.frontend.controller;
import java.io.File;
import java.io.IOException;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.DirectoryChooser;
// Controller and Root for EventTypeView
public class EventTypeView extends VBox
{
@FXML private Label eventLabel;
@FXML private TextField eventDirField;
@FXML private TextField numReqField;
@FXML private TextField totalField;
@FXML private ComboBox<String> reqTypeComboBox;
private File eventTypeDirectory;
private int viewNum;
private EventTypeViewCallback callback;
public interface EventTypeViewCallback
{
public void deleteEventTypeView(EventTypeView view);
}
public EventTypeView(int viewNum, EventTypeViewCallback callback)
{
this.viewNum = viewNum;
this.callback = callback;
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/view/EventTypeView.fxml"));
fxmlLoader.setRoot(this);
fxmlLoader.setController(this);
try
{
fxmlLoader.load();
eventLabel.setText("Event Type #" + viewNum);
}
catch(IOException exception)
{
throw new RuntimeException(exception);
}
}
public EventTypeView(int viewNum, EventTypeViewCallback callback, String eventTypeDir, String reqType, String numReqFieldText, String totalFieldText)
{
this.viewNum = viewNum;
this.callback = callback;
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/view/EventTypeView.fxml"));
fxmlLoader.setRoot(this);
fxmlLoader.setController(this);
try
{
fxmlLoader.load();
eventDirField.setText(eventTypeDir);
eventTypeDirectory = new File(eventTypeDir);
reqTypeComboBox.setValue(reqType);
numReqField.setText(numReqFieldText);
totalField.setText(totalFieldText);
eventLabel.setText("Event Type #" + viewNum + " (" + eventTypeDirectory.getName() + ")");
}
catch(IOException exception)
{
throw new RuntimeException(exception);
}
}
/**
* @return The selected directory for this event type (null if no directory selected).
*/
public File getEventTypeDirectory()
{
return eventTypeDirectory;
}
/**
* @return The value of the number req field.
*/
public int getNumReqField()
{
return Integer.parseInt(numReqField.getText());
}
/**
* @return The value of the total field.
*/
public int getTotalField()
{
return Integer.parseInt(totalField.getText());
}
/**
* @return The value of the req type combo box.
*/
public String getReqType()
{
return reqTypeComboBox.getSelectionModel().getSelectedItem();
}
/**
* @return True if all of the fields in the control have valid values, false otherwise.
*/
public boolean isValid()
{
return eventTypeDirectory != null && numReqField.getText().matches("[0-9]")
&& totalField.getText().matches("[0-9]");
}
@FXML
protected void handleBrowseButton()
{
DirectoryChooser chooser = new DirectoryChooser();
chooser.setInitialDirectory(new File(System.getProperty("user.home")));
eventTypeDirectory = chooser.showDialog(this.getScene().getWindow());
// update text field
if(eventTypeDirectory != null)
{
eventDirField.setText(eventTypeDirectory.getAbsolutePath());
eventLabel.setText("Event Type #" + viewNum + " (" + eventTypeDirectory.getName() + ")");
}
else
{
eventDirField.setText("");
eventLabel.setText("Event Type #" + viewNum);
}
}
@FXML
protected void handleEventRemoveButton()
{
callback.deleteEventTypeView(this);
}
}
| 24.578231 | 151 | 0.728757 |
8a6def7989be2cfea07ee93191e642d0178de005 | 4,883 |
package shiver.me.timbers.aws.msk;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import shiver.me.timbers.aws.Property;
/**
* ClusterBrokerLogs
* <p>
* http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-msk-cluster-brokerlogs.html
*
*/
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonPropertyOrder({
"S3",
"Firehose",
"CloudWatchLogs"
})
public class ClusterBrokerLogs implements Property<ClusterBrokerLogs>
{
/**
* ClusterS3
* <p>
* http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-msk-cluster-s3.html
*
*/
@JsonProperty("S3")
@JsonPropertyDescription("http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-msk-cluster-s3.html")
private Property<ClusterS3> s3;
/**
* ClusterFirehose
* <p>
* http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-msk-cluster-firehose.html
*
*/
@JsonProperty("Firehose")
@JsonPropertyDescription("http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-msk-cluster-firehose.html")
private Property<ClusterFirehose> firehose;
/**
* ClusterCloudWatchLogs
* <p>
* http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-msk-cluster-cloudwatchlogs.html
*
*/
@JsonProperty("CloudWatchLogs")
@JsonPropertyDescription("http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-msk-cluster-cloudwatchlogs.html")
private Property<ClusterCloudWatchLogs> cloudWatchLogs;
/**
* ClusterS3
* <p>
* http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-msk-cluster-s3.html
*
*/
@JsonIgnore
public Property<ClusterS3> getS3() {
return s3;
}
/**
* ClusterS3
* <p>
* http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-msk-cluster-s3.html
*
*/
@JsonIgnore
public void setS3(Property<ClusterS3> s3) {
this.s3 = s3;
}
public ClusterBrokerLogs withS3(Property<ClusterS3> s3) {
this.s3 = s3;
return this;
}
/**
* ClusterFirehose
* <p>
* http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-msk-cluster-firehose.html
*
*/
@JsonIgnore
public Property<ClusterFirehose> getFirehose() {
return firehose;
}
/**
* ClusterFirehose
* <p>
* http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-msk-cluster-firehose.html
*
*/
@JsonIgnore
public void setFirehose(Property<ClusterFirehose> firehose) {
this.firehose = firehose;
}
public ClusterBrokerLogs withFirehose(Property<ClusterFirehose> firehose) {
this.firehose = firehose;
return this;
}
/**
* ClusterCloudWatchLogs
* <p>
* http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-msk-cluster-cloudwatchlogs.html
*
*/
@JsonIgnore
public Property<ClusterCloudWatchLogs> getCloudWatchLogs() {
return cloudWatchLogs;
}
/**
* ClusterCloudWatchLogs
* <p>
* http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-msk-cluster-cloudwatchlogs.html
*
*/
@JsonIgnore
public void setCloudWatchLogs(Property<ClusterCloudWatchLogs> cloudWatchLogs) {
this.cloudWatchLogs = cloudWatchLogs;
}
public ClusterBrokerLogs withCloudWatchLogs(Property<ClusterCloudWatchLogs> cloudWatchLogs) {
this.cloudWatchLogs = cloudWatchLogs;
return this;
}
@Override
public String toString() {
return new ToStringBuilder(this).append("s3", s3).append("firehose", firehose).append("cloudWatchLogs", cloudWatchLogs).toString();
}
@Override
public int hashCode() {
return new HashCodeBuilder().append(s3).append(firehose).append(cloudWatchLogs).toHashCode();
}
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if ((other instanceof ClusterBrokerLogs) == false) {
return false;
}
ClusterBrokerLogs rhs = ((ClusterBrokerLogs) other);
return new EqualsBuilder().append(s3, rhs.s3).append(firehose, rhs.firehose).append(cloudWatchLogs, rhs.cloudWatchLogs).isEquals();
}
}
| 30.141975 | 140 | 0.68462 |
86aac571f1407e008a205b2a2f763f1ea4388d83 | 670 | package com.ruoyi.flowable.domain.vo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.Map;
/**
* <p>流程任务<p>
*
* @author XuanXuan
* @date 2021-04-03
*/
@Data
@ApiModel("工作流任务相关--请求参数")
public class FlowTaskVo {
@ApiModelProperty("任务Id")
private String taskId;
@ApiModelProperty("用户Id")
private String userId;
@ApiModelProperty("任务意见")
private String comment;
@ApiModelProperty("流程实例Id")
private String instanceId;
@ApiModelProperty("退回节点")
private String targetKey;
@ApiModelProperty("流程变量信息")
private Map<String, Object> values;
}
| 18.108108 | 47 | 0.702985 |
54020422200129f5522cf6b69f673b9944f67552 | 2,577 | /*
* 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.jetbrains.python.psi.impl;
import com.intellij.lang.ASTNode;
import com.intellij.psi.util.PsiTreeUtil;
import com.jetbrains.python.PyTokenTypes;
import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider;
import com.jetbrains.python.psi.PyElementVisitor;
import com.jetbrains.python.psi.PyExpression;
import com.jetbrains.python.psi.PyYieldExpression;
import com.jetbrains.python.psi.types.*;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import static com.jetbrains.python.psi.PyUtil.as;
/**
* @author yole
*/
public class PyYieldExpressionImpl extends PyElementImpl implements PyYieldExpression {
public PyYieldExpressionImpl(ASTNode astNode) {
super(astNode);
}
protected void acceptPyVisitor(PyElementVisitor pyVisitor) {
pyVisitor.visitPyYieldExpression(this);
}
@Override
public PyExpression getExpression() {
final PyExpression[] expressions = PsiTreeUtil.getChildrenOfType(this, PyExpression.class);
return (expressions != null && expressions.length > 0) ? expressions[0] : null;
}
@Override
public boolean isDelegating() {
return getNode().findChildByType(PyTokenTypes.FROM_KEYWORD) != null;
}
@Override
public PyType getType(@NotNull TypeEvalContext context, @NotNull TypeEvalContext.Key key) {
final PyExpression e = getExpression();
PyType type = e != null ? context.getType(e) : null;
if (isDelegating()) {
final PyClassLikeType classType = as(type, PyClassLikeType.class);
final PyCollectionType collectionType = as(type, PyCollectionType.class);
if (classType != null && collectionType != null) {
if (PyTypingTypeProvider.GENERATOR.equals(classType.getClassQName())) {
final List<PyType> elementTypes = collectionType.getElementTypes(context);
if (elementTypes.size() == 3) {
return elementTypes.get(2);
}
}
}
return PyNoneType.INSTANCE;
}
return type;
}
}
| 34.36 | 95 | 0.733411 |
dc6b3a41b4655bcdf70c8a9abf3acc89f5a84a04 | 944 | package link.standen.michael.fatesheets.model;
import android.support.annotation.NonNull;
import java.io.Serializable;
/**
* A class for skill information.
*/
public class Skill implements Serializable, Comparable<Skill> {
private Integer value;
private String description;
public Skill(Integer value){
this(value, "");
}
public Skill(Integer value, String description){
this.value = value;
this.description = description;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public int compareTo(@NonNull Skill other) {
if (this.getValue().equals(other.getValue())){
return this.getDescription().compareTo(other.getDescription());
}
return this.getValue().compareTo(other.getValue());
}
}
| 19.666667 | 66 | 0.728814 |
db5c02f6104905491ed412570b7bd2f7675b88cf | 380 | package br.com.omniatechnology.pernavendas.pernavendas.Presenter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
public interface IUsuarioPresenter extends IModelPresenter{
void getDadosSpinnerPerfil(Spinner spinner);
void setSpinnerPerfil(Spinner spinner);
void atualizarList(ListView view, TextView txtEmpty);
}
| 23.75 | 65 | 0.815789 |
3663d70049f0d81265d92dcffb4f89624c56b757 | 4,674 | /*
* Copyright © 2015 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package co.cask.cdap.etl.batch;
import co.cask.cdap.api.data.schema.Schema;
import co.cask.cdap.api.macro.MacroEvaluator;
import co.cask.cdap.api.metrics.Metrics;
import co.cask.cdap.api.workflow.AbstractWorkflow;
import co.cask.cdap.api.workflow.WorkflowContext;
import co.cask.cdap.etl.api.Engine;
import co.cask.cdap.etl.api.batch.BatchActionContext;
import co.cask.cdap.etl.api.batch.PostAction;
import co.cask.cdap.etl.batch.mapreduce.ETLMapReduce;
import co.cask.cdap.etl.common.BasicArguments;
import co.cask.cdap.etl.common.DefaultMacroEvaluator;
import co.cask.cdap.etl.planner.StageInfo;
import co.cask.cdap.etl.spark.batch.ETLSpark;
import co.cask.cdap.internal.io.SchemaTypeAdapter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Workflow for scheduling Batch ETL MapReduce Driver.
*/
public class ETLWorkflow extends AbstractWorkflow {
public static final String NAME = "ETLWorkflow";
public static final String DESCRIPTION = "Workflow for ETL Batch MapReduce Driver";
private static final Logger LOG = LoggerFactory.getLogger(ETLWorkflow.class);
private static final Gson GSON = new GsonBuilder()
.registerTypeAdapter(Schema.class, new SchemaTypeAdapter()).create();
private final Engine engine;
private final BatchPipelineSpec spec;
private Map<String, PostAction> postActions;
// injected by cdap
@SuppressWarnings("unused")
private Metrics workflowMetrics;
public ETLWorkflow(BatchPipelineSpec spec, Engine engine) {
this.engine = engine;
this.spec = spec;
}
@Override
protected void configure() {
setName(NAME);
setDescription(DESCRIPTION);
switch (engine) {
case MAPREDUCE:
addMapReduce(ETLMapReduce.NAME);
break;
case SPARK:
addSpark(ETLSpark.class.getSimpleName());
break;
}
Map<String, String> properties = new HashMap<>();
properties.put("pipeline.spec", GSON.toJson(spec));
setProperties(properties);
}
@Override
public void initialize(WorkflowContext context) throws Exception {
super.initialize(context);
postActions = new LinkedHashMap<>();
BatchPipelineSpec batchPipelineSpec =
GSON.fromJson(context.getWorkflowSpecification().getProperty("pipeline.spec"), BatchPipelineSpec.class);
MacroEvaluator macroEvaluator = new DefaultMacroEvaluator(context.getToken(), context.getRuntimeArguments(),
context.getLogicalStartTime(), context,
context.getNamespace());
for (ActionSpec actionSpec : batchPipelineSpec.getEndingActions()) {
postActions.put(actionSpec.getName(), (PostAction) context.newPluginInstance(actionSpec.getName(),
macroEvaluator));
}
}
@Override
public void destroy() {
WorkflowContext workflowContext = getContext();
if (workflowContext.getDataTracer(PostAction.PLUGIN_TYPE).isEnabled()) {
return;
}
BasicArguments arguments = new BasicArguments(workflowContext.getToken(), workflowContext.getRuntimeArguments());
for (Map.Entry<String, PostAction> endingActionEntry : postActions.entrySet()) {
String name = endingActionEntry.getKey();
PostAction action = endingActionEntry.getValue();
StageInfo stageInfo = StageInfo.builder(name, PostAction.PLUGIN_TYPE)
.setStageLoggingEnabled(spec.isStageLoggingEnabled())
.setProcessTimingEnabled(spec.isProcessTimingEnabled())
.build();
BatchActionContext context = new WorkflowBackedActionContext(workflowContext, workflowMetrics,
stageInfo, arguments);
try {
action.run(context);
} catch (Throwable t) {
LOG.error("Error while running ending action {}.", name, t);
}
}
}
}
| 38.311475 | 117 | 0.700685 |
924960adfae1b7b70cdf798ebbeebca045b0d421 | 2,007 | package com.smartdevicelink.test.rpc.datatypes;
import com.smartdevicelink.proxy.rpc.SeekStreamingIndicator;
import com.smartdevicelink.proxy.rpc.enums.SeekIndicatorType;
import com.smartdevicelink.test.JsonUtils;
import com.smartdevicelink.test.TestValues;
import junit.framework.TestCase;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Iterator;
public class SeekStreamingIndicatorTests extends TestCase {
private SeekStreamingIndicator msg;
@Override
protected void setUp() throws Exception {
msg = new SeekStreamingIndicator();
assertNotNull(TestValues.NOT_NULL, msg);
msg.setType(SeekIndicatorType.TRACK);
msg.setSeekTime(1);
}
public void testRpcValues() {
SeekIndicatorType indicator = msg.getType();
int seekTime = msg.getSeekTime();
assertEquals(TestValues.MATCH, SeekIndicatorType.TRACK, indicator);
assertEquals(TestValues.MATCH, 1, seekTime);
SeekStreamingIndicator msg = new SeekStreamingIndicator();
assertNotNull(TestValues.NOT_NULL, msg);
assertNull(TestValues.NULL, msg.getType());
assertNull(TestValues.NULL, msg.getSeekTime());
}
public void testJson() {
JSONObject reference = new JSONObject();
try {
reference.put(SeekStreamingIndicator.KEY_TYPE, SeekIndicatorType.TRACK);
reference.put(SeekStreamingIndicator.KEY_SEEK_TIME, 1);
JSONObject underTest = msg.serializeJSON();
assertEquals(TestValues.MATCH, reference.length(), underTest.length());
Iterator<?> iterator = reference.keys();
while (iterator.hasNext()) {
String key = (String) iterator.next();
assertEquals(TestValues.MATCH, JsonUtils.readObjectFromJsonObject(reference, key), JsonUtils.readObjectFromJsonObject(underTest, key));
}
} catch (JSONException e) {
fail(TestValues.JSON_FAIL);
}
}
} | 32.901639 | 151 | 0.689586 |
8e8c6c1ed702489c6e37a54af6be16163ef8e609 | 1,360 | /*
* Copyright 2018 ZJNU ACM.
*
* 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 jnc.platform.win32;
@SuppressWarnings("SpellCheckingInspection")
public final class TOKEN_DEFAULT_DACL extends TokenInformation {
public static TOKEN_DEFAULT_DACL ofSize(int size) {
TOKEN_DEFAULT_DACL tokenDefaultDacl = new TOKEN_DEFAULT_DACL();
if (size > Lazy.SIZE) {
tokenDefaultDacl.padding(size - Lazy.SIZE);
}
return tokenDefaultDacl;
}
private final Pointer DefaultDacl = new Pointer();
public final jnc.foreign.Pointer getDefaultDacl() {
return this.DefaultDacl.get();
}
public final void setDefaultDacl(jnc.foreign.Pointer value) {
this.DefaultDacl.set(value);
}
private interface Lazy {
int SIZE = new TOKEN_DEFAULT_DACL().size();
}
}
| 29.565217 | 75 | 0.702941 |
a73e5aa7e53fc37d7e2f135c2b6e9d737e1a4f5a | 2,282 | package com.github.chen0040.zookeeper.clients;
import com.github.chen0040.zkcoordinator.models.NodeUri;
import com.github.chen0040.zkcoordinator.models.ZkConfig;
import com.github.chen0040.zkcoordinator.nodes.RequestNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.List;
import java.util.Random;
import static spark.Spark.get;
import static spark.Spark.port;
/**
* Created by xschen on 1/7/2017.
*/
public class ProducerNodeServer extends RequestNode {
private static final Logger logger = LoggerFactory.getLogger(ProducerNodeServer.class);
final Random random = new Random();
public ProducerNodeServer(ZkConfig zkConfig) {
super(zkConfig);
}
@Override public void startSystem(String ipAddress, int port, String masterId){
logger.info("start system at {}:{} with id = {}", ipAddress, port, masterId);
port(port);
get("/hello", (req, res) -> {
List<NodeUri> masters = this.getMasters();
if(masters.isEmpty()) {
return "No master to handle the hello-task";
}
NodeUri anyMaster = masters.get(random.nextInt(masters.size()));
int masterPort = anyMaster.getPort();
String masterHost = anyMaster.getHost();
final String masterWebApiUrl = "http://" + masterHost + ":" + masterPort + "/hello";
StringBuilder sb = new StringBuilder();
sb.append("This is the producer node at " + this.getIpAddress() + ":" + this.getRegisteredPort() + " currently querying master " + masterWebApiUrl);
sb.append("<br />");
sb.append(HttpClient.get(masterWebApiUrl));
return sb.toString();
});
}
@Override public void stopSystem() {
logger.info("system shutdown");
}
public static void main(String[] args) throws IOException, InterruptedException {
ZkConfig config = new ZkConfig();
config.setZkConnect("localhost:2181");
int startingPort = 7000;
config.setStartingPort(startingPort); // request node java program will find an un-used port from the port range starting at 7000
final ProducerNodeServer application = new ProducerNodeServer(config);
application.addShutdownHook();
application.start();
}
}
| 32.6 | 157 | 0.683611 |
781c44a425e73814a926039157f962c860052ab3 | 3,292 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package net.morimekta.providence.serializer;
import net.morimekta.providence.PServiceCallType;
import net.morimekta.util.Stringable;
import com.google.common.base.MoreObjects;
/**
* @author Stein Eldar Johnsen
* @since 19.09.15
*/
public class SerializerException extends Exception implements Stringable {
private final static long serialVersionUID = 1442914425369642982L;
private String methodName;
private PServiceCallType callType;
private int sequenceNo;
private ApplicationExceptionType exceptionType;
public SerializerException(String format, Object... args) {
super(args.length == 0 ? format : String.format(format, args));
exceptionType = ApplicationExceptionType.PROTOCOL_ERROR;
}
public SerializerException(Throwable cause, String format, Object... args) {
super(args.length == 0 ? format : String.format(format, args), cause);
exceptionType = ApplicationExceptionType.PROTOCOL_ERROR;
}
public String getMethodName() {
return methodName == null ? "" : methodName;
}
public PServiceCallType getCallType() {
return callType;
}
public int getSequenceNo() {
return sequenceNo;
}
public ApplicationExceptionType getExceptionType() {
return exceptionType;
}
public SerializerException setMethodName(String methodName) {
this.methodName = methodName;
return this;
}
public SerializerException setCallType(PServiceCallType callType) {
this.callType = callType;
return this;
}
public SerializerException setSequenceNo(int sequenceNo) {
this.sequenceNo = sequenceNo;
return this;
}
public SerializerException setExceptionType(ApplicationExceptionType type) {
this.exceptionType = type;
return this;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(getClass())
.omitNullValues()
.addValue(getMessage())
.add("method", methodName)
.add("type", callType)
.add("seq", sequenceNo)
.toString();
}
@Override
public String asString() {
if (methodName != null) {
return "Error in " + methodName + ": " + getMessage();
} else {
return "Error: " + getMessage();
}
}
}
| 31.352381 | 80 | 0.657351 |
653655914a0a2ad18762824eb8841118f386acf7 | 2,424 | /**
* Mirai Song Plugin
* Copyright (C) 2021 khjxiaogu
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.khjxiaogu.MiraiSongPlugin.musicsource;
import java.io.FileReader;
import java.net.URLDecoder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.khjxiaogu.MiraiSongPlugin.MusicInfo;
import com.khjxiaogu.MiraiSongPlugin.MusicSource;
import com.khjxiaogu.MiraiSongPlugin.Utils;
public class LocalFileSource implements MusicSource {
public static boolean autoLocal = false;
@Override
public boolean isVisible() {
return autoLocal;
}
public LocalFileSource() {
}
String forceGetJsonString(JsonObject jo, String member) {
return forceGetJsonString(jo, member, "");
}
String forceGetJsonString(JsonObject jo, String member, String def) {
if (jo.has(member))
return jo.get(member).getAsString();
return def;
}
@Override
public MusicInfo get(String keyword) throws Exception {
String rkw = URLDecoder.decode(keyword, "UTF-8");
try(FileReader fr=new FileReader("SongPluginLocal.json")){
JsonArray localfs = JsonParser.parseReader(fr).getAsJsonArray();
JsonObject result = null;
double min = Integer.MAX_VALUE;
for (JsonElement je : localfs) {
JsonObject cur = je.getAsJsonObject();
String ckw = forceGetJsonString(cur, "title");
double curm = Utils.compare(rkw, ckw);
if (curm < min) {
min = curm;
result = cur;
}
}
return new MusicInfo(forceGetJsonString(result, "title"), forceGetJsonString(result, "desc"),
forceGetJsonString(result, "previewUrl"), forceGetJsonString(result, "musicUrl"),
forceGetJsonString(result, "jumpUrl"), forceGetJsonString(result, "source", "本地"));
}
}
}
| 31.480519 | 96 | 0.736386 |
1a1d671c3e7d9336f32dbe6c53420fa578f83b28 | 1,884 | package uk.gov.hmcts.reform.sandl.snlapi.config;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.ResponseErrorHandler;
import uk.gov.hmcts.reform.sandl.snlapi.exceptions.BeanValidationException;
import uk.gov.hmcts.reform.sandl.snlapi.exceptions.OptimisticLockException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import static org.mockito.Mockito.when;
@RunWith(SpringRunner.class)
public class RestTemplateConfigurationTest {
@Mock
ClientHttpResponse response;
@Test(expected = OptimisticLockException.class)
public void handleError_ThrowsExceptionOnConflict() throws IOException {
when(response.getStatusCode()).thenReturn(HttpStatus.CONFLICT);
ResponseErrorHandler handler = new RestTemplateConfiguration()
.restTemplate(new RestTemplateBuilder())
.getErrorHandler();
handler.handleError(response);
}
@Test(expected = BeanValidationException.class)
public void handleError_ThrowsExceptionOnBadRequest() throws IOException {
when(response.getStatusCode()).thenReturn(HttpStatus.BAD_REQUEST);
String validationErrorString = "{\"errorDetailsList\":[{\"field\":\"duration\","
+ "\"errorMessage\":\"Duration is shorter than 1 minutes\"}]}";
when(response.getBody()).thenReturn(new ByteArrayInputStream(validationErrorString.getBytes()));
ResponseErrorHandler handler = new RestTemplateConfiguration()
.restTemplate(new RestTemplateBuilder())
.getErrorHandler();
handler.handleError(response);
}
}
| 37.68 | 104 | 0.757962 |
31f55900115021620c34a6ae7b59cd5af9facb91 | 1,311 | package edu.udel.cis.vsl.abc.ast.value.common;
import edu.udel.cis.vsl.abc.ast.type.IF.IntegerType;
import edu.udel.cis.vsl.abc.ast.value.IF.CharacterValue;
import edu.udel.cis.vsl.abc.ast.value.IF.ValueFactory.Answer;
import edu.udel.cis.vsl.abc.token.IF.ExecutionCharacter;
public class CommonCharacterValue extends CommonValue implements CharacterValue {
private final static int classCode = CommonCharacterValue.class.hashCode();
private ExecutionCharacter character;
public CommonCharacterValue(IntegerType type, ExecutionCharacter character) {
super(type);
assert character != null;
this.character = character;
}
@Override
public boolean equals(Object object) {
if (this == object)
return true;
if (object instanceof CommonCharacterValue) {
CommonCharacterValue that = (CommonCharacterValue) object;
return getType().equals(that.getType())
&& character.equals(that.character);
}
return false;
}
@Override
public int hashCode() {
return classCode + getType().hashCode() + character.hashCode();
}
@Override
public ExecutionCharacter getCharacter() {
return character;
}
@Override
public Answer isZero() {
return character.getCodePoint() == 0 ? Answer.YES : Answer.NO;
}
@Override
public String toString() {
return character.toString();
}
}
| 24.277778 | 81 | 0.748284 |
d5851d9a2e4dc09492742db8fc7ac09a3c4339ad | 2,522 | package ar.edu.itba.ss;
public class Particle {
private static int counter = 1;
private Coordinates position;
private Double radius;
private Double color;
private Velocity velocity;
private int ID;
public Particle(Coordinates position, double radius,double color, Velocity velocity) {
this.position = position;
this.radius = radius;
this.velocity = velocity;
this.ID=counter++;
this.color = color;
}
public Particle(Coordinates position, double radius, double color) {
this(position,radius,color, new Velocity(0,0));
}
public Coordinates getPosition() {
return position;
}
public Double getRadius() {
return radius;
}
public int getID(){
return this.ID;
}
public Double getColor() {
return color;
}
public Velocity getVelocity() {
return velocity;
}
public void setRadius(Double radius) {
this.radius = radius;
}
public Double getDistance(Particle particle){
return Math.sqrt(Math.pow(this.getPosition().getX()-particle.getPosition().getX(), 2) +
Math.pow(this.getPosition().getY()-particle.getPosition().getY(), 2));
}
public double getPeriodicDistance(Particle particle, double L){
double dx = Math.abs(this.getPosition().getX() - particle.getPosition().getX());
if (dx > L / 2)
dx = L - dx;
double dy = Math.abs(this.getPosition().getY() - particle.getPosition().getY());
if (dy > L / 2)
dy = L - dy;
return Math.sqrt(Math.pow(dx,2) + Math.pow(dy,2));
}
public void updatePos(double time){
double x = position.getX()+velocity.getX()*time;
double y = position.getY()+velocity.getY()*time;
this.position.setX(x);
this.position.setY(y);
}
public void setPosition(double x, double y){
this.position.setX(x);
this.position.setY(y);
}
public void setAngle(double ang){
this.velocity.setAngle(ang);
}
@Override
public boolean equals(Object obj) {
if (obj == this)
return true;
if (!(obj instanceof Particle))
return false;
Particle other = (Particle) obj;
return (getID() == other.getID()) || (getPosition().equals(other.getPosition()) && getRadius().equals(other.getRadius()));
}
@Override
public int hashCode() {
return Integer.hashCode(getID());
}
}
| 25.734694 | 130 | 0.594766 |
bb4cd65be4563341e68a4a2c74d66e8a09f77f7c | 5,517 | package com.portalbot.main;
import com.portalbot.main.exceptions.BadLoggingException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
public class TaskListener {
private DataStream data;
private HttpConnection httpConnection;
private Serializer serializer;
private TaskParser taskParser;
private GarbageCollector gc = new GarbageCollector();
public TaskListener() {
data = new DataStream();
httpConnection = new HttpConnection();
serializer = new Serializer();
taskParser = new TaskParser();
}
public List<Task> listen(String chatID) throws BadLoggingException {
User user = serializer.loadTasks(chatID);
List<Task> newTasks = new ArrayList<>();
Map<String, Task> oldTasks;
List<Task> result;
String year = new SimpleDateFormat("yyyy").format(new Date());
String month = new SimpleDateFormat("MM").format(new Date());
String day = new SimpleDateFormat("dd").format(new Date());
DateIterator dateIterator = new DateIterator(year, month, day);
for (int i = 0; i < 7; i++) {
if (!user.getPortalLogin().equals("") && !user.getPortalPassword().equals("")) {
logging(user.getPortalLogin(), user.getPortalPassword());
} else {
break;
}
String currentDate = dateIterator.next();
switching(currentDate);
List<Task> temp;
try {
temp = taskParser.execute(data.getBody());
} catch (NullPointerException npe) {
i--;
LogWriter.add("HttpConnection is broke. One more trying to connect...");
continue;
}
setDate(temp, currentDate);
setOwnersChatID(temp, chatID);
newTasks.addAll(temp);
}
oldTasks = serializer.loadTasks(chatID).getTasks();
result = compareTasks(oldTasks, newTasks);
newTasks = removeTaskNumbersDuplicates(newTasks);
gc.turn(newTasks, chatID);
user.setTasks(newTasks.stream().collect(Collectors.toMap(o -> o.getTaskNumber(), o -> o)));
serializer.saveTasks(user);
return result;
}
public void logging(String login, String password) {
LogWriter.add(String.format("Logging in to login: %s", login));
data.setQuery("https://portal.alpm.com.ua/index.php?action=login");
data.setParams(String.format("login=%s&password=%s", login, password));
data = httpConnection.start(data);
}
public void switching(String date) {
LogWriter.add(String.format("Switching to date: %s", date));
data.setQuery("https://portal.alpm.com.ua/headless.php");
data.setParams(String.format("action=workschedule1&city=&data=%s", date));
data = httpConnection.start(data);
}
public List<Task> compareTasks(Map<String, Task> oldTasks, List<Task> newTasks) {
List<Task> result = new ArrayList<>();
for (Task newTask : newTasks) {
Task oldTask = oldTasks.get(newTask.getTaskNumber());
if (!oldTasks.containsKey(newTask.getTaskNumber())) {
LogWriter.add(String.format("Detected a new task %s", newTask.getTaskNumber()));
newTask.setStatusMessage(String.format("ДОБАВЛЕНА [НОВАЯ ЗАЯВКА](https://portal.alpm.com.ua/index.php?action=editWorkRequest_new&id=%s): ", newTask.getPortalTaskNumber()));
result.add(newTask);
} else if ((oldTask != null && !oldTask.getDate().equals(newTask.getDate()) && oldTask.getAddress().equals(newTask.getAddress()))
|| (oldTask != null && !oldTask.getTime().equals(newTask.getTime())) && oldTask.getAddress().equals(newTask.getAddress())) {
LogWriter.add(String.format("Detected moving the task %s", newTask.getTaskNumber()));
newTask.setStatusMessage(String.format("[ЗАЯВКА](https://portal.alpm.com.ua/index.php?action=editWorkRequest_new&id=%s) ПЕРЕНЕСЕНА С %s(%s) НА %s(%s)", newTask.getPortalTaskNumber(), oldTask.getDate(), oldTask.getTime(), newTask.getDate(), newTask.getTime()));
result.add(newTask);
}
}
return result;
}
public void setDate(List<Task> tasks, String date) {
tasks.stream().forEach(task -> task.setDate(date));
}
public List<Task> removeTaskNumbersDuplicates(List<Task> tasks) {
List<Task> result = new ArrayList<>();
for (Task task : tasks) {
List<String> strResult = result.stream().collect(() -> new ArrayList<String>(), (list, element) -> list.add(element.getTaskNumber()), (list1, list2)-> list1.addAll(list2));
if (!strResult.contains(task.getTaskNumber())) {
result.add(task);
}
}
return result;
}
public boolean checkingForClosing(String chatID) {
boolean result = false;
User user = serializer.loadTasks(chatID);
for (Task task : user.getTasks().values()) {
if (task.getStatus() != null && task.getStatus().equals("Назначено") && task.getDate().equals(new SimpleDateFormat("yyyy-MM-dd").format(new Date()))) {
result = true;
break;
}
}
return result;
}
public void setOwnersChatID(List<Task> tasks, String chatID) {
tasks.forEach(task -> task.setOwnersChatID(chatID));
}
}
| 42.114504 | 276 | 0.612833 |
e1f97feabab18c2d4548b762590052f4b7d16755 | 3,185 | /*
* Copyright 2021 dmfs GmbH
*
*
* 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.dmfs.jems2.iterable;
import org.junit.Test;
import static org.dmfs.jems2.hamcrest.matchers.iterable.IterableMatcher.iteratesTo;
import static org.dmfs.jems2.hamcrest.matchers.pair.PairMatcher.pair;
import static org.hamcrest.Matchers.emptyIterable;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
/**
*
*/
public class NumberedTest
{
@Test
public void testEmpty()
{
assertThat(new Numbered<>(EmptyIterable.emptyIterable()), emptyIterable());
assertThat(new Numbered<>(EmptyIterable.emptyIterable(), 1), emptyIterable());
assertThat(new Numbered<>(EmptyIterable.emptyIterable(), 1, 1), emptyIterable());
}
@Test
public void testBase0Step1()
{
assertThat(new Numbered<>(new Seq<>("a")), iteratesTo(pair(is(0), is("a"))));
assertThat(new Numbered<>(new Seq<>("a", "b", "c")), iteratesTo(pair(is(0), is("a")), pair(is(1), is("b")), pair(is(2), is("c"))));
assertThat(new Numbered<>(new Seq<>("a"), 0), iteratesTo(pair(is(0), is("a"))));
assertThat(new Numbered<>(new Seq<>("a", "b", "c"), 0), iteratesTo(pair(is(0), is("a")), pair(is(1), is("b")), pair(is(2), is("c"))));
assertThat(new Numbered<>(new Seq<>("a"), 0, 1), iteratesTo(pair(is(0), is("a"))));
assertThat(new Numbered<>(new Seq<>("a", "b", "c"), 0, 1), iteratesTo(pair(is(0), is("a")), pair(is(1), is("b")), pair(is(2), is("c"))));
}
@Test
public void testBase1Step1()
{
assertThat(new Numbered<>(new Seq<>("a"), 1), iteratesTo(pair(is(1), is("a"))));
assertThat(new Numbered<>(new Seq<>("a", "b", "c"), 1), iteratesTo(pair(is(1), is("a")), pair(is(2), is("b")), pair(is(3), is("c"))));
assertThat(new Numbered<>(new Seq<>("a"), 1, 1), iteratesTo(pair(is(1), is("a"))));
assertThat(new Numbered<>(new Seq<>("a", "b", "c"), 1, 1), iteratesTo(pair(is(1), is("a")), pair(is(2), is("b")), pair(is(3), is("c"))));
}
@Test
public void testBase0Step10()
{
assertThat(new Numbered<>(new Seq<>("a"), 0, 10), iteratesTo(pair(is(0), is("a"))));
assertThat(new Numbered<>(new Seq<>("a", "b", "c"), 0, 10), iteratesTo(pair(is(0), is("a")), pair(is(10), is("b")), pair(is(20), is("c"))));
}
@Test
public void testBase10Step10()
{
assertThat(new Numbered<>(new Seq<>("a"), 10, 10), iteratesTo(pair(is(10), is("a"))));
assertThat(new Numbered<>(new Seq<>("a", "b", "c"), 10, 10), iteratesTo(pair(is(10), is("a")), pair(is(20), is("b")), pair(is(30), is("c"))));
}
} | 38.373494 | 150 | 0.605651 |
d2efcdc865d364d091083d6163dfb37a3f6d7aba | 2,066 | /*
* jmimeinfo is an implementation of shared mime info specification
* The MIT License (MIT)
*
* Copyright (c) 2014 Andy Hedges
*
* 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.hedges.mimeinfo.test.globs;
import java.io.IOException;
import junit.framework.TestCase;
import net.hedges.mimeinfo.MimeInfoException;
import net.hedges.mimeinfo.globs.GlobsFileFactory;
import net.hedges.mimeinfo.util.IoUtil;
public class TestGlobs extends TestCase {
public void testNonCorruptGlobs() throws IOException, MimeInfoException {
GlobsFileFactory.create(IoUtil.getClasspathUrl("share/mime/globs"));
}
public void testCorruptHeaderGlobs() throws IOException {
// Just picked a file that I know exists but isn't a magic file
boolean exceptionHappened = false;
try {
GlobsFileFactory.create(IoUtil.getClasspathUrl("share/mime/magic"));
} catch (MimeInfoException e) {
exceptionHappened = true;
}
assertTrue(exceptionHappened);
}
}
| 40.509804 | 80 | 0.742498 |
90e78e1634f855afb045eec21cb1dda893c70a38 | 46,577 | /**
* 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.cxf.ws.rm.persistence.jdbc;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import javax.sql.DataSource;
import org.apache.cxf.common.i18n.Message;
import org.apache.cxf.common.injection.NoJSR250Annotations;
import org.apache.cxf.common.logging.LogUtils;
import org.apache.cxf.common.util.SystemPropertyAction;
import org.apache.cxf.helpers.IOUtils;
import org.apache.cxf.io.CachedOutputStream;
import org.apache.cxf.ws.addressing.EndpointReferenceType;
import org.apache.cxf.ws.rm.DestinationSequence;
import org.apache.cxf.ws.rm.ProtocolVariation;
import org.apache.cxf.ws.rm.RMUtils;
import org.apache.cxf.ws.rm.SourceSequence;
import org.apache.cxf.ws.rm.persistence.PersistenceUtils;
import org.apache.cxf.ws.rm.persistence.RMMessage;
import org.apache.cxf.ws.rm.persistence.RMStore;
import org.apache.cxf.ws.rm.persistence.RMStoreException;
import org.apache.cxf.ws.rm.v200702.Identifier;
import org.apache.cxf.ws.rm.v200702.SequenceAcknowledgement;
@NoJSR250Annotations
public class RMTxStore implements RMStore {
public static final String DEFAULT_DATABASE_NAME = "rmdb";
private static final String[][] DEST_SEQUENCES_TABLE_COLS
= {{"SEQ_ID", "VARCHAR(256) NOT NULL"},
{"ACKS_TO", "VARCHAR(1024) NOT NULL"},
{"LAST_MSG_NO", "DECIMAL(19, 0)"},
{"ENDPOINT_ID", "VARCHAR(1024)"},
{"ACKNOWLEDGED", "BLOB"},
{"TERMINATED", "CHAR(1)"},
{"PROTOCOL_VERSION", "VARCHAR(256)"}};
private static final String[] DEST_SEQUENCES_TABLE_KEYS = {"SEQ_ID"};
private static final String[][] SRC_SEQUENCES_TABLE_COLS
= {{"SEQ_ID", "VARCHAR(256) NOT NULL"},
{"CUR_MSG_NO", "DECIMAL(19, 0) DEFAULT 1 NOT NULL"},
{"LAST_MSG", "CHAR(1)"},
{"EXPIRY", "DECIMAL(19, 0)"},
{"OFFERING_SEQ_ID", "VARCHAR(256)"},
{"ENDPOINT_ID", "VARCHAR(1024)"},
{"PROTOCOL_VERSION", "VARCHAR(256)"}};
private static final String[] SRC_SEQUENCES_TABLE_KEYS = {"SEQ_ID"};
private static final String[][] MESSAGES_TABLE_COLS
= {{"SEQ_ID", "VARCHAR(256) NOT NULL"},
{"MSG_NO", "DECIMAL(19, 0) NOT NULL"},
{"SEND_TO", "VARCHAR(256)"},
{"CREATED_TIME", "DECIMAL(19, 0)"},
{"CONTENT", "BLOB"},
{"CONTENT_TYPE", "VARCHAR(1024)"}};
private static final String[] MESSAGES_TABLE_KEYS = {"SEQ_ID", "MSG_NO"};
private static final String DEST_SEQUENCES_TABLE_NAME = "CXF_RM_DEST_SEQUENCES";
private static final String SRC_SEQUENCES_TABLE_NAME = "CXF_RM_SRC_SEQUENCES";
private static final String INBOUND_MSGS_TABLE_NAME = "CXF_RM_INBOUND_MESSAGES";
private static final String OUTBOUND_MSGS_TABLE_NAME = "CXF_RM_OUTBOUND_MESSAGES";
private static final String CREATE_DEST_SEQUENCES_TABLE_STMT =
buildCreateTableStatement(DEST_SEQUENCES_TABLE_NAME,
DEST_SEQUENCES_TABLE_COLS, DEST_SEQUENCES_TABLE_KEYS);
private static final String CREATE_SRC_SEQUENCES_TABLE_STMT =
buildCreateTableStatement(SRC_SEQUENCES_TABLE_NAME,
SRC_SEQUENCES_TABLE_COLS, SRC_SEQUENCES_TABLE_KEYS);
private static final String CREATE_MESSAGES_TABLE_STMT =
buildCreateTableStatement("{0}", MESSAGES_TABLE_COLS, MESSAGES_TABLE_KEYS);
private static final String CREATE_DEST_SEQUENCE_STMT_STR
= "INSERT INTO CXF_RM_DEST_SEQUENCES "
+ "(SEQ_ID, ACKS_TO, ENDPOINT_ID, PROTOCOL_VERSION) "
+ "VALUES(?, ?, ?, ?)";
private static final String CREATE_SRC_SEQUENCE_STMT_STR
= "INSERT INTO CXF_RM_SRC_SEQUENCES "
+ "(SEQ_ID, CUR_MSG_NO, LAST_MSG, EXPIRY, OFFERING_SEQ_ID, ENDPOINT_ID, PROTOCOL_VERSION) "
+ "VALUES(?, 1, '0', ?, ?, ?, ?)";
private static final String DELETE_DEST_SEQUENCE_STMT_STR =
"DELETE FROM CXF_RM_DEST_SEQUENCES WHERE SEQ_ID = ?";
private static final String DELETE_SRC_SEQUENCE_STMT_STR =
"DELETE FROM CXF_RM_SRC_SEQUENCES WHERE SEQ_ID = ?";
private static final String UPDATE_DEST_SEQUENCE_STMT_STR =
"UPDATE CXF_RM_DEST_SEQUENCES SET LAST_MSG_NO = ?, TERMINATED = ?, ACKNOWLEDGED = ? WHERE SEQ_ID = ?";
private static final String UPDATE_SRC_SEQUENCE_STMT_STR =
"UPDATE CXF_RM_SRC_SEQUENCES SET CUR_MSG_NO = ?, LAST_MSG = ? WHERE SEQ_ID = ?";
private static final String CREATE_MESSAGE_STMT_STR
= "INSERT INTO {0} (SEQ_ID, MSG_NO, SEND_TO, CREATED_TIME, CONTENT, CONTENT_TYPE) VALUES(?, ?, ?, ?, ?, ?)";
private static final String DELETE_MESSAGE_STMT_STR =
"DELETE FROM {0} WHERE SEQ_ID = ? AND MSG_NO = ?";
private static final String SELECT_DEST_SEQUENCE_STMT_STR =
"SELECT ACKS_TO, LAST_MSG_NO, PROTOCOL_VERSION, TERMINATED, ACKNOWLEDGED FROM CXF_RM_DEST_SEQUENCES "
+ "WHERE SEQ_ID = ?";
private static final String SELECT_SRC_SEQUENCE_STMT_STR =
"SELECT CUR_MSG_NO, LAST_MSG, EXPIRY, OFFERING_SEQ_ID, PROTOCOL_VERSION FROM CXF_RM_SRC_SEQUENCES "
+ "WHERE SEQ_ID = ?";
private static final String SELECT_DEST_SEQUENCES_STMT_STR =
"SELECT SEQ_ID, ACKS_TO, LAST_MSG_NO, PROTOCOL_VERSION, TERMINATED, ACKNOWLEDGED FROM CXF_RM_DEST_SEQUENCES "
+ "WHERE ENDPOINT_ID = ?";
private static final String SELECT_SRC_SEQUENCES_STMT_STR =
"SELECT SEQ_ID, CUR_MSG_NO, LAST_MSG, EXPIRY, OFFERING_SEQ_ID, PROTOCOL_VERSION "
+ "FROM CXF_RM_SRC_SEQUENCES WHERE ENDPOINT_ID = ?";
private static final String SELECT_MESSAGES_STMT_STR =
"SELECT MSG_NO, SEND_TO, CREATED_TIME, CONTENT, CONTENT_TYPE FROM {0} WHERE SEQ_ID = ?";
private static final String ALTER_TABLE_STMT_STR =
"ALTER TABLE {0} ADD {1} {2}";
private static final String CREATE_INBOUND_MESSAGE_STMT_STR =
MessageFormat.format(CREATE_MESSAGE_STMT_STR, INBOUND_MSGS_TABLE_NAME);
private static final String CREATE_OUTBOUND_MESSAGE_STMT_STR =
MessageFormat.format(CREATE_MESSAGE_STMT_STR, OUTBOUND_MSGS_TABLE_NAME);
private static final String DELETE_INBOUND_MESSAGE_STMT_STR =
MessageFormat.format(DELETE_MESSAGE_STMT_STR, INBOUND_MSGS_TABLE_NAME);
private static final String DELETE_OUTBOUND_MESSAGE_STMT_STR =
MessageFormat.format(DELETE_MESSAGE_STMT_STR, OUTBOUND_MSGS_TABLE_NAME);
private static final String SELECT_INBOUND_MESSAGES_STMT_STR =
MessageFormat.format(SELECT_MESSAGES_STMT_STR, INBOUND_MSGS_TABLE_NAME);
private static final String SELECT_OUTBOUND_MESSAGES_STMT_STR =
MessageFormat.format(SELECT_MESSAGES_STMT_STR, OUTBOUND_MSGS_TABLE_NAME);
// create_schema may not work for several reasons, if so, create one manually
private static final String CREATE_SCHEMA_STMT_STR = "CREATE SCHEMA {0}";
// given the schema, try these standard statements to switch to the schema
private static final String[] SET_SCHEMA_STMT_STRS = {"SET SCHEMA {0}",
"SET CURRENT_SCHEMA = {0}",
"ALTER SESSION SET CURRENT_SCHEMA = {0}"};
private static final String DERBY_TABLE_EXISTS_STATE = "X0Y32";
private static final int ORACLE_TABLE_EXISTS_CODE = 955;
private static final Logger LOG = LogUtils.getL7dLogger(RMTxStore.class);
// the connection and statements are cached only if
private boolean keepConnection = true;
private Connection connection;
private boolean createdConnection = true;
private Map<Statement, Lock> statementLocks;
private Map<String, PreparedStatement> cachedStatements;
private DataSource dataSource;
private String driverClassName = "org.apache.derby.jdbc.EmbeddedDriver";
private String url = MessageFormat.format("jdbc:derby:{0};create=true", DEFAULT_DATABASE_NAME);
private String userName;
private String password;
private String schemaName;
private long initialReconnectDelay = 60000L;
private int useExponentialBackOff = 2;
private int maxReconnectAttempts = 10;
private long reconnectDelay;
private int reconnectAttempts;
private long nextReconnectAttempt;
private String tableExistsState = DERBY_TABLE_EXISTS_STATE;
private int tableExistsCode = ORACLE_TABLE_EXISTS_CODE;
public RMTxStore() {
}
public void destroy() {
if (connection != null && createdConnection) {
try {
connection.close();
} catch (SQLException e) {
//ignore
}
connection = null;
}
}
// configuration
public void setDriverClassName(String dcn) {
driverClassName = dcn;
}
public String getDriverClassName() {
return driverClassName;
}
public void setPassword(String p) {
password = p;
}
public String getPassword() {
return password;
}
public void setUrl(String u) {
url = u;
}
public String getUrl() {
return url;
}
public void setUserName(String un) {
userName = un;
}
public String getUserName() {
return userName;
}
public String getSchemaName() {
return schemaName;
}
public void setSchemaName(String sn) {
if (sn == null || Pattern.matches("[a-zA-Z\\d]{1,32}", sn)) {
schemaName = sn;
} else {
throw new IllegalArgumentException("Invalid schema name: " + sn);
}
}
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource ds) {
dataSource = ds;
}
public String getTableExistsState() {
return tableExistsState;
}
public void setTableExistsState(String tableExistsState) {
this.tableExistsState = tableExistsState;
}
public int getTableExistsCode() {
return tableExistsCode;
}
public void setTableExistsCode(int tableExistsCode) {
this.tableExistsCode = tableExistsCode;
}
public boolean isKeepConnection() {
return keepConnection;
}
public void setKeepConnection(boolean keepConnection) {
this.keepConnection = keepConnection;
}
public long getInitialReconnectDelay() {
return initialReconnectDelay;
}
public void setInitialReconnectDelay(long initialReconnectDelay) {
this.initialReconnectDelay = initialReconnectDelay;
}
public int getMaxReconnectAttempts() {
return maxReconnectAttempts;
}
public void setMaxReconnectAttempts(int maxReconnectAttempts) {
this.maxReconnectAttempts = maxReconnectAttempts;
}
public void setConnection(Connection c) {
connection = c;
createdConnection = false;
}
// RMStore interface
public void createDestinationSequence(DestinationSequence seq) {
String sequenceIdentifier = seq.getIdentifier().getValue();
String endpointIdentifier = seq.getEndpointIdentifier();
String protocolVersion = encodeProtocolVersion(seq.getProtocol());
if (LOG.isLoggable(Level.FINE)) {
LOG.info("Creating destination sequence: " + sequenceIdentifier + ", (endpoint: "
+ endpointIdentifier + ")");
}
Connection con = verifyConnection();
PreparedStatement stmt = null;
SQLException conex = null;
try {
beginTransaction();
stmt = getStatement(con, CREATE_DEST_SEQUENCE_STMT_STR);
stmt.setString(1, sequenceIdentifier);
String addr = seq.getAcksTo().getAddress().getValue();
stmt.setString(2, addr);
stmt.setString(3, endpointIdentifier);
stmt.setString(4, protocolVersion);
stmt.execute();
commit(con);
} catch (SQLException ex) {
abort(con);
conex = ex;
throw new RMStoreException(ex);
} finally {
releaseResources(stmt, null);
updateConnectionState(con, conex);
}
}
public void createSourceSequence(SourceSequence seq) {
String sequenceIdentifier = seq.getIdentifier().getValue();
String endpointIdentifier = seq.getEndpointIdentifier();
String protocolVersion = encodeProtocolVersion(seq.getProtocol());
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("Creating source sequence: " + sequenceIdentifier + ", (endpoint: "
+ endpointIdentifier + ")");
}
Connection con = verifyConnection();
PreparedStatement stmt = null;
SQLException conex = null;
try {
beginTransaction();
stmt = getStatement(con, CREATE_SRC_SEQUENCE_STMT_STR);
stmt.setString(1, sequenceIdentifier);
Date expiry = seq.getExpires();
stmt.setLong(2, expiry == null ? 0 : expiry.getTime());
Identifier osid = seq.getOfferingSequenceIdentifier();
stmt.setString(3, osid == null ? null : osid.getValue());
stmt.setString(4, endpointIdentifier);
stmt.setString(5, protocolVersion);
stmt.execute();
commit(con);
} catch (SQLException ex) {
conex = ex;
abort(con);
throw new RMStoreException(ex);
} finally {
releaseResources(stmt, null);
updateConnectionState(con, conex);
}
}
public DestinationSequence getDestinationSequence(Identifier sid) {
if (LOG.isLoggable(Level.FINE)) {
LOG.info("Getting destination sequence for id: " + sid);
}
Connection con = verifyConnection();
PreparedStatement stmt = null;
SQLException conex = null;
ResultSet res = null;
try {
stmt = getStatement(con, SELECT_DEST_SEQUENCE_STMT_STR);
stmt.setString(1, sid.getValue());
res = stmt.executeQuery();
if (res.next()) {
EndpointReferenceType acksTo = RMUtils.createReference(res.getString(1));
long lm = res.getLong(2);
ProtocolVariation pv = decodeProtocolVersion(res.getString(3));
boolean t = res.getBoolean(4);
InputStream is = res.getBinaryStream(5);
SequenceAcknowledgement ack = null;
if (null != is) {
ack = PersistenceUtils.getInstance()
.deserialiseAcknowledgment(is);
}
return new DestinationSequence(sid, acksTo, lm, t, ack, pv);
}
} catch (SQLException ex) {
conex = ex;
LOG.log(Level.WARNING, new Message("SELECT_DEST_SEQ_FAILED_MSG", LOG).toString(), ex);
} finally {
releaseResources(stmt, res);
updateConnectionState(con, conex);
}
return null;
}
public SourceSequence getSourceSequence(Identifier sid) {
if (LOG.isLoggable(Level.FINE)) {
LOG.info("Getting source sequences for id: " + sid);
}
Connection con = verifyConnection();
PreparedStatement stmt = null;
SQLException conex = null;
ResultSet res = null;
try {
stmt = getStatement(con, SELECT_SRC_SEQUENCE_STMT_STR);
stmt.setString(1, sid.getValue());
res = stmt.executeQuery();
if (res.next()) {
long cmn = res.getLong(1);
boolean lm = res.getBoolean(2);
long lval = res.getLong(3);
Date expiry = 0 == lval ? null : new Date(lval);
String oidValue = res.getString(4);
Identifier oi = null;
if (null != oidValue) {
oi = RMUtils.getWSRMFactory().createIdentifier();
oi.setValue(oidValue);
}
ProtocolVariation pv = decodeProtocolVersion(res.getString(5));
return new SourceSequence(sid, expiry, oi, cmn, lm, pv);
}
} catch (SQLException ex) {
conex = ex;
// ignore
LOG.log(Level.WARNING, new Message("SELECT_SRC_SEQ_FAILED_MSG", LOG).toString(), ex);
} finally {
releaseResources(stmt, res);
updateConnectionState(con, conex);
}
return null;
}
public void removeDestinationSequence(Identifier sid) {
Connection con = verifyConnection();
PreparedStatement stmt = null;
SQLException conex = null;
try {
beginTransaction();
stmt = getStatement(con, DELETE_DEST_SEQUENCE_STMT_STR);
stmt.setString(1, sid.getValue());
stmt.execute();
commit(con);
} catch (SQLException ex) {
conex = ex;
abort(con);
throw new RMStoreException(ex);
} finally {
releaseResources(stmt, null);
updateConnectionState(con, conex);
}
}
public void removeSourceSequence(Identifier sid) {
Connection con = verifyConnection();
PreparedStatement stmt = null;
SQLException conex = null;
try {
beginTransaction();
stmt = getStatement(con, DELETE_SRC_SEQUENCE_STMT_STR);
stmt.setString(1, sid.getValue());
stmt.execute();
commit(con);
} catch (SQLException ex) {
conex = ex;
abort(con);
throw new RMStoreException(ex);
} finally {
releaseResources(stmt, null);
updateConnectionState(con, conex);
}
}
public Collection<DestinationSequence> getDestinationSequences(String endpointIdentifier) {
if (LOG.isLoggable(Level.FINE)) {
LOG.info("Getting destination sequences for endpoint: " + endpointIdentifier);
}
Connection con = verifyConnection();
PreparedStatement stmt = null;
SQLException conex = null;
Collection<DestinationSequence> seqs = new ArrayList<>();
ResultSet res = null;
try {
stmt = getStatement(con, SELECT_DEST_SEQUENCES_STMT_STR);
stmt.setString(1, endpointIdentifier);
res = stmt.executeQuery();
while (res.next()) {
Identifier sid = new Identifier();
sid.setValue(res.getString(1));
EndpointReferenceType acksTo = RMUtils.createReference(res.getString(2));
long lm = res.getLong(3);
ProtocolVariation pv = decodeProtocolVersion(res.getString(4));
boolean t = res.getBoolean(5);
InputStream is = res.getBinaryStream(6);
SequenceAcknowledgement ack = null;
if (null != is) {
ack = PersistenceUtils.getInstance()
.deserialiseAcknowledgment(is);
}
DestinationSequence seq = new DestinationSequence(sid, acksTo, lm, t, ack, pv);
seqs.add(seq);
}
} catch (SQLException ex) {
conex = ex;
LOG.log(Level.WARNING, new Message("SELECT_DEST_SEQ_FAILED_MSG", LOG).toString(), ex);
} finally {
releaseResources(stmt, res);
updateConnectionState(con, conex);
}
return seqs;
}
public Collection<SourceSequence> getSourceSequences(String endpointIdentifier) {
if (LOG.isLoggable(Level.FINE)) {
LOG.info("Getting source sequences for endpoint: " + endpointIdentifier);
}
Connection con = verifyConnection();
PreparedStatement stmt = null;
SQLException conex = null;
Collection<SourceSequence> seqs = new ArrayList<>();
ResultSet res = null;
try {
stmt = getStatement(con, SELECT_SRC_SEQUENCES_STMT_STR);
stmt.setString(1, endpointIdentifier);
res = stmt.executeQuery();
while (res.next()) {
Identifier sid = new Identifier();
sid.setValue(res.getString(1));
long cmn = res.getLong(2);
boolean lm = res.getBoolean(3);
long lval = res.getLong(4);
Date expiry = 0 == lval ? null : new Date(lval);
String oidValue = res.getString(5);
Identifier oi = null;
if (null != oidValue) {
oi = new Identifier();
oi.setValue(oidValue);
}
ProtocolVariation pv = decodeProtocolVersion(res.getString(6));
SourceSequence seq = new SourceSequence(sid, expiry, oi, cmn, lm, pv);
seqs.add(seq);
}
} catch (SQLException ex) {
conex = ex;
// ignore
LOG.log(Level.WARNING, new Message("SELECT_SRC_SEQ_FAILED_MSG", LOG).toString(), ex);
} finally {
releaseResources(stmt, res);
updateConnectionState(con, conex);
}
return seqs;
}
public Collection<RMMessage> getMessages(Identifier sid, boolean outbound) {
Connection con = verifyConnection();
PreparedStatement stmt = null;
SQLException conex = null;
Collection<RMMessage> msgs = new ArrayList<>();
ResultSet res = null;
try {
stmt = getStatement(con, outbound ? SELECT_OUTBOUND_MESSAGES_STMT_STR : SELECT_INBOUND_MESSAGES_STMT_STR);
stmt.setString(1, sid.getValue());
res = stmt.executeQuery();
while (res.next()) {
long mn = res.getLong(1);
String to = res.getString(2);
long ct = res.getLong(3);
Blob blob = res.getBlob(4);
String contentType = res.getString(5);
RMMessage msg = new RMMessage();
msg.setMessageNumber(mn);
msg.setTo(to);
msg.setCreatedTime(ct);
CachedOutputStream cos = new CachedOutputStream();
IOUtils.copyAndCloseInput(blob.getBinaryStream(), cos);
cos.flush();
msg.setContent(cos);
msg.setContentType(contentType);
msgs.add(msg);
}
} catch (SQLException ex) {
conex = ex;
LOG.log(Level.WARNING, new Message(outbound ? "SELECT_OUTBOUND_MSGS_FAILED_MSG"
: "SELECT_INBOUND_MSGS_FAILED_MSG", LOG).toString(), ex);
} catch (IOException e) {
abort(con);
throw new RMStoreException(e);
} finally {
releaseResources(stmt, res);
updateConnectionState(con, conex);
}
return msgs;
}
public void persistIncoming(DestinationSequence seq, RMMessage msg) {
Connection con = verifyConnection();
SQLException conex = null;
try {
beginTransaction();
updateDestinationSequence(con, seq);
if (msg != null && msg.getContent() != null) {
storeMessage(con, seq.getIdentifier(), msg, false);
}
commit(con);
} catch (SQLException ex) {
conex = ex;
abort(con);
throw new RMStoreException(ex);
} catch (IOException ex) {
abort(con);
throw new RMStoreException(ex);
} finally {
updateConnectionState(con, conex);
}
}
public void persistOutgoing(SourceSequence seq, RMMessage msg) {
Connection con = verifyConnection();
SQLException conex = null;
try {
beginTransaction();
updateSourceSequence(con, seq);
if (msg != null && msg.getContent() != null) {
storeMessage(con, seq.getIdentifier(), msg, true);
}
commit(con);
} catch (SQLException ex) {
conex = ex;
abort(con);
throw new RMStoreException(ex);
} catch (IOException ex) {
abort(con);
throw new RMStoreException(ex);
} finally {
updateConnectionState(con, conex);
}
}
public void removeMessages(Identifier sid, Collection<Long> messageNrs, boolean outbound) {
Connection con = verifyConnection();
PreparedStatement stmt = null;
SQLException conex = null;
try {
stmt = getStatement(con, outbound ? DELETE_OUTBOUND_MESSAGE_STMT_STR : DELETE_INBOUND_MESSAGE_STMT_STR);
beginTransaction();
stmt.setString(1, sid.getValue());
for (Long messageNr : messageNrs) {
stmt.setLong(2, messageNr);
stmt.execute();
}
commit(con);
} catch (SQLException ex) {
conex = ex;
abort(con);
throw new RMStoreException(ex);
} finally {
releaseResources(stmt, null);
updateConnectionState(con, conex);
}
}
// transaction demarcation
//
protected void beginTransaction() {
}
protected void commit(Connection con) throws SQLException {
con.commit();
}
/**
* This method assumes that the connection is held and reused.
* Otherwise, use commit(Connection con)
*/
protected void commit() throws SQLException {
commit(connection);
}
protected void abort(Connection con) {
try {
con.rollback();
} catch (SQLException ex) {
LogUtils.log(LOG, Level.SEVERE, "ABORT_FAILED_MSG", ex);
}
}
protected void abort() {
abort(connection);
}
// helpers
protected void storeMessage(Connection con, Identifier sid, RMMessage msg, boolean outbound)
throws IOException, SQLException {
String id = sid.getValue();
long nr = msg.getMessageNumber();
String to = msg.getTo();
String contentType = msg.getContentType();
if (LOG.isLoggable(Level.FINE)) {
LOG.log(Level.FINE, "Storing {0} message number {1} for sequence {2}, to = {3}",
new Object[] {outbound ? "outbound" : "inbound", nr, id, to});
}
PreparedStatement stmt = null;
try (CachedOutputStream cos = msg.getContent()) {
try (InputStream msgin = cos.getInputStream()) {
stmt = getStatement(con, outbound ? CREATE_OUTBOUND_MESSAGE_STMT_STR : CREATE_INBOUND_MESSAGE_STMT_STR);
stmt.setString(1, id);
stmt.setLong(2, nr);
stmt.setString(3, to);
stmt.setLong(4, msg.getCreatedTime());
stmt.setBinaryStream(5, msgin);
stmt.setString(6, contentType);
stmt.execute();
if (LOG.isLoggable(Level.FINE)) {
LOG.log(Level.FINE, "Successfully stored {0} message number {1} for sequence {2}",
new Object[] {outbound ? "outbound" : "inbound", nr, id});
}
} finally {
releaseResources(stmt, null);
}
}
}
/**
* this method is only useful when keepConnection is set to true
*/
protected void storeMessage(Identifier sid, RMMessage msg, boolean outbound)
throws IOException, SQLException {
storeMessage(connection, sid, msg, outbound);
}
protected void updateSourceSequence(Connection con, SourceSequence seq)
throws SQLException {
PreparedStatement stmt = null;
try {
stmt = getStatement(con, UPDATE_SRC_SEQUENCE_STMT_STR);
stmt.setLong(1, seq.getCurrentMessageNr());
stmt.setString(2, seq.isLastMessage() ? "1" : "0");
stmt.setString(3, seq.getIdentifier().getValue());
stmt.execute();
} finally {
releaseResources(stmt, null);
}
}
/**
* @throws SQLException
*/
protected void updateSourceSequence(SourceSequence seq) throws SQLException {
updateSourceSequence(connection, seq);
}
protected void updateDestinationSequence(Connection con, DestinationSequence seq)
throws SQLException, IOException {
PreparedStatement stmt = null;
try {
stmt = getStatement(con, UPDATE_DEST_SEQUENCE_STMT_STR);
long lastMessageNr = seq.getLastMessageNumber();
stmt.setLong(1, lastMessageNr);
stmt.setString(2, seq.isTerminated() ? "1" : "0");
InputStream is = PersistenceUtils.getInstance().serialiseAcknowledgment(seq.getAcknowledgment());
stmt.setBinaryStream(3, is, is.available());
stmt.setString(4, seq.getIdentifier().getValue());
stmt.execute();
} finally {
releaseResources(stmt, null);
}
}
/**
* @throws IOException
* @throws SQLException
*/
protected void updateDestinationSequence(DestinationSequence seq)
throws SQLException, IOException {
updateDestinationSequence(connection, seq);
}
protected void createTables() throws SQLException {
Connection con = verifyConnection();
if (con == null) {
LOG.warning("Skip creating tables as we have no connection.");
return;
}
try { //NOPMD
con.setAutoCommit(true);
try (Statement stmt = con.createStatement()) {
stmt.executeUpdate(CREATE_SRC_SEQUENCES_TABLE_STMT);
} catch (SQLException ex) {
if (!isTableExistsError(ex)) {
throw ex;
}
LOG.fine("Table CXF_RM_SRC_SEQUENCES already exists.");
verifyTable(con, SRC_SEQUENCES_TABLE_NAME, SRC_SEQUENCES_TABLE_COLS);
}
try (Statement stmt = con.createStatement()) {
stmt.executeUpdate(CREATE_DEST_SEQUENCES_TABLE_STMT);
} catch (SQLException ex) {
if (!isTableExistsError(ex)) {
throw ex;
}
LOG.fine("Table CXF_RM_DEST_SEQUENCES already exists.");
verifyTable(con, DEST_SEQUENCES_TABLE_NAME, DEST_SEQUENCES_TABLE_COLS);
}
for (String tableName : new String[] {OUTBOUND_MSGS_TABLE_NAME, INBOUND_MSGS_TABLE_NAME}) {
try (Statement stmt = con.createStatement()) {
stmt.executeUpdate(MessageFormat.format(CREATE_MESSAGES_TABLE_STMT, tableName));
} catch (SQLException ex) {
if (!isTableExistsError(ex)) {
throw ex;
}
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("Table " + tableName + " already exists.");
}
verifyTable(con, tableName, MESSAGES_TABLE_COLS);
}
}
} finally {
con.setAutoCommit(false);
if (connection == null && con != null) {
con.close();
}
}
}
protected void verifyTable(Connection con, String tableName, String[][] tableCols) {
try {
DatabaseMetaData metadata = con.getMetaData();
ResultSet rs = metadata.getColumns(null, null, tableName, "%");
Set<String> dbCols = new HashSet<>();
List<String[]> newCols = new ArrayList<>();
while (rs.next()) {
dbCols.add(rs.getString(4));
}
for (String[] col : tableCols) {
if (!dbCols.contains(col[0])) {
newCols.add(col);
}
}
if (!newCols.isEmpty()) {
// need to add the new columns
if (LOG.isLoggable(Level.FINE)) {
LOG.log(Level.FINE, "Table " + tableName + " needs additional columns");
}
for (String[] newCol : newCols) {
try (Statement st = con.createStatement()) {
st.executeUpdate(MessageFormat.format(ALTER_TABLE_STMT_STR,
tableName, newCol[0], newCol[1]));
if (LOG.isLoggable(Level.FINE)) {
LOG.log(Level.FINE, "Successfully added column {0} to table {1}",
new Object[] {tableName, newCol[0]});
}
}
}
}
} catch (SQLException ex) {
LOG.log(Level.WARNING, "Table " + tableName + " cannot be altered.", ex);
}
}
protected void verifyTable(String tableName, String[][] tableCols) {
verifyTable(connection, tableName, tableCols);
}
/**
* Sets the current schema associated with the connection.
* If the connection is not set (e.g., keepConnection is false, it has no effect.
* @throws SQLException
*/
protected void setCurrentSchema() throws SQLException {
if (schemaName == null || connection == null) {
return;
}
// schemaName has been verified at setSchemaName(String)
try (Statement stmt = connection.createStatement()) {
stmt.executeUpdate(MessageFormat.format(CREATE_SCHEMA_STMT_STR,
schemaName));
} catch (SQLException ex) {
// assume it is already created or no authorization is provided (create one manually)
}
try (Statement stmt = connection.createStatement()) {
SQLException ex0 = null;
for (int i = 0; i < SET_SCHEMA_STMT_STRS.length; i++) {
try {
stmt.executeUpdate(MessageFormat.format(SET_SCHEMA_STMT_STRS[i], schemaName));
break;
} catch (SQLException ex) {
ex.setNextException(ex0);
ex0 = ex;
if (i == SET_SCHEMA_STMT_STRS.length - 1) {
throw ex0;
}
}
}
}
}
/**
* Returns either the locally cached statement or the one from the specified connection
* depending on whether the connection is held by this store. If the statement retrieved from
* the local cache, it is locked until it is released. The retrieved statement must be
* released using releaseResources(PreparedStatement stmt, ResultSet rs).
*
* @param con
* @param sql
* @return
* @throws SQLException
*/
protected PreparedStatement getStatement(Connection con, String sql) throws SQLException {
if (connection != null) {
PreparedStatement stmt = cachedStatements.get(sql);
statementLocks.get(stmt).lock();
return stmt;
}
return con.prepareStatement(sql);
}
/**
* Releases the statement and any result set.
*
* @param stmt
* @param rs
*/
protected void releaseResources(PreparedStatement stmt, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
// ignore
}
}
if (stmt != null) {
if (connection != null) {
statementLocks.get(stmt).unlock();
} else {
try {
stmt.close();
} catch (SQLException e) {
// ignore
}
}
}
}
protected void cacheStatement(Connection con, String sql) throws SQLException {
PreparedStatement stmt = con.prepareStatement(sql);
cachedStatements.put(sql, stmt);
statementLocks.put(stmt, new ReentrantLock());
}
protected void cacheStatements() throws SQLException {
if (connection == null) {
// if the connection is not held, no statement is cached.
return;
}
// create a statement specific lock table
statementLocks = new HashMap<>();
cachedStatements = new HashMap<>();
// create the statements in advance if the connection is to be kept
cacheStatement(connection, CREATE_DEST_SEQUENCE_STMT_STR);
cacheStatement(connection, CREATE_SRC_SEQUENCE_STMT_STR);
cacheStatement(connection, DELETE_DEST_SEQUENCE_STMT_STR);
cacheStatement(connection, DELETE_SRC_SEQUENCE_STMT_STR);
cacheStatement(connection, UPDATE_DEST_SEQUENCE_STMT_STR);
cacheStatement(connection, UPDATE_SRC_SEQUENCE_STMT_STR);
cacheStatement(connection, SELECT_DEST_SEQUENCES_STMT_STR);
cacheStatement(connection, SELECT_SRC_SEQUENCES_STMT_STR);
cacheStatement(connection, SELECT_DEST_SEQUENCE_STMT_STR);
cacheStatement(connection, SELECT_SRC_SEQUENCE_STMT_STR);
cacheStatement(connection, CREATE_INBOUND_MESSAGE_STMT_STR);
cacheStatement(connection, CREATE_OUTBOUND_MESSAGE_STMT_STR);
cacheStatement(connection, DELETE_INBOUND_MESSAGE_STMT_STR);
cacheStatement(connection, DELETE_OUTBOUND_MESSAGE_STMT_STR);
cacheStatement(connection, SELECT_INBOUND_MESSAGES_STMT_STR);
cacheStatement(connection, SELECT_OUTBOUND_MESSAGES_STMT_STR);
}
public synchronized void init() {
if (keepConnection && connection == null) {
connection = createConnection();
}
try {
if (connection != null && schemaName != null) {
setCurrentSchema();
}
createTables();
if (connection != null) {
cacheStatements();
}
} catch (SQLException ex) {
LogUtils.log(LOG, Level.SEVERE, "CONNECT_EXC", ex);
SQLException se = ex;
while (se.getNextException() != null) {
se = se.getNextException();
LogUtils.log(LOG, Level.SEVERE, "CONNECT_EXC", se);
}
throw new RMStoreException(ex);
} catch (Throwable ex) {
LogUtils.log(LOG, Level.SEVERE, "INITIALIZATION_FAILED_MSG", ex);
}
}
Connection getConnection() {
return connection;
}
protected Connection createConnection() {
LOG.log(Level.FINE, "Using derby.system.home: {0}",
SystemPropertyAction.getProperty("derby.system.home"));
Connection con = null;
if (null != dataSource) {
try {
if (LOG.isLoggable(Level.FINE)) {
LOG.log(Level.FINE, "Using dataSource: " + dataSource);
}
con = dataSource.getConnection();
} catch (SQLException ex) {
LogUtils.log(LOG, Level.SEVERE, "CONNECT_EXC", ex);
}
} else {
assert null != url;
assert null != driverClassName;
try {
if (LOG.isLoggable(Level.FINE)) {
LOG.log(Level.FINE, "Using url: " + url);
}
Class.forName(driverClassName);
con = DriverManager.getConnection(url, userName, password);
} catch (ClassNotFoundException | SQLException ex) {
LogUtils.log(LOG, Level.SEVERE, "CONNECT_EXC", ex);
}
}
return con;
}
protected Connection verifyConnection() {
Connection con;
if (connection == null) {
// return a new connection
con = createConnection();
} else {
// return the cached connection or create and cache a new one if the old one is dead
synchronized (this) {
if (createdConnection && nextReconnectAttempt > 0
&& (maxReconnectAttempts < 0 || maxReconnectAttempts > reconnectAttempts)) {
if (System.currentTimeMillis() > nextReconnectAttempt) {
// destroy the broken connection
destroy();
// try to reconnect
reconnectAttempts++;
init();
// reset the next reconnect attempt time
nextReconnectAttempt = 0;
} else {
LogUtils.log(LOG, Level.INFO, "WAIT_RECONNECT_MSG");
}
}
}
con = connection;
}
return con;
}
protected void updateConnectionState(Connection con, SQLException e) {
if (connection == null) {
// close the locally created connection
try {
con.close();
} catch (SQLException ex) {
// ignore
}
} else {
synchronized (this) {
// update the status of the cached connection
if (e == null) {
// reset the previous error status
reconnectDelay = 0;
reconnectAttempts = 0;
nextReconnectAttempt = 0;
} else if (createdConnection && isRecoverableError(e)) {
// update the next reconnect schedule
if (reconnectDelay == 0) {
reconnectDelay = initialReconnectDelay;
}
if (nextReconnectAttempt < System.currentTimeMillis()) {
nextReconnectAttempt = System.currentTimeMillis() + reconnectDelay;
reconnectDelay = reconnectDelay * useExponentialBackOff;
}
}
}
}
}
public static void deleteDatabaseFiles() {
deleteDatabaseFiles(DEFAULT_DATABASE_NAME, true);
}
public static void deleteDatabaseFiles(String dbName, boolean now) {
String dsh = SystemPropertyAction.getPropertyOrNull("derby.system.home");
File root = null;
File log = null;
if (null == dsh) {
log = new File("derby.log");
root = new File(dbName);
} else {
log = new File(dsh, "derby.log");
root = new File(dsh, dbName);
}
if (log.exists()) {
if (now) {
boolean deleted = log.delete();
LOG.log(Level.FINE, "Deleted log file {0}: {1}", new Object[] {log, deleted});
} else {
log.deleteOnExit();
}
}
if (root.exists()) {
LOG.log(Level.FINE, "Trying to delete directory {0}", root);
recursiveDelete(root, now);
}
}
protected static String encodeProtocolVersion(ProtocolVariation pv) {
return pv.getCodec().getWSRMNamespace() + ' ' + pv.getCodec().getWSANamespace();
}
protected static ProtocolVariation decodeProtocolVersion(String pv) {
if (null != pv) {
int d = pv.indexOf(' ');
if (d > 0) {
return ProtocolVariation.findVariant(pv.substring(0, d), pv.substring(d + 1));
}
}
return ProtocolVariation.RM10WSA200408;
}
private static void recursiveDelete(File dir, boolean now) {
for (File f : dir.listFiles()) {
if (f.isDirectory()) {
recursiveDelete(f, now);
} else {
if (now) {
f.delete();
} else {
f.deleteOnExit();
}
}
}
if (now) {
dir.delete();
} else {
dir.deleteOnExit();
}
}
private static String buildCreateTableStatement(String name, String[][] cols, String[] keys) {
StringBuilder buf = new StringBuilder(128);
buf.append("CREATE TABLE ").append(name).append(" (");
for (String[] col : cols) {
buf.append(col[0]).append(' ').append(col[1]).append(", ");
}
buf.append("PRIMARY KEY (");
for (int i = 0; i < keys.length; i++) {
if (i > 0) {
buf.append(", ");
}
buf.append(keys[i]);
}
buf.append("))");
return buf.toString();
}
protected boolean isTableExistsError(SQLException ex) {
// we could be deriving the state/code from the driver url to avoid explicit setting of them
return (null != tableExistsState && tableExistsState.equals(ex.getSQLState()))
|| tableExistsCode == ex.getErrorCode();
}
protected boolean isRecoverableError(SQLException ex) {
// check for a transient or non-transient connection exception
return ex.getSQLState() != null && ex.getSQLState().startsWith("08");
}
}
| 37.351243 | 120 | 0.584301 |
3fdcca6e543c89c56762e90a8c9f7f3945f66fd8 | 909 |
package cz.it4i.fiji.hpc_workflow.core;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
import cz.it4i.fiji.hpc_client.SynchronizableFileType;
public class ComputationAccessorAdapter implements ComputationAccessor {
@Override
public List<String> getActualOutput(List<SynchronizableFileType> content) {
return mapCollect(content, c -> "");
}
@Override
public List<Long> getFileSizes(List<String> names) {
return mapCollect(names, s -> 0l);
}
@Override
public List<String> getFileContents(List<String> logs) {
return mapCollect(logs, s -> "");
}
@Override
public Collection<String> getChangedFiles() {
return Collections.emptyList();
}
private <U, V> List<V> mapCollect(List<U> input, Function<U, V> map) {
return input.stream().map(map).collect(Collectors.toList());
}
}
| 23.921053 | 76 | 0.749175 |
3ac85734e49bf79c3bb50c67a8692cbc2796fcdc | 301 | package mchorse.snb.utils;
import mchorse.mclib.utils.files.FileTree;
import mchorse.mclib.utils.files.entries.FolderImageEntry;
import java.io.File;
public class SnBTree extends FileTree
{
public SnBTree(File folder)
{
this.root = new FolderImageEntry("s&b", folder, null);
}
} | 21.5 | 62 | 0.730897 |
6b54cbca8eebf3377dbbfeea8d9922c6d4c5fbb0 | 227 | package jp.co.worksap.oss.findbugs.jpa;
import javax.persistence.Column;
public class GetterWithTooLongLength {
private String name;
@Column(length = 10000)
public String getName() {
return name;
}
}
| 17.461538 | 39 | 0.69163 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.