repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
droolsjbpm/drools | kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/functions/TimeFunctionTest.java | 7736 | /*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.dmn.feel.runtime.functions;
import static org.junit.Assert.assertEquals;
import java.math.BigDecimal;
import java.time.DayOfWeek;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.temporal.TemporalAccessor;
import java.time.temporal.TemporalQueries;
import org.junit.Before;
import org.junit.Test;
import org.kie.dmn.feel.runtime.events.InvalidParametersEvent;
public class TimeFunctionTest {
private TimeFunction timeFunction;
@Before
public void setUp() {
timeFunction = new TimeFunction();
}
@Test
public void invokeStringParamNull() {
FunctionTestUtil.assertResultError(timeFunction.invoke((String) null), InvalidParametersEvent.class);
}
@Test
public void invokeStringParamNotDateOrTime() {
FunctionTestUtil.assertResultError(timeFunction.invoke("test"), InvalidParametersEvent.class);
}
@Test
public void invokeStringParamTimeWrongFormat() {
FunctionTestUtil.assertResultError(timeFunction.invoke("10-15:06"), InvalidParametersEvent.class);
}
@Test
public void invokeStringParamNoOffset() {
FunctionTestUtil.assertResult(timeFunction.invoke("10:15:06"), LocalTime.of(10,15,6));
}
@Test
public void invokeStringParamWithOffset() {
FunctionTestUtil.assertResult(timeFunction.invoke("10:15:06+01:00"), OffsetTime.of(10,15,6, 0, ZoneOffset.ofHours(1)));
FunctionTestUtil.assertResult(timeFunction.invoke("10:15:06-01:00"), OffsetTime.of(10,15,6, 0, ZoneOffset.ofHours(-1)));
}
@Test
public void parseWithZone() {
final TemporalAccessor parsedResult = timeFunction.invoke("00:01:00@Etc/UTC").getOrElse(null);
assertEquals(LocalTime.of(0, 1, 0), parsedResult.query(TemporalQueries.localTime()));
assertEquals(ZoneId.of("Etc/UTC"), parsedResult.query(TemporalQueries.zone()));
}
@Test
public void parseWithZoneIANA() {
final TemporalAccessor parsedResult = timeFunction.invoke("00:01:00@Europe/Paris").getOrElse(null);
assertEquals(LocalTime.of(0, 1, 0), parsedResult.query(TemporalQueries.localTime()));
assertEquals(ZoneId.of("Europe/Paris"), parsedResult.query(TemporalQueries.zone()));
}
@Test
public void invokeWrongIANAformat() {
FunctionTestUtil.assertResultError(timeFunction.invoke("13:20:00+02:00@Europe/Paris"), InvalidParametersEvent.class);
}
@Test
public void invokeTemporalAccessorParamNull() {
FunctionTestUtil.assertResultError(timeFunction.invoke((TemporalAccessor) null), InvalidParametersEvent.class);
}
@Test
public void invokeTemporalAccessorParamUnsupportedAccessor() {
FunctionTestUtil.assertResultError(timeFunction.invoke(DayOfWeek.MONDAY), InvalidParametersEvent.class);
}
@Test
public void invokeTemporalAccessorParamDate() {
FunctionTestUtil.assertResult(timeFunction.invoke(LocalDate.of(2017, 6, 12)), OffsetTime.of(0, 0, 0, 0, ZoneOffset.UTC));
}
@Test
public void invokeTemporalAccessorParamTime() {
FunctionTestUtil.assertResult(timeFunction.invoke(LocalTime.of(11, 43)), LocalTime.of(11, 43, 0));
}
@Test
public void invokeTemporalAccessorParamDateTime() {
FunctionTestUtil.assertResult(timeFunction.invoke(LocalDateTime.of(2017, 6, 12, 11, 43)), LocalTime.of(11, 43, 0));
}
@Test
public void invokeTimeUnitsParamsNull() {
FunctionTestUtil.assertResultError(timeFunction.invoke(null, null, null, null), InvalidParametersEvent.class);
FunctionTestUtil.assertResultError(timeFunction.invoke(null, null, 1, null), InvalidParametersEvent.class);
FunctionTestUtil.assertResultError(timeFunction.invoke(null, 1, null, null), InvalidParametersEvent.class);
FunctionTestUtil.assertResultError(timeFunction.invoke(null, 1, 1, null), InvalidParametersEvent.class);
FunctionTestUtil.assertResultError(timeFunction.invoke(1, null, null, null), InvalidParametersEvent.class);
FunctionTestUtil.assertResultError(timeFunction.invoke(1, null, 1, null), InvalidParametersEvent.class);
FunctionTestUtil.assertResultError(timeFunction.invoke(1, 1, null, null), InvalidParametersEvent.class);
}
@Test
public void invokeTimeUnitsParamsUnsupportedNumber() {
FunctionTestUtil.assertResultError(timeFunction.invoke(Double.POSITIVE_INFINITY, 1, 1, null), InvalidParametersEvent.class);
FunctionTestUtil.assertResultError(timeFunction.invoke(Double.NEGATIVE_INFINITY, 1, 1, null), InvalidParametersEvent.class);
FunctionTestUtil.assertResultError(timeFunction.invoke(1, Double.POSITIVE_INFINITY, 1, null), InvalidParametersEvent.class);
FunctionTestUtil.assertResultError(timeFunction.invoke(1, Double.NEGATIVE_INFINITY, 1, null), InvalidParametersEvent.class);
FunctionTestUtil.assertResultError(timeFunction.invoke(1, 1, Double.POSITIVE_INFINITY, null), InvalidParametersEvent.class);
FunctionTestUtil.assertResultError(timeFunction.invoke(1, 1, Double.NEGATIVE_INFINITY, null), InvalidParametersEvent.class);
}
@Test
public void invokeTimeUnitsParamsOutOfBounds() {
FunctionTestUtil.assertResultError(timeFunction.invoke(40, 1, 1, null), InvalidParametersEvent.class);
FunctionTestUtil.assertResultError(timeFunction.invoke(1, 900, 1, null), InvalidParametersEvent.class);
FunctionTestUtil.assertResultError(timeFunction.invoke(1, 1, 900, null), InvalidParametersEvent.class);
}
@Test
public void invokeTimeUnitsParamsNoOffset() {
FunctionTestUtil.assertResult(timeFunction.invoke(10, 43, 15, null), LocalTime.of(10, 43, 15));
}
@Test
public void invokeTimeUnitsParamsNoOffsetWithNanoseconds() {
FunctionTestUtil.assertResult(timeFunction.invoke(10, 43, BigDecimal.valueOf(15.154), null), LocalTime.of(10, 43, 15, 154000000));
}
@Test
public void invokeTimeUnitsParamsWithOffset() {
FunctionTestUtil.assertResult(timeFunction.invoke(10, 43, 15, Duration.ofHours(1)), OffsetTime.of(10, 43, 15, 0, ZoneOffset.ofHours(1)));
FunctionTestUtil.assertResult(timeFunction.invoke(10, 43, 15, Duration.ofHours(-1)), OffsetTime.of(10, 43, 15, 0, ZoneOffset.ofHours(-1)));
}
@Test
public void invokeTimeUnitsParamsWithNoOffset() {
FunctionTestUtil.assertResult(timeFunction.invoke(10, 43, 15), LocalTime.of(10, 43, 15));
}
@Test
public void invokeTimeUnitsParamsWithOffsetWithNanoseconds() {
FunctionTestUtil.assertResult(
timeFunction.invoke(10, 43, BigDecimal.valueOf(15.154), Duration.ofHours(1)),
OffsetTime.of(10, 43, 15, 154000000, ZoneOffset.ofHours(1)));
FunctionTestUtil.assertResult(
timeFunction.invoke(10, 43, BigDecimal.valueOf(15.154), Duration.ofHours(-1)),
OffsetTime.of(10, 43, 15, 154000000, ZoneOffset.ofHours(-1)));
}
} | apache-2.0 |
zxwing/zstack-1 | plugin/fusionstor/src/main/java/org/zstack/storage/fusionstor/primary/UploadBitsToBackupStorageReply.java | 207 | package org.zstack.storage.fusionstor.primary;
import org.zstack.header.message.MessageReply;
/**
* Created by xing5 on 2016/4/29.
*/
public class UploadBitsToBackupStorageReply extends MessageReply {
}
| apache-2.0 |
ravihansa3000/stratos | components/org.apache.stratos.messaging/src/main/java/org/apache/stratos/messaging/event/topology/MemberTerminatedEvent.java | 2692 | /*
* 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.stratos.messaging.event.topology;
import java.io.Serializable;
import java.util.Properties;
/**
* This event is fired by Cloud Controller when a member is terminated.
*/
public class MemberTerminatedEvent extends TopologyEvent implements Serializable {
private static final long serialVersionUID = -7899511757547631157L;
private final String serviceName;
private final String clusterId;
private final String memberId;
private final String clusterInstanceId;
private final String networkPartitionId;
private final String partitionId;
private String groupId;
private Properties properties;
public MemberTerminatedEvent(String serviceName, String clusterId, String memberId,
String clusterInstanceId, String networkPartitionId, String partitionId) {
this.serviceName = serviceName;
this.clusterId = clusterId;
this.memberId = memberId;
this.clusterInstanceId = clusterInstanceId;
this.networkPartitionId = networkPartitionId;
this.partitionId = partitionId;
}
public String getServiceName() {
return serviceName;
}
public String getClusterId() {
return clusterId;
}
public String getPartitionId() {
return partitionId;
}
public String getMemberId() {
return memberId;
}
public String getNetworkPartitionId() {
return networkPartitionId;
}
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
public Properties getProperties() {
return properties;
}
public void setProperties(Properties properties) {
this.properties = properties;
}
public String getClusterInstanceId() {
return clusterInstanceId;
}
}
| apache-2.0 |
curso007/camel | components/camel-mllp/src/test/java/org/apache/camel/test/mllp/Hl7TestMessageGenerator.java | 4192 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.test.mllp;
import java.text.SimpleDateFormat;
import java.util.Date;
public final class Hl7TestMessageGenerator {
static SimpleDateFormat timestampFormat = new SimpleDateFormat("YYYYMMddHHmmss");
static String messageControlIdFormat = "%05d";
static String hl7MessageTemplate =
"MSH|^~\\&|ADT|EPIC|JCAPS|CC|<MESSAGE_TIMESTAMP>|RISTECH|ADT^A08|<MESSAGE_CONTROL_ID>|D|2.3^^|||||||" + '\r'
+ "EVN|A08|20150107161440||REG_UPDATE_SEND_VISIT_MESSAGES_ON_PATIENT_CHANGES|RISTECH^RADIOLOGY^TECHNOLOGIST^^^^^^UCLA^^^^^RRMC||" + '\r'
+ "PID|1|2100355^^^MRN^MRN|2100355^^^MRN^MRN||MDCLS9^MC9||19700109|F||U|111 HOVER STREET^^LOS ANGELES^CA^90032^USA^P^^LOS ANGELE|LOS ANGELE|(310)"
+ "725-6952^P^PH^^^310^7256952||ENGLISH|U||60000013647|565-33-2222|||U||||||||N||" + '\r'
+ "PD1|||UCLA HEALTH SYSTEM^^10|10002116^ADAMS^JOHN^D^^^^^EPIC^^^^PROVID||||||||||||||" + '\r'
+ "NK1|1|DOE^MC9^^|OTH|^^^^^USA|(310)888-9999^^^^^310^8889999|(310)999-2222^^^^^310^9992222|Emergency Contact 1|||||||||||||||||||||||||||" + '\r'
+ "PV1|1|OUTPATIENT|RR CT^^^1000^^^^^^^DEPID|EL|||017511^TOBIAS^JONATHAN^^^^^^EPIC^^^^PROVID|017511^TOBIAS^JONATHAN^^^^^^EPIC^^^^PROVID||||||CLR|||||60000013647|SELF"
+ "|||||||||||||||||||||HOV_CONF|^^^1000^^^^^^^||20150107161438||||||||||" + '\r'
+ "PV2||||||||20150107161438||||CT BRAIN W WO CONTRAST||||||||||N|||||||||||||||||||||||||||" + '\r'
+ "ZPV||||||||||||20150107161438|||||||||" + '\r'
+ "AL1|1||33361^NO KNOWN ALLERGIES^^NOTCOMPUTRITION^NO KNOWN ALLERGIES^EXTELG||||||" + '\r'
+ "DG1|1|DX|784.0^Headache^DX|Headache||VISIT" + '\r'
+ "GT1|1|1000235129|MDCLS9^MC9^^||111 HOVER STREET^^LOS ANGELES^CA^90032^USA^^^LOS ANGELE|(310)"
+ "725-6952^^^^^310^7256952||19700109|F|P/F|SLF|565-33-2222|||||^^^^^USA|||UNKNOWN|||||||||||||||||||||||||||||" + '\r'
+ "UB2||||||||" + '\r'
+ '\n';
private Hl7TestMessageGenerator() {
}
public static String generateMessage() {
return generateMessage(new Date(), 1);
}
public static String generateMessage(int messageControlId) {
return generateMessage(new Date(), messageControlId);
}
public static String generateMessage(Date timestamp, int messageControlId) {
String tmpMessage = hl7MessageTemplate.replaceFirst("<MESSAGE_TIMESTAMP>", timestampFormat.format(timestamp));
return tmpMessage.replaceFirst("<MESSAGE_CONTROL_ID>", String.format("%05d", messageControlId));
}
public static String getHl7MessageTemplate() {
return hl7MessageTemplate;
}
public static void setHl7MessageTemplate(String hl7MessageTemplate) {
Hl7TestMessageGenerator.hl7MessageTemplate = hl7MessageTemplate;
}
public static SimpleDateFormat getTimestampFormat() {
return timestampFormat;
}
public static void setTimestampFormat(SimpleDateFormat timestampFormat) {
Hl7TestMessageGenerator.timestampFormat = timestampFormat;
}
public static String getMessageControlIdFormat() {
return messageControlIdFormat;
}
public static void setMessageControlIdFormat(String messageControlIdFormat) {
Hl7TestMessageGenerator.messageControlIdFormat = messageControlIdFormat;
}
}
| apache-2.0 |
donNewtonAlpha/onos | core/api/src/main/java/org/onosproject/net/device/DeviceProviderRegistry.java | 880 | /*
* Copyright 2014-present Open Networking Laboratory
*
* 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.onosproject.net.device;
import org.onosproject.net.provider.ProviderRegistry;
/**
* Abstraction of a device provider registry.
*/
public interface DeviceProviderRegistry
extends ProviderRegistry<DeviceProvider, DeviceProviderService> {
}
| apache-2.0 |
adessaigne/camel | components/camel-spring/src/test/java/org/apache/camel/spring/issues/ProduceSplitMethodCallIssueTest.java | 1853 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.spring.issues;
import org.apache.camel.spring.SpringTestSupport;
import org.junit.jupiter.api.Test;
import org.springframework.context.support.AbstractXmlApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class ProduceSplitMethodCallIssueTest extends SpringTestSupport {
@Override
protected AbstractXmlApplicationContext createApplicationContext() {
return new ClassPathXmlApplicationContext("org/apache/camel/spring/issues/ProduceSplitMethodCallIssueTest.xml");
}
@Test
public void testProduceSplitMethodCallIssue() throws Exception {
getMockEndpoint("mock:split").expectedBodiesReceived("Hello A", "Hello B");
CoolService cool = context.getRegistry().lookupByNameAndType("cool", CoolService.class);
String out = cool.stuff("A,B");
// keeps the original message
assertEquals("A,B", out);
assertMockEndpointsSatisfied();
}
}
| apache-2.0 |
apache/incubator-metron | metron-platform/metron-enrichment/src/main/java/org/apache/metron/enrichment/adapters/maxmind/geo/hash/DistanceStrategy.java | 1008 | /*
* 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.metron.enrichment.adapters.maxmind.geo.hash;
import ch.hsr.geohash.WGS84Point;
public interface DistanceStrategy {
public double distance(WGS84Point point1, WGS84Point point2);
}
| apache-2.0 |
SunguckLee/RocksDB | java/src/test/java/org/rocksdb/util/BytewiseComparatorTest.java | 16070 | // Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
// This source code is licensed under both the GPLv2 (found in the
// COPYING file in the root directory) and Apache 2.0 License
// (found in the LICENSE.Apache file in the root directory).
package org.rocksdb.util;
import org.junit.Test;
import org.rocksdb.*;
import org.rocksdb.Comparator;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.*;
import static org.junit.Assert.*;
/**
* This is a direct port of various C++
* tests from db/comparator_db_test.cc
* and some code to adapt it to RocksJava
*/
public class BytewiseComparatorTest {
private List<String> source_strings = Arrays.asList("b", "d", "f", "h", "j", "l");
private List<String> interleaving_strings = Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m");
/**
* Open the database using the C++ BytewiseComparatorImpl
* and test the results against our Java BytewiseComparator
*/
@Test
public void java_vs_cpp_bytewiseComparator()
throws IOException, RocksDBException {
for(int rand_seed = 301; rand_seed < 306; rand_seed++) {
final Path dbDir = Files.createTempDirectory("comparator_db_test");
try(final RocksDB db = openDatabase(dbDir,
BuiltinComparator.BYTEWISE_COMPARATOR)) {
final Random rnd = new Random(rand_seed);
try(final ComparatorOptions copt2 = new ComparatorOptions();
final Comparator comparator2 = new BytewiseComparator(copt2)) {
final java.util.Comparator<String> jComparator = toJavaComparator(comparator2);
doRandomIterationTest(
db,
jComparator,
rnd,
8, 100, 3
);
}
} finally {
removeData(dbDir);
}
}
}
/**
* Open the database using the Java BytewiseComparator
* and test the results against another Java BytewiseComparator
*/
@Test
public void java_vs_java_bytewiseComparator()
throws IOException, RocksDBException {
for(int rand_seed = 301; rand_seed < 306; rand_seed++) {
final Path dbDir = Files.createTempDirectory("comparator_db_test");
try(final ComparatorOptions copt = new ComparatorOptions();
final Comparator comparator = new BytewiseComparator(copt);
final RocksDB db = openDatabase(dbDir, comparator)) {
final Random rnd = new Random(rand_seed);
try(final ComparatorOptions copt2 = new ComparatorOptions();
final Comparator comparator2 = new BytewiseComparator(copt2)) {
final java.util.Comparator<String> jComparator = toJavaComparator(comparator2);
doRandomIterationTest(
db,
jComparator,
rnd,
8, 100, 3
);
}
} finally {
removeData(dbDir);
}
}
}
/**
* Open the database using the C++ BytewiseComparatorImpl
* and test the results against our Java DirectBytewiseComparator
*/
@Test
public void java_vs_cpp_directBytewiseComparator()
throws IOException, RocksDBException {
for(int rand_seed = 301; rand_seed < 306; rand_seed++) {
final Path dbDir = Files.createTempDirectory("comparator_db_test");
try(final RocksDB db = openDatabase(dbDir,
BuiltinComparator.BYTEWISE_COMPARATOR)) {
final Random rnd = new Random(rand_seed);
try(final ComparatorOptions copt2 = new ComparatorOptions();
final DirectComparator comparator2 = new DirectBytewiseComparator(copt2)) {
final java.util.Comparator<String> jComparator = toJavaComparator(comparator2);
doRandomIterationTest(
db,
jComparator,
rnd,
8, 100, 3
);
}
} finally {
removeData(dbDir);
}
}
}
/**
* Open the database using the Java DirectBytewiseComparator
* and test the results against another Java DirectBytewiseComparator
*/
@Test
public void java_vs_java_directBytewiseComparator()
throws IOException, RocksDBException {
for(int rand_seed = 301; rand_seed < 306; rand_seed++) {
final Path dbDir = Files.createTempDirectory("comparator_db_test");
try (final ComparatorOptions copt = new ComparatorOptions();
final DirectComparator comparator = new DirectBytewiseComparator(copt);
final RocksDB db = openDatabase(dbDir, comparator)) {
final Random rnd = new Random(rand_seed);
try(final ComparatorOptions copt2 = new ComparatorOptions();
final DirectComparator comparator2 = new DirectBytewiseComparator(copt2)) {
final java.util.Comparator<String> jComparator = toJavaComparator(comparator2);
doRandomIterationTest(
db,
jComparator,
rnd,
8, 100, 3
);
}
} finally {
removeData(dbDir);
}
}
}
/**
* Open the database using the C++ ReverseBytewiseComparatorImpl
* and test the results against our Java ReverseBytewiseComparator
*/
@Test
public void java_vs_cpp_reverseBytewiseComparator()
throws IOException, RocksDBException {
for(int rand_seed = 301; rand_seed < 306; rand_seed++) {
final Path dbDir = Files.createTempDirectory("comparator_db_test");
try(final RocksDB db = openDatabase(dbDir,
BuiltinComparator.REVERSE_BYTEWISE_COMPARATOR)) {
final Random rnd = new Random(rand_seed);
try(final ComparatorOptions copt2 = new ComparatorOptions();
final Comparator comparator2 = new ReverseBytewiseComparator(copt2)) {
final java.util.Comparator<String> jComparator = toJavaComparator(comparator2);
doRandomIterationTest(
db,
jComparator,
rnd,
8, 100, 3
);
}
} finally {
removeData(dbDir);
}
}
}
/**
* Open the database using the Java ReverseBytewiseComparator
* and test the results against another Java ReverseBytewiseComparator
*/
@Test
public void java_vs_java_reverseBytewiseComparator()
throws IOException, RocksDBException {
for(int rand_seed = 301; rand_seed < 306; rand_seed++) {
final Path dbDir = Files.createTempDirectory("comparator_db_test");
try (final ComparatorOptions copt = new ComparatorOptions();
final Comparator comparator = new ReverseBytewiseComparator(copt);
final RocksDB db = openDatabase(dbDir, comparator)) {
final Random rnd = new Random(rand_seed);
try(final ComparatorOptions copt2 = new ComparatorOptions();
final Comparator comparator2 = new ReverseBytewiseComparator(copt2)) {
final java.util.Comparator<String> jComparator = toJavaComparator(comparator2);
doRandomIterationTest(
db,
jComparator,
rnd,
8, 100, 3
);
}
} finally {
removeData(dbDir);
}
}
}
private void doRandomIterationTest(
final RocksDB db, final java.util.Comparator<String> javaComparator,
final Random rnd,
final int num_writes, final int num_iter_ops,
final int num_trigger_flush) throws RocksDBException {
final TreeMap<String, String> map = new TreeMap<>(javaComparator);
for (int i = 0; i < num_writes; i++) {
if (num_trigger_flush > 0 && i != 0 && i % num_trigger_flush == 0) {
db.flush(new FlushOptions());
}
final int type = rnd.nextInt(2);
final int index = rnd.nextInt(source_strings.size());
final String key = source_strings.get(index);
switch (type) {
case 0:
// put
map.put(key, key);
db.put(new WriteOptions(), bytes(key), bytes(key));
break;
case 1:
// delete
if (map.containsKey(key)) {
map.remove(key);
}
db.remove(new WriteOptions(), bytes(key));
break;
default:
fail("Should not be able to generate random outside range 1..2");
}
}
try(final RocksIterator iter = db.newIterator(new ReadOptions())) {
final KVIter<String, String> result_iter = new KVIter(map);
boolean is_valid = false;
for (int i = 0; i < num_iter_ops; i++) {
// Random walk and make sure iter and result_iter returns the
// same key and value
final int type = rnd.nextInt(7);
iter.status();
switch (type) {
case 0:
// Seek to First
iter.seekToFirst();
result_iter.seekToFirst();
break;
case 1:
// Seek to last
iter.seekToLast();
result_iter.seekToLast();
break;
case 2: {
// Seek to random (existing or non-existing) key
final int key_idx = rnd.nextInt(interleaving_strings.size());
final String key = interleaving_strings.get(key_idx);
iter.seek(bytes(key));
result_iter.seek(bytes(key));
break;
}
case 3: {
// SeekForPrev to random (existing or non-existing) key
final int key_idx = rnd.nextInt(interleaving_strings.size());
final String key = interleaving_strings.get(key_idx);
iter.seekForPrev(bytes(key));
result_iter.seekForPrev(bytes(key));
break;
}
case 4:
// Next
if (is_valid) {
iter.next();
result_iter.next();
} else {
continue;
}
break;
case 5:
// Prev
if (is_valid) {
iter.prev();
result_iter.prev();
} else {
continue;
}
break;
default: {
assert (type == 6);
final int key_idx = rnd.nextInt(source_strings.size());
final String key = source_strings.get(key_idx);
final byte[] result = db.get(new ReadOptions(), bytes(key));
if (!map.containsKey(key)) {
assertNull(result);
} else {
assertArrayEquals(bytes(map.get(key)), result);
}
break;
}
}
assertEquals(result_iter.isValid(), iter.isValid());
is_valid = iter.isValid();
if (is_valid) {
assertArrayEquals(bytes(result_iter.key()), iter.key());
//note that calling value on a non-valid iterator from the Java API
//results in a SIGSEGV
assertArrayEquals(bytes(result_iter.value()), iter.value());
}
}
}
}
/**
* Open the database using a C++ Comparator
*/
private RocksDB openDatabase(
final Path dbDir, final BuiltinComparator cppComparator)
throws IOException, RocksDBException {
final Options options = new Options()
.setCreateIfMissing(true)
.setComparator(cppComparator);
return RocksDB.open(options, dbDir.toAbsolutePath().toString());
}
/**
* Open the database using a Java Comparator
*/
private RocksDB openDatabase(
final Path dbDir,
final AbstractComparator<? extends AbstractSlice<?>> javaComparator)
throws IOException, RocksDBException {
final Options options = new Options()
.setCreateIfMissing(true)
.setComparator(javaComparator);
return RocksDB.open(options, dbDir.toAbsolutePath().toString());
}
private void closeDatabase(final RocksDB db) {
db.close();
}
private void removeData(final Path dbDir) throws IOException {
Files.walkFileTree(dbDir, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(
final Path file, final BasicFileAttributes attrs)
throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(
final Path dir, final IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
}
private byte[] bytes(final String s) {
return s.getBytes(StandardCharsets.UTF_8);
}
private java.util.Comparator<String> toJavaComparator(
final Comparator rocksComparator) {
return new java.util.Comparator<String>() {
@Override
public int compare(final String s1, final String s2) {
return rocksComparator.compare(new Slice(s1), new Slice(s2));
}
};
}
private java.util.Comparator<String> toJavaComparator(
final DirectComparator rocksComparator) {
return new java.util.Comparator<String>() {
@Override
public int compare(final String s1, final String s2) {
return rocksComparator.compare(new DirectSlice(s1),
new DirectSlice(s2));
}
};
}
private class KVIter<K, V> implements RocksIteratorInterface {
private final List<Map.Entry<K, V>> entries;
private final java.util.Comparator<? super K> comparator;
private int offset = -1;
private int lastPrefixMatchIdx = -1;
private int lastPrefixMatch = 0;
public KVIter(final TreeMap<K, V> map) {
this.entries = new ArrayList<>();
final Iterator<Map.Entry<K, V>> iterator = map.entrySet().iterator();
while(iterator.hasNext()) {
entries.add(iterator.next());
}
this.comparator = map.comparator();
}
@Override
public boolean isValid() {
return offset > -1 && offset < entries.size();
}
@Override
public void seekToFirst() {
offset = 0;
}
@Override
public void seekToLast() {
offset = entries.size() - 1;
}
@Override
public void seek(final byte[] target) {
for(offset = 0; offset < entries.size(); offset++) {
if(comparator.compare(entries.get(offset).getKey(),
(K)new String(target, StandardCharsets.UTF_8)) >= 0) {
return;
}
}
}
@Override
public void seekForPrev(final byte[] target) {
for(offset = entries.size()-1; offset >= 0; offset--) {
if(comparator.compare(entries.get(offset).getKey(),
(K)new String(target, StandardCharsets.UTF_8)) <= 0) {
return;
}
}
}
/**
* Is `a` a prefix of `b`
*
* @return The length of the matching prefix, or 0 if it is not a prefix
*/
private int isPrefix(final byte[] a, final byte[] b) {
if(b.length >= a.length) {
for(int i = 0; i < a.length; i++) {
if(a[i] != b[i]) {
return i;
}
}
return a.length;
} else {
return 0;
}
}
@Override
public void next() {
if(offset < entries.size()) {
offset++;
}
}
@Override
public void prev() {
if(offset >= 0) {
offset--;
}
}
@Override
public void status() throws RocksDBException {
if(offset < 0 || offset >= entries.size()) {
throw new RocksDBException("Index out of bounds. Size is: " +
entries.size() + ", offset is: " + offset);
}
}
public K key() {
if(!isValid()) {
if(entries.isEmpty()) {
return (K)"";
} else if(offset == -1){
return entries.get(0).getKey();
} else if(offset == entries.size()) {
return entries.get(offset - 1).getKey();
} else {
return (K)"";
}
} else {
return entries.get(offset).getKey();
}
}
public V value() {
if(!isValid()) {
return (V)"";
} else {
return entries.get(offset).getValue();
}
}
}
}
| bsd-3-clause |
tp81/openmicroscopy | components/tools/OmeroJava/test/integration/ProjectionServiceTest.java | 19753 | /*
* $Id$
*
* Copyright 2013 University of Dundee. All rights reserved.
* Use is subject to license terms supplied in LICENSE.txt
*/
package integration;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import omero.ValidationException;
import omero.api.IProjectionPrx;
import omero.constants.projection.ProjectionType;
import omero.model.Image;
import omero.model.Pixels;
import omero.model.PixelsType;
import omero.sys.EventContext;
import omero.sys.ParametersI;
import org.springframework.util.ResourceUtils;
import org.testng.annotations.Test;
/**
* Test the projection of an image by different users in all groups type.
* Test also methods by passing invalid parameters.
*
* @author Jean-Marie Burel <a
* href="mailto:j.burel@dundee.ac.uk">j.burel@dundee.ac.uk</a>
* @since 4.4.9
*/
public class ProjectionServiceTest extends AbstractServerTest
{
/**
* Imports the small dv.
* The image has 5 z-sections, 6 timepoints, 1 channel, signed 16-bit.
*
* @return The id of the pixels set.
* @throws Exception Thrown if an error occurred.
*/
private Pixels importImage() throws Exception
{
File srcFile = ResourceUtils.getFile("classpath:tinyTest.d3d.dv");
List<Pixels> pixels = null;
try {
pixels = importFile(srcFile, "dv");
} catch (Throwable e) {
throw new Exception("cannot import image", e);
}
return pixels.get(0);
}
/**
* Creates an image and projects it either by the owner or by another
* member of the group.
*
* @param perms The permissions of the group.
* @param role The role of the other group member projecting the image or
* <code>-1</code> if the owner projects the image.
* @throws Exception Thrown if an error occurred.
*/
private void projectImage(String perms, int memberRole)
throws Exception
{
EventContext ctx = newUserAndGroup(perms);
long ownerID = ctx.userId;
if (memberRole > 0) { //create a second user in the group.
EventContext ctx2 = newUserInGroup(ctx);
switch (memberRole) {
case AbstractServerTest.ADMIN:
logRootIntoGroup(ctx2);
break;
case AbstractServerTest.GROUP_OWNER:
makeGroupOwner();
}
ctx2 = iAdmin.getEventContext();
ownerID = ctx2.userId;
}
Pixels pixels = importImage();
List<Integer> channels = Arrays.asList(0);
Image img = projectImage(pixels, 0, pixels.getSizeT().getValue()-1, 0,
pixels.getSizeZ().getValue()-1, 1,
ProjectionType.MAXIMUMINTENSITY, null, channels);
assertEquals(ownerID, img.getDetails().getOwner().getId().getValue());
}
/**
* Projects the image.
*
* @param pixels The pixels set.
* @param startT The lower bound of the timepoint interval.
* @param endT The upper bound of the timepoint interval.
* @param startZ The lower bound of the z-section interval.
* @param endZ The upper bound of the z-section interval.
* @param stepping The stepping.
* @param prjType The type of projection to perform.
* @param pixelsType The type of pixels to generate.
* @param channels The list of channels' indexes.
* @return The projected image.
* @throws Exception Thrown if an error occurred.
*/
private Image projectImage(Pixels pixels, int startT, int endT, int startZ,
int endZ, int stepping, ProjectionType prjType,
PixelsType pixelsType, List<Integer> channels)
throws Exception
{
IProjectionPrx svc = factory.getProjectionService();
long imageID = svc.projectPixels(pixels.getId().getValue(), pixelsType,
prjType, startT, endT, channels, stepping, startZ, endZ,
"projectedImage");
assertTrue(imageID > 0);
List<Image> images =
factory.getContainerService().getImages(Image.class.getName(),
Arrays.asList(imageID), new ParametersI());
assertEquals(images.size(), 1);
Pixels p = images.get(0).getPixels(0);
assertEquals(p.getSizeC().getValue(), channels.size());
assertEquals(p.getSizeT().getValue(), Math.abs(startT-endT)+1);
assertEquals(p.getSizeZ().getValue(), 1);
if (pixelsType == null) pixelsType = pixels.getPixelsType();
assertEquals(p.getPixelsType().getValue().getValue(),
pixelsType.getValue().getValue());
return images.get(0);
}
/**
* Projects the image.
*
* @param pixelsID The id of the pixels set.
* @param timepoint The selected timepoint.
* @param startZ The lower bound of the z-section interval.
* @param endZ The upper bound of the z-section interval.
* @param stepping The stepping.
* @param prjType The type of projection to perform.
* @param pixelsType The type of pixels to generate.
* @param channelIndex The channel's index.
* @throws Exception Thrown if an error occurred.
*/
private void projectStackImage(long pixelsID, int timepoint, int startZ,
int endZ, int stepping, ProjectionType prjType,
PixelsType pixelsType, int channelIndex)
throws Exception
{
IProjectionPrx svc = factory.getProjectionService();
byte[] value = svc.projectStack(pixelsID, pixelsType, prjType,
timepoint, channelIndex, stepping, startZ, endZ);
assertTrue(value.length > 0);
//TODO: more check to be added
}
/**
* Test the possible projection type.
*
* @throws Exception Thrown if an error occurred.
*/
@Test
public void testProjectionMeanIntensity() throws Exception {
Pixels pixels = importImage();
List<Integer> channels = Arrays.asList(0);
projectImage(pixels, 0, pixels.getSizeT().getValue()-1, 0,
pixels.getSizeZ().getValue()-1, 1,
ProjectionType.MEANINTENSITY, null, channels);
}
/**
* Test the possible projection type.
*
* @throws Exception Thrown if an error occurred.
*/
@Test
public void testProjectionSumIntensity() throws Exception {
Pixels pixels = importImage();
List<Integer> channels = Arrays.asList(0);
projectImage(pixels, 0, 0, 0,
pixels.getSizeZ().getValue()-1, 1,
ProjectionType.SUMINTENSITY, null, channels);
}
/**
* Test the possible projection type.
*
* @throws Exception Thrown if an error occurred.
*/
@Test
public void testProjectionMaxIntensity() throws Exception {
Pixels pixels = importImage();
List<Integer> channels = Arrays.asList(0);
projectImage(pixels, 0, pixels.getSizeT().getValue()-1, 0,
pixels.getSizeZ().getValue()-1, 1,
ProjectionType.MAXIMUMINTENSITY, null, channels);
}
/**
* Test the projection with an invalid timepoint range.
*
* @throws Exception Thrown if an error occurred.
*/
@Test(expectedExceptions = ValidationException.class)
public void testWrongTimepointIntervalUpperBound() throws Exception {
Pixels pixels = importImage();
List<Integer> channels = Arrays.asList(0);
projectImage(pixels, 0, pixels.getSizeT().getValue(), 0,
pixels.getSizeZ().getValue()-1, 1,
ProjectionType.MAXIMUMINTENSITY, null, channels);
}
/**
* Test the projection with an invalid timepoint range.
*
* @throws Exception Thrown if an error occurred.
*/
@Test(expectedExceptions = ValidationException.class)
public void testWrongTimepointIntervalLowerBound() throws Exception {
Pixels pixels = importImage();
List<Integer> channels = Arrays.asList(0);
projectImage(pixels, -1, pixels.getSizeT().getValue()-1, 0,
pixels.getSizeZ().getValue()-1, 1,
ProjectionType.MAXIMUMINTENSITY, null, channels);
}
/**
* Test the projection with a timepoint range with lower bound = upper bound
*
* @throws Exception Thrown if an error occurred.
*/
@Test
public void testSameTimepointInterval() throws Exception {
Pixels pixels = importImage();
List<Integer> channels = Arrays.asList(0);
projectImage(pixels, 0, 0, 0, pixels.getSizeZ().getValue()-1, 1,
ProjectionType.MAXIMUMINTENSITY, null, channels);
}
/**
* Test the projection with an invalid timepoint range.
*
* @throws Exception Thrown if an error occurred.
*/
@Test(expectedExceptions = ValidationException.class)
public void testWrongTimepointInterval() throws Exception {
Pixels pixels = importImage();
List<Integer> channels = Arrays.asList(0);
projectImage(pixels, 6, 7, 0, pixels.getSizeZ().getValue()-1, 1,
ProjectionType.MAXIMUMINTENSITY, null, channels);
}
/**
* Test the projection with no channels specified.
*
* @throws Exception Thrown if an error occurred.
*/
@Test(expectedExceptions = ValidationException.class)
public void testNoChannels() throws Exception {
Pixels pixels = importImage();
List<Integer> channels = new ArrayList<Integer>();
projectImage(pixels, 0, pixels.getSizeT().getValue()-1, 0,
pixels.getSizeZ().getValue(), 1,
ProjectionType.MAXIMUMINTENSITY, null, channels);
}
/**
* Test the projection with <code>null</code> channels list.
*
* @throws Exception Thrown if an error occurred.
*/
@Test(expectedExceptions = ValidationException.class)
public void testNullChannels() throws Exception {
Pixels pixels = importImage();
projectImage(pixels, 0, pixels.getSizeT().getValue()-1, 0,
pixels.getSizeZ().getValue(), 1,
ProjectionType.MAXIMUMINTENSITY, null, null);
}
/**
* Test the projection with an invalid channel index
*
* @throws Exception Thrown if an error occurred.
*/
@Test(expectedExceptions = ValidationException.class)
public void testWrongChannels() throws Exception {
Pixels pixels = importImage();
List<Integer> channels = Arrays.asList(1);
projectImage(pixels, 0, pixels.getSizeT().getValue()-1, 0,
pixels.getSizeZ().getValue(), 1,
ProjectionType.MAXIMUMINTENSITY, null, channels);
}
/**
* Test the projection with an invalid z-section range.
*
* @throws Exception Thrown if an error occurred.
*/
@Test(expectedExceptions = ValidationException.class)
public void testWrongZSectionIntervalUpperBound() throws Exception {
Pixels pixels = importImage();
List<Integer> channels = Arrays.asList(0);
projectImage(pixels, 0, pixels.getSizeT().getValue()-1, 0,
pixels.getSizeZ().getValue(), 1,
ProjectionType.MAXIMUMINTENSITY, null, channels);
}
/**
* Test the projection with a z-sections range with same value.
*
* @throws Exception Thrown if an error occurred.
*/
@Test
public void testSameZSectionInterval() throws Exception {
Pixels pixels = importImage();
List<Integer> channels = Arrays.asList(0);
projectImage(pixels, 0, pixels.getSizeT().getValue()-1, 0, 1, 1,
ProjectionType.MAXIMUMINTENSITY, null, channels);
}
/**
* Test the projection with an invalid timepoint range.
*
* @throws Exception Thrown if an error occurred.
*/
@Test(expectedExceptions = ValidationException.class)
public void testWrongZSectionIntervalLowerBound() throws Exception {
Pixels pixels = importImage();
List<Integer> channels = Arrays.asList(0);
projectImage(pixels, 0, pixels.getSizeT().getValue()-1, -1,
pixels.getSizeZ().getValue()-1, 1,
ProjectionType.MAXIMUMINTENSITY, null, channels);
}
/**
* Test the projection with a negative stepping
*
* @throws Exception Thrown if an error occurred.
*/
@Test(expectedExceptions = ValidationException.class)
public void testNegativeStepping() throws Exception {
Pixels pixels = importImage();
List<Integer> channels = Arrays.asList(0);
projectImage(pixels, 0, pixels.getSizeT().getValue()-1, 0,
pixels.getSizeZ().getValue()-1, -10,
ProjectionType.MAXIMUMINTENSITY, null, channels);
}
/**
* Test the projection with 2 steps
*
* @throws Exception Thrown if an error occurred.
*/
public void testTwoSteps() throws Exception {
Pixels pixels = importImage();
List<Integer> channels = Arrays.asList(0);
projectImage(pixels, 0, pixels.getSizeT().getValue()-1, 0,
pixels.getSizeZ().getValue()-1, 2,
ProjectionType.MAXIMUMINTENSITY, null, channels);
}
/**
* Test the projection with 0 step
*
* @throws Exception Thrown if an error occurred.
*/
@Test(expectedExceptions = ValidationException.class)
public void testZeroStep() throws Exception {
Pixels pixels = importImage();
List<Integer> channels = Arrays.asList(0);
projectImage(pixels, 0, pixels.getSizeT().getValue()-1, 0,
pixels.getSizeZ().getValue()-1, 0,
ProjectionType.MAXIMUMINTENSITY, null, channels);
}
/**
* Test the projection of stack with a negative stepping
*
* @throws Exception Thrown if an error occurred.
*/
@Test(expectedExceptions = ValidationException.class)
public void testProjectStackNegativeStepping() throws Exception {
Pixels pixels = importImage();
projectStackImage(pixels.getId().getValue(), 0, 0,
pixels.getSizeZ().getValue()-1, -10,
ProjectionType.MAXIMUMINTENSITY, null, 0);
}
/**
* Test the projection of stack with a zero stepping
*
* @throws Exception Thrown if an error occurred.
*/
@Test(expectedExceptions = ValidationException.class)
public void testProjectStackZero() throws Exception {
Pixels pixels = importImage();
projectStackImage(pixels.getId().getValue(), 0, 0,
pixels.getSizeZ().getValue()-1, 0,
ProjectionType.MAXIMUMINTENSITY, null, 0);
}
//Permissions testing.
/**
* Test the projection of the image by the owner of the data in a
* RW---- group.
*
* @throws Exception Thrown if an error occurred.
*/
@Test
public void testProjectImageByOwnerRW() throws Exception {
projectImage("rw----", -1);
}
/**
* Test the projection of the image by the owner of the data in a
* RWR--- group.
*
* @throws Exception Thrown if an error occurred.
*/
@Test
public void testProjectImageByOwnerRWR() throws Exception {
projectImage("rwr---", -1);
}
/**
* Test the projection of the image by the owner of the data in a
* RWRA-- group.
*
* @throws Exception Thrown if an error occurred.
*/
@Test
public void testProjectImageByOwnerRWRA() throws Exception {
projectImage("rwra--", -1);
}
/**
* Test the projection of the image by the owner of the data in a
* RWR--- group.
*
* @throws Exception Thrown if an error occurred.
*/
@Test
public void testProjectImageByOwnerRWRW() throws Exception {
projectImage("rwrw--", -1);
}
/**
* Test the projection of the image by the member of the group
* in a RW---- group.
*
* @throws Exception Thrown if an error occurred.
*/
@Test
public void testProjectImageByMemberRW() throws Exception {
projectImage("rw----", AbstractServerTest.MEMBER);
}
/**
* Test the projection of the image by the group owner of the group
* in a RW---- group.
*
* @throws Exception Thrown if an error occurred.
*/
@Test
public void testProjectImageByGroupOwnerRW() throws Exception {
projectImage("rw----", AbstractServerTest.GROUP_OWNER);
}
/**
* Test the projection of the image by an administrator.
* in a RW---- group.
*
* @throws Exception Thrown if an error occurred.
*/
@Test
public void testProjectImageByAdminRW() throws Exception {
projectImage("rw----", AbstractServerTest.ADMIN);
}
/**
* Test the projection of the image by a member of the group
* in a RWR--- group.
*
* @throws Exception Thrown if an error occurred.
*/
@Test
public void testProjectImageByGroupMemberRWR() throws Exception {
projectImage("rwr---", AbstractServerTest.MEMBER);
}
/**
* Test the projection of the image by the group owner of the group
* in a RWR--- group.
*
* @throws Exception Thrown if an error occurred.
*/
@Test
public void testProjectImageByGroupOwnerRWR() throws Exception {
projectImage("rwr---", AbstractServerTest.GROUP_OWNER);
}
/**
* Test the projection of the image by an administrator.
* in a RWR--- group.
*
* @throws Exception Thrown if an error occurred.
*/
@Test
public void testProjectImageByAdminRWR() throws Exception {
projectImage("rwr---", AbstractServerTest.ADMIN);
}
/**
* Test the projection of the image by a member of the group
* in a RWRA-- group.
*
* @throws Exception Thrown if an error occurred.
*/
@Test
public void testProjectImageByGroupMemberRWRA() throws Exception {
projectImage("rwra--", AbstractServerTest.MEMBER);
}
/**
* Test the projection of the image by the group owner of the group
* in a RWRA-- group.
*
* @throws Exception Thrown if an error occurred.
*/
@Test
public void testProjectImageByGroupOwnerRWRA() throws Exception {
projectImage("rwra--", AbstractServerTest.GROUP_OWNER);
}
/**
* Test the projection of the image by an administrator.
* in a RWRA-- group.
*
* @throws Exception Thrown if an error occurred.
*/
@Test
public void testProjectImageByAdminRWRA() throws Exception {
projectImage("rwra--", AbstractServerTest.ADMIN);
}
/**
* Test the projection of the image by a member of the group
* in a RWRW-- group.
*
* @throws Exception Thrown if an error occurred.
*/
@Test
public void testProjectImageByGroupMemberRWRW() throws Exception {
projectImage("rwrw--", AbstractServerTest.MEMBER);
}
/**
* Test the projection of the image by the group owner of the group
* in a RWRW-- group.
*
* @throws Exception Thrown if an error occurred.
*/
@Test
public void testProjectImageByGroupOwnerRWRW() throws Exception {
projectImage("rwrw--", AbstractServerTest.GROUP_OWNER);
}
/**
* Test the projection of the image by an administrator.
* in a RWRW-- group.
*
* @throws Exception Thrown if an error occurred.
*/
@Test
public void testProjectImageByAdminRWRW() throws Exception {
projectImage("rwrw--", AbstractServerTest.ADMIN);
}
}
| gpl-2.0 |
PaulMcClernan/livecode | engine/src/java/com/runrev/android/billing/google/GoogleBillingProvider.java | 19100 |
package com.runrev.android.billing.google;
import com.runrev.android.billing.google.Purchase;
import com.runrev.android.billing.*;
import com.runrev.android.Engine;
import android.app.*;
import android.util.*;
import android.content.*;
import java.util.*;
public class GoogleBillingProvider implements BillingProvider
{
public static final String TAG = "GoogleBillingProvider";
private Activity mActivity;
private Boolean started = false;
private PurchaseObserver mPurchaseObserver;
private Map<String,String> types = new HashMap<String,String>();
private Map<String,Map<String,String>> itemProps = new HashMap<String, Map<String,String>>();
private List<SkuDetails> knownItems = new ArrayList<SkuDetails>();
private Set<String> ownedItems = new HashSet<String>();
/*
Temp var for holding the productId, to pass it in onIabPurchaseFinished(IabResult result, Purchase purchase), in case purchase is null.
Thus, purchase.getSku() will not work
*/
private String pendingPurchaseSku = "";
// (arbitrary) request code for the purchase flow
static final int RC_REQUEST = 10001;
// The helper object
IabHelper mHelper = null;
public void initBilling()
{
String t_public_key = Engine.doGetCustomPropertyValue("cREVStandaloneSettings", "android,storeKey");
if (t_public_key != null && t_public_key.length() > 0)
Security.setPublicKey(t_public_key);
// Create the helper, passing it our context and the public key to verify signatures with
Log.d(TAG, "Creating IAB helper.");
mHelper = new IabHelper(getActivity(), t_public_key);
// TODO enable debug logging (for a production application, you should set this to false).
mHelper.enableDebugLogging(false);
// Start setup. This is asynchronous and the specified listener
// will be called once setup completes.
Log.d(TAG, "Starting setup.");
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener()
{
public void onIabSetupFinished(IabResult result)
{
Log.d(TAG, "Setup finished.");
if (!result.isSuccess())
{
// Oh no, there was a problem.
complain("Problem setting up in-app billing: " + result);
return;
}
// Have we been disposed of in the meantime? If so, quit.
if (mHelper == null) return;
// IAB is fully set up.
Log.d(TAG, "Setup successful.");
//mHelper.queryInventoryAsync(mGotInventoryListener);
}
});
}
public void onDestroy()
{
if (mHelper != null)
mHelper.dispose();
mHelper = null;
}
public boolean canMakePurchase()
{
if (mHelper == null)
return false;
else
return mHelper.is_billing_supported;
}
public boolean enableUpdates()
{
if (mHelper == null)
return false;
return true;
}
public boolean disableUpdates()
{
if (mHelper == null)
return false;
return true;
}
public boolean restorePurchases()
{
if (mHelper == null)
{
return false;
}
Log.d(TAG, "Querying inventory.");
mHelper.queryInventoryAsync(mGotInventoryListener);
return true;
}
public boolean sendRequest(int purchaseId, String productId, String developerPayload)
{
if (mHelper == null)
return false;
String type = productGetType(productId);
if (type == null)
{
Log.i(TAG, "Item type is null (not specified). Exiting..");
return false;
}
pendingPurchaseSku = productId;
Log.i(TAG, "purchaseSendRequest(" + purchaseId + ", " + productId + ", " + type + ")");
if (type.equals("subs"))
{
mHelper.launchSubscriptionPurchaseFlow(getActivity(), productId, RC_REQUEST, mPurchaseFinishedListener, developerPayload);
return true;
}
else if (type.equals("inapp"))
{
mHelper.launchPurchaseFlow(getActivity(), productId, RC_REQUEST, mPurchaseFinishedListener, developerPayload);
return true;
}
else
{
Log.i(TAG, "Item type is not recognized. Exiting..");
return false;
}
}
public boolean makePurchase(String productId, String quantity, String payload)
{
if (mHelper == null)
return false;
String type = productGetType(productId);
if (type == null)
{
Log.i(TAG, "Item type is null (not specified). Exiting..");
return false;
}
pendingPurchaseSku = productId;
setPurchaseProperty(productId, "developerPayload", payload);
Log.i(TAG, "purchaseSendRequest(" + productId + ", " + type + ")");
if (type.equals("subs"))
{
mHelper.launchSubscriptionPurchaseFlow(getActivity(), productId, RC_REQUEST, mPurchaseFinishedListener, payload);
return true;
}
else if (type.equals("inapp"))
{
mHelper.launchPurchaseFlow(getActivity(), productId, RC_REQUEST, mPurchaseFinishedListener, payload);
return true;
}
else
{
Log.i(TAG, "Item type is not recognized. Exiting..");
return false;
}
}
public boolean productSetType(String productId, String productType)
{
Log.d(TAG, "Setting type for productId" + productId + ", type is : " + productType);
types.put(productId, productType);
Log.d(TAG, "Querying HashMap, type is " + types.get(productId));
return true;
}
private String productGetType(String productId)
{
return types.get(productId);
}
public boolean consumePurchase(final String productId)
{
mHelper.queryInventoryAsync(new IabHelper.QueryInventoryFinishedListener()
{
@Override
public void onQueryInventoryFinished(IabResult result, Inventory inventory)
{
if (result.isFailure())
{
return;
}
else
{
Purchase purchase = inventory.getPurchase(productId);
// Do this check to avoid a NullPointerException
if (purchase == null)
{
Log.d(TAG, "You cannot consume item : " + productId + ", since you don't own it!");
return;
}
mHelper.consumeAsync(purchase, mConsumeFinishedListener);
}
}
});
return true;
}
public boolean requestProductDetails(final String productId)
{
//arbitrary initial capacity
int capacity = 25;
List<String> productList = new ArrayList<String>(capacity);
productList.add(productId);
mHelper.queryInventoryAsync(true, productList, new IabHelper.QueryInventoryFinishedListener()
{
@Override
public void onQueryInventoryFinished(IabResult result, Inventory inventory)
{
if (result.isFailure())
{
return;
}
else
{
SkuDetails skuDetails = inventory.getSkuDetails(productId);
// Do this check to avoid a NullPointerException
if (skuDetails == null)
{
Log.d(TAG, "No product found with the specified ID : " + productId + " !");
mPurchaseObserver.onProductDetailsError(productId, "No product found with the specified ID");
return;
}
knownItems.add(skuDetails);
loadKnownItemToLocalInventory(skuDetails);
Log.d(TAG, "Details for requested product : " + skuDetails.toString());
mPurchaseObserver.onProductDetailsReceived(productId);
}
}
});
return true;
}
public String receiveProductDetails(String productId)
{
for (SkuDetails skuDetails : knownItems)
{
if (productId.equals(skuDetails.getSku()))
{
return skuDetails.toString();
}
}
return "Product ID not found";
}
public boolean confirmDelivery(int purchaseId)
{
if (mHelper == null)
return false;
else
return true;
}
public void setPurchaseObserver(PurchaseObserver observer)
{
mPurchaseObserver = observer;
}
Activity getActivity()
{
return mActivity;
}
public void setActivity(Activity activity)
{
mActivity = activity;
}
public boolean setPurchaseProperty(String productId, String propertyName, String propertyValue)
{
if (!itemProps.containsKey(productId))
itemProps.put(productId, new HashMap<String,String>());
(itemProps.get(productId)).put(propertyName, propertyValue);
return true;
}
public String getPurchaseProperty(String productId, String propName)
{
Log.d(TAG, "Stored properties for productId :" + productId);
Map<String,String> map = itemProps.get(productId);
if (map != null)
return map.get(propName);
else
return "";
}
public String getPurchaseList()
{
return ownedItems.toString();
}
//some helper methods
boolean addPurchaseToLocalInventory(Purchase purchase)
{
boolean success = true;
if (success)
success = setPurchaseProperty(purchase.getSku(), "productId", purchase.getSku());
if (success)
success = setPurchaseProperty(purchase.getSku(), "itemType", purchase.getItemType());
if (success)
success = setPurchaseProperty(purchase.getSku(), "orderId", purchase.getOrderId());
if (success)
success = setPurchaseProperty(purchase.getSku(), "packageName", purchase.getPackageName());
if (success)
success = setPurchaseProperty(purchase.getSku(), "purchaseToken", purchase.getToken());
if (success)
success = setPurchaseProperty(purchase.getSku(), "signature", purchase.getSignature());
if (success)
success = setPurchaseProperty(purchase.getSku(), "developerPayload", purchase.getDeveloperPayload());
if (success)
success = setPurchaseProperty(purchase.getSku(), "purchaseTime", new Long(purchase.getPurchaseTime()).toString());
return success;
}
boolean loadKnownItemToLocalInventory(SkuDetails skuDetails)
{
boolean success = true;
if (success)
success = setPurchaseProperty(skuDetails.getSku(), "productId", skuDetails.getSku());
if (success)
success = setPurchaseProperty(skuDetails.getSku(), "itemType", skuDetails.getType());
if (success)
success = setPurchaseProperty(skuDetails.getSku(), "price", skuDetails.getPrice());
if (success)
success = setPurchaseProperty(skuDetails.getSku(), "title", skuDetails.getTitle());
if (success)
success = setPurchaseProperty(skuDetails.getSku(), "description", skuDetails.getDescription());
return success;
}
void removePurchaseFromLocalInventory(Purchase purchase)
{
ownedItems.remove(purchase.getSku());
}
void complain(String message)
{
Log.d(TAG, "**** Error: " + message);
alert("Error: " + message);
}
void alert(String message)
{
AlertDialog.Builder bld = new AlertDialog.Builder(getActivity());
bld.setMessage(message);
bld.setNeutralButton("OK", null);
Log.d(TAG, "Showing alert dialog: " + message);
bld.create().show();
}
// Listeners
IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener()
{
// parameter "purchase" is null if purchase failed
public void onIabPurchaseFinished(IabResult result, Purchase purchase)
{
Log.d(TAG, "Purchase finished: " + result + ", purchase: " + purchase);
// if we were disposed of in the meantime, quit.
if (mHelper == null)
{
return;
}
if (result.isFailure())
{
// PM-2015-01-27: [[ Bug 14450 ]] [Removed code] No need to display an alert with the error message, since this information is also contained in the purchaseStateUpdate message
mPurchaseObserver.onPurchaseStateChanged(pendingPurchaseSku, mapResponseCode(result.getResponse()));
pendingPurchaseSku = "";
return;
}
if (!verifyDeveloperPayload(purchase))
{
complain("Error purchasing. Authenticity verification failed.");
return;
}
Log.d(TAG, "Purchase successful.");
pendingPurchaseSku = "";
ownedItems.add(purchase.getSku());
addPurchaseToLocalInventory(purchase);
offerPurchasedItems(purchase);
}
};
void offerPurchasedItems(Purchase purchase)
{
if (purchase != null)
mPurchaseObserver.onPurchaseStateChanged(purchase.getSku(), mapResponseCode(purchase.getPurchaseState()));
}
// Called when consumption is complete
IabHelper.OnConsumeFinishedListener mConsumeFinishedListener = new IabHelper.OnConsumeFinishedListener()
{
public void onConsumeFinished(Purchase purchase, IabResult result)
{
Log.d(TAG, "Consumption finished. Purchase: " + purchase + ", result: " + result);
if (result.isSuccess())
{
Log.d(TAG, "Consumption successful. Provisioning.");
removePurchaseFromLocalInventory(purchase);
}
else
{
complain("Error while consuming: " + result);
}
Log.d(TAG, "End consumption flow.");
}
};
// Called when we finish querying the items we own
IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener()
{
public void onQueryInventoryFinished(IabResult result, Inventory inventory)
{
Log.d(TAG, "Query inventory finished.");
// Have we been disposed of in the meantime? If so, quit.
if (mHelper == null)
return;
if (result.isFailure())
{
complain("Failed to query inventory: " + result);
return;
}
Log.d(TAG, "Query inventory was successful.");
Log.d(TAG, "Initial inventory query finished; enabling main UI.");
// PM-2015-02-05: [[ Bug 14402 ]] Handle case when calling mobileStoreRestorePurchases but there are no previous purchases to restore
boolean t_did_restore;
t_did_restore = false;
List<Purchase> purchaseList = inventory.getallpurchases();
for (Purchase p : purchaseList)
{
addPurchaseToLocalInventory(p);
ownedItems.add(p.getSku());
// onPurchaseStateChanged to be called with state = 5 (restored)
mPurchaseObserver.onPurchaseStateChanged(p.getSku(), 5);
t_did_restore = true;
}
if(!t_did_restore)
{
// PM-2015-02-12: [[ Bug 14402 ]] When there are no previous purchases to restore, send a purchaseStateUpdate msg with state=restored and productID=""
mPurchaseObserver.onPurchaseStateChanged("",5);
}
}
};
/** Verifies the developer payload of a purchase. */
boolean verifyDeveloperPayload(Purchase p)
{
String payload = p.getDeveloperPayload();
/*
* TODO: verify that the developer payload of the purchase is correct. It will be
* the same one that you sent when initiating the purchase.
*
* WARNING: Locally generating a random string when starting a purchase and
* verifying it here might seem like a good approach, but this will fail in the
* case where the user purchases an item on one device and then uses your app on
* a different device, because on the other device you will not have access to the
* random string you originally generated.
*
* So a good developer payload has these characteristics:
*
* 1. If two different users purchase an item, the payload is different between them,
* so that one user's purchase can't be replayed to another user.
*
* 2. The payload must be such that you can verify it even when the app wasn't the
* one who initiated the purchase flow (so that items purchased by the user on
* one device work on other devices owned by the user).
*
* Using your own server to store and verify developer payloads across app
* installations is recommended.
*/
return true;
}
public void onActivityResult (int requestCode, int resultCode, Intent data)
{
Log.d(TAG, "onActivityResult(" + requestCode + "," + resultCode + "," + data);
// Pass on the activity result to the helper for handling
if (!mHelper.handleActivityResult(requestCode, resultCode, data))
{
// not handled
Log.d(TAG, "onActivityResult NOT handled by IABUtil.");
}
else
{
Log.d(TAG, "onActivityResult handled by IABUtil.");
}
}
// Should match the order of enum MCAndroidPurchaseState (mblandroidstore.cpp)
int mapResponseCode(int responseCode)
{
int result;
switch(responseCode)
{
case IabHelper.BILLING_RESPONSE_RESULT_OK:
result = 0;
break;
case IabHelper.BILLING_RESPONSE_RESULT_USER_CANCELED:
result = 1;
break;
case IabHelper.BILLING_RESPONSE_RESULT_ITEM_UNAVAILABLE:
result = 2;
break;
case IabHelper.BILLING_RESPONSE_RESULT_ITEM_ALREADY_OWNED:
result = 3;
break;
default:
result = 1;
break;
}
return result;
}
}
| gpl-3.0 |
ritumalhotra8/IRIS | interaction-core/src/test/java/com/temenos/interaction/core/command/TestChainingCommandController.java | 2598 | package com.temenos.interaction.core.command;
/*
* #%L
* interaction-core
* %%
* Copyright (C) 2012 - 2015 Temenos Holdings N.V.
* %%
* 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 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/>.
* #L%
*/
import static org.junit.Assert.*;
import static org.mockito.Mockito.when;
import static org.mockito.Matchers.startsWith;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.CoreMatchers.equalTo;
import java.util.Arrays;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
/**
* Test class for the ChainingCommandController {@link ChainingCommandController}
*
* @author trojanbug
*/
@RunWith(MockitoJUnitRunner.class)
public class TestChainingCommandController {
@InjectMocks
private ChainingCommandController controller;
@Mock
private CommandController commandController;
@Before
public void setUp() throws Exception {
when(this.commandController.isValidCommand(startsWith("testCommand"))).thenReturn(true);
when(this.commandController.fetchCommand(startsWith("testCommand"))).thenReturn(new TestCommand());
this.controller.setCommandControllers(Arrays.asList(new CommandController[]{
this.commandController
}));
}
@After
public void tearDown() throws Exception {
}
@Test
public void testFetchCommand() {
assertThat(this.controller.fetchCommand("testCommand1"), notNullValue());
}
@Test
public void testFetchCommandWithInvalidCommandName(){
assertThat(this.controller.fetchCommand("notAValidCommand"), nullValue());
}
@Test
public void testIsValidCommand() {
assertThat(this.controller.isValidCommand("testCommand1"), equalTo(true));
}
@Test
public void testIsValidCommandWithInvalidCommandName() {
assertThat(this.controller.isValidCommand("notAValidCommand"), equalTo(false));
}
}
| agpl-3.0 |
jianglili007/jena | jena-sdb/src/main/java/org/apache/jena/sdb/layout1/StoreSimpleHSQL.java | 1984 | /*
* 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.jena.sdb.layout1;
import org.apache.jena.sdb.StoreDesc ;
import org.apache.jena.sdb.core.sqlnode.GenerateSQL ;
import org.apache.jena.sdb.layout2.TableDescTriples ;
import org.apache.jena.sdb.sql.SDBConnection ;
import org.apache.jena.sdb.util.HSQLUtils ;
/** Store class for the simple layout (i.e. one triple table)
*/
public class StoreSimpleHSQL extends StoreBase1
{
boolean currentlyOpen = true ;
public StoreSimpleHSQL(SDBConnection sdb, StoreDesc desc)
{
this(sdb, desc, new TableDescSPO(), new CodecSimple()) ;
}
private StoreSimpleHSQL(SDBConnection connection, StoreDesc desc, TableDescTriples triples, EncoderDecoder codec)
{
super(connection, desc,
new FormatterSimpleHSQL(connection) ,
new TupleLoaderSimple(connection, triples, codec),
new QueryCompilerFactory1(codec),
new SQLBridgeFactory1(codec),
new GenerateSQL(),
triples) ;
}
@Override
public void close()
{
if ( currentlyOpen )
HSQLUtils.shutdown(getConnection()) ;
currentlyOpen = false ;
}
}
| apache-2.0 |
gfyoung/elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/job/results/Forecast.java | 11369 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.core.ml.job.results;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.common.xcontent.ConstructingObjectParser;
import org.elasticsearch.common.xcontent.ObjectParser.ValueType;
import org.elasticsearch.common.xcontent.ToXContentObject;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.xpack.core.ml.job.config.Job;
import org.elasticsearch.xpack.core.ml.utils.time.TimeUtils;
import java.io.IOException;
import java.util.Date;
import java.util.Objects;
/**
* Model Forecast POJO.
*/
public class Forecast implements ToXContentObject, Writeable {
/**
* Result type
*/
public static final String RESULT_TYPE_VALUE = "model_forecast";
public static final ParseField RESULTS_FIELD = new ParseField(RESULT_TYPE_VALUE);
public static final ParseField FORECAST_ID = new ParseField("forecast_id");
public static final ParseField PARTITION_FIELD_NAME = new ParseField("partition_field_name");
public static final ParseField PARTITION_FIELD_VALUE = new ParseField("partition_field_value");
public static final ParseField BY_FIELD_NAME = new ParseField("by_field_name");
public static final ParseField BY_FIELD_VALUE = new ParseField("by_field_value");
public static final ParseField MODEL_FEATURE = new ParseField("model_feature");
public static final ParseField FORECAST_LOWER = new ParseField("forecast_lower");
public static final ParseField FORECAST_UPPER = new ParseField("forecast_upper");
public static final ParseField FORECAST_PREDICTION = new ParseField("forecast_prediction");
public static final ParseField BUCKET_SPAN = new ParseField("bucket_span");
public static final ParseField DETECTOR_INDEX = new ParseField("detector_index");
public static final ConstructingObjectParser<Forecast, Void> STRICT_PARSER = createParser(false);
private static ConstructingObjectParser<Forecast, Void> createParser(boolean ignoreUnknownFields) {
ConstructingObjectParser<Forecast, Void> parser = new ConstructingObjectParser<>(RESULT_TYPE_VALUE, ignoreUnknownFields,
a -> new Forecast((String) a[0], (String) a[1], (Date) a[2], (long) a[3], (int) a[4]));
parser.declareString(ConstructingObjectParser.constructorArg(), Job.ID);
parser.declareString(ConstructingObjectParser.constructorArg(), FORECAST_ID);
parser.declareField(ConstructingObjectParser.constructorArg(),
p -> TimeUtils.parseTimeField(p, Result.TIMESTAMP.getPreferredName()), Result.TIMESTAMP, ValueType.VALUE);
parser.declareLong(ConstructingObjectParser.constructorArg(), BUCKET_SPAN);
parser.declareInt(ConstructingObjectParser.constructorArg(), DETECTOR_INDEX);
parser.declareString((modelForecast, s) -> {}, Result.RESULT_TYPE);
parser.declareString(Forecast::setPartitionFieldName, PARTITION_FIELD_NAME);
parser.declareString(Forecast::setPartitionFieldValue, PARTITION_FIELD_VALUE);
parser.declareString(Forecast::setByFieldName, BY_FIELD_NAME);
parser.declareString(Forecast::setByFieldValue, BY_FIELD_VALUE);
parser.declareString(Forecast::setModelFeature, MODEL_FEATURE);
parser.declareDouble(Forecast::setForecastLower, FORECAST_LOWER);
parser.declareDouble(Forecast::setForecastUpper, FORECAST_UPPER);
parser.declareDouble(Forecast::setForecastPrediction, FORECAST_PREDICTION);
return parser;
}
private final String jobId;
private final String forecastId;
private final Date timestamp;
private final long bucketSpan;
private int detectorIndex;
private String partitionFieldName;
private String partitionFieldValue;
private String byFieldName;
private String byFieldValue;
private String modelFeature;
private double forecastLower;
private double forecastUpper;
private double forecastPrediction;
public Forecast(String jobId, String forecastId, Date timestamp, long bucketSpan, int detectorIndex) {
this.jobId = Objects.requireNonNull(jobId);
this.forecastId = Objects.requireNonNull(forecastId);
this.timestamp = timestamp;
this.bucketSpan = bucketSpan;
this.detectorIndex = detectorIndex;
}
public Forecast(StreamInput in) throws IOException {
jobId = in.readString();
forecastId = in.readString();
timestamp = new Date(in.readLong());
partitionFieldName = in.readOptionalString();
partitionFieldValue = in.readOptionalString();
byFieldName = in.readOptionalString();
byFieldValue = in.readOptionalString();
modelFeature = in.readOptionalString();
forecastLower = in.readDouble();
forecastUpper = in.readDouble();
forecastPrediction = in.readDouble();
bucketSpan = in.readLong();
detectorIndex = in.readInt();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(jobId);
out.writeString(forecastId);
out.writeLong(timestamp.getTime());
out.writeOptionalString(partitionFieldName);
out.writeOptionalString(partitionFieldValue);
out.writeOptionalString(byFieldName);
out.writeOptionalString(byFieldValue);
out.writeOptionalString(modelFeature);
out.writeDouble(forecastLower);
out.writeDouble(forecastUpper);
out.writeDouble(forecastPrediction);
out.writeLong(bucketSpan);
out.writeInt(detectorIndex);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field(Job.ID.getPreferredName(), jobId);
builder.field(FORECAST_ID.getPreferredName(), forecastId);
builder.field(Result.RESULT_TYPE.getPreferredName(), RESULT_TYPE_VALUE);
builder.field(BUCKET_SPAN.getPreferredName(), bucketSpan);
builder.field(DETECTOR_INDEX.getPreferredName(), detectorIndex);
if (timestamp != null) {
builder.timeField(Result.TIMESTAMP.getPreferredName(),
Result.TIMESTAMP.getPreferredName() + "_string", timestamp.getTime());
}
if (partitionFieldName != null) {
builder.field(PARTITION_FIELD_NAME.getPreferredName(), partitionFieldName);
}
if (partitionFieldValue != null) {
builder.field(PARTITION_FIELD_VALUE.getPreferredName(), partitionFieldValue);
}
if (byFieldName != null) {
builder.field(BY_FIELD_NAME.getPreferredName(), byFieldName);
}
if (byFieldValue != null) {
builder.field(BY_FIELD_VALUE.getPreferredName(), byFieldValue);
}
if (modelFeature != null) {
builder.field(MODEL_FEATURE.getPreferredName(), modelFeature);
}
builder.field(FORECAST_LOWER.getPreferredName(), forecastLower);
builder.field(FORECAST_UPPER.getPreferredName(), forecastUpper);
builder.field(FORECAST_PREDICTION.getPreferredName(), forecastPrediction);
builder.endObject();
return builder;
}
public String getJobId() {
return jobId;
}
public String getForecastId() {
return forecastId;
}
public String getId() {
int valuesHash = Objects.hash(byFieldValue, partitionFieldValue);
int length = (byFieldValue == null ? 0 : byFieldValue.length()) +
(partitionFieldValue == null ? 0 : partitionFieldValue.length());
return jobId + "_model_forecast_" + forecastId + "_" + timestamp.getTime()
+ "_" + bucketSpan + "_" + detectorIndex + "_"
+ valuesHash + "_" + length;
}
public Date getTimestamp() {
return timestamp;
}
public long getBucketSpan() {
return bucketSpan;
}
public String getPartitionFieldName() {
return partitionFieldName;
}
public void setPartitionFieldName(String partitionFieldName) {
this.partitionFieldName = partitionFieldName;
}
public int getDetectorIndex() {
return detectorIndex;
}
public String getPartitionFieldValue() {
return partitionFieldValue;
}
public void setPartitionFieldValue(String partitionFieldValue) {
this.partitionFieldValue = partitionFieldValue;
}
public String getByFieldName() {
return byFieldName;
}
public void setByFieldName(String byFieldName) {
this.byFieldName = byFieldName;
}
public String getByFieldValue() {
return byFieldValue;
}
public void setByFieldValue(String byFieldValue) {
this.byFieldValue = byFieldValue;
}
public String getModelFeature() {
return modelFeature;
}
public void setModelFeature(String modelFeature) {
this.modelFeature = modelFeature;
}
public double getForecastLower() {
return forecastLower;
}
public void setForecastLower(double forecastLower) {
this.forecastLower = forecastLower;
}
public double getForecastUpper() {
return forecastUpper;
}
public void setForecastUpper(double forecastUpper) {
this.forecastUpper = forecastUpper;
}
public double getForecastPrediction() {
return forecastPrediction;
}
public void setForecastPrediction(double forecastPrediction) {
this.forecastPrediction = forecastPrediction;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other instanceof Forecast == false) {
return false;
}
Forecast that = (Forecast) other;
return Objects.equals(this.jobId, that.jobId) &&
Objects.equals(this.forecastId, that.forecastId) &&
Objects.equals(this.timestamp, that.timestamp) &&
Objects.equals(this.partitionFieldValue, that.partitionFieldValue) &&
Objects.equals(this.partitionFieldName, that.partitionFieldName) &&
Objects.equals(this.byFieldValue, that.byFieldValue) &&
Objects.equals(this.byFieldName, that.byFieldName) &&
Objects.equals(this.modelFeature, that.modelFeature) &&
this.forecastLower == that.forecastLower &&
this.forecastUpper == that.forecastUpper &&
this.forecastPrediction == that.forecastPrediction &&
this.bucketSpan == that.bucketSpan &&
this.detectorIndex == that.detectorIndex;
}
@Override
public int hashCode() {
return Objects.hash(jobId, forecastId, timestamp, partitionFieldName, partitionFieldValue,
byFieldName, byFieldValue, modelFeature, forecastLower, forecastUpper,
forecastPrediction, bucketSpan, detectorIndex);
}
}
| apache-2.0 |
Panos-Bletsos/spark-cost-model-optimizer | common/network-common/src/test/java/org/apache/spark/network/sasl/SparkSaslSuite.java | 16455 | /*
* 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.spark.network.sasl;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import java.io.File;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import javax.security.sasl.SaslException;
import com.google.common.collect.Lists;
import com.google.common.io.ByteStreams;
import com.google.common.io.Files;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.apache.spark.network.TestUtils;
import org.apache.spark.network.TransportContext;
import org.apache.spark.network.buffer.FileSegmentManagedBuffer;
import org.apache.spark.network.buffer.ManagedBuffer;
import org.apache.spark.network.client.ChunkReceivedCallback;
import org.apache.spark.network.client.RpcResponseCallback;
import org.apache.spark.network.client.TransportClient;
import org.apache.spark.network.client.TransportClientBootstrap;
import org.apache.spark.network.server.RpcHandler;
import org.apache.spark.network.server.StreamManager;
import org.apache.spark.network.server.TransportServer;
import org.apache.spark.network.server.TransportServerBootstrap;
import org.apache.spark.network.util.ByteArrayWritableChannel;
import org.apache.spark.network.util.JavaUtils;
import org.apache.spark.network.util.SystemPropertyConfigProvider;
import org.apache.spark.network.util.TransportConf;
/**
* Jointly tests SparkSaslClient and SparkSaslServer, as both are black boxes.
*/
public class SparkSaslSuite {
/** Provides a secret key holder which returns secret key == appId */
private SecretKeyHolder secretKeyHolder = new SecretKeyHolder() {
@Override
public String getSaslUser(String appId) {
return "user";
}
@Override
public String getSecretKey(String appId) {
return appId;
}
};
@Test
public void testMatching() {
SparkSaslClient client = new SparkSaslClient("shared-secret", secretKeyHolder, false);
SparkSaslServer server = new SparkSaslServer("shared-secret", secretKeyHolder, false);
assertFalse(client.isComplete());
assertFalse(server.isComplete());
byte[] clientMessage = client.firstToken();
while (!client.isComplete()) {
clientMessage = client.response(server.response(clientMessage));
}
assertTrue(server.isComplete());
// Disposal should invalidate
server.dispose();
assertFalse(server.isComplete());
client.dispose();
assertFalse(client.isComplete());
}
@Test
public void testNonMatching() {
SparkSaslClient client = new SparkSaslClient("my-secret", secretKeyHolder, false);
SparkSaslServer server = new SparkSaslServer("your-secret", secretKeyHolder, false);
assertFalse(client.isComplete());
assertFalse(server.isComplete());
byte[] clientMessage = client.firstToken();
try {
while (!client.isComplete()) {
clientMessage = client.response(server.response(clientMessage));
}
fail("Should not have completed");
} catch (Exception e) {
assertTrue(e.getMessage().contains("Mismatched response"));
assertFalse(client.isComplete());
assertFalse(server.isComplete());
}
}
@Test
public void testSaslAuthentication() throws Throwable {
testBasicSasl(false);
}
@Test
public void testSaslEncryption() throws Throwable {
testBasicSasl(true);
}
private void testBasicSasl(boolean encrypt) throws Throwable {
RpcHandler rpcHandler = mock(RpcHandler.class);
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) {
ByteBuffer message = (ByteBuffer) invocation.getArguments()[1];
RpcResponseCallback cb = (RpcResponseCallback) invocation.getArguments()[2];
assertEquals("Ping", JavaUtils.bytesToString(message));
cb.onSuccess(JavaUtils.stringToBytes("Pong"));
return null;
}
})
.when(rpcHandler)
.receive(any(TransportClient.class), any(ByteBuffer.class), any(RpcResponseCallback.class));
SaslTestCtx ctx = new SaslTestCtx(rpcHandler, encrypt, false);
try {
ByteBuffer response = ctx.client.sendRpcSync(JavaUtils.stringToBytes("Ping"),
TimeUnit.SECONDS.toMillis(10));
assertEquals("Pong", JavaUtils.bytesToString(response));
} finally {
ctx.close();
// There should be 2 terminated events; one for the client, one for the server.
Throwable error = null;
long deadline = System.nanoTime() + TimeUnit.NANOSECONDS.convert(10, TimeUnit.SECONDS);
while (deadline > System.nanoTime()) {
try {
verify(rpcHandler, times(2)).channelInactive(any(TransportClient.class));
error = null;
break;
} catch (Throwable t) {
error = t;
TimeUnit.MILLISECONDS.sleep(10);
}
}
if (error != null) {
throw error;
}
}
}
@Test
public void testEncryptedMessage() throws Exception {
SaslEncryptionBackend backend = mock(SaslEncryptionBackend.class);
byte[] data = new byte[1024];
new Random().nextBytes(data);
when(backend.wrap(any(byte[].class), anyInt(), anyInt())).thenReturn(data);
ByteBuf msg = Unpooled.buffer();
try {
msg.writeBytes(data);
// Create a channel with a really small buffer compared to the data. This means that on each
// call, the outbound data will not be fully written, so the write() method should return a
// dummy count to keep the channel alive when possible.
ByteArrayWritableChannel channel = new ByteArrayWritableChannel(32);
SaslEncryption.EncryptedMessage emsg =
new SaslEncryption.EncryptedMessage(backend, msg, 1024);
long count = emsg.transferTo(channel, emsg.transfered());
assertTrue(count < data.length);
assertTrue(count > 0);
// Here, the output buffer is full so nothing should be transferred.
assertEquals(0, emsg.transferTo(channel, emsg.transfered()));
// Now there's room in the buffer, but not enough to transfer all the remaining data,
// so the dummy count should be returned.
channel.reset();
assertEquals(1, emsg.transferTo(channel, emsg.transfered()));
// Eventually, the whole message should be transferred.
for (int i = 0; i < data.length / 32 - 2; i++) {
channel.reset();
assertEquals(1, emsg.transferTo(channel, emsg.transfered()));
}
channel.reset();
count = emsg.transferTo(channel, emsg.transfered());
assertTrue("Unexpected count: " + count, count > 1 && count < data.length);
assertEquals(data.length, emsg.transfered());
} finally {
msg.release();
}
}
@Test
public void testEncryptedMessageChunking() throws Exception {
File file = File.createTempFile("sasltest", ".txt");
try {
TransportConf conf = new TransportConf("shuffle", new SystemPropertyConfigProvider());
byte[] data = new byte[8 * 1024];
new Random().nextBytes(data);
Files.write(data, file);
SaslEncryptionBackend backend = mock(SaslEncryptionBackend.class);
// It doesn't really matter what we return here, as long as it's not null.
when(backend.wrap(any(byte[].class), anyInt(), anyInt())).thenReturn(data);
FileSegmentManagedBuffer msg = new FileSegmentManagedBuffer(conf, file, 0, file.length());
SaslEncryption.EncryptedMessage emsg =
new SaslEncryption.EncryptedMessage(backend, msg.convertToNetty(), data.length / 8);
ByteArrayWritableChannel channel = new ByteArrayWritableChannel(data.length);
while (emsg.transfered() < emsg.count()) {
channel.reset();
emsg.transferTo(channel, emsg.transfered());
}
verify(backend, times(8)).wrap(any(byte[].class), anyInt(), anyInt());
} finally {
file.delete();
}
}
@Test
public void testFileRegionEncryption() throws Exception {
final String blockSizeConf = "spark.network.sasl.maxEncryptedBlockSize";
System.setProperty(blockSizeConf, "1k");
final AtomicReference<ManagedBuffer> response = new AtomicReference<>();
final File file = File.createTempFile("sasltest", ".txt");
SaslTestCtx ctx = null;
try {
final TransportConf conf = new TransportConf("shuffle", new SystemPropertyConfigProvider());
StreamManager sm = mock(StreamManager.class);
when(sm.getChunk(anyLong(), anyInt())).thenAnswer(new Answer<ManagedBuffer>() {
@Override
public ManagedBuffer answer(InvocationOnMock invocation) {
return new FileSegmentManagedBuffer(conf, file, 0, file.length());
}
});
RpcHandler rpcHandler = mock(RpcHandler.class);
when(rpcHandler.getStreamManager()).thenReturn(sm);
byte[] data = new byte[8 * 1024];
new Random().nextBytes(data);
Files.write(data, file);
ctx = new SaslTestCtx(rpcHandler, true, false);
final CountDownLatch lock = new CountDownLatch(1);
ChunkReceivedCallback callback = mock(ChunkReceivedCallback.class);
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) {
response.set((ManagedBuffer) invocation.getArguments()[1]);
response.get().retain();
lock.countDown();
return null;
}
}).when(callback).onSuccess(anyInt(), any(ManagedBuffer.class));
ctx.client.fetchChunk(0, 0, callback);
lock.await(10, TimeUnit.SECONDS);
verify(callback, times(1)).onSuccess(anyInt(), any(ManagedBuffer.class));
verify(callback, never()).onFailure(anyInt(), any(Throwable.class));
byte[] received = ByteStreams.toByteArray(response.get().createInputStream());
assertTrue(Arrays.equals(data, received));
} finally {
file.delete();
if (ctx != null) {
ctx.close();
}
if (response.get() != null) {
response.get().release();
}
System.clearProperty(blockSizeConf);
}
}
@Test
public void testServerAlwaysEncrypt() throws Exception {
final String alwaysEncryptConfName = "spark.network.sasl.serverAlwaysEncrypt";
System.setProperty(alwaysEncryptConfName, "true");
SaslTestCtx ctx = null;
try {
ctx = new SaslTestCtx(mock(RpcHandler.class), false, false);
fail("Should have failed to connect without encryption.");
} catch (Exception e) {
assertTrue(e.getCause() instanceof SaslException);
} finally {
if (ctx != null) {
ctx.close();
}
System.clearProperty(alwaysEncryptConfName);
}
}
@Test
public void testDataEncryptionIsActuallyEnabled() throws Exception {
// This test sets up an encrypted connection but then, using a client bootstrap, removes
// the encryption handler from the client side. This should cause the server to not be
// able to understand RPCs sent to it and thus close the connection.
SaslTestCtx ctx = null;
try {
ctx = new SaslTestCtx(mock(RpcHandler.class), true, true);
ctx.client.sendRpcSync(JavaUtils.stringToBytes("Ping"),
TimeUnit.SECONDS.toMillis(10));
fail("Should have failed to send RPC to server.");
} catch (Exception e) {
assertFalse(e.getCause() instanceof TimeoutException);
} finally {
if (ctx != null) {
ctx.close();
}
}
}
@Test
public void testRpcHandlerDelegate() throws Exception {
// Tests all delegates exception for receive(), which is more complicated and already handled
// by all other tests.
RpcHandler handler = mock(RpcHandler.class);
RpcHandler saslHandler = new SaslRpcHandler(null, null, handler, null);
saslHandler.getStreamManager();
verify(handler).getStreamManager();
saslHandler.channelInactive(null);
verify(handler).channelInactive(any(TransportClient.class));
saslHandler.exceptionCaught(null, null);
verify(handler).exceptionCaught(any(Throwable.class), any(TransportClient.class));
}
@Test
public void testDelegates() throws Exception {
Method[] rpcHandlerMethods = RpcHandler.class.getDeclaredMethods();
for (Method m : rpcHandlerMethods) {
SaslRpcHandler.class.getDeclaredMethod(m.getName(), m.getParameterTypes());
}
}
private static class SaslTestCtx {
final TransportClient client;
final TransportServer server;
private final boolean encrypt;
private final boolean disableClientEncryption;
private final EncryptionCheckerBootstrap checker;
SaslTestCtx(
RpcHandler rpcHandler,
boolean encrypt,
boolean disableClientEncryption)
throws Exception {
TransportConf conf = new TransportConf("shuffle", new SystemPropertyConfigProvider());
SecretKeyHolder keyHolder = mock(SecretKeyHolder.class);
when(keyHolder.getSaslUser(anyString())).thenReturn("user");
when(keyHolder.getSecretKey(anyString())).thenReturn("secret");
TransportContext ctx = new TransportContext(conf, rpcHandler);
this.checker = new EncryptionCheckerBootstrap();
this.server = ctx.createServer(Arrays.asList(new SaslServerBootstrap(conf, keyHolder),
checker));
try {
List<TransportClientBootstrap> clientBootstraps = Lists.newArrayList();
clientBootstraps.add(new SaslClientBootstrap(conf, "user", keyHolder, encrypt));
if (disableClientEncryption) {
clientBootstraps.add(new EncryptionDisablerBootstrap());
}
this.client = ctx.createClientFactory(clientBootstraps)
.createClient(TestUtils.getLocalHost(), server.getPort());
} catch (Exception e) {
close();
throw e;
}
this.encrypt = encrypt;
this.disableClientEncryption = disableClientEncryption;
}
void close() {
if (!disableClientEncryption) {
assertEquals(encrypt, checker.foundEncryptionHandler);
}
if (client != null) {
client.close();
}
if (server != null) {
server.close();
}
}
}
private static class EncryptionCheckerBootstrap extends ChannelOutboundHandlerAdapter
implements TransportServerBootstrap {
boolean foundEncryptionHandler;
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise)
throws Exception {
if (!foundEncryptionHandler) {
foundEncryptionHandler =
ctx.channel().pipeline().get(SaslEncryption.ENCRYPTION_HANDLER_NAME) != null;
}
ctx.write(msg, promise);
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
super.handlerRemoved(ctx);
}
@Override
public RpcHandler doBootstrap(Channel channel, RpcHandler rpcHandler) {
channel.pipeline().addFirst("encryptionChecker", this);
return rpcHandler;
}
}
private static class EncryptionDisablerBootstrap implements TransportClientBootstrap {
@Override
public void doBootstrap(TransportClient client, Channel channel) {
channel.pipeline().remove(SaslEncryption.ENCRYPTION_HANDLER_NAME);
}
}
}
| apache-2.0 |
droolsjbpm/drools | drools-core/src/main/java/org/drools/core/fluent/impl/KieSessionFluentImpl.java | 2632 | /*
* Copyright 2016 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.core.fluent.impl;
import org.drools.core.command.SetActiveAgendaGroup;
import org.drools.core.command.runtime.DisposeCommand;
import org.drools.core.command.runtime.GetGlobalCommand;
import org.drools.core.command.runtime.rule.FireAllRulesCommand;
import org.drools.core.command.runtime.rule.InsertObjectCommand;
import org.kie.api.runtime.rule.FactHandle;
import org.kie.internal.builder.fluent.ExecutableBuilder;
import org.kie.internal.builder.fluent.KieSessionFluent;
public class KieSessionFluentImpl extends BaseBatchWithProcessFluent<KieSessionFluent, ExecutableBuilder> implements KieSessionFluent {
public KieSessionFluentImpl(ExecutableImpl fluentCtx) {
super(fluentCtx);
}
@Override
public KieSessionFluent fireAllRules() {
fluentCtx.addCommand(new FireAllRulesCommand());
return this;
}
@Override
public KieSessionFluent setGlobal(String identifier, Object object) {
return this;
}
@Override
public KieSessionFluent getGlobal(String identifier) {
fluentCtx.addCommand(new GetGlobalCommand(identifier));
return this;
}
@Override
public KieSessionFluent insert(Object object) {
fluentCtx.addCommand(new InsertObjectCommand(object));
return this;
}
@Override
public KieSessionFluent update(FactHandle handle, Object object) {
return this;
}
@Override
public KieSessionFluent delete(FactHandle handle) {
return this;
}
@Override
public KieSessionFluent setActiveRuleFlowGroup(String ruleFlowGroup) {
return setActiveAgendaGroup(ruleFlowGroup);
}
@Override
public KieSessionFluent setActiveAgendaGroup(String agendaGroup) {
fluentCtx.addCommand(new SetActiveAgendaGroup(agendaGroup));
return this;
}
@Override
public ExecutableBuilder dispose() {
fluentCtx.addCommand(new DisposeCommand());
return fluentCtx.getExecutableBuilder();
}
} | apache-2.0 |
priyatransbit/aws-sdk-java | aws-java-sdk-iam/src/main/java/com/amazonaws/services/identitymanagement/model/transform/PolicyEvaluationExceptionUnmarshaller.java | 1553 | /*
* Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.identitymanagement.model.transform;
import org.w3c.dom.Node;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.util.XpathUtils;
import com.amazonaws.transform.StandardErrorUnmarshaller;
import com.amazonaws.services.identitymanagement.model.PolicyEvaluationException;
public class PolicyEvaluationExceptionUnmarshaller extends StandardErrorUnmarshaller {
public PolicyEvaluationExceptionUnmarshaller() {
super(PolicyEvaluationException.class);
}
public AmazonServiceException unmarshall(Node node) throws Exception {
// Bail out if this isn't the right error code that this
// marshaller understands.
String errorCode = parseErrorCode(node);
if (errorCode == null || !errorCode.equals("PolicyEvaluation"))
return null;
PolicyEvaluationException e = (PolicyEvaluationException)super.unmarshall(node);
return e;
}
}
| apache-2.0 |
iotivity/iotivity | service/notification/examples/android/NotiProviderExample/app/src/androidTest/java/org/iotivity/service/ns/sample/provider/ConsumerSimulator.java | 2830 | //******************************************************************
//
// Copyright 2016 Samsung Electronics All Rights Reserved.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
package org.iotivity.service.ns.sample.provider;
import android.util.Log;
import org.iotivity.service.ns.common.Message;
import org.iotivity.service.ns.common.SyncInfo;
import org.iotivity.service.ns.consumer.ConsumerService;
import org.iotivity.service.ns.consumer.Provider;
import java.util.concurrent.CountDownLatch;
class ConsumerSimulator implements ConsumerService.OnProviderDiscoveredListener,
Provider.OnProviderStateListener, Provider.OnMessageReceivedListener,
Provider.OnSyncInfoReceivedListener {
private String TAG = "Consumer Simulator";
private Provider mProvider;
private CountDownLatch mLockObject;
private Response mResponse;
private String mExpectCb;
public void set(CountDownLatch lockObject, Response response, String name) {
Log.i(TAG, "Setting lock Simulator: ");
mLockObject = lockObject;
mResponse = response;
mExpectCb = name;
}
@Override
public void onProviderDiscovered(Provider provider) {
mProvider = provider;
try {
provider.setListener(this, this, this);
if (!provider.isSubscribed()) {
provider.subscribe();
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onProviderStateReceived(Provider.ProviderState providerState) {
}
@Override
public void onMessageReceived(Message message) {
if (mExpectCb == "msg") {
mResponse.set(true);
mLockObject.countDown();
}
}
@Override
public void onSyncInfoReceived(SyncInfo syncInfo) {
if (mExpectCb == "sync") {
mResponse.set(true);
mLockObject.countDown();
}
}
public void sendSyncInfo(long id, SyncInfo.SyncType type) {
try {
mProvider.sendSyncInfo(id, type);
} catch (Exception e) {
e.printStackTrace();
}
}
} | apache-2.0 |
Soya93/Extract-Refactoring | java/java-tests/testSrc/com/intellij/find/FindInEditorMultiCaretTest.java | 7943 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.find;
import com.intellij.find.editorHeaderActions.*;
import com.intellij.ide.IdeEventQueue;
import com.intellij.ide.impl.DataManagerImpl;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.editor.impl.EditorImpl;
import com.intellij.testFramework.fixtures.EditorMouseFixture;
import com.intellij.testFramework.fixtures.LightPlatformCodeInsightFixtureTestCase;
import javax.swing.text.JTextComponent;
import java.io.IOException;
public class FindInEditorMultiCaretTest extends LightPlatformCodeInsightFixtureTestCase {
public void testBasic() throws IOException {
init("abc\n" +
"abc\n" +
"abc");
initFind();
setTextToFind("b");
checkResultByText("a<selection>b<caret></selection>c\n" +
"abc\n" +
"abc");
addOccurrence();
checkResultByText("a<selection>b<caret></selection>c\n" +
"a<selection>b<caret></selection>c\n" +
"abc");
nextOccurrence();
checkResultByText("a<selection>b<caret></selection>c\n" +
"abc\n" +
"a<selection>b<caret></selection>c");
prevOccurrence();
checkResultByText("a<selection>b<caret></selection>c\n" +
"a<selection>b<caret></selection>c\n" +
"abc");
removeOccurrence();
checkResultByText("a<selection>b<caret></selection>c\n" +
"abc\n" +
"abc");
allOccurrences();
checkResultByText("a<selection>b<caret></selection>c\n" +
"a<selection>b<caret></selection>c\n" +
"a<selection>b<caret></selection>c");
assertNull(getEditorSearchComponent());
}
public void testActionsInEditorWorkIndependently() throws IOException {
init("abc\n" +
"abc\n" +
"abc");
initFind();
setTextToFind("b");
checkResultByText("a<selection>b<caret></selection>c\n" +
"abc\n" +
"abc");
new EditorMouseFixture((EditorImpl)myFixture.getEditor()).clickAt(0, 1);
addOccurrenceFromEditor();
addOccurrenceFromEditor();
checkResultByText("<selection>a<caret>bc</selection>\n" +
"<selection>a<caret>bc</selection>\n" +
"abc");
nextOccurrenceFromEditor();
checkResultByText("<selection>a<caret>bc</selection>\n" +
"abc\n" +
"<selection>a<caret>bc</selection>");
prevOccurrenceFromEditor();
checkResultByText("<selection>a<caret>bc</selection>\n" +
"<selection>a<caret>bc</selection>\n" +
"abc");
removeOccurrenceFromEditor();
checkResultByText("<selection>a<caret>bc</selection>\n" +
"abc\n" +
"abc");
allOccurrencesFromEditor();
checkResultByText("<selection>a<caret>bc</selection>\n" +
"<selection>a<caret>bc</selection>\n" +
"<selection>a<caret>bc</selection>");
assertNotNull(getEditorSearchComponent());
}
public void testCloseRetainsMulticaretSelection() throws IOException {
init("abc\n" +
"abc\n" +
"abc");
initFind();
setTextToFind("b");
addOccurrence();
closeFind();
checkResultByText("a<selection>b<caret></selection>c\n" +
"a<selection>b<caret></selection>c\n" +
"abc");
}
public void testTextModificationRemovesOldSelections() throws IOException {
init("abc\n" +
"abc\n" +
"abc");
initFind();
setTextToFind("b");
addOccurrence();
setTextToFind("bc");
assertEquals(1, myFixture.getEditor().getCaretModel().getCaretCount());
assertEquals("bc", myFixture.getEditor().getSelectionModel().getSelectedText());
}
public void testSecondFindNavigatesToTheSameOccurrence() throws IOException {
init("ab<caret>c\n" +
"abc\n" +
"abc");
initFind();
setTextToFind("abc");
checkResultByText("abc\n" +
"<selection>abc<caret></selection>\n" +
"abc");
closeFind();
initFind();
setTextToFind("abc");
checkResultByText("abc\n" +
"<selection>abc<caret></selection>\n" +
"abc");
}
public void testFindNextRetainsOnlyOneCaretIfNotUsedAsMoveToNextOccurrence() throws Exception {
init("<caret>To be or not to be?");
initFind();
setTextToFind("be");
checkResultByText("To <selection>be<caret></selection> or not to be?");
closeFind();
new EditorMouseFixture((EditorImpl)myFixture.getEditor()).alt().shift().clickAt(0, 8); // adding second caret
checkResultByText("To <selection>be<caret></selection> or<caret> not to be?");
nextOccurrenceFromEditor();
checkResultByText("To be or not to <selection>be<caret></selection>?");
}
private void setTextToFind(String text) {
EditorSearchSession editorSearchSession = getEditorSearchComponent();
assertNotNull(editorSearchSession);
JTextComponent searchField = editorSearchSession.getComponent().getSearchTextComponent();
assertNotNull(searchField);
for (int i = 0; i <= text.length(); i++) {
searchField.setText(text.substring(0, i)); // emulate typing chars one by one
IdeEventQueue.getInstance().flushQueue();
}
}
private void nextOccurrence() {
executeHeaderAction(new NextOccurrenceAction());
}
private void prevOccurrence() {
executeHeaderAction(new PrevOccurrenceAction());
}
private void addOccurrence() {
executeHeaderAction(new AddOccurrenceAction());
}
private void removeOccurrence() {
executeHeaderAction(new RemoveOccurrenceAction());
}
private void allOccurrences() {
executeHeaderAction(new SelectAllAction());
}
private void nextOccurrenceFromEditor() {
myFixture.performEditorAction(IdeActions.ACTION_FIND_NEXT);
}
private void prevOccurrenceFromEditor() {
myFixture.performEditorAction(IdeActions.ACTION_FIND_PREVIOUS);
}
private void addOccurrenceFromEditor() {
myFixture.performEditorAction(IdeActions.ACTION_SELECT_NEXT_OCCURENCE);
}
private void removeOccurrenceFromEditor() {
myFixture.performEditorAction(IdeActions.ACTION_UNSELECT_PREVIOUS_OCCURENCE);
}
private void allOccurrencesFromEditor() {
myFixture.performEditorAction(IdeActions.ACTION_SELECT_ALL_OCCURRENCES);
}
private void closeFind() {
EditorSearchSession editorSearchSession = getEditorSearchComponent();
editorSearchSession.close();
}
private void executeHeaderAction(AnAction action) {
DataContext context = new DataManagerImpl.MyDataContext(getEditorSearchComponent().getComponent());
action.actionPerformed(AnActionEvent.createFromDataContext(ActionPlaces.EDITOR_TOOLBAR, null, context));
}
private void initFind() {
myFixture.performEditorAction(IdeActions.ACTION_FIND);
}
private EditorSearchSession getEditorSearchComponent() {
return EditorSearchSession.get(myFixture.getEditor());
}
private void init(String text) {
myFixture.configureByText(getTestName(false) + ".txt", text);
}
private void checkResultByText(String text) {
myFixture.checkResult(text);
}
}
| apache-2.0 |
ankit318/appengine-mapreduce | java/example/src/com/google/appengine/demos/mapreduce/bigqueryload/RandomBigQueryDataCreator.java | 1195 | package com.google.appengine.demos.mapreduce.bigqueryload;
import com.google.appengine.tools.mapreduce.MapOnlyMapper;
import com.google.common.collect.Lists;
import java.util.Date;
import java.util.Random;
public class RandomBigQueryDataCreator extends MapOnlyMapper<Long, SampleTable> {
private static final long serialVersionUID = -4247519870584497230L;
private static Random r;
@Override
public void map(Long value) {
SampleTable toWrite = getSampleTableData(value);
emit(toWrite);
}
public static SampleTable getSampleTableData(Long value) {
r = new Random(value);
SampleTable toWrite = new SampleTable(value,
randomInt(),
String.format("colvalue %d", randomInt()),
Lists.newArrayList(String.format("column value %d", randomInt()),
String.format("colvalue %d", randomInt())),
new String[] {String.format("column value %d", randomInt()),
String.format("column value %d", randomInt())},
new SampleNestedRecord(randomInt(), String.format("column value %d", randomInt())),
new Date(randomInt()));
return toWrite;
}
private static int randomInt() {
return r.nextInt();
}
}
| apache-2.0 |
tiarebalbi/spring-boot | spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/ConnectionInputStreamTests.java | 2888 | /*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.devtools.livereload;
import java.io.ByteArrayInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIOException;
/**
* Tests for {@link ConnectionInputStream}.
*
* @author Phillip Webb
*/
@SuppressWarnings("resource")
class ConnectionInputStreamTests {
private static final byte[] NO_BYTES = {};
@Test
void readHeader() throws Exception {
String header = "";
for (int i = 0; i < 100; i++) {
header += "x-something-" + i + ": xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
}
String data = header + "\r\n\r\ncontent\r\n";
ConnectionInputStream inputStream = new ConnectionInputStream(new ByteArrayInputStream(data.getBytes()));
assertThat(inputStream.readHeader()).isEqualTo(header);
}
@Test
void readFully() throws Exception {
byte[] bytes = "the data that we want to read fully".getBytes();
LimitedInputStream source = new LimitedInputStream(new ByteArrayInputStream(bytes), 2);
ConnectionInputStream inputStream = new ConnectionInputStream(source);
byte[] buffer = new byte[bytes.length];
inputStream.readFully(buffer, 0, buffer.length);
assertThat(buffer).isEqualTo(bytes);
}
@Test
void checkedRead() throws Exception {
ConnectionInputStream inputStream = new ConnectionInputStream(new ByteArrayInputStream(NO_BYTES));
assertThatIOException().isThrownBy(inputStream::checkedRead).withMessageContaining("End of stream");
}
@Test
void checkedReadArray() throws Exception {
byte[] buffer = new byte[100];
ConnectionInputStream inputStream = new ConnectionInputStream(new ByteArrayInputStream(NO_BYTES));
assertThatIOException().isThrownBy(() -> inputStream.checkedRead(buffer, 0, buffer.length))
.withMessageContaining("End of stream");
}
static class LimitedInputStream extends FilterInputStream {
private final int max;
protected LimitedInputStream(InputStream in, int max) {
super(in);
this.max = max;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
return super.read(b, off, Math.min(len, this.max));
}
}
}
| apache-2.0 |
OpenCollabZA/sakai | kernel/component-manager/src/main/java/org/sakaiproject/util/SakaiProperties.java | 18268 | /**********************************************************************************
*
* $Id$
*
***********************************************************************************
*
* Copyright (c) 2007, 2008 Sakai Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ECL-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
package org.sakaiproject.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.core.io.Resource;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DefaultPropertiesPersister;
import org.springframework.util.PropertiesPersister;
/**
* A configurer for "sakai.properties" files. These differ from the usual Spring default properties
* files by mixing together lines which define property-value pairs and lines which define
* bean property overrides. The two can be distinguished because Sakai conventionally uses
* the bean name separator "@" instead of the default "."
*
* This class creates separate PropertyPlaceholderConfigurer and PropertyOverrideConfigurer
* objects to handle bean configuration, and loads them with the input properties.
*
* SakaiProperties configuration supports most of the properties documented for
* PropertiesFactoryBean, PropertyPlaceholderConfigurer, and PropertyOverrideConfigurer.
*/
@Slf4j
public class SakaiProperties implements BeanFactoryPostProcessorCreator, InitializingBean {
private SakaiPropertiesFactoryBean propertiesFactoryBean = new SakaiPropertiesFactoryBean();
//private PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
private ReversiblePropertyOverrideConfigurer propertyOverrideConfigurer = new ReversiblePropertyOverrideConfigurer();
private PropertyPlaceholderConfigurer propertyPlaceholderConfigurer = new PropertyPlaceholderConfigurer();
public SakaiProperties() {
// Set defaults.
propertiesFactoryBean.setIgnoreResourceNotFound(true);
propertyPlaceholderConfigurer.setIgnoreUnresolvablePlaceholders(true);
propertyPlaceholderConfigurer.setOrder(0);
propertyOverrideConfigurer.setBeanNameAtEnd(true);
propertyOverrideConfigurer.setBeanNameSeparator("@");
propertyOverrideConfigurer.setIgnoreInvalidKeys(true);
}
public void afterPropertiesSet() throws Exception {
// Connect properties to configurers.
propertiesFactoryBean.afterPropertiesSet();
propertyPlaceholderConfigurer.setProperties((Properties)propertiesFactoryBean.getObject());
propertyOverrideConfigurer.setProperties((Properties)propertiesFactoryBean.getObject());
}
/* (non-Javadoc)
* @see org.sakaiproject.util.BeanFactoryPostProcessorCreator#getBeanFactoryPostProcessors()
*/
public Collection<BeanFactoryPostProcessor> getBeanFactoryPostProcessors() {
return (Arrays.asList(new BeanFactoryPostProcessor[] {propertyOverrideConfigurer, propertyPlaceholderConfigurer}));
}
/**
* Gets the individual properties from each properties file which is read in
*
* @return a map of filename -> Properties
*/
public Map<String, Properties> getSeparateProperties() {
LinkedHashMap<String, Properties> m = new LinkedHashMap<String, Properties>();
/* This doesn't work because spring always returns only the first of the properties files -AZ
* very disappointing because it means we can't tell which file a property came from
try {
// have to use reflection to get the fields here because Spring does not expose them directly
Field localPropertiesField = PropertiesLoaderSupport.class.getDeclaredField("localProperties");
Field locationsField = PropertiesLoaderSupport.class.getDeclaredField("locations");
localPropertiesField.setAccessible(true);
locationsField.setAccessible(true);
Properties[] localProperties = (Properties[]) localPropertiesField.get(propertiesFactoryBean);
Resource[] locations = (Resource[]) locationsField.get(propertiesFactoryBean);
log.info("found "+locations.length+" locations and "+localProperties.length+" props files");
for (int i = 0; i < localProperties.length; i++) {
Properties p = localProperties[i];
Properties props = dereferenceProperties(p);
Resource r = locations[i];
log.info("found "+p.size()+" props ("+props.size()+") in "+r.getFilename());
if (m.put(r.getFilename(), props) != null) {
log.warn("SeparateProperties: Found use of 2 sakai properties files with the same name (probable data loss): "+r.getFilename());
}
}
} catch (Exception e) {
log.warn("SeparateProperties: Failure trying to get the separate properties: "+e);
m.clear();
m.put("ALL", getProperties());
}
*/
/*
m.put("ALL", getProperties());
*/
for (Entry<String, Properties> entry : propertiesFactoryBean.getLoadedProperties().entrySet()) {
m.put(entry.getKey(), dereferenceProperties(entry.getValue()));
}
return m;
}
/**
* INTERNAL
* @return the set of properties after processing
*/
public Properties getProperties() {
Properties rawProperties = getRawProperties();
Properties parsedProperties = dereferenceProperties(rawProperties);
return parsedProperties;
}
/**
* INTERNAL
* @return the complete set of properties exactly as read from the files
*/
public Properties getRawProperties() {
try {
return (Properties)propertiesFactoryBean.getObject();
} catch (IOException e) {
if (log.isWarnEnabled()) log.warn("Error collecting Sakai properties", e);
return new Properties();
}
}
/**
* Dereferences property placeholders in the given {@link Properties}
* in exactly the same way the {@link BeanFactoryPostProcessor}s in this
* object perform their placeholder dereferencing. Unfortunately, this
* process is not readily decoupled from the act of processing a
* bean factory in the Spring libraries. Hence the reflection.
*
* @param srcProperties a collection of name-value pairs
* @return a new collection of properties. If <code>srcProperties</code>
* is <code>null</code>, returns null. If <code>srcProperties</code>
* is empty, returns a reference to same object.
* @throws RuntimeException if any aspect of processing fails
*/
private Properties dereferenceProperties(Properties srcProperties) throws RuntimeException {
if ( srcProperties == null ) {
return null;
}
if ( srcProperties.isEmpty() ) {
return srcProperties;
}
try {
Properties parsedProperties = new Properties();
PropertyPlaceholderConfigurer resolver = new PropertyPlaceholderConfigurer();
resolver.setIgnoreUnresolvablePlaceholders(true);
Method parseStringValue =
resolver.getClass().getDeclaredMethod("parseStringValue", String.class, Properties.class, Set.class);
parseStringValue.setAccessible(true);
for ( Map.Entry<Object, Object> propEntry : srcProperties.entrySet() ) {
String parsedPropValue = (String)parseStringValue.invoke(resolver, (String)propEntry.getValue(), srcProperties, new HashSet<Object>());
parsedProperties.setProperty((String)propEntry.getKey(), parsedPropValue);
}
return parsedProperties;
} catch ( RuntimeException e ) {
throw e;
} catch ( Exception e ) {
throw new RuntimeException("Failed to dereference properties", e);
}
}
// Delegate properties loading.
public void setProperties(Properties properties) {
propertiesFactoryBean.setProperties(properties);
}
public void setPropertiesArray(Properties[] propertiesArray) {
propertiesFactoryBean.setPropertiesArray(propertiesArray);
}
public void setLocation(Resource location) {
propertiesFactoryBean.setLocation(location);
}
public void setLocations(Resource[] locations) {
propertiesFactoryBean.setLocations(locations);
}
public void setFileEncoding(String encoding) {
propertiesFactoryBean.setFileEncoding(encoding);
}
public void setIgnoreResourceNotFound(boolean ignoreResourceNotFound) {
propertiesFactoryBean.setIgnoreResourceNotFound(ignoreResourceNotFound);
}
public void setLocalOverride(boolean localOverride) {
propertiesFactoryBean.setLocalOverride(localOverride);
}
// Delegate PropertyPlaceholderConfigurer.
public void setIgnoreUnresolvablePlaceholders(boolean ignoreUnresolvablePlaceholders) {
propertyPlaceholderConfigurer.setIgnoreUnresolvablePlaceholders(ignoreUnresolvablePlaceholders);
}
public void setOrder(int order) {
propertyPlaceholderConfigurer.setOrder(order);
}
public void setPlaceholderPrefix(String placeholderPrefix) {
propertyPlaceholderConfigurer.setPlaceholderPrefix(placeholderPrefix);
}
public void setPlaceholderSuffix(String placeholderSuffix) {
propertyPlaceholderConfigurer.setPlaceholderSuffix(placeholderSuffix);
}
public void setSearchSystemEnvironment(boolean searchSystemEnvironment) {
propertyPlaceholderConfigurer.setSearchSystemEnvironment(searchSystemEnvironment);
}
public void setSystemPropertiesMode(int systemPropertiesMode) {
propertyPlaceholderConfigurer.setSystemPropertiesMode(systemPropertiesMode);
}
public void setSystemPropertiesModeName(String constantName) throws IllegalArgumentException {
propertyPlaceholderConfigurer.setSystemPropertiesModeName(constantName);
}
// Delegate PropertyOverrideConfigurer.
public void setBeanNameAtEnd(boolean beanNameAtEnd) {
propertyOverrideConfigurer.setBeanNameAtEnd(beanNameAtEnd);
}
public void setBeanNameSeparator(String beanNameSeparator) {
propertyOverrideConfigurer.setBeanNameSeparator(beanNameSeparator);
}
public void setIgnoreInvalidKeys(boolean ignoreInvalidKeys) {
propertyOverrideConfigurer.setIgnoreInvalidKeys(ignoreInvalidKeys);
}
/**
* Blatantly stolen from the Spring classes in order to get access to the properties files as they are read in,
* this could not be done by overrides because the stupid finals and private vars, this is why frameworks should
* never use final and private in their code.... sigh
*
* @author Spring Framework
* @author Aaron Zeckoski (azeckoski @ vt.edu)
*/
public class SakaiPropertiesFactoryBean implements FactoryBean, InitializingBean {
public static final String XML_FILE_EXTENSION = ".xml";
private Map<String, Properties> loadedProperties = new LinkedHashMap<String, Properties>();
/**
* @return a map of file -> properties for everything loaded here
*/
public Map<String, Properties> getLoadedProperties() {
return loadedProperties;
}
private Properties[] localProperties;
private Resource[] locations;
private boolean localOverride = false;
private boolean ignoreResourceNotFound = false;
private String fileEncoding;
private PropertiesPersister propertiesPersister = new DefaultPropertiesPersister();
private boolean singleton = true;
private Object singletonInstance;
public final void setSingleton(boolean singleton) {
// ignore this
}
public final boolean isSingleton() {
return this.singleton;
}
public final void afterPropertiesSet() throws IOException {
if (this.singleton) {
this.singletonInstance = createInstance();
}
}
public final Object getObject() throws IOException {
if (this.singleton) {
return this.singletonInstance;
} else {
return createInstance();
}
}
@SuppressWarnings("rawtypes")
public Class getObjectType() {
return Properties.class;
}
protected Object createInstance() throws IOException {
return mergeProperties();
}
public void setProperties(Properties properties) {
this.localProperties = new Properties[] {properties};
}
public void setPropertiesArray(Properties[] propertiesArray) { // unused
this.localProperties = propertiesArray;
}
public void setLocation(Resource location) { // unused
this.locations = new Resource[] {location};
}
public void setLocations(Resource[] locations) {
this.locations = locations;
}
public void setLocalOverride(boolean localOverride) {
this.localOverride = localOverride;
}
public void setIgnoreResourceNotFound(boolean ignoreResourceNotFound) {
this.ignoreResourceNotFound = ignoreResourceNotFound;
}
public void setFileEncoding(String encoding) {
this.fileEncoding = encoding;
}
public void setPropertiesPersister(PropertiesPersister propertiesPersister) {
this.propertiesPersister =
(propertiesPersister != null ? propertiesPersister : new DefaultPropertiesPersister());
}
/**
* Return a merged Properties instance containing both the loaded properties
* and properties set on this FactoryBean.
*/
protected Properties mergeProperties() throws IOException {
Properties result = new Properties();
if (this.localOverride) {
// Load properties from file upfront, to let local properties override.
loadProperties(result);
}
if (this.localProperties != null) {
for (int i = 0; i < this.localProperties.length; i++) {
loadedProperties.put("local"+i, this.localProperties[i]);
CollectionUtils.mergePropertiesIntoMap(this.localProperties[i], result);
}
}
if (!this.localOverride) {
// Load properties from file afterwards, to let those properties override.
loadProperties(result);
}
if (log.isInfoEnabled()) log.info("Loaded a total of "+result.size()+" properties");
return result;
}
/**
* Load properties into the given instance.
*
* @param props the Properties instance to load into
* @throws java.io.IOException in case of I/O errors
* @see #setLocations
*/
protected void loadProperties(Properties props) throws IOException {
if (this.locations != null) {
for (int i = 0; i < this.locations.length; i++) {
Resource location = this.locations[i];
if (log.isDebugEnabled()) {
log.debug("Loading properties file from " + location);
}
InputStream is = null;
try {
Properties p = new Properties();
is = location.getInputStream();
if (location.getFilename().endsWith(XML_FILE_EXTENSION)) {
this.propertiesPersister.loadFromXml(p, is);
} else {
if (this.fileEncoding != null) {
this.propertiesPersister.load(p, new InputStreamReader(is, this.fileEncoding));
} else {
this.propertiesPersister.load(p, is);
}
}
if (log.isInfoEnabled()) {
log.info("Loaded "+p.size()+" properties from file " + location);
}
loadedProperties.put(location.getFilename(), p);
props.putAll(p); // merge the properties
} catch (IOException ex) {
if (this.ignoreResourceNotFound) {
if (log.isWarnEnabled()) {
log.warn("Could not load properties from " + location + ": " + ex.getMessage());
}
} else {
throw ex;
}
} finally {
if (is != null) {
is.close();
}
}
}
}
}
}
}
| apache-2.0 |
onedox/selenium | java/client/test/org/openqa/selenium/interactions/IndividualKeyboardActionsTest.java | 4940 | /*
Copyright 2007-2010 Selenium committers
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.openqa.selenium.interactions;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.openqa.selenium.Keys;
import org.openqa.selenium.interactions.internal.Coordinates;
import org.openqa.selenium.internal.Locatable;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.when;
/**
* Unit test for all simple keyboard actions.
*
*/
public class IndividualKeyboardActionsTest {
@Mock private Keyboard mockKeyboard;
@Mock private Mouse mockMouse;
@Mock private Coordinates mockCoordinates;
@Mock private Locatable stubLocatable;
final String keysToSend = "hello";
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
when(stubLocatable.getCoordinates()).thenReturn(mockCoordinates);
}
@Test
public void keyDownActionWithoutProvidedElement() {
final Keys keyToPress = Keys.SHIFT;
KeyDownAction keyDown = new KeyDownAction(mockKeyboard, mockMouse, keyToPress);
keyDown.perform();
InOrder order = Mockito.inOrder(mockKeyboard, mockMouse, mockCoordinates);
order.verify(mockKeyboard).pressKey(keyToPress);
order.verifyNoMoreInteractions();
}
@Test
public void keyDownActionOnAnElement() {
final Keys keyToPress = Keys.SHIFT;
KeyDownAction keyDown = new KeyDownAction(
mockKeyboard, mockMouse, stubLocatable, keyToPress);
keyDown.perform();
InOrder order = Mockito.inOrder(mockKeyboard, mockMouse, mockCoordinates);
order.verify(mockMouse).click(mockCoordinates);
order.verify(mockKeyboard).pressKey(keyToPress);
order.verifyNoMoreInteractions();
}
@Test
public void keyUpActionWithoutProvidedElement() {
final Keys keyToRelease = Keys.CONTROL;
KeyUpAction keyUp = new KeyUpAction(mockKeyboard, mockMouse, keyToRelease);
keyUp.perform();
InOrder order = Mockito.inOrder(mockKeyboard, mockMouse, mockCoordinates);
order.verify(mockKeyboard).releaseKey(keyToRelease);
order.verifyNoMoreInteractions();
}
@Test
public void keyUpOnAnAnElement() {
final Keys keyToRelease = Keys.SHIFT;
KeyUpAction upAction = new KeyUpAction(
mockKeyboard, mockMouse, stubLocatable, keyToRelease);
upAction.perform();
InOrder order = Mockito.inOrder(mockKeyboard, mockMouse, mockCoordinates);
order.verify(mockMouse).click(mockCoordinates);
order.verify(mockKeyboard).releaseKey(keyToRelease);
order.verifyNoMoreInteractions();
}
@Test
public void sendKeysActionWithoutProvidedElement() {
SendKeysAction sendKeys = new SendKeysAction(mockKeyboard, mockMouse, keysToSend);
sendKeys.perform();
InOrder order = Mockito.inOrder(mockKeyboard, mockMouse, mockCoordinates);
order.verify(mockKeyboard).sendKeys(keysToSend);
order.verifyNoMoreInteractions();
}
@Test
public void sendKeysActionOnAnElement() {
SendKeysAction sendKeys = new SendKeysAction(
mockKeyboard, mockMouse, stubLocatable, keysToSend);
sendKeys.perform();
InOrder order = Mockito.inOrder(mockKeyboard, mockMouse, mockCoordinates);
order.verify(mockMouse).click(mockCoordinates);
order.verify(mockKeyboard).sendKeys(keysToSend);
order.verifyNoMoreInteractions();
}
@Test
public void keyDownActionFailsOnNonModifier() {
final Keys keyToPress = Keys.BACK_SPACE;
try {
new KeyDownAction(mockKeyboard, mockMouse, stubLocatable, keyToPress);
fail();
} catch (IllegalArgumentException e) {
assertTrue(e.getMessage().contains("modifier keys"));
}
}
@Test
public void testAllModifierKeysRegardedAsSuch() {
new KeyDownAction(mockKeyboard, mockMouse, stubLocatable, Keys.SHIFT);
new KeyDownAction(mockKeyboard, mockMouse, stubLocatable, Keys.LEFT_SHIFT);
new KeyDownAction(mockKeyboard, mockMouse, stubLocatable, Keys.CONTROL);
new KeyDownAction(mockKeyboard, mockMouse, stubLocatable, Keys.LEFT_CONTROL);
new KeyDownAction(mockKeyboard, mockMouse, stubLocatable, Keys.ALT);
new KeyDownAction(mockKeyboard, mockMouse, stubLocatable, Keys.LEFT_ALT);
new KeyDownAction(mockKeyboard, mockMouse, stubLocatable, Keys.META);
new KeyDownAction(mockKeyboard, mockMouse, stubLocatable, Keys.COMMAND);
}
}
| apache-2.0 |
paplorinc/intellij-community | platform/lang-impl/src/com/intellij/application/options/colors/fileStatus/FileStatusColorsConfigurable.java | 2552 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.application.options.colors.fileStatus;
import com.intellij.openapi.application.ApplicationBundle;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.options.SearchableConfigurable;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.vcs.FileStatusFactory;
import com.intellij.openapi.vcs.FileStatusManager;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
public class FileStatusColorsConfigurable implements SearchableConfigurable, Configurable.NoScroll, Configurable.VariableProjectAppLevel {
private final static String FILE_STATUS_COLORS_ID = "file.status.colors";
private final FileStatusColorsPanel myPanel;
public FileStatusColorsConfigurable() {
myPanel = new FileStatusColorsPanel(FileStatusFactory.getInstance().getAllFileStatuses());
}
@NotNull
@Override
public String getId() {
return FILE_STATUS_COLORS_ID;
}
@Override
public String getHelpTopic() {
return "reference.versionControl.highlight";
}
@Nls
@Override
public String getDisplayName() {
return ApplicationBundle.message("title.file.status.colors");
}
@Nullable
@Override
public JComponent createComponent() {
return myPanel.getComponent();
}
@Override
public boolean isModified() {
return myPanel.getModel().isModified();
}
@Override
public void apply() throws ConfigurationException {
myPanel.getModel().apply();
for (Project project : ProjectManager.getInstance().getOpenProjects()) {
FileStatusManager.getInstance(project).fileStatusesChanged();
}
}
@Override
public void reset() {
myPanel.getModel().reset();
}
@Override
public boolean isProjectLevel() {
return false;
}
}
| apache-2.0 |
youngilcho/internet-application-2014 | test/java/org/galagosearch/core/retrieval/extents/StatisticsGathererTest.java | 854 | // BSD License (http://www.galagosearch.org/license)
package org.galagosearch.core.retrieval.extents;
import org.galagosearch.core.retrieval.structured.ExtentIterator;
import org.galagosearch.core.retrieval.structured.StatisticsGatherer;
import java.io.IOException;
import junit.framework.*;
/**
*
* @author trevor
*/
public class StatisticsGathererTest extends TestCase {
public StatisticsGathererTest(String testName) {
super(testName);
}
public void testGather() throws IOException {
int[][] data = { { 1, 5 }, { 3, 7 } };
ExtentIterator iterator = new FakeExtentIterator( data );
StatisticsGatherer instance = new StatisticsGatherer( iterator );
instance.run();
assertEquals( instance.getTermCount(), 2 );
assertEquals( instance.getDocumentCount(), 2 );
}
}
| mit |
neuroidss/adempiere | extend/src/test/functional/MCurrencyAcctTest.java | 1790 | /******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 2008 SC ARHIPAC SERVICE SRL. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
*****************************************************************************/
package test.functional;
import org.compiere.model.MAcctSchemaDefault;
import org.compiere.util.Env;
import test.AdempiereTestCase;
/**
* @author Teo Sarca, www.arhipac.ro //red1 borrows from MInvoiceTest
*/
public class MCurrencyAcctTest extends AdempiereTestCase
{
@Override
protected void setUp() throws Exception
{
super.setUp();
assertEquals("Client is not GardenWorld", 11, Env.getAD_Client_ID(getCtx()));
}
public void testQuery() throws Exception
{ //red1 create C_Currency_Acct wih SchemaDef = 101 and C_Currency = 100
MAcctSchemaDefault as = MAcctSchemaDefault.get(getCtx(), 101);
int a = as.getRealizedGain_Acct(100);
assertTrue("No test record been setup", a > 0);
}
}
| gpl-2.0 |
siosio/intellij-community | platform/platform-impl/src/com/intellij/openapi/wm/impl/content/ComboIcon.java | 1641 | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.wm.impl.content;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.ui.popup.ActiveIcon;
import java.awt.*;
public abstract class ComboIcon {
private final ActiveIcon myIcon = new ActiveIcon(AllIcons.General.ArrowDown);
public void paintIcon(final Component c, final Graphics g) {
myIcon.setActive(isActive());
final Rectangle moreRect = getIconRec();
if (moreRect == null) return;
int iconY = getIconY(moreRect);
int iconX = getIconX(moreRect);
myIcon.paintIcon(c, g, iconX, iconY);
}
protected int getIconX(final Rectangle iconRec) {
return iconRec.x + iconRec.width / 2 - getIconWidth() / 2;
}
public int getIconWidth() {
return myIcon.getIconWidth();
}
protected int getIconY(final Rectangle iconRec) {
return iconRec.y + iconRec.height / 2 - getIconHeight() / 2 + 1;
}
public int getIconHeight() {
return myIcon.getIconHeight();
}
public abstract Rectangle getIconRec();
public abstract boolean isActive();
}
| apache-2.0 |
anne/google-gin | test/com/google/gwt/inject/generated/client/Framework.java | 694 | /*
* Copyright 2011 Google 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.google.gwt.inject.generated.client;
public interface Framework {
void initialize();
}
| apache-2.0 |
eonezhang/avro | lang/java/avro/src/test/java/org/apache/avro/TestSchemaValidation.java | 6816 | /**
* 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.avro;
import java.util.ArrayList;
import org.apache.avro.reflect.ReflectData;
import org.junit.Assert;
import org.junit.Test;
public class TestSchemaValidation {
SchemaValidatorBuilder builder = new SchemaValidatorBuilder();
Schema rec = SchemaBuilder.record("test.Rec").fields()
.name("a").type().intType().intDefault(1)
.name("b").type().longType().noDefault()
.endRecord();
Schema rec2 = SchemaBuilder.record("test.Rec").fields()
.name("a").type().intType().intDefault(1)
.name("b").type().longType().noDefault()
.name("c").type().intType().intDefault(0)
.endRecord();
Schema rec3 = SchemaBuilder.record("test.Rec").fields()
.name("b").type().longType().noDefault()
.name("c").type().intType().intDefault(0)
.endRecord();
Schema rec4 = SchemaBuilder.record("test.Rec").fields()
.name("b").type().longType().noDefault()
.name("c").type().intType().noDefault()
.endRecord();
Schema rec5 = SchemaBuilder.record("test.Rec").fields()
.name("a").type().stringType().stringDefault("") // different type from original
.name("b").type().longType().noDefault()
.name("c").type().intType().intDefault(0)
.endRecord();
@Test
public void testAllTypes() throws SchemaValidationException {
Schema s = SchemaBuilder.record("r").fields()
.requiredBoolean("boolF")
.requiredInt("intF")
.requiredLong("longF")
.requiredFloat("floatF")
.requiredDouble("doubleF")
.requiredString("stringF")
.requiredBytes("bytesF")
.name("fixedF1").type().fixed("F1").size(1).noDefault()
.name("enumF").type().enumeration("E1").symbols("S").noDefault()
.name("mapF").type().map().values().stringType().noDefault()
.name("arrayF").type().array().items().stringType().noDefault()
.name("recordF").type().record("inner").fields()
.name("f").type().intType().noDefault()
.endRecord().noDefault()
.optionalBoolean("boolO")
.endRecord();
testValidatorPasses(builder.mutualReadStrategy().validateLatest(), s, s);
}
@Test
public void testReadOnePrior() throws SchemaValidationException {
testValidatorPasses(builder.canReadStrategy().validateLatest(), rec3, rec);
testValidatorPasses(builder.canReadStrategy().validateLatest(), rec5, rec3);
testValidatorFails(builder.canReadStrategy().validateLatest(), rec4, rec);
}
@Test
public void testReadAllPrior() throws SchemaValidationException {
testValidatorPasses(builder.canReadStrategy().validateAll(), rec3, rec, rec2);
testValidatorFails(builder.canReadStrategy().validateAll(), rec4, rec, rec2, rec3);
testValidatorFails(builder.canReadStrategy().validateAll(), rec5, rec, rec2, rec3);
}
@Test
public void testOnePriorCanRead() throws SchemaValidationException {
testValidatorPasses(builder.canBeReadStrategy().validateLatest(), rec, rec3);
testValidatorFails(builder.canBeReadStrategy().validateLatest(), rec, rec4);
}
@Test
public void testAllPriorCanRead() throws SchemaValidationException {
testValidatorPasses(builder.canBeReadStrategy().validateAll(), rec, rec3, rec2);
testValidatorFails(builder.canBeReadStrategy().validateAll(), rec, rec4, rec3, rec2);
}
@Test
public void testOnePriorCompatible() throws SchemaValidationException {
testValidatorPasses(builder.mutualReadStrategy().validateLatest(), rec, rec3);
testValidatorFails(builder.mutualReadStrategy().validateLatest(), rec, rec4);
}
@Test
public void testAllPriorCompatible() throws SchemaValidationException {
testValidatorPasses(builder.mutualReadStrategy().validateAll(), rec, rec3, rec2);
testValidatorFails(builder.mutualReadStrategy().validateAll(), rec, rec4, rec3, rec2);
}
@Test(expected=AvroRuntimeException.class)
public void testInvalidBuild() {
builder.strategy(null).validateAll();
}
public static class Point {
double x;
double y;
}
public static class Circle {
Point center;
double radius;
}
public static final Schema circleSchema = SchemaBuilder.record("Circle")
.fields()
.name("center").type().record("Point")
.fields()
.requiredDouble("x")
.requiredDouble("y")
.endRecord().noDefault()
.requiredDouble("radius")
.endRecord();
public static final Schema circleSchemaDifferentNames = SchemaBuilder
.record("crcl").fields()
.name("center").type().record("pt")
.fields()
.requiredDouble("x")
.requiredDouble("y")
.endRecord().noDefault()
.requiredDouble("radius")
.endRecord();
@Test
public void testReflectMatchStructure() throws SchemaValidationException {
testValidatorPasses(builder.canBeReadStrategy().validateAll(),
circleSchemaDifferentNames, ReflectData.get().getSchema(Circle.class));
}
@Test
public void testReflectWithAllowNullMatchStructure() throws SchemaValidationException {
testValidatorPasses(builder.canBeReadStrategy().validateAll(),
circleSchemaDifferentNames, ReflectData.AllowNull.get().getSchema(Circle.class));
}
private void testValidatorPasses(SchemaValidator validator,
Schema schema, Schema... prev) throws SchemaValidationException {
ArrayList<Schema> prior = new ArrayList<Schema>();
for(int i = prev.length - 1; i >= 0; i--) {
prior.add(prev[i]);
}
validator.validate(schema, prior);
}
private void testValidatorFails(SchemaValidator validator,
Schema schemaFails, Schema... prev) throws SchemaValidationException {
ArrayList<Schema> prior = new ArrayList<Schema>();
for(int i = prev.length - 1; i >= 0; i--) {
prior.add(prev[i]);
}
boolean threw = false;
try {
// should fail
validator.validate(schemaFails, prior);
} catch (SchemaValidationException sve) {
threw = true;
}
Assert.assertTrue(threw);
}
}
| apache-2.0 |
RayyyyyNY/gwtbootstrap3 | gwtbootstrap3/src/main/java/org/gwtbootstrap3/client/ui/base/mixin/package-info.java | 700 | package org.gwtbootstrap3.client.ui.base.mixin;
/*
* #%L
* GwtBootstrap3
* %%
* Copyright (C) 2013 - 2014 GwtBootstrap3
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
| apache-2.0 |
papicella/snappy-store | lgpl/gemfire-jgroups/src/main/java/com/gemstone/org/jgroups/oswego/concurrent/Callable.java | 1316 | /** Notice of modification as required by the LGPL
* This file was modified by Gemstone Systems Inc. on
* $Date$
**/
/*
File: Callable.java
Originally written by Doug Lea and released into the public domain.
This may be used for any purposes whatsoever without acknowledgment.
Thanks for the assistance and support of Sun Microsystems Labs,
and everyone contributing, testing, and using this code.
History:
Date Who What
30Jun1998 dl Create public version
5Jan1999 dl Change Exception to Throwable in call signature
27Jan1999 dl Undo last change
*/
package com.gemstone.org.jgroups.oswego.concurrent;
/**
* Interface for runnable actions that bear results and/or throw Exceptions.
* This interface is designed to provide a common protocol for
* result-bearing actions that can be run independently in threads,
* in which case
* they are ordinarily used as the bases of Runnables that set
* FutureResults
* <p>
* <p>[<a href="http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/intro.html"> Introduction to this package. </a>]
* @see FutureResult
**/
public interface Callable {
/** Perform some action that returns a result or throws an exception **/
Object call() throws Exception;
}
| apache-2.0 |
smmribeiro/intellij-community | java/java-tests/testData/inspection/duplicateBranchesInSwitch/NoExceptionWhenFirstLabelIsMissing.java | 457 | class C {
public static void main(String[] args) {
switch (args.length) {
<error descr="Statement must be prepended with case label">return;</error>
case 1:
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
case 2:
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
}
}
} | apache-2.0 |
jcastroe1000/vidis | src/vidis/ui/events/jobs/ILayoutJob.java | 1081 | /* VIDIS is a simulation and visualisation framework for distributed systems.
Copyright (C) 2009 Dominik Psenner, Christoph Caks
This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. */
package vidis.ui.events.jobs;
import java.util.Collection;
import vidis.data.sim.SimNode;
import vidis.ui.model.graph.layouts.IGraphLayout;
/**
* layout job interface
* @author Dominik
*
*/
public interface ILayoutJob extends IJob {
public IGraphLayout getLayout();
public Collection<SimNode> getNodes();
}
| gpl-3.0 |
jruchcolo/rice-cd | rice-middleware/ksb/client-impl/src/main/java/org/kuali/rice/ksb/security/AbstractDigitalSigner.java | 1713 | /**
* Copyright 2005-2015 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.rice.ksb.security;
import java.security.Signature;
import java.security.cert.Certificate;
import org.apache.commons.codec.binary.Base64;
/**
* An abstract implementation of a DigitalSigner which provides convienance utilities for storing a reference
* to the Signature and also generating and encoding the actual digital signature.
*
* @author Kuali Rice Team (rice.collab@kuali.org)
*/
public abstract class AbstractDigitalSigner implements DigitalSigner {
private Signature signature;
public AbstractDigitalSigner(Signature signature) {
this.signature = signature;
}
public Signature getSignature() {
return this.signature;
}
protected byte[] getSignatureBytes() throws Exception {
return getSignature().sign();
}
protected String getEncodedSignature() throws Exception {
return new String(Base64.encodeBase64(getSignatureBytes()), "UTF-8");
}
protected String getEncodedCertificate(Certificate certificate) throws Exception {
return new String(Base64.encodeBase64(certificate.getEncoded()), "UTF-8");
}
}
| apache-2.0 |
samaitra/jena | jena-arq/src/main/java/org/apache/jena/sparql/expr/E_URI.java | 1313 | /*
* 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.jena.sparql.expr;
import org.apache.jena.sparql.sse.Tags ;
public class E_URI extends E_IRI
{
private static final String symbol = Tags.tagUri ;
public E_URI(Expr expr)
{
super(expr, symbol) ;
}
public E_URI(Expr expr, String altSymbol)
{
super(expr, altSymbol) ;
}
// @Override
// public NodeValue eval(NodeValue v) { return super.eval(v) ; }
@Override
public Expr copy(Expr expr) { return new E_URI(expr) ; }
}
| apache-2.0 |
apache/flink | flink-connectors/flink-connector-hive/src/main/java/org/apache/flink/table/catalog/hive/client/HiveShimV235.java | 946 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.table.catalog.hive.client;
/** Shim for Hive version 2.3.5. */
public class HiveShimV235 extends HiveShimV234 {}
| apache-2.0 |
bhutchinson/rice | rice-middleware/kns/src/main/java/org/kuali/rice/kns/datadictionary/BusinessObjectEntry.java | 3692 | /**
* Copyright 2005-2015 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.rice.kns.datadictionary;
/**
* @author Kuali Rice Team (rice.collab@kuali.org)
*
* @deprecated Use {@link org.kuali.rice.krad.datadictionary.BusinessObjectEntry}.
*/
@Deprecated
public class BusinessObjectEntry extends org.kuali.rice.krad.datadictionary.BusinessObjectEntry {
protected InquiryDefinition inquiryDefinition;
protected LookupDefinition lookupDefinition;
@Override
public void completeValidation() {
super.completeValidation();
if (hasInquiryDefinition()) {
inquiryDefinition.completeValidation(getDataObjectClass(), null);
}
if (hasLookupDefinition()) {
lookupDefinition.completeValidation(getDataObjectClass(), null);
}
}
/**
* @return true if this instance has an inquiryDefinition
*/
public boolean hasInquiryDefinition() {
return (inquiryDefinition != null);
}
/**
* @return current inquiryDefinition for this BusinessObjectEntry, or null if there is none
*/
public InquiryDefinition getInquiryDefinition() {
return inquiryDefinition;
}
/**
* The inquiry element is used to specify the fields that will be displayed on the
* inquiry screen for this business object and the order in which they will appear.
*
* DD: See InquiryDefinition.java
*
* JSTL: The inquiry element is a Map which is accessed using
* a key of "inquiry". This map contains the following keys:
* title (String)
* inquiryFields (Map)
*
* See InquiryMapBuilder.java
*/
public void setInquiryDefinition(InquiryDefinition inquiryDefinition) {
this.inquiryDefinition = inquiryDefinition;
}
/**
* @return true if this instance has a lookupDefinition
*/
public boolean hasLookupDefinition() {
return (lookupDefinition != null);
}
/**
* @return current lookupDefinition for this BusinessObjectEntry, or null if there is none
*/
public LookupDefinition getLookupDefinition() {
return lookupDefinition;
}
/**
* The lookup element is used to specify the rules for "looking up"
* a business object. These specifications define the following:
* How to specify the search criteria used to locate a set of business objects
* How to display the search results
*
* DD: See LookupDefinition.java
*
* JSTL: The lookup element is a Map which is accessed using
* a key of "lookup". This map contains the following keys:
* lookupableID (String, optional)
* title (String)
* menubar (String, optional)
* defaultSort (Map, optional)
* lookupFields (Map)
* resultFields (Map)
* resultSetLimit (String, optional)
*
* See LookupMapBuilder.java
*/
public void setLookupDefinition(LookupDefinition lookupDefinition) {
this.lookupDefinition = lookupDefinition;
}
}
| apache-2.0 |
ThiagoGarciaAlves/drools | drools-compiler/src/test/java/org/drools/compiler/Cheese.java | 3161 | /*
* Copyright 2005 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.compiler;
import java.io.Serializable;
import java.util.Date;
public class Cheese
implements
Serializable {
public static final String STILTON = "stilton";
public static final int BASE_PRICE = 10;
private static final long serialVersionUID = 510l;
private String type;
private int price;
private int oldPrice;
private Date usedBy;
private double doublePrice;
public Cheese() {
}
public Cheese(final String type) {
super();
this.type = type;
this.price = 0;
}
public Cheese(final String type,
final int price) {
super();
this.type = type;
this.price = price;
}
public Cheese(final String type,
final int price,
final int oldPrice ) {
super();
this.type = type;
this.price = price;
this.oldPrice = oldPrice;
}
public int getPrice() {
return this.price;
}
public String getType() {
return this.type;
}
public void setType(final String type) {
this.type = type;
}
public void setPrice(final int price) {
this.price = price;
}
public String toString() {
return "Cheese( type='" + this.type + "', price=" + this.price + " )";
}
public int hashCode() {
final int PRIME = 31;
int result = 1;
result = PRIME * result + price;
result = PRIME * result + ((type == null) ? 0 : type.hashCode());
return result;
}
public boolean equals(Object obj) {
if ( this == obj ) return true;
if ( obj == null ) return false;
if ( getClass() != obj.getClass() ) return false;
final Cheese other = (Cheese) obj;
if ( price != other.price ) return false;
if ( type == null ) {
if ( other.type != null ) return false;
} else if ( !type.equals( other.type ) ) return false;
return true;
}
public int getOldPrice() {
return oldPrice;
}
public void setOldPrice(int oldPrice) {
this.oldPrice = oldPrice;
}
public Date getUsedBy() {
return usedBy;
}
public void setUsedBy(Date usedBy) {
this.usedBy = usedBy;
}
public synchronized double getDoublePrice() {
return doublePrice;
}
public synchronized void setDoublePrice(double doublePrice) {
this.doublePrice = doublePrice;
}
}
| apache-2.0 |
slietz/gobblin | gobblin-core/src/main/java/gobblin/source/extractor/partition/Partitioner.java | 15418 | /*
* Copyright (C) 2014-2015 LinkedIn Corp. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use
* this file except in compliance with the License. You may obtain a copy of the
* License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied.
*/
package gobblin.source.extractor.partition;
import java.util.HashMap;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Strings;
import gobblin.configuration.ConfigurationKeys;
import gobblin.configuration.SourceState;
import gobblin.source.extractor.extract.ExtractType;
import gobblin.source.extractor.utils.Utils;
import gobblin.source.extractor.watermark.WatermarkPredicate;
import gobblin.source.extractor.watermark.WatermarkType;
/**
* An implementation of default partitioner for all types of sources
*/
public class Partitioner {
private static final String WATERMARKTIMEFORMAT = "yyyyMMddHHmmss";
private static final Logger LOG = LoggerFactory.getLogger(Partitioner.class);
private SourceState state;
public Partitioner(SourceState state) {
super();
this.state = state;
}
/**
* Get partitions with low and high water marks
*
* @param previous water mark from metadata
* @return map of partition intervals
*/
public HashMap<Long, Long> getPartitions(long previousWatermark) {
HashMap<Long, Long> defaultPartition = new HashMap<Long, Long>();
if (!isWatermarkExists()) {
defaultPartition.put(ConfigurationKeys.DEFAULT_WATERMARK_VALUE, ConfigurationKeys.DEFAULT_WATERMARK_VALUE);
LOG.info("Watermark column or type not found - Default partition with low watermark and high watermark as "
+ ConfigurationKeys.DEFAULT_WATERMARK_VALUE);
return defaultPartition;
}
ExtractType extractType =
ExtractType.valueOf(this.state.getProp(ConfigurationKeys.SOURCE_QUERYBASED_EXTRACT_TYPE).toUpperCase());
WatermarkType watermarkType =
WatermarkType.valueOf(this.state.getProp(ConfigurationKeys.SOURCE_QUERYBASED_WATERMARK_TYPE,
ConfigurationKeys.DEFAULT_WATERMARK_TYPE).toUpperCase());
int interval =
this.getUpdatedInterval(this.state.getPropAsInt(ConfigurationKeys.SOURCE_QUERYBASED_PARTITION_INTERVAL, 0),
extractType, watermarkType);
int sourceMaxAllowedPartitions = this.state.getPropAsInt(ConfigurationKeys.SOURCE_MAX_NUMBER_OF_PARTITIONS, 0);
int maxPartitions =
(sourceMaxAllowedPartitions != 0 ? sourceMaxAllowedPartitions
: ConfigurationKeys.DEFAULT_MAX_NUMBER_OF_PARTITIONS);
WatermarkPredicate watermark = new WatermarkPredicate(null, watermarkType);
int deltaForNextWatermark = watermark.getDeltaNumForNextWatermark();
LOG.info("is watermark override: " + this.isWatermarkOverride());
LOG.info("is full extract: " + this.isFullDump());
long lowWatermark = this.getLowWatermark(extractType, watermarkType, previousWatermark, deltaForNextWatermark);
long highWatermark = this.getHighWatermark(extractType, watermarkType);
if (lowWatermark == ConfigurationKeys.DEFAULT_WATERMARK_VALUE
|| highWatermark == ConfigurationKeys.DEFAULT_WATERMARK_VALUE) {
LOG.info("Low watermark or high water mark is not found. Hence cannot generate partitions - Default partition with low watermark: "
+ lowWatermark + " and high watermark: " + highWatermark);
defaultPartition.put(lowWatermark, highWatermark);
return defaultPartition;
}
LOG.info("Generate partitions with low watermark: " + lowWatermark + "; high watermark: " + highWatermark
+ "; partition interval in hours: " + interval + "; Maximum number of allowed partitions: " + maxPartitions);
return watermark.getPartitions(lowWatermark, highWatermark, interval, maxPartitions);
}
/**
* Calculate interval in hours with the given interval
*
* @param input interval
* @param Extract type
* @param Watermark type
* @return interval in range
*/
private int getUpdatedInterval(int inputInterval, ExtractType extractType, WatermarkType watermarkType) {
LOG.debug("Getting updated interval");
if ((extractType == ExtractType.SNAPSHOT && watermarkType == WatermarkType.DATE)) {
return inputInterval * 24;
} else if (extractType == ExtractType.APPEND_DAILY) {
return (inputInterval < 1 ? 1 : inputInterval) * 24;
} else {
return inputInterval;
}
}
/**
* Get low water mark
*
* @param Extract type
* @param Watermark type
* @param Previous water mark
* @param delta number for next water mark
* @return low water mark
*/
private long getLowWatermark(ExtractType extractType, WatermarkType watermarkType, long previousWatermark,
int deltaForNextWatermark) {
long lowWatermark = ConfigurationKeys.DEFAULT_WATERMARK_VALUE;
if (this.isFullDump() || this.isWatermarkOverride()) {
String timeZone = this.state.getProp(ConfigurationKeys.SOURCE_TIMEZONE, ConfigurationKeys.DEFAULT_SOURCE_TIMEZONE);
lowWatermark = Utils.getLongWithCurrentDate(
this.state.getProp(ConfigurationKeys.SOURCE_QUERYBASED_START_VALUE), timeZone);
LOG.info("Overriding low water mark with the given start value: " + lowWatermark);
} else {
if (this.isSnapshot(extractType)) {
lowWatermark = this.getSnapshotLowWatermark(watermarkType, previousWatermark, deltaForNextWatermark);
} else {
lowWatermark = this.getAppendLowWatermark(watermarkType, previousWatermark, deltaForNextWatermark);
}
}
return (lowWatermark == 0 ? ConfigurationKeys.DEFAULT_WATERMARK_VALUE : lowWatermark);
}
/**
* Get low water mark
*
* @param Watermark type
* @param Previous water mark
* @param delta number for next water mark
* @return snapshot low water mark
*/
private long getSnapshotLowWatermark(WatermarkType watermarkType, long previousWatermark, int deltaForNextWatermark) {
LOG.debug("Getting snapshot low water mark");
String timeZone = this.state.getProp(ConfigurationKeys.SOURCE_TIMEZONE, ConfigurationKeys.DEFAULT_SOURCE_TIMEZONE);
if (this.isPreviousWatermarkExists(previousWatermark)) {
if (this.isSimpleWatermark(watermarkType)) {
return previousWatermark + deltaForNextWatermark
- this.state.getPropAsInt(ConfigurationKeys.SOURCE_QUERYBASED_LOW_WATERMARK_BACKUP_SECS, 0);
} else {
DateTime wm =
Utils.toDateTime(previousWatermark, WATERMARKTIMEFORMAT, timeZone).plusSeconds(
(deltaForNextWatermark - this.state
.getPropAsInt(ConfigurationKeys.SOURCE_QUERYBASED_LOW_WATERMARK_BACKUP_SECS)));
return Long.parseLong(Utils.dateTimeToString(wm, WATERMARKTIMEFORMAT, timeZone));
}
} else {
// if previous watermark is not found, override with the start value(irrespective of source.is.watermark.override flag)
long startValue =
Utils.getLongWithCurrentDate(this.state.getProp(ConfigurationKeys.SOURCE_QUERYBASED_START_VALUE), timeZone);
LOG.info("Overriding low water mark with the given start value: " + startValue);
return startValue;
}
}
/**
* Get low water mark
*
* @param Watermark type
* @param Previous water mark
* @param delta number for next water mark
* @return append low water mark
*/
private long getAppendLowWatermark(WatermarkType watermarkType, long previousWatermark, int deltaForNextWatermark) {
LOG.debug("Getting append low water mark");
String timeZone = this.state.getProp(ConfigurationKeys.SOURCE_TIMEZONE);
if (this.isPreviousWatermarkExists(previousWatermark)) {
if (this.isSimpleWatermark(watermarkType)) {
return previousWatermark + deltaForNextWatermark;
} else {
DateTime wm =
Utils.toDateTime(previousWatermark, WATERMARKTIMEFORMAT, timeZone).plusSeconds(deltaForNextWatermark);
return Long.parseLong(Utils.dateTimeToString(wm, WATERMARKTIMEFORMAT, timeZone));
}
} else {
LOG.info("Overriding low water mark with start value: " + ConfigurationKeys.SOURCE_QUERYBASED_START_VALUE);
return Utils.getLongWithCurrentDate(this.state.getProp(ConfigurationKeys.SOURCE_QUERYBASED_START_VALUE), timeZone);
}
}
/**
* Get high water mark
*
* @param Extract type
* @param Watermark type
* @return high water mark
*/
private long getHighWatermark(ExtractType extractType, WatermarkType watermarkType) {
LOG.debug("Getting high watermark");
String timeZone = this.state.getProp(ConfigurationKeys.SOURCE_TIMEZONE);
long highWatermark = ConfigurationKeys.DEFAULT_WATERMARK_VALUE;
if (this.isWatermarkOverride()) {
highWatermark = this.state.getPropAsLong(ConfigurationKeys.SOURCE_QUERYBASED_END_VALUE, 0);
if (highWatermark == 0) {
highWatermark =
Long.parseLong(Utils.dateTimeToString(Utils.getCurrentTime(timeZone), WATERMARKTIMEFORMAT, timeZone));
}
LOG.info("Overriding high water mark with the given end value:" + highWatermark);
} else {
if (this.isSnapshot(extractType)) {
highWatermark = this.getSnapshotHighWatermark(watermarkType);
} else {
highWatermark = this.getAppendHighWatermark(extractType);
}
}
return (highWatermark == 0 ? ConfigurationKeys.DEFAULT_WATERMARK_VALUE : highWatermark);
}
/**
* Get snapshot high water mark
*
* @param Watermark type
* @return snapshot high water mark
*/
private long getSnapshotHighWatermark(WatermarkType watermarkType) {
LOG.debug("Getting snapshot high water mark");
if (this.isSimpleWatermark(watermarkType)) {
return ConfigurationKeys.DEFAULT_WATERMARK_VALUE;
}
String timeZone = this.state.getProp(ConfigurationKeys.SOURCE_TIMEZONE);
return Long.parseLong(Utils.dateTimeToString(Utils.getCurrentTime(timeZone), WATERMARKTIMEFORMAT, timeZone));
}
/**
* Get append high water mark
*
* @param Extract type
* @return append high water mark
*/
private long getAppendHighWatermark(ExtractType extractType) {
LOG.debug("Getting append high water mark");
if (this.isFullDump()) {
LOG.info("Overriding high water mark with end value:" + ConfigurationKeys.SOURCE_QUERYBASED_END_VALUE);
return this.state.getPropAsLong(ConfigurationKeys.SOURCE_QUERYBASED_END_VALUE, 0);
} else {
return this.getAppendWatermarkCutoff(extractType);
}
}
/**
* Get cutoff for high water mark
*
* @param Extract type
* @return cutoff
*/
private long getAppendWatermarkCutoff(ExtractType extractType) {
LOG.debug("Getting append water mark cutoff");
long highWatermark = ConfigurationKeys.DEFAULT_WATERMARK_VALUE;
String timeZone = this.state.getProp(ConfigurationKeys.SOURCE_TIMEZONE);
AppendMaxLimitType limitType =
this.getAppendLimitType(extractType,
this.state.getProp(ConfigurationKeys.SOURCE_QUERYBASED_APPEND_MAX_WATERMARK_LIMIT));
if (limitType == null) {
LOG.debug("Limit type is not found");
return highWatermark;
}
int limitDelta =
this.getAppendLimitDelta(this.state.getProp(ConfigurationKeys.SOURCE_QUERYBASED_APPEND_MAX_WATERMARK_LIMIT));
// if it is CURRENTDATE or CURRENTHOUR then high water mark is current time
if (limitDelta == 0) {
highWatermark =
Long.parseLong(Utils.dateTimeToString(Utils.getCurrentTime(timeZone), WATERMARKTIMEFORMAT, timeZone));
}
// if CURRENTDATE or CURRENTHOUR has offset then high water mark is end of day of the given offset
else {
int seconds = 3599; // x:59:59
String format = null;
switch (limitType) {
case CURRENTDATE:
format = "yyyyMMdd";
limitDelta = limitDelta * 24;
seconds = 86399; // 23:59:59
break;
case CURRENTHOUR:
format = "yyyyMMddHH";
seconds = 3599; // x:59:59
break;
}
DateTime deltaTime = Utils.getCurrentTime(timeZone).minusHours(limitDelta);
DateTime previousTime =
Utils.toDateTime(Utils.dateTimeToString(deltaTime, format, timeZone), format, timeZone).plusSeconds(seconds);
highWatermark = Long.parseLong(Utils.dateTimeToString(previousTime, WATERMARKTIMEFORMAT, timeZone));
}
return highWatermark;
}
/**
* Get append max limit type from the input
*
* @param Extract type
* @param maxLimit
* @return Max limit type
*/
private AppendMaxLimitType getAppendLimitType(ExtractType extractType, String maxLimit) {
LOG.debug("Getting append limit type");
AppendMaxLimitType limitType;
switch (extractType) {
case APPEND_DAILY:
limitType = AppendMaxLimitType.CURRENTDATE;
break;
case APPEND_HOURLY:
limitType = AppendMaxLimitType.CURRENTHOUR;
break;
default:
limitType = null;
break;
}
if (!Strings.isNullOrEmpty(maxLimit)) {
LOG.debug("Getting append limit type from the config");
String[] limitParams = maxLimit.split("-");
if (limitParams.length >= 1) {
limitType = AppendMaxLimitType.valueOf(limitParams[0]);
}
}
return limitType;
}
/**
* Get append max limit delta num
*
* @param maxLimit
* @return Max limit delta number
*/
private int getAppendLimitDelta(String maxLimit) {
LOG.debug("Getting append limit delta");
int limitDelta = 0;
if (!Strings.isNullOrEmpty(maxLimit)) {
String[] limitParams = maxLimit.split("-");
if (limitParams.length >= 2) {
limitDelta = Integer.parseInt(limitParams[1]);
}
}
return limitDelta;
}
/**
* true if previous water mark equals default water mark
*
* @param previous water mark
* @return true if previous water mark exists
*/
private boolean isPreviousWatermarkExists(long previousWatermark) {
if (!(previousWatermark == ConfigurationKeys.DEFAULT_WATERMARK_VALUE)) {
return true;
}
return false;
}
/**
* true if water mark columns and water mark type provided
*
* @return true if water mark exists
*/
private boolean isWatermarkExists() {
if (!Strings.isNullOrEmpty(this.state.getProp(ConfigurationKeys.EXTRACT_DELTA_FIELDS_KEY))
&& !Strings.isNullOrEmpty(this.state.getProp(ConfigurationKeys.SOURCE_QUERYBASED_WATERMARK_TYPE))) {
return true;
}
return false;
}
private boolean isSnapshot(ExtractType extractType) {
if (extractType == ExtractType.SNAPSHOT) {
return true;
}
return false;
}
private boolean isSimpleWatermark(WatermarkType watermarkType) {
if (watermarkType == WatermarkType.SIMPLE) {
return true;
}
return false;
}
/**
* @return full dump or not
*/
public boolean isFullDump() {
return Boolean.valueOf(this.state.getProp(ConfigurationKeys.EXTRACT_IS_FULL_KEY));
}
/**
* @return full dump or not
*/
public boolean isWatermarkOverride() {
return Boolean.valueOf(this.state.getProp(ConfigurationKeys.SOURCE_QUERYBASED_IS_WATERMARK_OVERRIDE));
}
}
| apache-2.0 |
fabiofumarola/elasticsearch | src/test/java/org/elasticsearch/index/mapper/path/PathMapperTests.java | 3512 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.index.mapper.path;
import org.elasticsearch.index.mapper.DocumentMapper;
import org.elasticsearch.index.mapper.MapperTestUtils;
import org.elasticsearch.test.ElasticsearchTestCase;
import org.junit.Test;
import java.io.IOException;
import static org.elasticsearch.common.io.Streams.copyToStringFromClasspath;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
/**
*
*/
public class PathMapperTests extends ElasticsearchTestCase {
@Test
public void testPathMapping() throws IOException {
String mapping = copyToStringFromClasspath("/org/elasticsearch/index/mapper/path/test-mapping.json");
DocumentMapper docMapper = MapperTestUtils.newParser().parse(mapping);
assertThat(docMapper.mappers().indexName("first1"), notNullValue());
assertThat(docMapper.mappers().indexName("name1.first1"), nullValue());
assertThat(docMapper.mappers().indexName("last1"), nullValue());
assertThat(docMapper.mappers().indexName("i_last_1"), notNullValue());
assertThat(docMapper.mappers().indexName("name1.last1"), nullValue());
assertThat(docMapper.mappers().indexName("name1.i_last_1"), nullValue());
assertThat(docMapper.mappers().indexName("first2"), nullValue());
assertThat(docMapper.mappers().indexName("name2.first2"), notNullValue());
assertThat(docMapper.mappers().indexName("last2"), nullValue());
assertThat(docMapper.mappers().indexName("i_last_2"), nullValue());
assertThat(docMapper.mappers().indexName("name2.i_last_2"), notNullValue());
assertThat(docMapper.mappers().indexName("name2.last2"), nullValue());
// test full name
assertThat(docMapper.mappers().fullName("first1"), nullValue());
assertThat(docMapper.mappers().fullName("name1.first1"), notNullValue());
assertThat(docMapper.mappers().fullName("last1"), nullValue());
assertThat(docMapper.mappers().fullName("i_last_1"), nullValue());
assertThat(docMapper.mappers().fullName("name1.last1"), notNullValue());
assertThat(docMapper.mappers().fullName("name1.i_last_1"), nullValue());
assertThat(docMapper.mappers().fullName("first2"), nullValue());
assertThat(docMapper.mappers().fullName("name2.first2"), notNullValue());
assertThat(docMapper.mappers().fullName("last2"), nullValue());
assertThat(docMapper.mappers().fullName("i_last_2"), nullValue());
assertThat(docMapper.mappers().fullName("name2.i_last_2"), nullValue());
assertThat(docMapper.mappers().fullName("name2.last2"), notNullValue());
}
}
| apache-2.0 |
mcgilman/nifi | nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/flow/GetReportingTasks.java | 2228 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.nifi.toolkit.cli.impl.command.nifi.flow;
import org.apache.commons.cli.MissingOptionException;
import org.apache.nifi.toolkit.cli.api.CommandException;
import org.apache.nifi.toolkit.cli.impl.client.nifi.FlowClient;
import org.apache.nifi.toolkit.cli.impl.client.nifi.NiFiClient;
import org.apache.nifi.toolkit.cli.impl.client.nifi.NiFiClientException;
import org.apache.nifi.toolkit.cli.impl.command.nifi.AbstractNiFiCommand;
import org.apache.nifi.toolkit.cli.impl.result.nifi.ReportingTasksResult;
import org.apache.nifi.web.api.entity.ReportingTasksEntity;
import java.io.IOException;
import java.util.Properties;
/**
* Command to get the list of reporting tasks.
*/
public class GetReportingTasks extends AbstractNiFiCommand<ReportingTasksResult> {
public GetReportingTasks() {
super("get-reporting-tasks", ReportingTasksResult.class);
}
@Override
public String getDescription() {
return "Retrieves the list of reporting tasks.";
}
@Override
public ReportingTasksResult doExecute(NiFiClient client, Properties properties)
throws NiFiClientException, IOException, MissingOptionException, CommandException {
final FlowClient flowClient = client.getFlowClient();
final ReportingTasksEntity tasksEntity = flowClient.getReportingTasks();
return new ReportingTasksResult(getResultType(properties), tasksEntity);
}
}
| apache-2.0 |
VegasCoin/vegascoinj | core/src/test/java/com/google/bitcoin/crypto/HDUtilsTest.java | 7705 | package com.google.bitcoin.crypto;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spongycastle.crypto.params.ECDomainParameters;
import org.spongycastle.math.ec.ECCurve;
import org.spongycastle.math.ec.ECPoint;
import org.spongycastle.util.encoders.Hex;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.List;
/**
* @author Matija Mazi <br/>
*/
public class HDUtilsTest {
private static final Logger log = LoggerFactory.getLogger(HDUtilsTest.class);
@Test
public void testHmac() throws Exception {
String tv[] = {
"0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b" +
"0b0b0b0b",
"4869205468657265",
"87aa7cdea5ef619d4ff0b4241a1d6cb0" +
"2379f4e2ce4ec2787ad0b30545e17cde" +
"daa833b7d6b8a702038b274eaea3f4e4" +
"be9d914eeb61f1702e696c203a126854",
"4a656665",
"7768617420646f2079612077616e7420" +
"666f72206e6f7468696e673f",
"164b7a7bfcf819e2e395fbe73b56e0a3" +
"87bd64222e831fd610270cd7ea250554" +
"9758bf75c05a994a6d034f65f8f0e6fd" +
"caeab1a34d4a6b4b636e070a38bce737",
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" +
"aaaaaaaa",
"dddddddddddddddddddddddddddddddd" +
"dddddddddddddddddddddddddddddddd" +
"dddddddddddddddddddddddddddddddd" +
"dddd",
"fa73b0089d56a284efb0f0756c890be9" +
"b1b5dbdd8ee81a3655f83e33b2279d39" +
"bf3e848279a722c806b485a47e67c807" +
"b946a337bee8942674278859e13292fb",
"0102030405060708090a0b0c0d0e0f10" +
"111213141516171819",
"cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd" +
"cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd" +
"cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd" +
"cdcd",
"b0ba465637458c6990e5a8c5f61d4af7" +
"e576d97ff94b872de76f8050361ee3db" +
"a91ca5c11aa25eb4d679275cc5788063" +
"a5f19741120c4f2de2adebeb10a298dd",
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" +
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" +
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" +
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" +
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" +
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" +
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" +
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" +
"aaaaaa",
"54657374205573696e67204c61726765" +
"72205468616e20426c6f636b2d53697a" +
"65204b6579202d2048617368204b6579" +
"204669727374",
"80b24263c7c1a3ebb71493c1dd7be8b4" +
"9b46d1f41b4aeec1121b013783f8f352" +
"6b56d037e05f2598bd0fd2215d6a1e52" +
"95e64f73f63f0aec8b915a985d786598",
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" +
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" +
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" +
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" +
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" +
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" +
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" +
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" +
"aaaaaa",
"54686973206973206120746573742075" +
"73696e672061206c6172676572207468" +
"616e20626c6f636b2d73697a65206b65" +
"7920616e642061206c61726765722074" +
"68616e20626c6f636b2d73697a652064" +
"6174612e20546865206b6579206e6565" +
"647320746f2062652068617368656420" +
"6265666f7265206265696e6720757365" +
"642062792074686520484d414320616c" +
"676f726974686d2e",
"e37b6a775dc87dbaa4dfa9f96e5e3ffd" +
"debd71f8867289865df5a32d20cdc944" +
"b6022cac3c4982b10d5eeb55c3e4de15" +
"134676fb6de0446065c97440fa8c6a58"
};
for (int i = 0; i < tv.length; i += 3) {
Assert.assertArrayEquals("Case " + i, getBytes(tv, i + 2), HDUtils.hmacSha512(getBytes(tv, i), getBytes(tv, i + 1)));
}
}
private static byte[] getBytes(String[] hmacTestVectors, int i) {
return Hex.decode(hmacTestVectors[i]);
}
@Test
public void testPointCompression() {
List<String> testPubKey = Arrays.asList(
"044f355bdcb7cc0af728ef3cceb9615d90684bb5b2ca5f859ab0f0b704075871aa385b6b1b8ead809ca67454d9683fcf2ba03456d6fe2c4abe2b07f0fbdbb2f1c1",
"04ed83704c95d829046f1ac27806211132102c34e9ac7ffa1b71110658e5b9d1bdedc416f5cefc1db0625cd0c75de8192d2b592d7e3b00bcfb4a0e860d880fd1fc",
"042596957532fc37e40486b910802ff45eeaa924548c0e1c080ef804e523ec3ed3ed0a9004acf927666eee18b7f5e8ad72ff100a3bb710a577256fd7ec81eb1cb3");
ECDomainParameters ecp = HDUtils.getEcParams();
ECCurve curve = ecp.getCurve();
for (String testpkStr : testPubKey) {
byte[] testpk = Hex.decode(testpkStr);
BigInteger pubX = HDUtils.toBigInteger(Arrays.copyOfRange(testpk, 1, 33));
BigInteger pubY = HDUtils.toBigInteger(Arrays.copyOfRange(testpk, 33, 65));
ECPoint ptFlat = curve.createPoint(pubX, pubY, false); // 65
ECPoint ptComp = curve.createPoint(pubX, pubY, true); // 33
ECPoint uncompressed = HDUtils.toUncompressed(ptComp);
ECPoint recompressed = HDUtils.compressedCopy(uncompressed);
ECPoint orig = curve.decodePoint(testpk);
log.info("====================");
log.info("Flat: {}", asHexStr(ptFlat));
log.info("Compressed: {}", asHexStr(ptComp));
log.info("Uncompressed: {}", asHexStr(uncompressed));
log.info("Recompressed: {}", asHexStr(recompressed));
log.info("Original (uncomp): {}", asHexStr(orig));
// assert point equality:
Assert.assertEquals(ptFlat, uncompressed);
Assert.assertEquals(ptFlat, ptComp);
Assert.assertEquals(ptComp, recompressed);
Assert.assertEquals(ptComp, orig);
// assert bytes equality:
Assert.assertArrayEquals(ptFlat.getEncoded(), uncompressed.getEncoded());
Assert.assertArrayEquals(ptComp.getEncoded(), recompressed.getEncoded());
Assert.assertArrayEquals(ptFlat.getEncoded(), orig.getEncoded());
Assert.assertFalse(Arrays.equals(ptFlat.getEncoded(), ptComp.getEncoded()));
// todo: assert header byte
}
}
private String asHexStr(ECPoint ptFlat) {
return new String(Hex.encode(ptFlat.getEncoded()));
}
@Test
public void testLongToByteArray() throws Exception {
byte[] bytes = HDUtils.longTo4ByteArray(1026);
Assert.assertEquals("00000402", new String(Hex.encode(bytes)));
}
}
| apache-2.0 |
kamleshbhatt/storm | storm-client/src/jvm/org/apache/storm/serialization/KryoValuesSerializer.java | 2201 | /**
* 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.storm.serialization;
import org.apache.storm.utils.ListDelegate;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Output;
import java.io.IOException;
import java.util.List;
import java.util.Map;
public class KryoValuesSerializer {
Kryo _kryo;
ListDelegate _delegate;
Output _kryoOut;
public KryoValuesSerializer(Map<String, Object> conf) {
_kryo = SerializationFactory.getKryo(conf);
_delegate = new ListDelegate();
_kryoOut = new Output(2000, 2000000000);
}
public void serializeInto(List<Object> values, Output out) throws IOException {
// this ensures that list of values is always written the same way, regardless
// of whether it's a java collection or one of clojure's persistent collections
// (which have different serializers)
// Doing this lets us deserialize as ArrayList and avoid writing the class here
_delegate.setDelegate(values);
_kryo.writeObject(out, _delegate);
}
public byte[] serialize(List<Object> values) throws IOException {
_kryoOut.clear();
serializeInto(values, _kryoOut);
return _kryoOut.toBytes();
}
public byte[] serializeObject(Object obj) {
_kryoOut.clear();
_kryo.writeClassAndObject(_kryoOut, obj);
return _kryoOut.toBytes();
}
}
| apache-2.0 |
hongyangAndroid/LitePal | litepal/src/main/java/org/litepal/exceptions/GlobalException.java | 1412 | /*
* Copyright (C) Tony Green, LitePal Framework Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.litepal.exceptions;
/**
* This is where all the global exceptions declared of LitePal.
*
* @author Tony Green
* @since 1.0
*/
public class GlobalException extends RuntimeException {
private static final long serialVersionUID = 1L;
/**
* Application context is null.
*/
public static final String APPLICATION_CONTEXT_IS_NULL = "Application context is null. Maybe you haven't configured your application name with \"org.litepal.LitePalApplication\" in your AndroidManifest.xml. Or you can call LitePalApplication.initialize(Context) method instead.";
/**
* Constructor of GlobalException.
*
* @param errorMessage
* the description of this exception.
*/
public GlobalException(String errorMessage) {
super(errorMessage);
}
}
| apache-2.0 |
Widen/elasticsearch | core/src/test/java/org/elasticsearch/index/mapper/MapperServiceTest.java | 1809 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.index.mapper;
import org.elasticsearch.test.ESSingleNodeTestCase;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.Matchers.hasToString;
public class MapperServiceTest extends ESSingleNodeTestCase {
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Test
public void testTypeNameStartsWithIllegalDot() {
expectedException.expect(MapperParsingException.class);
expectedException.expect(hasToString(containsString("mapping type name [.test-type] must not start with a '.'")));
String index = "test-index";
String type = ".test-type";
String field = "field";
client()
.admin()
.indices()
.prepareCreate(index)
.addMapping(type, field, "type=string")
.execute()
.actionGet();
}
}
| apache-2.0 |
Servoy/wicket | wicket/src/test/java/org/apache/wicket/markup/html/link/AutolinkPage_2.java | 1304 | /*
* 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.wicket.markup.html.link;
import java.util.Locale;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
/**
* Mock page for testing.
*
* @author Chris Turner
*/
public class AutolinkPage_2 extends WebPage
{
private static final long serialVersionUID = 1L;
/**
* Construct.
*/
public AutolinkPage_2()
{
add(new Label("myLabel", "Home"));
getSession().setStyle("myStyle");
getSession().setLocale(Locale.GERMANY);
}
}
| apache-2.0 |
rgoldberg/guava | guava-testlib/src/com/google/common/escape/testing/package-info.java | 919 | /*
* Copyright (C) 2016 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Testing utilities for use in tests of {@code com.google.common.escape}.
*
* <p>This package is a part of the open-source <a href="http://github.com/google/guava">Guava</a>
* library.
*/
@CheckReturnValue
package com.google.common.escape.testing;
import com.google.errorprone.annotations.CheckReturnValue;
| apache-2.0 |
inoshperera/carbon-device-mgt-plugins | components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/DeviceTypeConfigurationService.java | 12315 | /*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.carbon.mdm.services.android.services;
import io.swagger.annotations.SwaggerDefinition;
import io.swagger.annotations.Info;
import io.swagger.annotations.ExtensionProperty;
import io.swagger.annotations.Extension;
import io.swagger.annotations.Tag;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import io.swagger.annotations.ResponseHeader;
import org.wso2.carbon.apimgt.annotations.api.Scope;
import org.wso2.carbon.apimgt.annotations.api.Scopes;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.mdm.services.android.bean.AndroidPlatformConfiguration;
import org.wso2.carbon.mdm.services.android.exception.AndroidAgentException;
import org.wso2.carbon.mdm.services.android.util.AndroidConstants;
import javax.validation.Valid;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@SwaggerDefinition(
info = @Info(
version = "1.0.0",
title = "",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = "name",
value = "Android Configuration Management"),
@ExtensionProperty(name = "context",
value = "/api/device-mgt/android/v1.0/configuration"),
})
}
),
tags = {
@Tag(name = "android,device_management", description = "")
}
)
@Api(value = "Android Configuration Management", description = "This API carries all the resource used to mange the Android platform configurations.")
@Path("/configuration")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Scopes(
scopes = {
@Scope(
name = "Enroll Device",
description = "Register an Android device",
key = "perm:android:enroll",
permissions = {"/device-mgt/devices/enroll/android"}
),
@Scope(
name = "View Configurations",
description = "Getting Android Platform Configurations",
key = "perm:android:view-configuration",
permissions = {"/device-mgt/devices/enroll/android"}
),
@Scope(
name = "Manage Configurations",
description = "Updating Android Platform Configurations",
key = "perm:android:manage-configuration",
permissions = {"/device-mgt/platform-configurations/manage"}
)
}
)
public interface DeviceTypeConfigurationService {
@GET
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Getting Android Platform Configurations",
notes = "Get the Android platform configuration details using this REST API.",
response = PlatformConfiguration.class,
tags = "Android Configuration Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:android:view-configuration")
})
}
)
@ApiResponses(value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully fetched the Android platform configurations.",
response = PlatformConfiguration.class,
responseHeaders = {
@ResponseHeader(
name = "Content-Type",
description = "Content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource was last modified.\n" +
"Used by caches, or in conditional requests."),
}),
@ApiResponse(
code = 304,
message = "Not Modified. \n Empty body because the client already has the latest version of the requested resource."),
@ApiResponse(
code = 404,
message = "Not Found. \n The specified resource does not exist."),
@ApiResponse(
code = 406,
message = "Not Acceptable.\n The requested media type is not supported"),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Server error occurred while fetching the Android platform configuration.")
})
Response getConfiguration(
@ApiParam(
name = "If-Modified-Since",
value = "Checks if the requested variant was modified, since the specified date-time.\n" +
"Provide the value in the following format: EEE, d MMM yyyy HH:mm:ss Z.\n" +
"Example: Mon, 05 Jan 2014 15:10:00 +0200",
required = false)
@HeaderParam("If-Modified-Since") String ifModifiedSince);
@PUT
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "PUT",
value = "Updating Android Platform Configurations",
notes = "Update the Android platform configurations using this REST API.",
tags = "Android Configuration Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:android:manage-configuration")
})
}
)
@ApiResponses(value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully updated the Android platform configurations.",
responseHeaders = {
@ResponseHeader(
name = "Content-Location",
description = "URL of the updated Android platform configuration."),
@ResponseHeader(
name = "Content-Type",
description = "Content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource was last modified.\n" +
"Used by caches, or in conditional requests.")}),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error."),
@ApiResponse(
code = 404,
message = "Not Found. \n The specified resource does not exist."),
@ApiResponse(
code = 415,
message = "Unsupported media type. \n The format of the requested entity was not supported."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n " +
"Server error occurred while modifying the Android platform configuration.")
})
Response updateConfiguration(
@ApiParam(name = "configuration",
value = "The properties to update the Android platform configurations.")
@Valid AndroidPlatformConfiguration androidPlatformConfiguration);
@GET
@Path("license")
@Produces(MediaType.TEXT_PLAIN)
@ApiOperation(
produces = MediaType.TEXT_PLAIN,
httpMethod = "GET",
value = "Getting the License Agreement for the Android Device Registration",
notes = "Use this REST API to retrieve the license agreement that is used for the Android device " +
"registration process.",
response = String.class,
tags = "Android Configuration Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:android:enroll")
})
}
)
@ApiResponses(value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully fetched Android license configuration.",
response = String.class,
responseHeaders = {
@ResponseHeader(
name = "Content-Type",
description = "Content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource was last modified.\n" +
"Used by caches, or in conditional requests."),
}),
@ApiResponse(
code = 304,
message = "Not Modified. \n Empty body because the client already has the latest version of the requested resource."),
@ApiResponse(
code = 404,
message = "Not Found. \n The specified resource does not exist."),
@ApiResponse(
code = 406,
message = "Not Acceptable.\n The requested media type is not supported"),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Server error occurred while fetching the Android license configuration.")
})
Response getLicense(
@ApiParam(
name = "If-Modified-Since",
value = "Checks if the requested variant was modified, since the specified date-time.\n" +
"Provide the value in the following format: EEE, d MMM yyyy HH:mm:ss Z.\n" +
"Example: Mon, 05 Jan 2014 15:10:00 +0200.",
required = false)
@HeaderParam("If-Modified-Since") String ifModifiedSince) throws AndroidAgentException;
}
| apache-2.0 |
DariusX/camel | components/camel-jira/src/main/java/org/apache/camel/component/jira/oauth/OAuthHttpClientDecorator.java | 4172 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.jira.oauth;
import java.net.URI;
import java.util.regex.Pattern;
import com.atlassian.httpclient.apache.httpcomponents.DefaultRequest;
import com.atlassian.httpclient.api.HttpClient;
import com.atlassian.httpclient.api.Request;
import com.atlassian.httpclient.api.ResponsePromise;
import com.atlassian.httpclient.api.ResponseTransformation;
import com.atlassian.jira.rest.client.api.AuthenticationHandler;
import com.atlassian.jira.rest.client.internal.async.DisposableHttpClient;
/**
* Similar to AtlassianHttpClientDecorator, except this class exposes the URI and HTTP Method to the request builder
*/
public abstract class OAuthHttpClientDecorator implements DisposableHttpClient {
private final HttpClient httpClient;
private final AuthenticationHandler authenticationHandler;
private URI uri;
public OAuthHttpClientDecorator(HttpClient httpClient, AuthenticationHandler authenticationHandler) {
this.httpClient = httpClient;
this.authenticationHandler = authenticationHandler;
}
@Override
public void flushCacheByUriPattern(Pattern urlPattern) {
httpClient.flushCacheByUriPattern(urlPattern);
}
@Override
public Request.Builder newRequest() {
return new OAuthAuthenticatedRequestBuilder();
}
@Override
public Request.Builder newRequest(URI uri) {
final Request.Builder builder = new OAuthAuthenticatedRequestBuilder();
builder.setUri(uri);
this.uri = uri;
return builder;
}
@Override
public Request.Builder newRequest(URI uri, String contentType, String entity) {
final Request.Builder builder = new OAuthAuthenticatedRequestBuilder();
this.uri = uri;
builder.setUri(uri);
builder.setContentType(contentType);
builder.setEntity(entity);
return builder;
}
@Override
public Request.Builder newRequest(String uri) {
final Request.Builder builder = new OAuthAuthenticatedRequestBuilder();
this.uri = URI.create(uri);
builder.setUri(this.uri);
return builder;
}
@Override
public Request.Builder newRequest(String uri, String contentType, String entity) {
final Request.Builder builder = new OAuthAuthenticatedRequestBuilder();
this.uri = URI.create(uri);
builder.setUri(this.uri);
builder.setContentType(contentType);
builder.setEntity(entity);
return builder;
}
@Override
public <A> ResponseTransformation.Builder<A> transformation() {
return httpClient.transformation();
}
@Override
public ResponsePromise execute(Request request) {
return httpClient.execute(request);
}
public class OAuthAuthenticatedRequestBuilder extends DefaultRequest.DefaultRequestBuilder {
Request.Method method;
OAuthAuthenticatedRequestBuilder() {
super(httpClient);
}
@Override
public ResponsePromise execute(Request.Method method) {
if (authenticationHandler != null) {
this.setMethod(method);
this.method = method;
authenticationHandler.configure(this);
}
return super.execute(method);
}
public URI getUri() {
return uri;
}
}
}
| apache-2.0 |
rokn/Count_Words_2015 | testing/openjdk/jdk/src/share/sample/nio/file/Xdd.java | 4290 | /*
* Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.file.*;
import java.nio.file.attribute.*;
import java.io.IOException;
/**
* Example code to list/set/get/delete the user-defined attributes of a file.
*/
public class Xdd {
static void usage() {
System.out.println("Usage: java Xdd <file>");
System.out.println(" java Xdd -set <name>=<value> <file>");
System.out.println(" java Xdd -get <name> <file>");
System.out.println(" java Xdd -del <name> <file>");
System.exit(-1);
}
public static void main(String[] args) throws IOException {
// one or three parameters
if (args.length != 1 && args.length != 3)
usage();
Path file = (args.length == 1) ?
Paths.get(args[0]) : Paths.get(args[2]);
// check that user defined attributes are supported by the file store
FileStore store = Files.getFileStore(file);
if (!store.supportsFileAttributeView(UserDefinedFileAttributeView.class)) {
System.err.format("UserDefinedFileAttributeView not supported on %s\n", store);
System.exit(-1);
}
UserDefinedFileAttributeView view =
Files.getFileAttributeView(file, UserDefinedFileAttributeView.class);
// list user defined attributes
if (args.length == 1) {
System.out.println(" Size Name");
System.out.println("-------- --------------------------------------");
for (String name: view.list()) {
System.out.format("%8d %s\n", view.size(name), name);
}
return;
}
// Add/replace a file's user defined attribute
if (args[0].equals("-set")) {
// name=value
String[] s = args[1].split("=");
if (s.length != 2)
usage();
String name = s[0];
String value = s[1];
view.write(name, Charset.defaultCharset().encode(value));
return;
}
// Print out the value of a file's user defined attribute
if (args[0].equals("-get")) {
String name = args[1];
int size = view.size(name);
ByteBuffer buf = ByteBuffer.allocateDirect(size);
view.read(name, buf);
buf.flip();
System.out.println(Charset.defaultCharset().decode(buf).toString());
return;
}
// Delete a file's user defined attribute
if (args[0].equals("-del")) {
view.delete(args[1]);
return;
}
// option not recognized
usage();
}
}
| mit |
openedbox/mondrian | src/main/mondrian/rolap/agg/DrillThroughCellRequest.java | 2297 | /*
// This software is subject to the terms of the Eclipse Public License v1.0
// Agreement, available at the following URL:
// http://www.eclipse.org/legal/epl-v10.html.
// You must accept the terms of that agreement to use this software.
//
// Copyright (c) 2002-2015 Pentaho Corporation.. All rights reserved.
*/
package mondrian.rolap.agg;
import mondrian.olap.OlapElement;
import mondrian.rolap.RolapStar;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Subclass of {@link CellRequest} that allows to specify
* which columns and measures to return as part of the ResultSet
* which we return to the client.
*/
public class DrillThroughCellRequest extends CellRequest {
private final List<RolapStar.Column> drillThroughColumns =
new ArrayList<RolapStar.Column>();
private final List<RolapStar.Measure> drillThroughMeasures =
new ArrayList<RolapStar.Measure>();
private final List<OlapElement> nonApplicableMembers;
public DrillThroughCellRequest(
RolapStar.Measure measure,
boolean extendedContext, List<OlapElement> nonApplicableFields)
{
super(measure, extendedContext, true);
this.nonApplicableMembers = nonApplicableFields;
}
public void addDrillThroughColumn(RolapStar.Column column) {
this.drillThroughColumns.add(column);
}
public boolean includeInSelect(RolapStar.Column column) {
if (drillThroughColumns.size() == 0
&& drillThroughMeasures.size() == 0)
{
return true;
}
return drillThroughColumns.contains(column);
}
public void addDrillThroughMeasure(RolapStar.Measure measure) {
this.drillThroughMeasures.add(measure);
}
public boolean includeInSelect(RolapStar.Measure measure) {
if (drillThroughColumns.size() == 0
&& drillThroughMeasures.size() == 0)
{
return true;
}
return drillThroughMeasures.contains(measure);
}
public List<RolapStar.Measure> getDrillThroughMeasures() {
return Collections.unmodifiableList(drillThroughMeasures);
}
public List<OlapElement> getNonApplicableMembers() {
return nonApplicableMembers;
}
}
// End DrillThroughCellRequest.java
| epl-1.0 |
fengshao0907/disconf | disconf-web/src/main/java/com/baidu/disconf/web/service/user/form/UserListForm.java | 301 | package com.baidu.disconf.web.service.user.form;
import com.baidu.dsp.common.form.RequestListBase;
/**
* @author liaoqiqi
* @version 2014-1-24
*/
public class UserListForm extends RequestListBase {
/**
*
*/
private static final long serialVersionUID = 4329463343279659715L;
}
| gpl-2.0 |
fengshao0907/disconf | disconf-web/src/main/java/com/baidu/disconf/web/service/app/bo/App.java | 2114 | package com.baidu.disconf.web.service.app.bo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baidu.dsp.common.dao.Columns;
import com.baidu.dsp.common.dao.DB;
import com.baidu.unbiz.common.genericdao.annotation.Column;
import com.baidu.unbiz.common.genericdao.annotation.Table;
import com.github.knightliao.apollo.db.bo.BaseObject;
/**
* @author liaoqiqi
* @version 2014-6-16
*/
@Table(db = DB.DB_NAME, name = "app", keyColumn = Columns.APP_ID)
public class App extends BaseObject<Long> {
protected static final Logger LOG = LoggerFactory.getLogger(App.class);
/**
*
*/
private static final long serialVersionUID = -2217832889126331664L;
/**
*
*/
@Column(value = Columns.NAME)
private String name;
/**
*
*/
@Column(value = Columns.DESC)
private String desc;
/**
*
*/
@Column(value = Columns.EMAILS)
private String emails;
/**
* 创建时间
*/
@Column(value = Columns.CREATE_TIME)
private String createTime;
/**
* 更新时间
*/
@Column(value = Columns.UPDATE_TIME)
private String updateTime;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public String getUpdateTime() {
return updateTime;
}
public void setUpdateTime(String updateTime) {
this.updateTime = updateTime;
}
@Override
public String toString() {
return "App [name=" + name + ", desc=" + desc + ", emails=" + emails + ", createTime=" + createTime +
", updateTime=" + updateTime + "]";
}
public String getEmails() {
return emails;
}
public void setEmails(String emails) {
this.emails = emails;
}
}
| gpl-2.0 |
Bizyroth/hadoop | hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/web/resources/NamenodeWebHdfsMethods.java | 46290 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs.server.namenode.web.resources;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.PrivilegedExceptionAction;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.ContentSummary;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.Options;
import org.apache.hadoop.fs.XAttr;
import org.apache.hadoop.fs.permission.AclStatus;
import org.apache.hadoop.fs.permission.FsAction;
import org.apache.hadoop.hdfs.DFSUtil;
import org.apache.hadoop.hdfs.XAttrHelper;
import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
import org.apache.hadoop.hdfs.protocol.DirectoryListing;
import org.apache.hadoop.hdfs.protocol.HdfsFileStatus;
import org.apache.hadoop.hdfs.protocol.LocatedBlocks;
import org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenIdentifier;
import org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenSecretManager;
import org.apache.hadoop.hdfs.server.blockmanagement.BlockManager;
import org.apache.hadoop.hdfs.server.blockmanagement.DatanodeDescriptor;
import org.apache.hadoop.hdfs.server.blockmanagement.DatanodeStorageInfo;
import org.apache.hadoop.hdfs.server.common.JspHelper;
import org.apache.hadoop.hdfs.server.namenode.NameNode;
import org.apache.hadoop.hdfs.server.protocol.NamenodeProtocols;
import org.apache.hadoop.hdfs.web.JsonUtil;
import org.apache.hadoop.hdfs.web.ParamFilter;
import org.apache.hadoop.hdfs.web.SWebHdfsFileSystem;
import org.apache.hadoop.hdfs.web.WebHdfsFileSystem;
import org.apache.hadoop.hdfs.web.resources.*;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.ipc.RetriableException;
import org.apache.hadoop.ipc.Server;
import org.apache.hadoop.net.NetworkTopology.InvalidTopologyException;
import org.apache.hadoop.net.Node;
import org.apache.hadoop.net.NodeBase;
import org.apache.hadoop.security.Credentials;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.token.Token;
import org.apache.hadoop.security.token.TokenIdentifier;
import org.apache.hadoop.util.StringUtils;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Charsets;
import com.google.common.collect.Lists;
import com.sun.jersey.spi.container.ResourceFilters;
/** Web-hdfs NameNode implementation. */
@Path("")
@ResourceFilters(ParamFilter.class)
public class NamenodeWebHdfsMethods {
public static final Log LOG = LogFactory.getLog(NamenodeWebHdfsMethods.class);
private static final UriFsPathParam ROOT = new UriFsPathParam("");
private static final ThreadLocal<String> REMOTE_ADDRESS = new ThreadLocal<String>();
/** @return the remote client address. */
public static String getRemoteAddress() {
return REMOTE_ADDRESS.get();
}
public static InetAddress getRemoteIp() {
try {
return InetAddress.getByName(getRemoteAddress());
} catch (Exception e) {
return null;
}
}
/**
* Returns true if a WebHdfs request is in progress. Akin to
* {@link Server#isRpcInvocation()}.
*/
public static boolean isWebHdfsInvocation() {
return getRemoteAddress() != null;
}
private @Context ServletContext context;
private @Context HttpServletRequest request;
private @Context HttpServletResponse response;
private void init(final UserGroupInformation ugi,
final DelegationParam delegation,
final UserParam username, final DoAsParam doAsUser,
final UriFsPathParam path, final HttpOpParam<?> op,
final Param<?, ?>... parameters) {
if (LOG.isTraceEnabled()) {
LOG.trace("HTTP " + op.getValue().getType() + ": " + op + ", " + path
+ ", ugi=" + ugi + ", " + username + ", " + doAsUser
+ Param.toSortedString(", ", parameters));
}
//clear content type
response.setContentType(null);
// set the remote address, if coming in via a trust proxy server then
// the address with be that of the proxied client
REMOTE_ADDRESS.set(JspHelper.getRemoteAddr(request));
}
private void reset() {
REMOTE_ADDRESS.set(null);
}
private static NamenodeProtocols getRPCServer(NameNode namenode)
throws IOException {
final NamenodeProtocols np = namenode.getRpcServer();
if (np == null) {
throw new RetriableException("Namenode is in startup mode");
}
return np;
}
@VisibleForTesting
static DatanodeInfo chooseDatanode(final NameNode namenode,
final String path, final HttpOpParam.Op op, final long openOffset,
final long blocksize, final String excludeDatanodes) throws IOException {
final BlockManager bm = namenode.getNamesystem().getBlockManager();
HashSet<Node> excludes = new HashSet<Node>();
if (excludeDatanodes != null) {
for (String host : StringUtils
.getTrimmedStringCollection(excludeDatanodes)) {
int idx = host.indexOf(":");
if (idx != -1) {
excludes.add(bm.getDatanodeManager().getDatanodeByXferAddr(
host.substring(0, idx), Integer.parseInt(host.substring(idx + 1))));
} else {
excludes.add(bm.getDatanodeManager().getDatanodeByHost(host));
}
}
}
if (op == PutOpParam.Op.CREATE) {
//choose a datanode near to client
final DatanodeDescriptor clientNode = bm.getDatanodeManager(
).getDatanodeByHost(getRemoteAddress());
if (clientNode != null) {
final DatanodeStorageInfo[] storages = bm.chooseTarget4WebHDFS(
path, clientNode, excludes, blocksize);
if (storages.length > 0) {
return storages[0].getDatanodeDescriptor();
}
}
} else if (op == GetOpParam.Op.OPEN
|| op == GetOpParam.Op.GETFILECHECKSUM
|| op == PostOpParam.Op.APPEND) {
//choose a datanode containing a replica
final NamenodeProtocols np = getRPCServer(namenode);
final HdfsFileStatus status = np.getFileInfo(path);
if (status == null) {
throw new FileNotFoundException("File " + path + " not found.");
}
final long len = status.getLen();
if (op == GetOpParam.Op.OPEN) {
if (openOffset < 0L || (openOffset >= len && len > 0)) {
throw new IOException("Offset=" + openOffset
+ " out of the range [0, " + len + "); " + op + ", path=" + path);
}
}
if (len > 0) {
final long offset = op == GetOpParam.Op.OPEN? openOffset: len - 1;
final LocatedBlocks locations = np.getBlockLocations(path, offset, 1);
final int count = locations.locatedBlockCount();
if (count > 0) {
return bestNode(locations.get(0).getLocations(), excludes);
}
}
}
return (DatanodeDescriptor)bm.getDatanodeManager().getNetworkTopology(
).chooseRandom(NodeBase.ROOT);
}
/**
* Choose the datanode to redirect the request. Note that the nodes have been
* sorted based on availability and network distances, thus it is sufficient
* to return the first element of the node here.
*/
private static DatanodeInfo bestNode(DatanodeInfo[] nodes,
HashSet<Node> excludes) throws IOException {
for (DatanodeInfo dn: nodes) {
if (false == dn.isDecommissioned() && false == excludes.contains(dn)) {
return dn;
}
}
throw new IOException("No active nodes contain this block");
}
private Token<? extends TokenIdentifier> generateDelegationToken(
final NameNode namenode, final UserGroupInformation ugi,
final String renewer) throws IOException {
final Credentials c = DelegationTokenSecretManager.createCredentials(
namenode, ugi, renewer != null? renewer: ugi.getShortUserName());
if (c == null) {
return null;
}
final Token<? extends TokenIdentifier> t = c.getAllTokens().iterator().next();
Text kind = request.getScheme().equals("http") ? WebHdfsFileSystem.TOKEN_KIND
: SWebHdfsFileSystem.TOKEN_KIND;
t.setKind(kind);
return t;
}
private URI redirectURI(final NameNode namenode,
final UserGroupInformation ugi, final DelegationParam delegation,
final UserParam username, final DoAsParam doAsUser,
final String path, final HttpOpParam.Op op, final long openOffset,
final long blocksize, final String excludeDatanodes,
final Param<?, ?>... parameters) throws URISyntaxException, IOException {
final DatanodeInfo dn;
try {
dn = chooseDatanode(namenode, path, op, openOffset, blocksize,
excludeDatanodes);
} catch (InvalidTopologyException ite) {
throw new IOException("Failed to find datanode, suggest to check cluster health.", ite);
}
final String delegationQuery;
if (!UserGroupInformation.isSecurityEnabled()) {
//security disabled
delegationQuery = Param.toSortedString("&", doAsUser, username);
} else if (delegation.getValue() != null) {
//client has provided a token
delegationQuery = "&" + delegation;
} else {
//generate a token
final Token<? extends TokenIdentifier> t = generateDelegationToken(
namenode, ugi, request.getUserPrincipal().getName());
delegationQuery = "&" + new DelegationParam(t.encodeToUrlString());
}
final String query = op.toQueryString() + delegationQuery
+ "&" + new NamenodeAddressParam(namenode)
+ Param.toSortedString("&", parameters);
final String uripath = WebHdfsFileSystem.PATH_PREFIX + path;
final String scheme = request.getScheme();
int port = "http".equals(scheme) ? dn.getInfoPort() : dn
.getInfoSecurePort();
final URI uri = new URI(scheme, null, dn.getHostName(), port, uripath,
query, null);
if (LOG.isTraceEnabled()) {
LOG.trace("redirectURI=" + uri);
}
return uri;
}
/** Handle HTTP PUT request for the root. */
@PUT
@Path("/")
@Consumes({"*/*"})
@Produces({MediaType.APPLICATION_OCTET_STREAM, MediaType.APPLICATION_JSON})
public Response putRoot(
@Context final UserGroupInformation ugi,
@QueryParam(DelegationParam.NAME) @DefaultValue(DelegationParam.DEFAULT)
final DelegationParam delegation,
@QueryParam(UserParam.NAME) @DefaultValue(UserParam.DEFAULT)
final UserParam username,
@QueryParam(DoAsParam.NAME) @DefaultValue(DoAsParam.DEFAULT)
final DoAsParam doAsUser,
@QueryParam(PutOpParam.NAME) @DefaultValue(PutOpParam.DEFAULT)
final PutOpParam op,
@QueryParam(DestinationParam.NAME) @DefaultValue(DestinationParam.DEFAULT)
final DestinationParam destination,
@QueryParam(OwnerParam.NAME) @DefaultValue(OwnerParam.DEFAULT)
final OwnerParam owner,
@QueryParam(GroupParam.NAME) @DefaultValue(GroupParam.DEFAULT)
final GroupParam group,
@QueryParam(PermissionParam.NAME) @DefaultValue(PermissionParam.DEFAULT)
final PermissionParam permission,
@QueryParam(OverwriteParam.NAME) @DefaultValue(OverwriteParam.DEFAULT)
final OverwriteParam overwrite,
@QueryParam(BufferSizeParam.NAME) @DefaultValue(BufferSizeParam.DEFAULT)
final BufferSizeParam bufferSize,
@QueryParam(ReplicationParam.NAME) @DefaultValue(ReplicationParam.DEFAULT)
final ReplicationParam replication,
@QueryParam(BlockSizeParam.NAME) @DefaultValue(BlockSizeParam.DEFAULT)
final BlockSizeParam blockSize,
@QueryParam(ModificationTimeParam.NAME) @DefaultValue(ModificationTimeParam.DEFAULT)
final ModificationTimeParam modificationTime,
@QueryParam(AccessTimeParam.NAME) @DefaultValue(AccessTimeParam.DEFAULT)
final AccessTimeParam accessTime,
@QueryParam(RenameOptionSetParam.NAME) @DefaultValue(RenameOptionSetParam.DEFAULT)
final RenameOptionSetParam renameOptions,
@QueryParam(CreateParentParam.NAME) @DefaultValue(CreateParentParam.DEFAULT)
final CreateParentParam createParent,
@QueryParam(TokenArgumentParam.NAME) @DefaultValue(TokenArgumentParam.DEFAULT)
final TokenArgumentParam delegationTokenArgument,
@QueryParam(AclPermissionParam.NAME) @DefaultValue(AclPermissionParam.DEFAULT)
final AclPermissionParam aclPermission,
@QueryParam(XAttrNameParam.NAME) @DefaultValue(XAttrNameParam.DEFAULT)
final XAttrNameParam xattrName,
@QueryParam(XAttrValueParam.NAME) @DefaultValue(XAttrValueParam.DEFAULT)
final XAttrValueParam xattrValue,
@QueryParam(XAttrSetFlagParam.NAME) @DefaultValue(XAttrSetFlagParam.DEFAULT)
final XAttrSetFlagParam xattrSetFlag,
@QueryParam(SnapshotNameParam.NAME) @DefaultValue(SnapshotNameParam.DEFAULT)
final SnapshotNameParam snapshotName,
@QueryParam(OldSnapshotNameParam.NAME) @DefaultValue(OldSnapshotNameParam.DEFAULT)
final OldSnapshotNameParam oldSnapshotName,
@QueryParam(ExcludeDatanodesParam.NAME) @DefaultValue(ExcludeDatanodesParam.DEFAULT)
final ExcludeDatanodesParam excludeDatanodes
) throws IOException, InterruptedException {
return put(ugi, delegation, username, doAsUser, ROOT, op, destination,
owner, group, permission, overwrite, bufferSize, replication,
blockSize, modificationTime, accessTime, renameOptions, createParent,
delegationTokenArgument, aclPermission, xattrName, xattrValue,
xattrSetFlag, snapshotName, oldSnapshotName, excludeDatanodes);
}
/** Handle HTTP PUT request. */
@PUT
@Path("{" + UriFsPathParam.NAME + ":.*}")
@Consumes({"*/*"})
@Produces({MediaType.APPLICATION_OCTET_STREAM, MediaType.APPLICATION_JSON})
public Response put(
@Context final UserGroupInformation ugi,
@QueryParam(DelegationParam.NAME) @DefaultValue(DelegationParam.DEFAULT)
final DelegationParam delegation,
@QueryParam(UserParam.NAME) @DefaultValue(UserParam.DEFAULT)
final UserParam username,
@QueryParam(DoAsParam.NAME) @DefaultValue(DoAsParam.DEFAULT)
final DoAsParam doAsUser,
@PathParam(UriFsPathParam.NAME) final UriFsPathParam path,
@QueryParam(PutOpParam.NAME) @DefaultValue(PutOpParam.DEFAULT)
final PutOpParam op,
@QueryParam(DestinationParam.NAME) @DefaultValue(DestinationParam.DEFAULT)
final DestinationParam destination,
@QueryParam(OwnerParam.NAME) @DefaultValue(OwnerParam.DEFAULT)
final OwnerParam owner,
@QueryParam(GroupParam.NAME) @DefaultValue(GroupParam.DEFAULT)
final GroupParam group,
@QueryParam(PermissionParam.NAME) @DefaultValue(PermissionParam.DEFAULT)
final PermissionParam permission,
@QueryParam(OverwriteParam.NAME) @DefaultValue(OverwriteParam.DEFAULT)
final OverwriteParam overwrite,
@QueryParam(BufferSizeParam.NAME) @DefaultValue(BufferSizeParam.DEFAULT)
final BufferSizeParam bufferSize,
@QueryParam(ReplicationParam.NAME) @DefaultValue(ReplicationParam.DEFAULT)
final ReplicationParam replication,
@QueryParam(BlockSizeParam.NAME) @DefaultValue(BlockSizeParam.DEFAULT)
final BlockSizeParam blockSize,
@QueryParam(ModificationTimeParam.NAME) @DefaultValue(ModificationTimeParam.DEFAULT)
final ModificationTimeParam modificationTime,
@QueryParam(AccessTimeParam.NAME) @DefaultValue(AccessTimeParam.DEFAULT)
final AccessTimeParam accessTime,
@QueryParam(RenameOptionSetParam.NAME) @DefaultValue(RenameOptionSetParam.DEFAULT)
final RenameOptionSetParam renameOptions,
@QueryParam(CreateParentParam.NAME) @DefaultValue(CreateParentParam.DEFAULT)
final CreateParentParam createParent,
@QueryParam(TokenArgumentParam.NAME) @DefaultValue(TokenArgumentParam.DEFAULT)
final TokenArgumentParam delegationTokenArgument,
@QueryParam(AclPermissionParam.NAME) @DefaultValue(AclPermissionParam.DEFAULT)
final AclPermissionParam aclPermission,
@QueryParam(XAttrNameParam.NAME) @DefaultValue(XAttrNameParam.DEFAULT)
final XAttrNameParam xattrName,
@QueryParam(XAttrValueParam.NAME) @DefaultValue(XAttrValueParam.DEFAULT)
final XAttrValueParam xattrValue,
@QueryParam(XAttrSetFlagParam.NAME) @DefaultValue(XAttrSetFlagParam.DEFAULT)
final XAttrSetFlagParam xattrSetFlag,
@QueryParam(SnapshotNameParam.NAME) @DefaultValue(SnapshotNameParam.DEFAULT)
final SnapshotNameParam snapshotName,
@QueryParam(OldSnapshotNameParam.NAME) @DefaultValue(OldSnapshotNameParam.DEFAULT)
final OldSnapshotNameParam oldSnapshotName,
@QueryParam(ExcludeDatanodesParam.NAME) @DefaultValue(ExcludeDatanodesParam.DEFAULT)
final ExcludeDatanodesParam excludeDatanodes
) throws IOException, InterruptedException {
init(ugi, delegation, username, doAsUser, path, op, destination, owner,
group, permission, overwrite, bufferSize, replication, blockSize,
modificationTime, accessTime, renameOptions, delegationTokenArgument,
aclPermission, xattrName, xattrValue, xattrSetFlag, snapshotName,
oldSnapshotName, excludeDatanodes);
return ugi.doAs(new PrivilegedExceptionAction<Response>() {
@Override
public Response run() throws IOException, URISyntaxException {
try {
return put(ugi, delegation, username, doAsUser,
path.getAbsolutePath(), op, destination, owner, group,
permission, overwrite, bufferSize, replication, blockSize,
modificationTime, accessTime, renameOptions, createParent,
delegationTokenArgument, aclPermission, xattrName, xattrValue,
xattrSetFlag, snapshotName, oldSnapshotName, excludeDatanodes);
} finally {
reset();
}
}
});
}
private Response put(
final UserGroupInformation ugi,
final DelegationParam delegation,
final UserParam username,
final DoAsParam doAsUser,
final String fullpath,
final PutOpParam op,
final DestinationParam destination,
final OwnerParam owner,
final GroupParam group,
final PermissionParam permission,
final OverwriteParam overwrite,
final BufferSizeParam bufferSize,
final ReplicationParam replication,
final BlockSizeParam blockSize,
final ModificationTimeParam modificationTime,
final AccessTimeParam accessTime,
final RenameOptionSetParam renameOptions,
final CreateParentParam createParent,
final TokenArgumentParam delegationTokenArgument,
final AclPermissionParam aclPermission,
final XAttrNameParam xattrName,
final XAttrValueParam xattrValue,
final XAttrSetFlagParam xattrSetFlag,
final SnapshotNameParam snapshotName,
final OldSnapshotNameParam oldSnapshotName,
final ExcludeDatanodesParam exclDatanodes
) throws IOException, URISyntaxException {
final Configuration conf = (Configuration)context.getAttribute(JspHelper.CURRENT_CONF);
final NameNode namenode = (NameNode)context.getAttribute("name.node");
final NamenodeProtocols np = getRPCServer(namenode);
switch(op.getValue()) {
case CREATE:
{
final URI uri = redirectURI(namenode, ugi, delegation, username,
doAsUser, fullpath, op.getValue(), -1L, blockSize.getValue(conf),
exclDatanodes.getValue(), permission, overwrite, bufferSize,
replication, blockSize);
return Response.temporaryRedirect(uri).type(MediaType.APPLICATION_OCTET_STREAM).build();
}
case MKDIRS:
{
final boolean b = np.mkdirs(fullpath, permission.getFsPermission(), true);
final String js = JsonUtil.toJsonString("boolean", b);
return Response.ok(js).type(MediaType.APPLICATION_JSON).build();
}
case CREATESYMLINK:
{
np.createSymlink(destination.getValue(), fullpath,
PermissionParam.getDefaultFsPermission(), createParent.getValue());
return Response.ok().type(MediaType.APPLICATION_OCTET_STREAM).build();
}
case RENAME:
{
final EnumSet<Options.Rename> s = renameOptions.getValue();
if (s.isEmpty()) {
final boolean b = np.rename(fullpath, destination.getValue());
final String js = JsonUtil.toJsonString("boolean", b);
return Response.ok(js).type(MediaType.APPLICATION_JSON).build();
} else {
np.rename2(fullpath, destination.getValue(),
s.toArray(new Options.Rename[s.size()]));
return Response.ok().type(MediaType.APPLICATION_OCTET_STREAM).build();
}
}
case SETREPLICATION:
{
final boolean b = np.setReplication(fullpath, replication.getValue(conf));
final String js = JsonUtil.toJsonString("boolean", b);
return Response.ok(js).type(MediaType.APPLICATION_JSON).build();
}
case SETOWNER:
{
if (owner.getValue() == null && group.getValue() == null) {
throw new IllegalArgumentException("Both owner and group are empty.");
}
np.setOwner(fullpath, owner.getValue(), group.getValue());
return Response.ok().type(MediaType.APPLICATION_OCTET_STREAM).build();
}
case SETPERMISSION:
{
np.setPermission(fullpath, permission.getFsPermission());
return Response.ok().type(MediaType.APPLICATION_OCTET_STREAM).build();
}
case SETTIMES:
{
np.setTimes(fullpath, modificationTime.getValue(), accessTime.getValue());
return Response.ok().type(MediaType.APPLICATION_OCTET_STREAM).build();
}
case RENEWDELEGATIONTOKEN:
{
final Token<DelegationTokenIdentifier> token = new Token<DelegationTokenIdentifier>();
token.decodeFromUrlString(delegationTokenArgument.getValue());
final long expiryTime = np.renewDelegationToken(token);
final String js = JsonUtil.toJsonString("long", expiryTime);
return Response.ok(js).type(MediaType.APPLICATION_JSON).build();
}
case CANCELDELEGATIONTOKEN:
{
final Token<DelegationTokenIdentifier> token = new Token<DelegationTokenIdentifier>();
token.decodeFromUrlString(delegationTokenArgument.getValue());
np.cancelDelegationToken(token);
return Response.ok().type(MediaType.APPLICATION_OCTET_STREAM).build();
}
case MODIFYACLENTRIES: {
np.modifyAclEntries(fullpath, aclPermission.getAclPermission(true));
return Response.ok().type(MediaType.APPLICATION_OCTET_STREAM).build();
}
case REMOVEACLENTRIES: {
np.removeAclEntries(fullpath, aclPermission.getAclPermission(false));
return Response.ok().type(MediaType.APPLICATION_OCTET_STREAM).build();
}
case REMOVEDEFAULTACL: {
np.removeDefaultAcl(fullpath);
return Response.ok().type(MediaType.APPLICATION_OCTET_STREAM).build();
}
case REMOVEACL: {
np.removeAcl(fullpath);
return Response.ok().type(MediaType.APPLICATION_OCTET_STREAM).build();
}
case SETACL: {
np.setAcl(fullpath, aclPermission.getAclPermission(true));
return Response.ok().type(MediaType.APPLICATION_OCTET_STREAM).build();
}
case SETXATTR: {
np.setXAttr(
fullpath,
XAttrHelper.buildXAttr(xattrName.getXAttrName(),
xattrValue.getXAttrValue()), xattrSetFlag.getFlag());
return Response.ok().type(MediaType.APPLICATION_OCTET_STREAM).build();
}
case REMOVEXATTR: {
np.removeXAttr(fullpath, XAttrHelper.buildXAttr(xattrName.getXAttrName()));
return Response.ok().type(MediaType.APPLICATION_OCTET_STREAM).build();
}
case CREATESNAPSHOT: {
String snapshotPath = np.createSnapshot(fullpath, snapshotName.getValue());
final String js = JsonUtil.toJsonString(
org.apache.hadoop.fs.Path.class.getSimpleName(), snapshotPath);
return Response.ok(js).type(MediaType.APPLICATION_JSON).build();
}
case RENAMESNAPSHOT: {
np.renameSnapshot(fullpath, oldSnapshotName.getValue(),
snapshotName.getValue());
return Response.ok().type(MediaType.APPLICATION_OCTET_STREAM).build();
}
default:
throw new UnsupportedOperationException(op + " is not supported");
}
}
/** Handle HTTP POST request for the root. */
@POST
@Path("/")
@Consumes({"*/*"})
@Produces({MediaType.APPLICATION_OCTET_STREAM, MediaType.APPLICATION_JSON})
public Response postRoot(
@Context final UserGroupInformation ugi,
@QueryParam(DelegationParam.NAME) @DefaultValue(DelegationParam.DEFAULT)
final DelegationParam delegation,
@QueryParam(UserParam.NAME) @DefaultValue(UserParam.DEFAULT)
final UserParam username,
@QueryParam(DoAsParam.NAME) @DefaultValue(DoAsParam.DEFAULT)
final DoAsParam doAsUser,
@QueryParam(PostOpParam.NAME) @DefaultValue(PostOpParam.DEFAULT)
final PostOpParam op,
@QueryParam(ConcatSourcesParam.NAME) @DefaultValue(ConcatSourcesParam.DEFAULT)
final ConcatSourcesParam concatSrcs,
@QueryParam(BufferSizeParam.NAME) @DefaultValue(BufferSizeParam.DEFAULT)
final BufferSizeParam bufferSize,
@QueryParam(ExcludeDatanodesParam.NAME) @DefaultValue(ExcludeDatanodesParam.DEFAULT)
final ExcludeDatanodesParam excludeDatanodes,
@QueryParam(NewLengthParam.NAME) @DefaultValue(NewLengthParam.DEFAULT)
final NewLengthParam newLength
) throws IOException, InterruptedException {
return post(ugi, delegation, username, doAsUser, ROOT, op, concatSrcs,
bufferSize, excludeDatanodes, newLength);
}
/** Handle HTTP POST request. */
@POST
@Path("{" + UriFsPathParam.NAME + ":.*}")
@Consumes({"*/*"})
@Produces({MediaType.APPLICATION_OCTET_STREAM, MediaType.APPLICATION_JSON})
public Response post(
@Context final UserGroupInformation ugi,
@QueryParam(DelegationParam.NAME) @DefaultValue(DelegationParam.DEFAULT)
final DelegationParam delegation,
@QueryParam(UserParam.NAME) @DefaultValue(UserParam.DEFAULT)
final UserParam username,
@QueryParam(DoAsParam.NAME) @DefaultValue(DoAsParam.DEFAULT)
final DoAsParam doAsUser,
@PathParam(UriFsPathParam.NAME) final UriFsPathParam path,
@QueryParam(PostOpParam.NAME) @DefaultValue(PostOpParam.DEFAULT)
final PostOpParam op,
@QueryParam(ConcatSourcesParam.NAME) @DefaultValue(ConcatSourcesParam.DEFAULT)
final ConcatSourcesParam concatSrcs,
@QueryParam(BufferSizeParam.NAME) @DefaultValue(BufferSizeParam.DEFAULT)
final BufferSizeParam bufferSize,
@QueryParam(ExcludeDatanodesParam.NAME) @DefaultValue(ExcludeDatanodesParam.DEFAULT)
final ExcludeDatanodesParam excludeDatanodes,
@QueryParam(NewLengthParam.NAME) @DefaultValue(NewLengthParam.DEFAULT)
final NewLengthParam newLength
) throws IOException, InterruptedException {
init(ugi, delegation, username, doAsUser, path, op, concatSrcs, bufferSize,
excludeDatanodes, newLength);
return ugi.doAs(new PrivilegedExceptionAction<Response>() {
@Override
public Response run() throws IOException, URISyntaxException {
try {
return post(ugi, delegation, username, doAsUser,
path.getAbsolutePath(), op, concatSrcs, bufferSize,
excludeDatanodes, newLength);
} finally {
reset();
}
}
});
}
private Response post(
final UserGroupInformation ugi,
final DelegationParam delegation,
final UserParam username,
final DoAsParam doAsUser,
final String fullpath,
final PostOpParam op,
final ConcatSourcesParam concatSrcs,
final BufferSizeParam bufferSize,
final ExcludeDatanodesParam excludeDatanodes,
final NewLengthParam newLength
) throws IOException, URISyntaxException {
final NameNode namenode = (NameNode)context.getAttribute("name.node");
final NamenodeProtocols np = getRPCServer(namenode);
switch(op.getValue()) {
case APPEND:
{
final URI uri = redirectURI(namenode, ugi, delegation, username,
doAsUser, fullpath, op.getValue(), -1L, -1L,
excludeDatanodes.getValue(), bufferSize);
return Response.temporaryRedirect(uri).type(MediaType.APPLICATION_OCTET_STREAM).build();
}
case CONCAT:
{
np.concat(fullpath, concatSrcs.getAbsolutePaths());
return Response.ok().build();
}
case TRUNCATE:
{
// We treat each rest request as a separate client.
final boolean b = np.truncate(fullpath, newLength.getValue(),
"DFSClient_" + DFSUtil.getSecureRandom().nextLong());
final String js = JsonUtil.toJsonString("boolean", b);
return Response.ok(js).type(MediaType.APPLICATION_JSON).build();
}
default:
throw new UnsupportedOperationException(op + " is not supported");
}
}
/** Handle HTTP GET request for the root. */
@GET
@Path("/")
@Produces({MediaType.APPLICATION_OCTET_STREAM, MediaType.APPLICATION_JSON})
public Response getRoot(
@Context final UserGroupInformation ugi,
@QueryParam(DelegationParam.NAME) @DefaultValue(DelegationParam.DEFAULT)
final DelegationParam delegation,
@QueryParam(UserParam.NAME) @DefaultValue(UserParam.DEFAULT)
final UserParam username,
@QueryParam(DoAsParam.NAME) @DefaultValue(DoAsParam.DEFAULT)
final DoAsParam doAsUser,
@QueryParam(GetOpParam.NAME) @DefaultValue(GetOpParam.DEFAULT)
final GetOpParam op,
@QueryParam(OffsetParam.NAME) @DefaultValue(OffsetParam.DEFAULT)
final OffsetParam offset,
@QueryParam(LengthParam.NAME) @DefaultValue(LengthParam.DEFAULT)
final LengthParam length,
@QueryParam(RenewerParam.NAME) @DefaultValue(RenewerParam.DEFAULT)
final RenewerParam renewer,
@QueryParam(BufferSizeParam.NAME) @DefaultValue(BufferSizeParam.DEFAULT)
final BufferSizeParam bufferSize,
@QueryParam(XAttrNameParam.NAME) @DefaultValue(XAttrNameParam.DEFAULT)
final List<XAttrNameParam> xattrNames,
@QueryParam(XAttrEncodingParam.NAME) @DefaultValue(XAttrEncodingParam.DEFAULT)
final XAttrEncodingParam xattrEncoding,
@QueryParam(ExcludeDatanodesParam.NAME) @DefaultValue(ExcludeDatanodesParam.DEFAULT)
final ExcludeDatanodesParam excludeDatanodes,
@QueryParam(FsActionParam.NAME) @DefaultValue(FsActionParam.DEFAULT)
final FsActionParam fsAction,
@QueryParam(TokenKindParam.NAME) @DefaultValue(TokenKindParam.DEFAULT)
final TokenKindParam tokenKind,
@QueryParam(TokenServiceParam.NAME) @DefaultValue(TokenServiceParam.DEFAULT)
final TokenServiceParam tokenService
) throws IOException, InterruptedException {
return get(ugi, delegation, username, doAsUser, ROOT, op, offset, length,
renewer, bufferSize, xattrNames, xattrEncoding, excludeDatanodes, fsAction,
tokenKind, tokenService);
}
/** Handle HTTP GET request. */
@GET
@Path("{" + UriFsPathParam.NAME + ":.*}")
@Produces({MediaType.APPLICATION_OCTET_STREAM, MediaType.APPLICATION_JSON})
public Response get(
@Context final UserGroupInformation ugi,
@QueryParam(DelegationParam.NAME) @DefaultValue(DelegationParam.DEFAULT)
final DelegationParam delegation,
@QueryParam(UserParam.NAME) @DefaultValue(UserParam.DEFAULT)
final UserParam username,
@QueryParam(DoAsParam.NAME) @DefaultValue(DoAsParam.DEFAULT)
final DoAsParam doAsUser,
@PathParam(UriFsPathParam.NAME) final UriFsPathParam path,
@QueryParam(GetOpParam.NAME) @DefaultValue(GetOpParam.DEFAULT)
final GetOpParam op,
@QueryParam(OffsetParam.NAME) @DefaultValue(OffsetParam.DEFAULT)
final OffsetParam offset,
@QueryParam(LengthParam.NAME) @DefaultValue(LengthParam.DEFAULT)
final LengthParam length,
@QueryParam(RenewerParam.NAME) @DefaultValue(RenewerParam.DEFAULT)
final RenewerParam renewer,
@QueryParam(BufferSizeParam.NAME) @DefaultValue(BufferSizeParam.DEFAULT)
final BufferSizeParam bufferSize,
@QueryParam(XAttrNameParam.NAME) @DefaultValue(XAttrNameParam.DEFAULT)
final List<XAttrNameParam> xattrNames,
@QueryParam(XAttrEncodingParam.NAME) @DefaultValue(XAttrEncodingParam.DEFAULT)
final XAttrEncodingParam xattrEncoding,
@QueryParam(ExcludeDatanodesParam.NAME) @DefaultValue(ExcludeDatanodesParam.DEFAULT)
final ExcludeDatanodesParam excludeDatanodes,
@QueryParam(FsActionParam.NAME) @DefaultValue(FsActionParam.DEFAULT)
final FsActionParam fsAction,
@QueryParam(TokenKindParam.NAME) @DefaultValue(TokenKindParam.DEFAULT)
final TokenKindParam tokenKind,
@QueryParam(TokenServiceParam.NAME) @DefaultValue(TokenServiceParam.DEFAULT)
final TokenServiceParam tokenService
) throws IOException, InterruptedException {
init(ugi, delegation, username, doAsUser, path, op, offset, length,
renewer, bufferSize, xattrEncoding, excludeDatanodes, fsAction,
tokenKind, tokenService);
return ugi.doAs(new PrivilegedExceptionAction<Response>() {
@Override
public Response run() throws IOException, URISyntaxException {
try {
return get(ugi, delegation, username, doAsUser,
path.getAbsolutePath(), op, offset, length, renewer, bufferSize,
xattrNames, xattrEncoding, excludeDatanodes, fsAction, tokenKind,
tokenService);
} finally {
reset();
}
}
});
}
private Response get(
final UserGroupInformation ugi,
final DelegationParam delegation,
final UserParam username,
final DoAsParam doAsUser,
final String fullpath,
final GetOpParam op,
final OffsetParam offset,
final LengthParam length,
final RenewerParam renewer,
final BufferSizeParam bufferSize,
final List<XAttrNameParam> xattrNames,
final XAttrEncodingParam xattrEncoding,
final ExcludeDatanodesParam excludeDatanodes,
final FsActionParam fsAction,
final TokenKindParam tokenKind,
final TokenServiceParam tokenService
) throws IOException, URISyntaxException {
final NameNode namenode = (NameNode)context.getAttribute("name.node");
final NamenodeProtocols np = getRPCServer(namenode);
switch(op.getValue()) {
case OPEN:
{
final URI uri = redirectURI(namenode, ugi, delegation, username,
doAsUser, fullpath, op.getValue(), offset.getValue(), -1L,
excludeDatanodes.getValue(), offset, length, bufferSize);
return Response.temporaryRedirect(uri).type(MediaType.APPLICATION_OCTET_STREAM).build();
}
case GET_BLOCK_LOCATIONS:
{
final long offsetValue = offset.getValue();
final Long lengthValue = length.getValue();
final LocatedBlocks locatedblocks = np.getBlockLocations(fullpath,
offsetValue, lengthValue != null? lengthValue: Long.MAX_VALUE);
final String js = JsonUtil.toJsonString(locatedblocks);
return Response.ok(js).type(MediaType.APPLICATION_JSON).build();
}
case GETFILESTATUS:
{
final HdfsFileStatus status = np.getFileInfo(fullpath);
if (status == null) {
throw new FileNotFoundException("File does not exist: " + fullpath);
}
final String js = JsonUtil.toJsonString(status, true);
return Response.ok(js).type(MediaType.APPLICATION_JSON).build();
}
case LISTSTATUS:
{
final StreamingOutput streaming = getListingStream(np, fullpath);
return Response.ok(streaming).type(MediaType.APPLICATION_JSON).build();
}
case GETCONTENTSUMMARY:
{
final ContentSummary contentsummary = np.getContentSummary(fullpath);
final String js = JsonUtil.toJsonString(contentsummary);
return Response.ok(js).type(MediaType.APPLICATION_JSON).build();
}
case GETFILECHECKSUM:
{
final URI uri = redirectURI(namenode, ugi, delegation, username, doAsUser,
fullpath, op.getValue(), -1L, -1L, null);
return Response.temporaryRedirect(uri).type(MediaType.APPLICATION_OCTET_STREAM).build();
}
case GETDELEGATIONTOKEN:
{
if (delegation.getValue() != null) {
throw new IllegalArgumentException(delegation.getName()
+ " parameter is not null.");
}
final Token<? extends TokenIdentifier> token = generateDelegationToken(
namenode, ugi, renewer.getValue());
final String setServiceName = tokenService.getValue();
final String setKind = tokenKind.getValue();
if (setServiceName != null) {
token.setService(new Text(setServiceName));
}
if (setKind != null) {
token.setKind(new Text(setKind));
}
final String js = JsonUtil.toJsonString(token);
return Response.ok(js).type(MediaType.APPLICATION_JSON).build();
}
case GETHOMEDIRECTORY:
{
final String js = JsonUtil.toJsonString(
org.apache.hadoop.fs.Path.class.getSimpleName(),
WebHdfsFileSystem.getHomeDirectoryString(ugi));
return Response.ok(js).type(MediaType.APPLICATION_JSON).build();
}
case GETACLSTATUS: {
AclStatus status = np.getAclStatus(fullpath);
if (status == null) {
throw new FileNotFoundException("File does not exist: " + fullpath);
}
final String js = JsonUtil.toJsonString(status);
return Response.ok(js).type(MediaType.APPLICATION_JSON).build();
}
case GETXATTRS: {
List<String> names = null;
if (xattrNames != null) {
names = Lists.newArrayListWithCapacity(xattrNames.size());
for (XAttrNameParam xattrName : xattrNames) {
if (xattrName.getXAttrName() != null) {
names.add(xattrName.getXAttrName());
}
}
}
List<XAttr> xAttrs = np.getXAttrs(fullpath, (names != null &&
!names.isEmpty()) ? XAttrHelper.buildXAttrs(names) : null);
final String js = JsonUtil.toJsonString(xAttrs,
xattrEncoding.getEncoding());
return Response.ok(js).type(MediaType.APPLICATION_JSON).build();
}
case LISTXATTRS: {
final List<XAttr> xAttrs = np.listXAttrs(fullpath);
final String js = JsonUtil.toJsonString(xAttrs);
return Response.ok(js).type(MediaType.APPLICATION_JSON).build();
}
case CHECKACCESS: {
np.checkAccess(fullpath, FsAction.getFsAction(fsAction.getValue()));
return Response.ok().build();
}
default:
throw new UnsupportedOperationException(op + " is not supported");
}
}
private static DirectoryListing getDirectoryListing(final NamenodeProtocols np,
final String p, byte[] startAfter) throws IOException {
final DirectoryListing listing = np.getListing(p, startAfter, false);
if (listing == null) { // the directory does not exist
throw new FileNotFoundException("File " + p + " does not exist.");
}
return listing;
}
private static StreamingOutput getListingStream(final NamenodeProtocols np,
final String p) throws IOException {
// allows exceptions like FNF or ACE to prevent http response of 200 for
// a failure since we can't (currently) return error responses in the
// middle of a streaming operation
final DirectoryListing firstDirList = getDirectoryListing(np, p,
HdfsFileStatus.EMPTY_NAME);
// must save ugi because the streaming object will be executed outside
// the remote user's ugi
final UserGroupInformation ugi = UserGroupInformation.getCurrentUser();
return new StreamingOutput() {
@Override
public void write(final OutputStream outstream) throws IOException {
final PrintWriter out = new PrintWriter(new OutputStreamWriter(
outstream, Charsets.UTF_8));
out.println("{\"" + FileStatus.class.getSimpleName() + "es\":{\""
+ FileStatus.class.getSimpleName() + "\":[");
try {
// restore remote user's ugi
ugi.doAs(new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws IOException {
long n = 0;
for (DirectoryListing dirList = firstDirList; ;
dirList = getDirectoryListing(np, p, dirList.getLastName())
) {
// send each segment of the directory listing
for (HdfsFileStatus s : dirList.getPartialListing()) {
if (n++ > 0) {
out.println(',');
}
out.print(JsonUtil.toJsonString(s, false));
}
// stop if last segment
if (!dirList.hasMore()) {
break;
}
}
return null;
}
});
} catch (InterruptedException e) {
throw new IOException(e);
}
out.println();
out.println("]}}");
out.flush();
}
};
}
/** Handle HTTP DELETE request for the root. */
@DELETE
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
public Response deleteRoot(
@Context final UserGroupInformation ugi,
@QueryParam(DelegationParam.NAME) @DefaultValue(DelegationParam.DEFAULT)
final DelegationParam delegation,
@QueryParam(UserParam.NAME) @DefaultValue(UserParam.DEFAULT)
final UserParam username,
@QueryParam(DoAsParam.NAME) @DefaultValue(DoAsParam.DEFAULT)
final DoAsParam doAsUser,
@QueryParam(DeleteOpParam.NAME) @DefaultValue(DeleteOpParam.DEFAULT)
final DeleteOpParam op,
@QueryParam(RecursiveParam.NAME) @DefaultValue(RecursiveParam.DEFAULT)
final RecursiveParam recursive,
@QueryParam(SnapshotNameParam.NAME) @DefaultValue(SnapshotNameParam.DEFAULT)
final SnapshotNameParam snapshotName
) throws IOException, InterruptedException {
return delete(ugi, delegation, username, doAsUser, ROOT, op, recursive,
snapshotName);
}
/** Handle HTTP DELETE request. */
@DELETE
@Path("{" + UriFsPathParam.NAME + ":.*}")
@Produces(MediaType.APPLICATION_JSON)
public Response delete(
@Context final UserGroupInformation ugi,
@QueryParam(DelegationParam.NAME) @DefaultValue(DelegationParam.DEFAULT)
final DelegationParam delegation,
@QueryParam(UserParam.NAME) @DefaultValue(UserParam.DEFAULT)
final UserParam username,
@QueryParam(DoAsParam.NAME) @DefaultValue(DoAsParam.DEFAULT)
final DoAsParam doAsUser,
@PathParam(UriFsPathParam.NAME) final UriFsPathParam path,
@QueryParam(DeleteOpParam.NAME) @DefaultValue(DeleteOpParam.DEFAULT)
final DeleteOpParam op,
@QueryParam(RecursiveParam.NAME) @DefaultValue(RecursiveParam.DEFAULT)
final RecursiveParam recursive,
@QueryParam(SnapshotNameParam.NAME) @DefaultValue(SnapshotNameParam.DEFAULT)
final SnapshotNameParam snapshotName
) throws IOException, InterruptedException {
init(ugi, delegation, username, doAsUser, path, op, recursive, snapshotName);
return ugi.doAs(new PrivilegedExceptionAction<Response>() {
@Override
public Response run() throws IOException {
try {
return delete(ugi, delegation, username, doAsUser,
path.getAbsolutePath(), op, recursive, snapshotName);
} finally {
reset();
}
}
});
}
private Response delete(
final UserGroupInformation ugi,
final DelegationParam delegation,
final UserParam username,
final DoAsParam doAsUser,
final String fullpath,
final DeleteOpParam op,
final RecursiveParam recursive,
final SnapshotNameParam snapshotName
) throws IOException {
final NameNode namenode = (NameNode)context.getAttribute("name.node");
final NamenodeProtocols np = getRPCServer(namenode);
switch(op.getValue()) {
case DELETE: {
final boolean b = np.delete(fullpath, recursive.getValue());
final String js = JsonUtil.toJsonString("boolean", b);
return Response.ok(js).type(MediaType.APPLICATION_JSON).build();
}
case DELETESNAPSHOT: {
np.deleteSnapshot(fullpath, snapshotName.getValue());
return Response.ok().type(MediaType.APPLICATION_OCTET_STREAM).build();
}
default:
throw new UnsupportedOperationException(op + " is not supported");
}
}
}
| apache-2.0 |
idea4bsd/idea4bsd | java/idea-ui/src/com/intellij/ide/util/newProjectWizard/SourceRootFinder.java | 1167 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide.util.newProjectWizard;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.util.Pair;
import java.io.File;
import java.util.List;
/**
* @deprecated use {@link com.intellij.ide.util.projectWizard.importSources.JavaSourceRootDetector} instead
*/
@Deprecated
public interface SourceRootFinder {
ExtensionPointName<SourceRootFinder> EP_NAME = ExtensionPointName.create("com.intellij.sourceRootFinder");
List<Pair<File, String>> findRoots(File dir);
String getDescription();
String getName();
}
| apache-2.0 |
mgherghe/gateway | transport/ws/src/main/java/org/kaazing/gateway/transport/ws/WsBinaryMessage.java | 1016 | /**
* Copyright 2007-2016, Kaazing Corporation. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kaazing.gateway.transport.ws;
import org.kaazing.mina.core.buffer.IoBufferEx;
public class WsBinaryMessage extends WsMessage {
public WsBinaryMessage(IoBufferEx buf) {
super();
setBytes(buf);
}
public WsBinaryMessage(IoBufferEx buf, boolean fin) {
super(fin);
setBytes(buf);
}
@Override
public Kind getKind() {
return Kind.BINARY;
}
}
| apache-2.0 |
mgherghe/gateway | mina.netty/src/test/java/org/jboss/netty/channel/socket/OioNioSocketEchoTest.java | 1939 | /**
* Copyright 2007-2016, Kaazing Corporation. 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.
*/
/*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.jboss.netty.channel.socket;
import java.util.concurrent.Executor;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.channel.socket.oio.OioClientSocketChannelFactory;
public class OioNioSocketEchoTest extends AbstractSocketEchoTest {
@Override
protected ChannelFactory newClientSocketChannelFactory(Executor executor) {
return new OioClientSocketChannelFactory(executor);
}
@Override
protected ChannelFactory newServerSocketChannelFactory(Executor executor) {
return new NioServerSocketChannelFactory(executor, executor);
}
}
| apache-2.0 |
wstrzelczyk/modules | sms/src/main/java/org/motechproject/sms/util/SmsEventSubjects.java | 787 | package org.motechproject.sms.util;
/**
* Event subjects, mirrors DeliveryStatus
*/
public final class SmsEventSubjects {
private SmsEventSubjects() { }
public static final String PENDING = "outbound_sms_pending";
public static final String RETRYING = "outbound_sms_retrying";
public static final String ABORTED = "outbound_sms_aborted";
public static final String SCHEDULED = "outbound_sms_scheduled";
public static final String DISPATCHED = "outbound_sms_dispatched";
public static final String DELIVERY_CONFIRMED = "outbound_sms_delivery_confirmed";
public static final String FAILURE_CONFIRMED = "outbound_sms_failure_confirmed";
public static final String SEND_SMS = "send_sms";
public static final String INBOUND_SMS = "inbound_sms";
}
| bsd-3-clause |
wstrzelczyk/modules | commcare/src/main/java/org/motechproject/commcare/domain/FormValueAttribute.java | 479 | package org.motechproject.commcare.domain;
/**
* Represents a form value attribute.
*/
public class FormValueAttribute implements FormNode {
private final String value;
/**
* Creates new form value attribute with value set to {@code value}.
*
* @param value the value of the attribute
*/
public FormValueAttribute(String value) {
this.value = value;
}
@Override
public String getValue() {
return value;
}
}
| bsd-3-clause |
Puja-Mishra/Android_FreeChat | Telegram-master/TMessagesProj/src/main/java/org/telegram/messenger/exoplayer/extractor/ts/PtsTimestampAdjuster.java | 3914 | /*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.telegram.messenger.exoplayer.extractor.ts;
import org.telegram.messenger.exoplayer.C;
/**
* Scales and adjusts MPEG-2 TS presentation timestamps, taking into account an initial offset and
* timestamp rollover.
*/
public final class PtsTimestampAdjuster {
/**
* A special {@code firstSampleTimestampUs} value indicating that presentation timestamps should
* not be offset.
*/
public static final long DO_NOT_OFFSET = Long.MAX_VALUE;
/**
* The value one greater than the largest representable (33 bit) presentation timestamp.
*/
private static final long MAX_PTS_PLUS_ONE = 0x200000000L;
private final long firstSampleTimestampUs;
private long timestampOffsetUs;
// Volatile to allow isInitialized to be called on a different thread to adjustTimestamp.
private volatile long lastPts;
/**
* @param firstSampleTimestampUs The desired result of the first call to
* {@link #adjustTimestamp(long)}, or {@link #DO_NOT_OFFSET} if presentation timestamps
* should not be offset.
*/
public PtsTimestampAdjuster(long firstSampleTimestampUs) {
this.firstSampleTimestampUs = firstSampleTimestampUs;
lastPts = Long.MIN_VALUE;
}
/**
* Resets the instance to its initial state.
*/
public void reset() {
lastPts = Long.MIN_VALUE;
}
/**
* Whether this adjuster has been initialized with a first MPEG-2 TS presentation timestamp.
*/
public boolean isInitialized() {
return lastPts != Long.MIN_VALUE;
}
/**
* Scales and offsets an MPEG-2 TS presentation timestamp.
*
* @param pts The MPEG-2 TS presentation timestamp.
* @return The adjusted timestamp in microseconds.
*/
public long adjustTimestamp(long pts) {
if (lastPts != Long.MIN_VALUE) {
// The wrap count for the current PTS may be closestWrapCount or (closestWrapCount - 1),
// and we need to snap to the one closest to lastPts.
long closestWrapCount = (lastPts + (MAX_PTS_PLUS_ONE / 2)) / MAX_PTS_PLUS_ONE;
long ptsWrapBelow = pts + (MAX_PTS_PLUS_ONE * (closestWrapCount - 1));
long ptsWrapAbove = pts + (MAX_PTS_PLUS_ONE * closestWrapCount);
pts = Math.abs(ptsWrapBelow - lastPts) < Math.abs(ptsWrapAbove - lastPts)
? ptsWrapBelow : ptsWrapAbove;
}
// Calculate the corresponding timestamp.
long timeUs = ptsToUs(pts);
if (firstSampleTimestampUs != DO_NOT_OFFSET && lastPts == Long.MIN_VALUE) {
// Calculate the timestamp offset.
timestampOffsetUs = firstSampleTimestampUs - timeUs;
}
// Record the adjusted PTS to adjust for wraparound next time.
lastPts = pts;
return timeUs + timestampOffsetUs;
}
/**
* Converts a value in MPEG-2 timestamp units to the corresponding value in microseconds.
*
* @param pts A value in MPEG-2 timestamp units.
* @return The corresponding value in microseconds.
*/
public static long ptsToUs(long pts) {
return (pts * C.MICROS_PER_SECOND) / 90000;
}
/**
* Converts a value in microseconds to the corresponding values in MPEG-2 timestamp units.
*
* @param us A value in microseconds.
* @return The corresponding value in MPEG-2 timestamp units.
*/
public static long usToPts(long us) {
return (us * 90000) / C.MICROS_PER_SECOND;
}
}
| gpl-2.0 |
jdahlstrom/vaadin.react | uitest/src/test/java/com/vaadin/tests/components/menubar/MenuBarNavigationKeyboardTest.java | 3047 | package com.vaadin.tests.components.menubar;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Assert;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.interactions.Actions;
import com.vaadin.testbench.elements.MenuBarElement;
import com.vaadin.tests.tb3.MultiBrowserTest;
public class MenuBarNavigationKeyboardTest extends MultiBrowserTest {
@Override
protected Class<?> getUIClass() {
return com.vaadin.tests.components.menubar.MenuBarNavigation.class;
}
@Override
protected boolean requireWindowFocusForIE() {
return true;
}
@Override
protected boolean usePersistentHoverForIE() {
return false;
}
@Test
public void testKeyboardNavigation() throws Exception {
openTestURL();
openMenu("File");
getMenuBar().sendKeys(Keys.DOWN, Keys.DOWN, Keys.DOWN, Keys.DOWN,
Keys.RIGHT, Keys.ENTER);
Assert.assertEquals("1. MenuItem File/Export../As PDF... selected",
getLogRow(0));
openMenu("File");
getMenuBar().sendKeys(Keys.RIGHT, Keys.RIGHT, Keys.RIGHT, Keys.ENTER);
Assert.assertEquals("2. MenuItem Help selected", getLogRow(0));
openMenu("Edit");
getMenuBar().sendKeys(Keys.LEFT, Keys.DOWN, Keys.DOWN, Keys.ENTER);
Assert.assertEquals("3. MenuItem Edit/Cut selected", getLogRow(0));
openMenu("Edit");
getMenuBar().sendKeys(Keys.ENTER);
Assert.assertEquals("3. MenuItem Edit/Cut selected", getLogRow(0));
getMenuBar().sendKeys(Keys.ENTER);
Assert.assertEquals("4. MenuItem Edit/Copy selected", getLogRow(0));
/* Enter while menubar has focus but no selection should focus "File" */
getMenuBar().sendKeys(Keys.ENTER);
Assert.assertEquals("4. MenuItem Edit/Copy selected", getLogRow(0));
/* Enter again should open File and focus Open */
getMenuBar().sendKeys(Keys.ENTER);
Assert.assertEquals("4. MenuItem Edit/Copy selected", getLogRow(0));
getMenuBar().sendKeys(Keys.ENTER);
Assert.assertEquals("5. MenuItem File/Open selected", getLogRow(0));
}
@Test
public void testMenuSelectWithKeyboardStateClearedCorrectly()
throws InterruptedException {
openTestURL();
openMenu("File");
getMenuBar().sendKeys(Keys.ARROW_RIGHT, Keys.ARROW_RIGHT,
Keys.ARROW_RIGHT, Keys.ENTER);
assertTrue("Help menu was not selected",
logContainsText("MenuItem Help selected"));
new Actions(driver).moveToElement(getMenuBar(), 10, 10).perform();
assertFalse("Unexpected MenuBar popup is visible",
isElementPresent(By.className("v-menubar-popup")));
}
public MenuBarElement getMenuBar() {
return $(MenuBarElement.class).first();
}
public void openMenu(String name) {
getMenuBar().clickItem(name);
}
}
| apache-2.0 |
GlenRSmith/elasticsearch | x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/action/TransportGetTrainedModelsAction.java | 4022 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.ml.action;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.support.ActionFilters;
import org.elasticsearch.action.support.HandledTransportAction;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.core.Tuple;
import org.elasticsearch.tasks.Task;
import org.elasticsearch.transport.TransportService;
import org.elasticsearch.xpack.core.ml.action.GetTrainedModelsAction;
import org.elasticsearch.xpack.core.ml.action.GetTrainedModelsAction.Request;
import org.elasticsearch.xpack.core.ml.action.GetTrainedModelsAction.Response;
import org.elasticsearch.xpack.core.ml.job.messages.Messages;
import org.elasticsearch.xpack.core.ml.utils.ExceptionsHelper;
import org.elasticsearch.xpack.ml.inference.ModelAliasMetadata;
import org.elasticsearch.xpack.ml.inference.persistence.TrainedModelProvider;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class TransportGetTrainedModelsAction extends HandledTransportAction<Request, Response> {
private final TrainedModelProvider provider;
private final ClusterService clusterService;
@Inject
public TransportGetTrainedModelsAction(
TransportService transportService,
ActionFilters actionFilters,
ClusterService clusterService,
TrainedModelProvider trainedModelProvider
) {
super(GetTrainedModelsAction.NAME, transportService, actionFilters, GetTrainedModelsAction.Request::new);
this.provider = trainedModelProvider;
this.clusterService = clusterService;
}
@Override
protected void doExecute(Task task, Request request, ActionListener<Response> listener) {
Response.Builder responseBuilder = Response.builder();
ActionListener<Tuple<Long, Map<String, Set<String>>>> idExpansionListener = ActionListener.wrap(totalAndIds -> {
responseBuilder.setTotalCount(totalAndIds.v1());
if (totalAndIds.v2().isEmpty()) {
listener.onResponse(responseBuilder.build());
return;
}
if (request.getIncludes().isIncludeModelDefinition() && totalAndIds.v2().size() > 1) {
listener.onFailure(ExceptionsHelper.badRequestException(Messages.INFERENCE_TOO_MANY_DEFINITIONS_REQUESTED));
return;
}
if (request.getIncludes().isIncludeModelDefinition()) {
Map.Entry<String, Set<String>> modelIdAndAliases = totalAndIds.v2().entrySet().iterator().next();
provider.getTrainedModel(
modelIdAndAliases.getKey(),
modelIdAndAliases.getValue(),
request.getIncludes(),
ActionListener.wrap(
config -> listener.onResponse(responseBuilder.setModels(Collections.singletonList(config)).build()),
listener::onFailure
)
);
} else {
provider.getTrainedModels(
totalAndIds.v2(),
request.getIncludes(),
request.isAllowNoResources(),
ActionListener.wrap(configs -> listener.onResponse(responseBuilder.setModels(configs).build()), listener::onFailure)
);
}
}, listener::onFailure);
provider.expandIds(
request.getResourceId(),
request.isAllowNoResources(),
request.getPageParams(),
new HashSet<>(request.getTags()),
ModelAliasMetadata.fromState(clusterService.state()),
idExpansionListener
);
}
}
| apache-2.0 |
strapdata/elassandra | modules/parent-join/src/main/java/org/elasticsearch/join/aggregations/ParentToChildrenAggregator.java | 2501 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.join.aggregations;
import org.apache.lucene.search.Query;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.search.aggregations.Aggregator;
import org.elasticsearch.search.aggregations.AggregatorFactories;
import org.elasticsearch.search.aggregations.InternalAggregation;
import org.elasticsearch.search.aggregations.pipeline.PipelineAggregator;
import org.elasticsearch.search.aggregations.support.ValuesSource;
import org.elasticsearch.search.internal.SearchContext;
import java.io.IOException;
import java.util.List;
import java.util.Map;
public class ParentToChildrenAggregator extends ParentJoinAggregator {
static final ParseField TYPE_FIELD = new ParseField("type");
public ParentToChildrenAggregator(String name, AggregatorFactories factories,
SearchContext context, Aggregator parent, Query childFilter,
Query parentFilter, ValuesSource.Bytes.WithOrdinals valuesSource,
long maxOrd, List<PipelineAggregator> pipelineAggregators, Map<String, Object> metaData) throws IOException {
super(name, factories, context, parent, parentFilter, childFilter, valuesSource, maxOrd, pipelineAggregators, metaData);
}
@Override
public InternalAggregation buildAggregation(long owningBucketOrdinal) throws IOException {
return new InternalChildren(name, bucketDocCount(owningBucketOrdinal),
bucketAggregations(owningBucketOrdinal), pipelineAggregators(), metaData());
}
@Override
public InternalAggregation buildEmptyAggregation() {
return new InternalChildren(name, 0, buildEmptySubAggregations(), pipelineAggregators(),
metaData());
}
}
| apache-2.0 |
Chilledheart/chromium | content/public/android/java/src/org/chromium/content/browser/ChildProcessConnection.java | 5578 | // Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.content.browser;
import android.os.Bundle;
import org.chromium.content.common.IChildProcessCallback;
import org.chromium.content.common.IChildProcessService;
/**
* Manages a connection between the browser activity and a child service. ChildProcessConnection is
* responsible for estabilishing the connection (start()), closing it (stop()) and manipulating the
* bindings held onto the service (addStrongBinding(), removeStrongBinding(),
* removeInitialBinding()).
*/
public interface ChildProcessConnection {
/**
* Used to notify the consumer about disconnection of the service. This callback is provided
* earlier than ConnectionCallbacks below, as a child process might die before the connection is
* fully set up.
*/
interface DeathCallback {
void onChildProcessDied(ChildProcessConnection connection);
}
/**
* Used to notify the consumer about the connection being established.
*/
interface ConnectionCallback {
/**
* Called when the connection to the service is established.
* @param pid the pid of the child process
*/
void onConnected(int pid);
}
// Names of items placed in the bind intent or connection bundle.
public static final String EXTRA_COMMAND_LINE =
"com.google.android.apps.chrome.extra.command_line";
// Note the FDs may only be passed in the connection bundle.
public static final String EXTRA_FILES = "com.google.android.apps.chrome.extra.extraFiles";
// Used to pass the CPU core count to child processes.
public static final String EXTRA_CPU_COUNT =
"com.google.android.apps.chrome.extra.cpu_count";
// Used to pass the CPU features mask to child processes.
public static final String EXTRA_CPU_FEATURES =
"com.google.android.apps.chrome.extra.cpu_features";
int getServiceNumber();
boolean isInSandbox();
IChildProcessService getService();
/**
* @return the connection pid, or 0 if not yet connected
*/
int getPid();
/**
* Starts a connection to an IChildProcessService. This must be followed by a call to
* setupConnection() to setup the connection parameters. start() and setupConnection() are
* separate to allow to pass whatever parameters are available in start(), and complete the
* remainder later while reducing the connection setup latency.
* @param commandLine (optional) command line for the child process. If omitted, then
* the command line parameters must instead be passed to setupConnection().
*/
void start(String[] commandLine);
/**
* Setups the connection after it was started with start().
* @param commandLine (optional) will be ignored if the command line was already sent in start()
* @param filesToBeMapped a list of file descriptors that should be registered
* @param processCallback used for status updates regarding this process connection
* @param connectionCallback will be called exactly once after the connection is set up or the
* setup fails
*/
void setupConnection(
String[] commandLine,
FileDescriptorInfo[] filesToBeMapped,
IChildProcessCallback processCallback,
ConnectionCallback connectionCallback,
Bundle sharedRelros);
/**
* Terminates the connection to IChildProcessService, closing all bindings. It is safe to call
* this multiple times.
*/
void stop();
/** @return true iff the initial oom binding is currently bound. */
boolean isInitialBindingBound();
/** @return true iff the strong oom binding is currently bound. */
boolean isStrongBindingBound();
/**
* Called to remove the strong binding established when the connection was started. It is safe
* to call this multiple times.
*/
void removeInitialBinding();
/**
* For live connections, this returns true iff either the initial or the strong binding is
* bound, i.e. the connection has at least one oom binding. For connections that disconnected
* (did not exit properly), this returns true iff the connection had at least one oom binding
* when it disconnected.
*/
boolean isOomProtectedOrWasWhenDied();
/**
* Unbinds the bindings that protect the process from oom killing. It is safe to call this
* multiple times, before as well as after stop().
*/
void dropOomBindings();
/**
* Attaches a strong binding that will make the service as important as the main process. Each
* call should be succeeded by removeStrongBinding(), but multiple strong bindings can be
* requested and released independently.
*/
void addStrongBinding();
/**
* Called when the service is no longer in active use of the consumer.
*/
void removeStrongBinding();
/**
* Attaches a moderate binding that will give the service the priority of a visible process, but
* keep the priority below a strongly bound process.
*/
void addModerateBinding();
/**
* Called when the service is no longer in moderate use of the consumer.
*/
void removeModerateBinding();
/** @return true iff the moderate oom binding is currently bound. */
boolean isModerateBindingBound();
}
| bsd-3-clause |
asedunov/intellij-community | platform/platform-impl/src/com/intellij/openapi/diff/impl/incrementalMerge/SimpleChange.java | 3835 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.diff.impl.incrementalMerge;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.diff.impl.highlighting.FragmentSide;
import com.intellij.openapi.util.TextRange;
import org.jetbrains.annotations.NotNull;
class SimpleChange extends Change implements DiffRangeMarker.RangeInvalidListener{
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.diff.impl.incrementalMerge.Change");
private ChangeType myType;
private final SimpleChangeSide[] mySides;
private final ChangeList myChangeList;
SimpleChange(@NotNull ChangeType type, @NotNull TextRange range1, @NotNull TextRange range2, @NotNull ChangeList changeList) {
mySides = new SimpleChangeSide[]{ createSide(changeList, range1, FragmentSide.SIDE1),
createSide(changeList, range2, FragmentSide.SIDE2)};
myType = type;
myChangeList = changeList;
}
@NotNull
private SimpleChangeSide createSide(@NotNull ChangeList changeList, @NotNull TextRange range1, @NotNull FragmentSide side) {
return new SimpleChangeSide(side, new DiffRangeMarker(changeList.getDocument(side), range1, this));
}
/**
* Changes the given Side of a Change to a new text range.
* @param sideToChange Side to be changed.
* @param newRange New change range.
*/
@Override
protected void changeSide(@NotNull ChangeSide sideToChange, @NotNull DiffRangeMarker newRange) {
for (int i = 0; i < mySides.length; i++) {
SimpleChangeSide side = mySides[i];
if (side.equals(sideToChange)) {
mySides[i] = new SimpleChangeSide(sideToChange, newRange);
break;
}
}
}
@Override
protected void removeFromList() {
myChangeList.remove(this);
}
@Override
@NotNull
public ChangeSide getChangeSide(@NotNull FragmentSide side) {
return mySides[side.getIndex()];
}
@Override
public ChangeType getType() {
return myType;
}
@Override
public ChangeList getChangeList() {
return myChangeList;
}
@Override
public void onApplied() {
myType = ChangeType.deriveApplied(myType);
for (SimpleChangeSide side : mySides) {
ChangeHighlighterHolder highlighterHolder = side.getHighlighterHolder();
highlighterHolder.setActions(AnAction.EMPTY_ARRAY);
highlighterHolder.updateHighlighter(side, myType);
}
myChangeList.apply(this);
}
@Override
public void onRemovedFromList() {
for (int i = 0; i < mySides.length; i++) {
SimpleChangeSide side = mySides[i];
side.getRange().removeListener(this);
side.getHighlighterHolder().removeHighlighters();
mySides[i] = null;
}
}
@Override
public boolean isValid() {
LOG.assertTrue((mySides[0] == null) == (mySides[1] == null));
return mySides[0] != null;
}
@Override
public void onRangeInvalidated() {
myChangeList.remove(this);
}
static Change fromRanges(@NotNull TextRange baseRange, @NotNull TextRange versionRange, @NotNull ChangeList changeList) {
ChangeType type = ChangeType.fromRanges(baseRange, versionRange);
return new SimpleChange(type, baseRange, versionRange, changeList);
}
}
| apache-2.0 |
gemmellr/qpid-proton-j | proton-j/src/main/java/org/apache/qpid/proton/engine/impl/AmqpErrorException.java | 913 | /*
*
* 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.qpid.proton.engine.impl;
public class AmqpErrorException extends Exception
{
}
| apache-2.0 |
alonsod86/orientdb | tests/src/test/java/com/orientechnologies/orient/test/database/speed/IteratorSpeedTest.java | 1288 | package com.orientechnologies.orient.test.database.speed;
import org.testng.annotations.Test;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.iterator.ORecordIteratorClass;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.record.impl.ODocument;
/**
* @author Andrey Lomakin (a.lomakin-at-orientechnologies.com)
* @since 9/17/14
*/
@Test
public class IteratorSpeedTest {
public void testIterationSpeed() {
ODatabaseDocumentTx db = new ODatabaseDocumentTx("memory:speedTest");
db.create();
OClass oClass = db.getMetadata().getSchema().createClass("SpeedTest");
for (int i = 0; i < 1000000; i++) {
ODocument document = new ODocument("SpeedTest");
document.save();
}
ORecordIteratorClass iterator = new ORecordIteratorClass(db, db, "SpeedTest", true);
iterator.setRange(new ORecordId(oClass.getDefaultClusterId(), 999998), new ORecordId(oClass.getDefaultClusterId(), 999999));
long start = System.nanoTime();
while (iterator.hasNext())
iterator.next();
long end = System.nanoTime();
System.out.println(end - start);
db.drop();
}
}
| apache-2.0 |
tremes/testng | src/test/java/test/sanitycheck/CheckTestNamesTest.java | 2782 | package test.sanitycheck;
import java.util.Arrays;
import org.testng.Assert;
import org.testng.TestListenerAdapter;
import org.testng.TestNG;
import org.testng.TestNGException;
import org.testng.annotations.Test;
import org.testng.xml.XmlClass;
import org.testng.xml.XmlSuite;
import org.testng.xml.XmlTest;
import test.SimpleBaseTest;
public class CheckTestNamesTest extends SimpleBaseTest {
/**
* Child suites and same suite has two tests with same name
*/
@Test
public void checkWithChildSuites() {
runSuite("sanitycheck/test-a.xml");
}
/**
* Simple suite with two tests with same name
*/
@Test
public void checkWithoutChildSuites() {
runSuite("sanitycheck/test1.xml");
}
private void runSuite(String suitePath)
{
TestListenerAdapter tla = new TestListenerAdapter();
boolean exceptionRaised = false;
try {
TestNG tng = create();
String testngXmlPath = getPathToResource(suitePath);
tng.setTestSuites(Arrays.asList(testngXmlPath));
tng.addListener(tla);
tng.run();
} catch (TestNGException ex) {
exceptionRaised = true;
Assert.assertEquals(tla.getPassedTests().size(), 0);
Assert.assertEquals(tla.getFailedTests().size(), 0);
}
Assert.assertTrue(exceptionRaised);
}
/**
* Simple suite with no two tests with same name
*/
@Test
public void checkNoError() {
TestListenerAdapter tla = new TestListenerAdapter();
TestNG tng = create();
String testngXmlPath = getPathToResource("sanitycheck/test2.xml");
tng.setTestSuites(Arrays.asList(testngXmlPath));
tng.addListener(tla);
tng.run();
Assert.assertEquals(tla.getPassedTests().size(), 2);
}
/**
* Child suites and tests within different suites have same names
*/
@Test(enabled = false)
public void checkNoErrorWtihChildSuites() {
TestListenerAdapter tla = new TestListenerAdapter();
TestNG tng = create();
String testngXmlPath = getPathToResource("sanitycheck/test-b.xml");
tng.setTestSuites(Arrays.asList(testngXmlPath));
tng.addListener(tla);
tng.run();
Assert.assertEquals(tla.getPassedTests().size(), 4);
}
/**
* Checks that suites created programmatically also run as expected
*/
@Test
public void checkTestNamesForProgrammaticSuites() {
XmlSuite xmlSuite = new XmlSuite();
xmlSuite.setName("SanityCheckSuite");
XmlTest result = new XmlTest(xmlSuite);
result.getXmlClasses().add(new XmlClass(SampleTest1.class.getCanonicalName()));
result = new XmlTest(xmlSuite);
result.getXmlClasses().add(new XmlClass(SampleTest2.class.getCanonicalName()));
TestNG tng = new TestNG();
tng.setVerbose(0);
tng.setXmlSuites(Arrays.asList(new XmlSuite[] { xmlSuite }));
tng.run();
}
}
| apache-2.0 |
ThalaivaStars/OrgRepo1 | core/src/test/java/org/elasticsearch/search/aggregations/metrics/MaxTests.java | 13833 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.search.aggregations.metrics;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptService.ScriptType;
import org.elasticsearch.search.aggregations.bucket.global.Global;
import org.elasticsearch.search.aggregations.bucket.histogram.Histogram;
import org.elasticsearch.search.aggregations.metrics.max.Max;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
import static org.elasticsearch.search.aggregations.AggregationBuilders.global;
import static org.elasticsearch.search.aggregations.AggregationBuilders.histogram;
import static org.elasticsearch.search.aggregations.AggregationBuilders.max;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
/**
*
*/
public class MaxTests extends AbstractNumericTests {
@Override
@Test
public void testEmptyAggregation() throws Exception {
SearchResponse searchResponse = client().prepareSearch("empty_bucket_idx")
.setQuery(matchAllQuery())
.addAggregation(histogram("histo").field("value").interval(1l).minDocCount(0).subAggregation(max("max")))
.execute().actionGet();
assertThat(searchResponse.getHits().getTotalHits(), equalTo(2l));
Histogram histo = searchResponse.getAggregations().get("histo");
assertThat(histo, notNullValue());
Histogram.Bucket bucket = histo.getBuckets().get(1);
assertThat(bucket, notNullValue());
Max max = bucket.getAggregations().get("max");
assertThat(max, notNullValue());
assertThat(max.getName(), equalTo("max"));
assertThat(max.getValue(), equalTo(Double.NEGATIVE_INFINITY));
}
@Override
@Test
public void testUnmapped() throws Exception {
SearchResponse searchResponse = client().prepareSearch("idx_unmapped")
.setQuery(matchAllQuery())
.addAggregation(max("max").field("value"))
.execute().actionGet();
assertThat(searchResponse.getHits().getTotalHits(), equalTo(0l));
Max max = searchResponse.getAggregations().get("max");
assertThat(max, notNullValue());
assertThat(max.getName(), equalTo("max"));
assertThat(max.getValue(), equalTo(Double.NEGATIVE_INFINITY));
}
@Override
@Test
public void testSingleValuedField() throws Exception {
SearchResponse searchResponse = client().prepareSearch("idx")
.setQuery(matchAllQuery())
.addAggregation(max("max").field("value"))
.execute().actionGet();
assertThat(searchResponse.getHits().getTotalHits(), equalTo(10l));
Max max = searchResponse.getAggregations().get("max");
assertThat(max, notNullValue());
assertThat(max.getName(), equalTo("max"));
assertThat(max.getValue(), equalTo(10.0));
}
@Test
public void testSingleValuedField_WithFormatter() throws Exception {
SearchResponse searchResponse = client().prepareSearch("idx").setQuery(matchAllQuery())
.addAggregation(max("max").format("0000.0").field("value")).execute().actionGet();
assertThat(searchResponse.getHits().getTotalHits(), equalTo(10l));
Max max = searchResponse.getAggregations().get("max");
assertThat(max, notNullValue());
assertThat(max.getName(), equalTo("max"));
assertThat(max.getValue(), equalTo(10.0));
assertThat(max.getValueAsString(), equalTo("0010.0"));
}
@Override
@Test
public void testSingleValuedField_getProperty() throws Exception {
SearchResponse searchResponse = client().prepareSearch("idx").setQuery(matchAllQuery())
.addAggregation(global("global").subAggregation(max("max").field("value"))).execute().actionGet();
assertThat(searchResponse.getHits().getTotalHits(), equalTo(10l));
Global global = searchResponse.getAggregations().get("global");
assertThat(global, notNullValue());
assertThat(global.getName(), equalTo("global"));
assertThat(global.getDocCount(), equalTo(10l));
assertThat(global.getAggregations(), notNullValue());
assertThat(global.getAggregations().asMap().size(), equalTo(1));
Max max = global.getAggregations().get("max");
assertThat(max, notNullValue());
assertThat(max.getName(), equalTo("max"));
double expectedMaxValue = 10.0;
assertThat(max.getValue(), equalTo(expectedMaxValue));
assertThat((Max) global.getProperty("max"), equalTo(max));
assertThat((double) global.getProperty("max.value"), equalTo(expectedMaxValue));
assertThat((double) max.getProperty("value"), equalTo(expectedMaxValue));
}
@Override
@Test
public void testSingleValuedField_PartiallyUnmapped() throws Exception {
SearchResponse searchResponse = client().prepareSearch("idx", "idx_unmapped")
.setQuery(matchAllQuery())
.addAggregation(max("max").field("value"))
.execute().actionGet();
assertThat(searchResponse.getHits().getTotalHits(), equalTo(10l));
Max max = searchResponse.getAggregations().get("max");
assertThat(max, notNullValue());
assertThat(max.getName(), equalTo("max"));
assertThat(max.getValue(), equalTo(10.0));
}
@Override
@Test
public void testSingleValuedField_WithValueScript() throws Exception {
SearchResponse searchResponse = client().prepareSearch("idx")
.setQuery(matchAllQuery())
.addAggregation(max("max").field("value").script(new Script("_value + 1")))
.execute().actionGet();
assertThat(searchResponse.getHits().getTotalHits(), equalTo(10l));
Max max = searchResponse.getAggregations().get("max");
assertThat(max, notNullValue());
assertThat(max.getName(), equalTo("max"));
assertThat(max.getValue(), equalTo(11.0));
}
@Override
@Test
public void testSingleValuedField_WithValueScript_WithParams() throws Exception {
Map<String, Object> params = new HashMap<>();
params.put("inc", 1);
SearchResponse searchResponse = client().prepareSearch("idx")
.setQuery(matchAllQuery())
.addAggregation(max("max").field("value").script(new Script("_value + inc", ScriptType.INLINE, null, params)))
.execute().actionGet();
assertThat(searchResponse.getHits().getTotalHits(), equalTo(10l));
Max max = searchResponse.getAggregations().get("max");
assertThat(max, notNullValue());
assertThat(max.getName(), equalTo("max"));
assertThat(max.getValue(), equalTo(11.0));
}
@Override
@Test
public void testMultiValuedField() throws Exception {
SearchResponse searchResponse = client().prepareSearch("idx")
.setQuery(matchAllQuery())
.addAggregation(max("max").field("values"))
.execute().actionGet();
assertThat(searchResponse.getHits().getTotalHits(), equalTo(10l));
Max max = searchResponse.getAggregations().get("max");
assertThat(max, notNullValue());
assertThat(max.getName(), equalTo("max"));
assertThat(max.getValue(), equalTo(12.0));
}
@Override
@Test
public void testMultiValuedField_WithValueScript() throws Exception {
SearchResponse searchResponse = client().prepareSearch("idx")
.setQuery(matchAllQuery())
.addAggregation(max("max").field("values").script(new Script("_value + 1")))
.execute().actionGet();
assertThat(searchResponse.getHits().getTotalHits(), equalTo(10l));
Max max = searchResponse.getAggregations().get("max");
assertThat(max, notNullValue());
assertThat(max.getName(), equalTo("max"));
assertThat(max.getValue(), equalTo(13.0));
}
@Override
@Test
public void testMultiValuedField_WithValueScript_WithParams() throws Exception {
Map<String, Object> params = new HashMap<>();
params.put("inc", 1);
SearchResponse searchResponse = client().prepareSearch("idx")
.setQuery(matchAllQuery())
.addAggregation(max("max").field("values").script(new Script("_value + inc", ScriptType.INLINE, null, params)))
.execute().actionGet();
assertThat(searchResponse.getHits().getTotalHits(), equalTo(10l));
Max max = searchResponse.getAggregations().get("max");
assertThat(max, notNullValue());
assertThat(max.getName(), equalTo("max"));
assertThat(max.getValue(), equalTo(13.0));
}
@Override
@Test
public void testScript_SingleValued() throws Exception {
SearchResponse searchResponse = client().prepareSearch("idx")
.setQuery(matchAllQuery())
.addAggregation(max("max").script(new Script("doc['value'].value")))
.execute().actionGet();
assertThat(searchResponse.getHits().getTotalHits(), equalTo(10l));
Max max = searchResponse.getAggregations().get("max");
assertThat(max, notNullValue());
assertThat(max.getName(), equalTo("max"));
assertThat(max.getValue(), equalTo(10.0));
}
@Override
@Test
public void testScript_SingleValued_WithParams() throws Exception {
Map<String, Object> params = new HashMap<>();
params.put("inc", 1);
SearchResponse searchResponse = client().prepareSearch("idx")
.setQuery(matchAllQuery())
.addAggregation(max("max").script(new Script("doc['value'].value + inc", ScriptType.INLINE, null, params)))
.execute().actionGet();
assertThat(searchResponse.getHits().getTotalHits(), equalTo(10l));
Max max = searchResponse.getAggregations().get("max");
assertThat(max, notNullValue());
assertThat(max.getName(), equalTo("max"));
assertThat(max.getValue(), equalTo(11.0));
}
@Override
@Test
public void testScript_ExplicitSingleValued_WithParams() throws Exception {
Map<String, Object> params = new HashMap<>();
params.put("inc", 1);
SearchResponse searchResponse = client().prepareSearch("idx")
.setQuery(matchAllQuery())
.addAggregation(max("max").script(new Script("doc['value'].value + inc", ScriptType.INLINE, null, params)))
.execute().actionGet();
assertThat(searchResponse.getHits().getTotalHits(), equalTo(10l));
Max max = searchResponse.getAggregations().get("max");
assertThat(max, notNullValue());
assertThat(max.getName(), equalTo("max"));
assertThat(max.getValue(), equalTo(11.0));
}
@Override
@Test
public void testScript_MultiValued() throws Exception {
SearchResponse searchResponse = client().prepareSearch("idx")
.setQuery(matchAllQuery())
.addAggregation(max("max").script(new Script("doc['values'].values")))
.execute().actionGet();
assertThat(searchResponse.getHits().getTotalHits(), equalTo(10l));
Max max = searchResponse.getAggregations().get("max");
assertThat(max, notNullValue());
assertThat(max.getName(), equalTo("max"));
assertThat(max.getValue(), equalTo(12.0));
}
@Override
@Test
public void testScript_ExplicitMultiValued() throws Exception {
SearchResponse searchResponse = client().prepareSearch("idx")
.setQuery(matchAllQuery())
.addAggregation(max("max").script(new Script("doc['values'].values")))
.execute().actionGet();
assertThat(searchResponse.getHits().getTotalHits(), equalTo(10l));
Max max = searchResponse.getAggregations().get("max");
assertThat(max, notNullValue());
assertThat(max.getName(), equalTo("max"));
assertThat(max.getValue(), equalTo(12.0));
}
@Override
@Test
public void testScript_MultiValued_WithParams() throws Exception {
Map<String, Object> params = new HashMap<>();
params.put("inc", 1);
SearchResponse searchResponse = client().prepareSearch("idx").setQuery(matchAllQuery())
.addAggregation(
max("max").script(new Script("[ doc['value'].value, doc['value'].value + inc ]", ScriptType.INLINE, null, params)))
.execute().actionGet();
assertThat(searchResponse.getHits().getTotalHits(), equalTo(10l));
Max max = searchResponse.getAggregations().get("max");
assertThat(max, notNullValue());
assertThat(max.getName(), equalTo("max"));
assertThat(max.getValue(), equalTo(11.0));
}
} | apache-2.0 |
dosoudil/jboss-eap-quickstarts | kitchensink-jsp/src/main/java/org/jboss/as/quickstarts/kitchensinkjsp/controller/MemberRegistration.java | 2559 | /*
* 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.jboss.as.quickstarts.kitchensinkjsp.controller;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.ejb.Stateful;
import javax.enterprise.event.Event;
import javax.enterprise.inject.Model;
import javax.enterprise.inject.Produces;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;
import org.jboss.as.quickstarts.kitchensinkjsp.model.Member;
// The @Stateful annotation eliminates the need for manual transaction demarcation
@Stateful
// The @Model stereotype is a convenience mechanism to make this a request-scoped bean that has an
// EL name
// Read more about the @Model stereotype in this FAQ:
// http://sfwk.org/Documentation/WhatIsThePurposeOfTheModelAnnotation
@Model
public class MemberRegistration {
@Inject
private Logger log;
@Inject
private EntityManager em;
@Inject
private Event<Member> memberEventSrc;
private Member newMember;
@Produces
@Named
public Member getNewMember() {
log.info("getNewMember: called" + newMember);
return newMember;
}
public void register() throws Exception {
try {
log.info("Registering " + newMember.getName());
em.persist(newMember);
memberEventSrc.fire(newMember);
initNewMember();
} catch (Exception e) {
Throwable t = e;
while ((t.getCause()) != null) {
t = t.getCause();
}
log.info("Exception:" + t.getMessage());
throw ((Exception) t);
}
}
@PostConstruct
public void initNewMember() {
newMember = new Member();
log.info("@PostConstruct:initNewMember called");
}
}
| apache-2.0 |
mumer92/libgdx | backends/gdx-backend-robovm/src/com/badlogic/gdx/backends/iosrobovm/IOSInput.java | 21073 | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.badlogic.gdx.backends.iosrobovm;
import org.robovm.apple.audiotoolbox.AudioServices;
import org.robovm.apple.coregraphics.CGPoint;
import org.robovm.apple.coregraphics.CGRect;
import org.robovm.apple.foundation.NSExtensions;
import org.robovm.apple.foundation.NSObject;
import org.robovm.apple.foundation.NSRange;
import org.robovm.apple.uikit.UIAlertView;
import org.robovm.apple.uikit.UIAlertViewDelegate;
import org.robovm.apple.uikit.UIAlertViewDelegateAdapter;
import org.robovm.apple.uikit.UIAlertViewStyle;
import org.robovm.apple.uikit.UIApplication;
import org.robovm.apple.uikit.UIDevice;
import org.robovm.apple.uikit.UIEvent;
import org.robovm.apple.uikit.UIInterfaceOrientation;
import org.robovm.apple.uikit.UIKeyboardType;
import org.robovm.apple.uikit.UIReturnKeyType;
import org.robovm.apple.uikit.UITextAutocapitalizationType;
import org.robovm.apple.uikit.UITextAutocorrectionType;
import org.robovm.apple.uikit.UITextField;
import org.robovm.apple.uikit.UITextFieldDelegate;
import org.robovm.apple.uikit.UITextFieldDelegateAdapter;
import org.robovm.apple.uikit.UITextSpellCheckingType;
import org.robovm.apple.uikit.UITouch;
import org.robovm.apple.uikit.UITouchPhase;
import org.robovm.objc.annotation.Method;
import org.robovm.rt.VM;
import org.robovm.rt.bro.NativeObject;
import org.robovm.rt.bro.annotation.MachineSizedUInt;
import org.robovm.rt.bro.annotation.Pointer;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.backends.iosrobovm.custom.UIAcceleration;
import com.badlogic.gdx.backends.iosrobovm.custom.UIAccelerometer;
import com.badlogic.gdx.backends.iosrobovm.custom.UIAccelerometerDelegate;
import com.badlogic.gdx.backends.iosrobovm.custom.UIAccelerometerDelegateAdapter;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.badlogic.gdx.utils.Pool;
public class IOSInput implements Input {
static final int MAX_TOUCHES = 20;
private static class NSObjectWrapper<T extends NSObject> {
private static final long HANDLE_OFFSET;
static {
try {
HANDLE_OFFSET = VM.getInstanceFieldOffset(VM.getFieldAddress(NativeObject.class.getDeclaredField("handle")));
} catch (Throwable t) {
throw new Error(t);
}
}
private final T instance;
public NSObjectWrapper (Class<T> cls) {
instance = VM.allocateObject(cls);
}
public T wrap (long handle) {
VM.setLong(VM.getObjectAddress(instance) + HANDLE_OFFSET, handle);
return instance;
}
}
private static final NSObjectWrapper<UITouch> UI_TOUCH_WRAPPER = new NSObjectWrapper<UITouch>(UITouch.class);
static final NSObjectWrapper<UIAcceleration> UI_ACCELERATION_WRAPPER = new NSObjectWrapper<UIAcceleration>(UIAcceleration.class);
IOSApplication app;
IOSApplicationConfiguration config;
int[] deltaX = new int[MAX_TOUCHES];
int[] deltaY = new int[MAX_TOUCHES];
int[] touchX = new int[MAX_TOUCHES];
int[] touchY = new int[MAX_TOUCHES];
// we store the pointer to the UITouch struct here, or 0
long[] touchDown = new long[MAX_TOUCHES];
int numTouched = 0;
boolean justTouched = false;
Pool<TouchEvent> touchEventPool = new Pool<TouchEvent>() {
@Override
protected TouchEvent newObject () {
return new TouchEvent();
}
};
Array<TouchEvent> touchEvents = new Array<TouchEvent>();
TouchEvent currentEvent = null;
float[] acceleration = new float[3];
float[] rotation = new float[3];
float[] R = new float[9];
InputProcessor inputProcessor = null;
boolean hasVibrator;
//CMMotionManager motionManager;
UIAccelerometerDelegate accelerometerDelegate;
boolean compassSupported;
boolean keyboardCloseOnReturn;
public IOSInput (IOSApplication app) {
this.app = app;
this.config = app.config;
this.keyboardCloseOnReturn = app.config.keyboardCloseOnReturn;
}
void setupPeripherals () {
//motionManager = new CMMotionManager();
setupAccelerometer();
setupCompass();
UIDevice device = UIDevice.getCurrentDevice();
if (device.getModel().equalsIgnoreCase("iphone")) hasVibrator = true;
}
private void setupCompass () {
if (config.useCompass) {
//setupMagnetometer();
}
}
private void setupAccelerometer () {
if (config.useAccelerometer) {
accelerometerDelegate = new UIAccelerometerDelegateAdapter() {
@Method(selector = "accelerometer:didAccelerate:")
public void didAccelerate (UIAccelerometer accelerometer, @Pointer long valuesPtr) {
UIAcceleration values = UI_ACCELERATION_WRAPPER.wrap(valuesPtr);
float x = (float)values.getX() * 10;
float y = (float)values.getY() * 10;
float z = (float)values.getZ() * 10;
acceleration[0] = -x;
acceleration[1] = -y;
acceleration[2] = -z;
}
};
UIAccelerometer.getSharedAccelerometer().setDelegate(accelerometerDelegate);
UIAccelerometer.getSharedAccelerometer().setUpdateInterval(config.accelerometerUpdate);
}
}
// need to retain a reference so GC doesn't get right of the
// object passed to the native thread
// VoidBlock2<CMAccelerometerData, NSError> accelVoid = null;
// private void setupAccelerometer () {
// if (config.useAccelerometer) {
// motionManager.setAccelerometerUpdateInterval(config.accelerometerUpdate);
// accelVoid = new VoidBlock2<CMAccelerometerData, NSError>() {
// @Override
// public void invoke(CMAccelerometerData accelData, NSError error) {
// updateAccelerometer(accelData);
// }
// };
// motionManager.startAccelerometerUpdates(new NSOperationQueue(), accelVoid);
// }
// }
// need to retain a reference so GC doesn't get right of the
// object passed to the native thread
// VoidBlock2<CMMagnetometerData, NSError> magnetVoid = null;
// private void setupMagnetometer () {
// if (motionManager.isMagnetometerAvailable() && config.useCompass) compassSupported = true;
// else return;
// motionManager.setMagnetometerUpdateInterval(config.magnetometerUpdate);
// magnetVoid = new VoidBlock2<CMMagnetometerData, NSError>() {
// @Override
// public void invoke(CMMagnetometerData magnetData, NSError error) {
// updateRotation(magnetData);
// }
// };
// motionManager.startMagnetometerUpdates(new NSOperationQueue(), magnetVoid);
// }
// private void updateAccelerometer (CMAccelerometerData data) {
// float x = (float) data.getAcceleration().x() * 10f;
// float y = (float) data.getAcceleration().y() * 10f;
// float z = (float) data.getAcceleration().z() * 10f;
// acceleration[0] = -x;
// acceleration[1] = -y;
// acceleration[2] = -z;
// }
//
// private void updateRotation (CMMagnetometerData data) {
// final float eX = (float) data.getMagneticField().x();
// final float eY = (float) data.getMagneticField().y();
// final float eZ = (float) data.getMagneticField().z();
//
// float gX = acceleration[0];
// float gY = acceleration[1];
// float gZ = acceleration[2];
//
// float cX = eY * gZ - eZ * gY;
// float cY = eZ * gX - eX * gZ;
// float cZ = eX * gY - eY * gX;
//
// final float normal = (float) Math.sqrt(cX * cX + cY * cY + cZ * cZ);
// final float invertC = 1.0f / normal;
// cX *= invertC;
// cY *= invertC;
// cZ *= invertC;
// final float invertG = 1.0f / (float) Math.sqrt(gX * gX + gY * gY + gZ * gZ);
// gX *= invertG;
// gY *= invertG;
// gZ *= invertG;
// final float mX = gY * cZ - gZ * cY;
// final float mY = gZ * cX - gX * cZ;
// final float mZ = gX * cY - gY * cX;
//
// R[0] = cX; R[1] = cY; R[2] = cZ;
// R[3] = mX; R[4] = mY; R[5] = mZ;
// R[6] = gX; R[7] = gY; R[8] = gZ;
//
// rotation[0] = (float) Math.atan2(R[1], R[4]) * MathUtils.radDeg;
// rotation[1] = (float) Math.asin(-R[7]) * MathUtils.radDeg;
// rotation[2] = (float) Math.atan2(-R[6], R[8]) * MathUtils.radDeg;
// }
@Override
public float getAccelerometerX () {
return acceleration[0];
}
@Override
public float getAccelerometerY () {
return acceleration[1];
}
@Override
public float getAccelerometerZ () {
return acceleration[2];
}
@Override
public float getAzimuth () {
if (!compassSupported) return 0;
return rotation[0];
}
@Override
public float getPitch () {
if (!compassSupported) return 0;
return rotation[1];
}
@Override
public float getRoll () {
if (!compassSupported) return 0;
return rotation[2];
}
@Override
public void getRotationMatrix (float[] matrix) {
if (matrix.length != 9) return;
//TODO implement when azimuth is fixed
}
@Override
public int getX () {
return touchX[0];
}
@Override
public int getX (int pointer) {
return touchX[pointer];
}
@Override
public int getDeltaX () {
return deltaX[0];
}
@Override
public int getDeltaX (int pointer) {
return deltaX[pointer];
}
@Override
public int getY () {
return touchY[0];
}
@Override
public int getY (int pointer) {
return touchY[pointer];
}
@Override
public int getDeltaY () {
return deltaY[0];
}
@Override
public int getDeltaY (int pointer) {
return deltaY[pointer];
}
@Override
public boolean isTouched () {
for (int pointer = 0; pointer < MAX_TOUCHES; pointer++) {
if (touchDown[pointer] != 0) {
return true;
}
}
return false;
}
@Override
public boolean justTouched () {
return justTouched;
}
@Override
public boolean isTouched (int pointer) {
return touchDown[pointer] != 0;
}
@Override
public boolean isButtonPressed (int button) {
return button == Buttons.LEFT && numTouched > 0;
}
@Override
public boolean isKeyPressed (int key) {
return false;
}
@Override
public boolean isKeyJustPressed (int key) {
return false;
}
@Override
public void getTextInput(TextInputListener listener, String title, String text, String hint) {
buildUIAlertView(listener, title, text, hint).show();
}
// hack for software keyboard support
// uses a hidden textfield to capture input
// see: http://www.badlogicgames.com/forum/viewtopic.php?f=17&t=11788
private class HiddenTextField extends UITextField {
public HiddenTextField (CGRect frame) {
super(frame);
setKeyboardType(UIKeyboardType.Default);
setReturnKeyType(UIReturnKeyType.Done);
setAutocapitalizationType(UITextAutocapitalizationType.None);
setAutocorrectionType(UITextAutocorrectionType.No);
setSpellCheckingType(UITextSpellCheckingType.No);
setHidden(true);
}
@Override
public void deleteBackward () {
app.input.inputProcessor.keyTyped((char)8);
super.deleteBackward();
Gdx.graphics.requestRendering();
}
}
private UITextField textfield = null;
private final UITextFieldDelegate textDelegate = new UITextFieldDelegateAdapter() {
@Override
public boolean shouldChangeCharacters (UITextField textField, NSRange range, String string) {
for (int i = 0; i < range.getLength(); i++) {
app.input.inputProcessor.keyTyped((char)8);
}
if (string.isEmpty()) {
if (range.getLength() > 0) Gdx.graphics.requestRendering();
return false;
}
char[] chars = new char[string.length()];
string.getChars(0, string.length(), chars, 0);
for (int i = 0; i < chars.length; i++) {
app.input.inputProcessor.keyTyped(chars[i]);
}
Gdx.graphics.requestRendering();
return true;
}
@Override
public boolean shouldEndEditing (UITextField textField) {
// Text field needs to have at least one symbol - so we can use backspace
textField.setText("x");
Gdx.graphics.requestRendering();
return true;
}
@Override
public boolean shouldReturn (UITextField textField) {
if (keyboardCloseOnReturn) setOnscreenKeyboardVisible(false);
app.input.inputProcessor.keyDown(Keys.ENTER);
app.input.inputProcessor.keyTyped((char)13);
Gdx.graphics.requestRendering();
return false;
}
};
@Override
public void setOnscreenKeyboardVisible (boolean visible) {
if (textfield == null) createDefaultTextField();
if (visible) {
textfield.becomeFirstResponder();
textfield.setDelegate(textDelegate);
} else {
textfield.resignFirstResponder();
}
}
/**
* Set the keyboard to close when the UITextField return key is pressed
* @param shouldClose Whether or not the keyboard should clsoe on return key press
*/
public void setKeyboardCloseOnReturnKey (boolean shouldClose) {
keyboardCloseOnReturn = shouldClose;
}
public UITextField getKeyboardTextField () {
if (textfield == null) createDefaultTextField();
return textfield;
}
private void createDefaultTextField () {
textfield = new UITextField(new CGRect(10, 10, 100, 50));
//Parameters
// Setting parameters
textfield.setKeyboardType(UIKeyboardType.Default);
textfield.setReturnKeyType(UIReturnKeyType.Done);
textfield.setAutocapitalizationType(UITextAutocapitalizationType.None);
textfield.setAutocorrectionType(UITextAutocorrectionType.No);
textfield.setSpellCheckingType(UITextSpellCheckingType.No);
textfield.setHidden(true);
// Text field needs to have at least one symbol - so we can use backspace
textfield.setText("x");
app.getUIViewController().getView().addSubview(textfield);
}
// Issue 773 indicates this may solve a premature GC issue
UIAlertViewDelegate delegate;
/** Builds an {@link UIAlertView} with an added {@link UITextField} for inputting text.
* @param listener Text input listener
* @param title Dialog title
* @param text Text for text field
* @return UiAlertView */
private UIAlertView buildUIAlertView (final TextInputListener listener, String title, String text, String placeholder) {
delegate = new UIAlertViewDelegateAdapter() {
@Override
public void clicked (UIAlertView view, long clicked) {
if (clicked == 0) {
// user clicked "Cancel" button
listener.canceled();
} else if (clicked == 1) {
// user clicked "Ok" button
UITextField textField = view.getTextField(0);
listener.input(textField.getText());
}
delegate = null;
}
@Override
public void cancel (UIAlertView view) {
listener.canceled();
delegate = null;
}
};
// build the view
final UIAlertView uiAlertView = new UIAlertView();
uiAlertView.setTitle(title);
uiAlertView.addButton("Cancel");
uiAlertView.addButton("Ok");
uiAlertView.setAlertViewStyle(UIAlertViewStyle.PlainTextInput);
uiAlertView.setDelegate(delegate);
UITextField textField = uiAlertView.getTextField(0);
textField.setPlaceholder(placeholder);
textField.setText(text);
return uiAlertView;
}
@Override
public void vibrate (int milliseconds) {
AudioServices.playSystemSound(4095);
}
@Override
public void vibrate (long[] pattern, int repeat) {
// FIXME implement this
}
@Override
public void cancelVibrate () {
// FIXME implement this
}
@Override
public long getCurrentEventTime () {
return currentEvent.timestamp;
}
@Override
public void setCatchBackKey (boolean catchBack) {
}
@Override
public boolean isCatchBackKey () {
return false;
}
@Override
public void setCatchMenuKey (boolean catchMenu) {
}
@Override
public void setInputProcessor (InputProcessor processor) {
this.inputProcessor = processor;
}
@Override
public InputProcessor getInputProcessor () {
return inputProcessor;
}
@Override
public boolean isPeripheralAvailable (Peripheral peripheral) {
if (peripheral == Peripheral.Accelerometer && config.useAccelerometer) return true;
if (peripheral == Peripheral.MultitouchScreen) return true;
if (peripheral == Peripheral.Vibrator) return hasVibrator;
if (peripheral == Peripheral.Compass) return compassSupported;
// if(peripheral == Peripheral.OnscreenKeyboard) return true;
return false;
}
@Override
public int getRotation () {
UIInterfaceOrientation orientation = app.graphics.viewController != null ? app.graphics.viewController
.getInterfaceOrientation() : UIApplication.getSharedApplication().getStatusBarOrientation();
// we measure orientation counter clockwise, just like on Android
if (orientation == UIInterfaceOrientation.Portrait) return 0;
if (orientation == UIInterfaceOrientation.LandscapeLeft) return 270;
if (orientation == UIInterfaceOrientation.PortraitUpsideDown) return 180;
if (orientation == UIInterfaceOrientation.LandscapeRight) return 90;
return 0;
}
@Override
public Orientation getNativeOrientation () {
return Orientation.Portrait;
}
@Override
public void setCursorCatched (boolean catched) {
}
@Override
public boolean isCursorCatched () {
return false;
}
@Override
public void setCursorPosition (int x, int y) {
}
public void touchDown (long touches, UIEvent event) {
toTouchEvents(touches, event);
Gdx.graphics.requestRendering();
}
public void touchUp (long touches, UIEvent event) {
toTouchEvents(touches, event);
Gdx.graphics.requestRendering();
}
public void touchMoved (long touches, UIEvent event) {
toTouchEvents(touches, event);
Gdx.graphics.requestRendering();
}
void processEvents () {
synchronized (touchEvents) {
justTouched = false;
for (TouchEvent event : touchEvents) {
currentEvent = event;
switch (event.phase) {
case Began:
if (inputProcessor != null) inputProcessor.touchDown(event.x, event.y, event.pointer, Buttons.LEFT);
if (numTouched == 1) justTouched = true;
break;
case Cancelled:
case Ended:
if (inputProcessor != null) inputProcessor.touchUp(event.x, event.y, event.pointer, Buttons.LEFT);
break;
case Moved:
case Stationary:
if (inputProcessor != null) inputProcessor.touchDragged(event.x, event.y, event.pointer);
break;
}
}
touchEventPool.freeAll(touchEvents);
touchEvents.clear();
}
}
private int getFreePointer () {
for (int i = 0; i < touchDown.length; i++) {
if (touchDown[i] == 0) return i;
}
throw new GdxRuntimeException("Couldn't find free pointer id!");
}
private int findPointer (UITouch touch) {
long ptr = touch.getHandle();
for (int i = 0; i < touchDown.length; i++) {
if (touchDown[i] == ptr) return i;
}
throw new GdxRuntimeException("Couldn't find pointer id for touch event!");
}
private static class NSSetExtensions extends NSExtensions {
@Method(selector = "allObjects")
public static native @Pointer long allObjects (@Pointer long thiz);
}
private static class NSArrayExtensions extends NSExtensions {
@Method(selector = "objectAtIndex:")
public static native @Pointer long objectAtIndex$ (@Pointer long thiz, @MachineSizedUInt long index);
@Method(selector = "count")
public static native @MachineSizedUInt long count (@Pointer long thiz);
}
private void toTouchEvents (long touches, UIEvent uiEvent) {
long array = NSSetExtensions.allObjects(touches);
int length = (int)NSArrayExtensions.count(array);
for (int i = 0; i < length; i++) {
long touchHandle = NSArrayExtensions.objectAtIndex$(array, i);
UITouch touch = UI_TOUCH_WRAPPER.wrap(touchHandle);
CGPoint loc = touch.getLocationInView(touch.getView());
synchronized (touchEvents) {
UITouchPhase phase = touch.getPhase();
TouchEvent event = touchEventPool.obtain();
event.x = (int)(loc.getX() * app.displayScaleFactor);
event.y = (int)(loc.getY() * app.displayScaleFactor);
event.phase = phase;
event.timestamp = (long)(touch.getTimestamp() * 1000000000);
touchEvents.add(event);
if (phase == UITouchPhase.Began) {
event.pointer = getFreePointer();
touchDown[event.pointer] = touch.getHandle();
touchX[event.pointer] = event.x;
touchY[event.pointer] = event.y;
deltaX[event.pointer] = 0;
deltaY[event.pointer] = 0;
numTouched++;
}
if (phase == UITouchPhase.Moved || phase == UITouchPhase.Stationary) {
event.pointer = findPointer(touch);
deltaX[event.pointer] = event.x - touchX[event.pointer];
deltaY[event.pointer] = event.y - touchY[event.pointer];
touchX[event.pointer] = event.x;
touchY[event.pointer] = event.y;
}
if (phase == UITouchPhase.Cancelled || phase == UITouchPhase.Ended) {
event.pointer = findPointer(touch);
touchDown[event.pointer] = 0;
touchX[event.pointer] = event.x;
touchY[event.pointer] = event.y;
deltaX[event.pointer] = 0;
deltaY[event.pointer] = 0;
numTouched--;
}
}
}
}
static class TouchEvent {
UITouchPhase phase;
long timestamp;
int x, y;
int pointer;
}
}
| apache-2.0 |
holisticon/camunda-bpm-platform | engine/src/main/java/org/camunda/bpm/engine/impl/calendar/MapBusinessCalendarManager.java | 1217 | /* 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.camunda.bpm.engine.impl.calendar;
import java.util.HashMap;
import java.util.Map;
/**
* @author Tom Baeyens
*/
public class MapBusinessCalendarManager implements BusinessCalendarManager {
private Map<String, BusinessCalendar> businessCalendars = new HashMap<String, BusinessCalendar>();
public BusinessCalendar getBusinessCalendar(String businessCalendarRef) {
return businessCalendars.get(businessCalendarRef);
}
public BusinessCalendarManager addBusinessCalendar(String businessCalendarRef, BusinessCalendar businessCalendar) {
businessCalendars.put(businessCalendarRef, businessCalendar);
return this;
}
}
| apache-2.0 |
qingsong-xu/Smack | smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/package-info.java | 686 | /**
*
* Copyright 2015 Florian Schmaus
*
* 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.
*/
/**
* TODO describe me.
*/
package org.jivesoftware.smackx.jingleold.mediaimpl;
| apache-2.0 |
cniesen/rice | rice-framework/krad-it/src/test/java/org/kuali/rice/krad/test/document/bo/SimpleAccount.java | 2291 | /**
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.rice.krad.test.document.bo;
import org.kuali.rice.krad.bo.DataObjectBase;
import org.kuali.rice.krad.data.jpa.PortableSequenceGenerator;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
/**
* Duplicate of {@link Account} which overrides {@link #getExtension()} to avoid
* automatic extension creation
*/
@Entity
@Table(name="TRV_ACCT")
public class SimpleAccount extends DataObjectBase {
@Id
@GeneratedValue(generator="TRVL_ID_SEQ")
@PortableSequenceGenerator(name="TRVL_ID_SEQ")
@Column(name="ACCT_NUM")
private String number;
@Column(name="ACCT_NAME")
private String name;
@Column(name="ACCT_FO_ID")
private Long amId;
@Transient
private Object extension;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public Long getAmId() {
return this.amId;
}
public void setAmId(Long id) {
System.err.println("Setting AmId from " + this.amId + " to " + id);
this.amId = id;
}
public Object getExtension() {
return extension;
}
public void setExtension(Object extension) {
this.extension = extension;
}
}
| apache-2.0 |
wscqs/Legou | ultimateandroid/src/main/java/com/marshalchen/common/commonUtils/basicUtils/CrashHandler.java | 6737 | package com.marshalchen.common.commonUtils.basicUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
import android.os.Environment;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
import com.marshalchen.common.commonUtils.logUtils.Logs;
import com.nostra13.universalimageloader.utils.StorageUtils;
/**
* Catch the uncaught exception
* Usage:
* CrashHandler crashHandler = CrashHandler.getInstance();
crashHandler.init(getApplicationContext(), "/crash/", "Something error,please try again");
*/
public class CrashHandler implements UncaughtExceptionHandler {
public static String TAG = "Chen";
String showMessage = "There is something wrong with the app.";
private UncaughtExceptionHandler mDefaultHandler;
private static CrashHandler INSTANCE = new CrashHandler();
private Context mContext;
private Map<String, String> infos = new HashMap<String, String>();
private SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
String crashFilePath = "/crash/";
private CrashHandler() {
}
/**
* Singleton
*/
public static CrashHandler getInstance() {
return INSTANCE;
}
/**
* Initialize
*
* @param context
* @param crashFilePath
*/
public void init(Context context, String crashFilePath, String showMessage) {
mContext = context;
mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(this);
// this.systemServiceObject = systemServiceObject;
this.crashFilePath = crashFilePath;
if (BasicUtils.judgeNotNull(showMessage)) {
this.showMessage = showMessage;
}
}
/**
* Initialize
*
* @param context
*/
public void init(Context context) {
init(context, "/crash/");
}
/**
* Initialize
*
* @param context
*/
public void init(Context context, String crashFilePath) {
init(context, crashFilePath, "");
}
/**
* Caught Exception
*/
@Override
public void uncaughtException(Thread thread, Throwable ex) {
if (!handleException(ex) && mDefaultHandler != null) {
mDefaultHandler.uncaughtException(thread, ex);
} else {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Logs.e("error : ", e);
}
Logs.d("uncaught exception is catched!");
System.exit(0);
android.os.Process.killProcess(android.os.Process.myPid());
}
}
private boolean handleException(Throwable ex) {
if (ex == null) {
return false;
}
new Thread() {
@Override
public void run() {
Looper.prepare();
Toast.makeText(mContext, showMessage, Toast.LENGTH_SHORT).show();
Looper.loop();
}
}.start();
collectDeviceInfo(mContext);
String filemameString = saveCrashInfo2File(ex);
Logs.d("filemameString", filemameString);
return true;
}
/**
* Collect Device info
*
* @param ctx
*/
public void collectDeviceInfo(Context ctx) {
try {
PackageManager pm = ctx.getPackageManager();
PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES);
if (pi != null) {
String versionName = pi.versionName == null ? "null" : pi.versionName;
String versionCode = pi.versionCode + "";
infos.put("versionName", versionName);
infos.put("versionCode", versionCode);
}
} catch (NameNotFoundException e) {
Logs.e("an error occured when collect package info", e);
}
Field[] fields = Build.class.getDeclaredFields();
for (Field field : fields) {
try {
field.setAccessible(true);
infos.put(field.getName(), field.get(null).toString());
Logs.d(field.getName() + " : " + field.get(null));
} catch (Exception e) {
Logs.e("an error occured when collect crash info", e);
}
}
}
/**
* Save Info to files
*
* @param ex
* @return filename
*/
private String saveCrashInfo2File(Throwable ex) {
StringBuffer sb = new StringBuffer();
for (Map.Entry<String, String> entry : infos.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
sb.append(key + "=" + value + "\n");
}
Writer writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
ex.printStackTrace(printWriter);
Throwable cause = ex.getCause();
while (cause != null) {
cause.printStackTrace(printWriter);
cause = cause.getCause();
}
printWriter.close();
String result = writer.toString();
sb.append(result);
try {
long timestamp = System.currentTimeMillis();
String time = formatter.format(new Date());
String fileName = "crash-" + time + "-" + timestamp + ".log";
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
String path =
//StorageUtils.getCacheDirectory(mContext) +
Environment.getExternalStorageDirectory().getAbsolutePath() +
(BasicUtils.judgeNotNull(crashFilePath) ? crashFilePath : "/crash/");
Logs.d("path----" + path);
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
FileOutputStream fos = new FileOutputStream(path + fileName);
fos.write(sb.toString().getBytes());
fos.close();
}
return fileName;
} catch (Exception e) {
Logs.e("an error occured while writing file...", e);
}
return null;
}
}
| apache-2.0 |
lburgazzoli/apache-camel | camel-core/src/main/java/org/apache/camel/processor/SetBodyProcessor.java | 3607 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.processor;
import org.apache.camel.AsyncCallback;
import org.apache.camel.AsyncProcessor;
import org.apache.camel.Exchange;
import org.apache.camel.Expression;
import org.apache.camel.Message;
import org.apache.camel.Traceable;
import org.apache.camel.impl.DefaultMessage;
import org.apache.camel.spi.IdAware;
import org.apache.camel.support.ServiceSupport;
import org.apache.camel.util.AsyncProcessorHelper;
import org.apache.camel.util.ExchangeHelper;
/**
* A processor which sets the body on the IN or OUT message with an {@link Expression}
*/
public class SetBodyProcessor extends ServiceSupport implements AsyncProcessor, Traceable, IdAware {
private String id;
private final Expression expression;
public SetBodyProcessor(Expression expression) {
this.expression = expression;
}
public void process(Exchange exchange) throws Exception {
AsyncProcessorHelper.process(this, exchange);
}
@Override
public boolean process(Exchange exchange, AsyncCallback callback) {
try {
Object newBody = expression.evaluate(exchange, Object.class);
if (exchange.getException() != null) {
// the expression threw an exception so we should break-out
callback.done(true);
return true;
}
boolean out = exchange.hasOut();
Message old = out ? exchange.getOut() : exchange.getIn();
// create a new message container so we do not drag specialized message objects along
// but that is only needed if the old message is a specialized message
boolean copyNeeded = !(old.getClass().equals(DefaultMessage.class));
if (copyNeeded) {
Message msg = new DefaultMessage();
msg.copyFromWithNewBody(old, newBody);
// replace message on exchange
ExchangeHelper.replaceMessage(exchange, msg, false);
} else {
// no copy needed so set replace value directly
old.setBody(newBody);
}
} catch (Throwable e) {
exchange.setException(e);
}
callback.done(true);
return true;
}
@Override
public String toString() {
return "SetBody(" + expression + ")";
}
public String getTraceLabel() {
return "setBody[" + expression + "]";
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Expression getExpression() {
return expression;
}
@Override
protected void doStart() throws Exception {
// noop
}
@Override
protected void doStop() throws Exception {
// noop
}
} | apache-2.0 |
rokn/Count_Words_2015 | testing/openjdk2/jdk/test/sun/security/ssl/com/sun/net/ssl/internal/ssl/SSLEngineImpl/SSLEngineDeadlock.java | 14248 | /*
* Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
// SunJSSE does not support dynamic system properties, no way to re-use
// system properties in samevm/agentvm mode.
/*
* @test
* @bug 6492872
* @summary Deadlock in SSLEngine
* @run main/othervm SSLEngineDeadlock
* @author Brad R. Wetmore
*/
/**
* A SSLEngine usage example which simplifies the presentation
* by removing the I/O and multi-threading concerns.
*
* The test creates two SSLEngines, simulating a client and server.
* The "transport" layer consists two byte buffers: think of them
* as directly connected pipes.
*
* Note, this is a *very* simple example: real code will be much more
* involved. For example, different threading and I/O models could be
* used, transport mechanisms could close unexpectedly, and so on.
*
* When this application runs, notice that several messages
* (wrap/unwrap) pass before any application data is consumed or
* produced. (For more information, please see the SSL/TLS
* specifications.) There may several steps for a successful handshake,
* so it's typical to see the following series of operations:
*
* client server message
* ====== ====== =======
* wrap() ... ClientHello
* ... unwrap() ClientHello
* ... wrap() ServerHello/Certificate
* unwrap() ... ServerHello/Certificate
* wrap() ... ClientKeyExchange
* wrap() ... ChangeCipherSpec
* wrap() ... Finished
* ... unwrap() ClientKeyExchange
* ... unwrap() ChangeCipherSpec
* ... unwrap() Finished
* ... wrap() ChangeCipherSpec
* ... wrap() Finished
* unwrap() ... ChangeCipherSpec
* unwrap() ... Finished
*/
import javax.net.ssl.*;
import javax.net.ssl.SSLEngineResult.*;
import java.io.*;
import java.security.*;
import java.nio.*;
import java.lang.management.*;
public class SSLEngineDeadlock {
/*
* Enables logging of the SSLEngine operations.
*/
private static boolean logging = false;
/*
* Enables the JSSE system debugging system property:
*
* -Djavax.net.debug=all
*
* This gives a lot of low-level information about operations underway,
* including specific handshake messages, and might be best examined
* after gaining some familiarity with this application.
*/
private static boolean debug = false;
private SSLContext sslc;
private SSLEngine clientEngine; // client Engine
private ByteBuffer clientOut; // write side of clientEngine
private ByteBuffer clientIn; // read side of clientEngine
private SSLEngine serverEngine; // server Engine
private ByteBuffer serverOut; // write side of serverEngine
private ByteBuffer serverIn; // read side of serverEngine
private volatile boolean testDone = false;
/*
* For data transport, this example uses local ByteBuffers. This
* isn't really useful, but the purpose of this example is to show
* SSLEngine concepts, not how to do network transport.
*/
private ByteBuffer cTOs; // "reliable" transport client->server
private ByteBuffer sTOc; // "reliable" transport server->client
/*
* The following is to set up the keystores.
*/
private static String pathToStores = "../../../../../../../etc";
private static String keyStoreFile = "keystore";
private static String trustStoreFile = "truststore";
private static String passwd = "passphrase";
private static String keyFilename =
System.getProperty("test.src", ".") + "/" + pathToStores +
"/" + keyStoreFile;
private static String trustFilename =
System.getProperty("test.src", ".") + "/" + pathToStores +
"/" + trustStoreFile;
/*
* Main entry point for this test.
*/
public static void main(String args[]) throws Exception {
if (debug) {
System.setProperty("javax.net.debug", "all");
}
// Turn off logging, and only output the test iteration to keep
// the noise down.
for (int i = 1; i <= 200; i++) {
if ((i % 5) == 0) {
System.out.println("Test #: " + i);
}
SSLEngineDeadlock test = new SSLEngineDeadlock();
test.runTest();
detectDeadLock();
}
System.out.println("Test Passed.");
}
/*
* Create an initialized SSLContext to use for these tests.
*/
public SSLEngineDeadlock() throws Exception {
KeyStore ks = KeyStore.getInstance("JKS");
KeyStore ts = KeyStore.getInstance("JKS");
char[] passphrase = "passphrase".toCharArray();
ks.load(new FileInputStream(keyFilename), passphrase);
ts.load(new FileInputStream(trustFilename), passphrase);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, passphrase);
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(ts);
SSLContext sslCtx = SSLContext.getInstance("TLS");
sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
sslc = sslCtx;
}
/*
* Create a thread which simply spins on tasks. This will hopefully
* trigger a deadlock between the wrap/unwrap and the tasks. On our
* slow, single-CPU build machine (sol8), it was very repeatable.
*/
private void doTask() {
Runnable task;
while (!testDone) {
if ((task = clientEngine.getDelegatedTask()) != null) {
task.run();
}
if ((task = serverEngine.getDelegatedTask()) != null) {
task.run();
}
}
}
/*
* Run the test.
*
* Sit in a tight loop, both engines calling wrap/unwrap regardless
* of whether data is available or not. We do this until both engines
* report back they are closed.
*
* The main loop handles all of the I/O phases of the SSLEngine's
* lifetime:
*
* initial handshaking
* application data transfer
* engine closing
*
* One could easily separate these phases into separate
* sections of code.
*/
private void runTest() throws Exception {
boolean dataDone = false;
createSSLEngines();
createBuffers();
SSLEngineResult clientResult; // results from client's last operation
SSLEngineResult serverResult; // results from server's last operation
new Thread("SSLEngine Task Dispatcher") {
public void run() {
try {
doTask();
} catch (Exception e) {
System.err.println("Task thread died...test will hang");
}
}
}.start();
/*
* Examining the SSLEngineResults could be much more involved,
* and may alter the overall flow of the application.
*
* For example, if we received a BUFFER_OVERFLOW when trying
* to write to the output pipe, we could reallocate a larger
* pipe, but instead we wait for the peer to drain it.
*/
while (!isEngineClosed(clientEngine) ||
!isEngineClosed(serverEngine)) {
log("================");
clientResult = clientEngine.wrap(clientOut, cTOs);
log("client wrap: ", clientResult);
serverResult = serverEngine.wrap(serverOut, sTOc);
log("server wrap: ", serverResult);
cTOs.flip();
sTOc.flip();
log("----");
clientResult = clientEngine.unwrap(sTOc, clientIn);
log("client unwrap: ", clientResult);
serverResult = serverEngine.unwrap(cTOs, serverIn);
log("server unwrap: ", serverResult);
cTOs.compact();
sTOc.compact();
/*
* After we've transfered all application data between the client
* and server, we close the clientEngine's outbound stream.
* This generates a close_notify handshake message, which the
* server engine receives and responds by closing itself.
*/
if (!dataDone && (clientOut.limit() == serverIn.position()) &&
(serverOut.limit() == clientIn.position())) {
/*
* A sanity check to ensure we got what was sent.
*/
checkTransfer(serverOut, clientIn);
checkTransfer(clientOut, serverIn);
log("\tClosing clientEngine's *OUTBOUND*...");
clientEngine.closeOutbound();
dataDone = true;
}
}
testDone = true;
}
/*
* Using the SSLContext created during object creation,
* create/configure the SSLEngines we'll use for this test.
*/
private void createSSLEngines() throws Exception {
/*
* Configure the serverEngine to act as a server in the SSL/TLS
* handshake. Also, require SSL client authentication.
*/
serverEngine = sslc.createSSLEngine();
serverEngine.setUseClientMode(false);
serverEngine.setNeedClientAuth(true);
/*
* Similar to above, but using client mode instead.
*/
clientEngine = sslc.createSSLEngine("client", 80);
clientEngine.setUseClientMode(true);
}
/*
* Create and size the buffers appropriately.
*/
private void createBuffers() {
/*
* We'll assume the buffer sizes are the same
* between client and server.
*/
SSLSession session = clientEngine.getSession();
int appBufferMax = session.getApplicationBufferSize();
int netBufferMax = session.getPacketBufferSize();
/*
* We'll make the input buffers a bit bigger than the max needed
* size, so that unwrap()s following a successful data transfer
* won't generate BUFFER_OVERFLOWS.
*
* We'll use a mix of direct and indirect ByteBuffers for
* tutorial purposes only. In reality, only use direct
* ByteBuffers when they give a clear performance enhancement.
*/
clientIn = ByteBuffer.allocate(appBufferMax + 50);
serverIn = ByteBuffer.allocate(appBufferMax + 50);
cTOs = ByteBuffer.allocateDirect(netBufferMax);
sTOc = ByteBuffer.allocateDirect(netBufferMax);
clientOut = ByteBuffer.wrap("Hi Server, I'm Client".getBytes());
serverOut = ByteBuffer.wrap("Hello Client, I'm Server".getBytes());
}
private static boolean isEngineClosed(SSLEngine engine) {
return (engine.isOutboundDone() && engine.isInboundDone());
}
/*
* Simple check to make sure everything came across as expected.
*/
private static void checkTransfer(ByteBuffer a, ByteBuffer b)
throws Exception {
a.flip();
b.flip();
if (!a.equals(b)) {
throw new Exception("Data didn't transfer cleanly");
} else {
log("\tData transferred cleanly");
}
a.position(a.limit());
b.position(b.limit());
a.limit(a.capacity());
b.limit(b.capacity());
}
/*
* Detect dead lock
*/
private static void detectDeadLock() throws Exception {
ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
long[] threadIds = threadBean.findDeadlockedThreads();
if (threadIds != null && threadIds.length != 0) {
for (long id : threadIds) {
ThreadInfo info =
threadBean.getThreadInfo(id, Integer.MAX_VALUE);
System.out.println("Deadlocked ThreadInfo: " + info);
}
throw new Exception("Found Deadlock!");
}
}
/*
* Logging code
*/
private static boolean resultOnce = true;
private static void log(String str, SSLEngineResult result) {
if (!logging) {
return;
}
if (resultOnce) {
resultOnce = false;
System.out.println("The format of the SSLEngineResult is: \n" +
"\t\"getStatus() / getHandshakeStatus()\" +\n" +
"\t\"bytesConsumed() / bytesProduced()\"\n");
}
HandshakeStatus hsStatus = result.getHandshakeStatus();
log(str +
result.getStatus() + "/" + hsStatus + ", " +
result.bytesConsumed() + "/" + result.bytesProduced() +
" bytes");
if (hsStatus == HandshakeStatus.FINISHED) {
log("\t...ready for application data");
}
}
private static void log(String str) {
if (logging) {
System.out.println(str);
}
}
}
| mit |
chiastic-security/phoenix-for-cloudera | phoenix-core/src/test/java/org/apache/phoenix/compile/QueryMetaDataTest.java | 25296 | /*
* 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.phoenix.compile;
import static org.apache.phoenix.util.TestUtil.PHOENIX_JDBC_URL;
import static org.junit.Assert.assertEquals;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSetMetaData;
import org.apache.phoenix.query.BaseConnectionlessQueryTest;
import org.apache.phoenix.util.PropertiesUtil;
import org.apache.phoenix.util.TestUtil;
import org.junit.Test;
/**
*
* Tests for getting PreparedStatement meta data
*
*
* @since 0.1
*/
public class QueryMetaDataTest extends BaseConnectionlessQueryTest {
@Test
public void testNoParameterMetaData() throws Exception {
String query = "SELECT a_string, b_string FROM atable WHERE organization_id='000000000000000'";
Connection conn = DriverManager.getConnection(getUrl(), PropertiesUtil.deepCopy(TestUtil.TEST_PROPERTIES));
PreparedStatement statement = conn.prepareStatement(query);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(0, pmd.getParameterCount());
}
@Test
public void testCaseInsensitive() throws Exception {
String query = "SELECT A_string, b_striNG FROM ataBle WHERE ORGANIZATION_ID='000000000000000'";
Connection conn = DriverManager.getConnection(getUrl(), PropertiesUtil.deepCopy(TestUtil.TEST_PROPERTIES));
PreparedStatement statement = conn.prepareStatement(query);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(0, pmd.getParameterCount());
}
@Test
public void testParameterMetaData() throws Exception {
String query = "SELECT a_string, b_string FROM atable WHERE organization_id=? and (a_integer = ? or a_date = ? or b_string = ? or a_string = 'foo')";
Connection conn = DriverManager.getConnection(getUrl(), PropertiesUtil.deepCopy(TestUtil.TEST_PROPERTIES));
PreparedStatement statement = conn.prepareStatement(query);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(4, pmd.getParameterCount());
assertEquals(String.class.getName(), pmd.getParameterClassName(1));
assertEquals(Integer.class.getName(), pmd.getParameterClassName(2));
assertEquals(Date.class.getName(), pmd.getParameterClassName(3));
assertEquals(String.class.getName(), pmd.getParameterClassName(4));
}
@Test
public void testUpsertParameterMetaData() throws Exception {
String query = "UPSERT INTO atable VALUES (?, ?, ?, ?, ?)";
Connection conn = DriverManager.getConnection(getUrl(), PropertiesUtil.deepCopy(TestUtil.TEST_PROPERTIES));
PreparedStatement statement = conn.prepareStatement(query);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(5, pmd.getParameterCount());
assertEquals(String.class.getName(), pmd.getParameterClassName(1));
assertEquals(String.class.getName(), pmd.getParameterClassName(2));
assertEquals(String.class.getName(), pmd.getParameterClassName(3));
assertEquals(String.class.getName(), pmd.getParameterClassName(4));
assertEquals(Integer.class.getName(), pmd.getParameterClassName(5));
}
@Test
public void testToDateFunctionMetaData() throws Exception {
String query = "SELECT a_string, b_string FROM atable WHERE a_date > to_date(?)";
Connection conn = DriverManager.getConnection(getUrl(), PropertiesUtil.deepCopy(TestUtil.TEST_PROPERTIES));
PreparedStatement statement = conn.prepareStatement(query);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(1, pmd.getParameterCount());
assertEquals(String.class.getName(), pmd.getParameterClassName(1));
}
@Test
public void testLimitParameterMetaData() throws Exception {
String query = "SELECT a_string, b_string FROM atable WHERE organization_id=? and a_string = 'foo' LIMIT ?";
Connection conn = DriverManager.getConnection(getUrl(), PropertiesUtil.deepCopy(TestUtil.TEST_PROPERTIES));
PreparedStatement statement = conn.prepareStatement(query);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(2, pmd.getParameterCount());
assertEquals(String.class.getName(), pmd.getParameterClassName(1));
assertEquals(Integer.class.getName(), pmd.getParameterClassName(2));
}
@Test
public void testRoundParameterMetaData() throws Exception {
String query = "SELECT a_string, b_string FROM atable WHERE round(a_date,'day', ?) = ?";
Connection conn = DriverManager.getConnection(getUrl(), PropertiesUtil.deepCopy(TestUtil.TEST_PROPERTIES));
PreparedStatement statement = conn.prepareStatement(query);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(2, pmd.getParameterCount());
assertEquals(Integer.class.getName(), pmd.getParameterClassName(1));
assertEquals(Date.class.getName(), pmd.getParameterClassName(2));
}
@Test
public void testInListParameterMetaData1() throws Exception {
String query = "SELECT a_string, b_string FROM atable WHERE a_string IN (?, ?)";
Connection conn = DriverManager.getConnection(getUrl(), PropertiesUtil.deepCopy(TestUtil.TEST_PROPERTIES));
PreparedStatement statement = conn.prepareStatement(query);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(2, pmd.getParameterCount());
assertEquals(String.class.getName(), pmd.getParameterClassName(1));
assertEquals(String.class.getName(), pmd.getParameterClassName(2));
}
@Test
public void testInListParameterMetaData2() throws Exception {
String query = "SELECT a_string, b_string FROM atable WHERE ? IN (2.2, 3)";
Connection conn = DriverManager.getConnection(getUrl(), PropertiesUtil.deepCopy(TestUtil.TEST_PROPERTIES));
PreparedStatement statement = conn.prepareStatement(query);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(1, pmd.getParameterCount());
assertEquals(BigDecimal.class.getName(), pmd.getParameterClassName(1));
}
@Test
public void testInListParameterMetaData3() throws Exception {
String query = "SELECT a_string, b_string FROM atable WHERE ? IN ('foo')";
Connection conn = DriverManager.getConnection(getUrl(), PropertiesUtil.deepCopy(TestUtil.TEST_PROPERTIES));
PreparedStatement statement = conn.prepareStatement(query);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(1, pmd.getParameterCount());
assertEquals(String.class.getName(), pmd.getParameterClassName(1));
}
@Test
public void testInListParameterMetaData4() throws Exception {
String query = "SELECT a_string, b_string FROM atable WHERE ? IN (?, ?)";
Connection conn = DriverManager.getConnection(getUrl(), PropertiesUtil.deepCopy(TestUtil.TEST_PROPERTIES));
PreparedStatement statement = conn.prepareStatement(query);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(3, pmd.getParameterCount());
assertEquals(null, pmd.getParameterClassName(1));
assertEquals(null, pmd.getParameterClassName(2));
assertEquals(null, pmd.getParameterClassName(3));
}
@Test
public void testCaseMetaData() throws Exception {
String query1 = "SELECT a_string, b_string FROM atable WHERE case when a_integer = 1 then ? when a_integer > 2 then 2 end > 3";
Connection conn = DriverManager.getConnection(getUrl(), PropertiesUtil.deepCopy(TestUtil.TEST_PROPERTIES));
PreparedStatement statement = conn.prepareStatement(query1);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(1, pmd.getParameterCount());
assertEquals(BigDecimal.class.getName(), pmd.getParameterClassName(1));
assertEquals(ParameterMetaData.parameterNullable, pmd.isNullable(1));
String query2 = "SELECT a_string, b_string FROM atable WHERE case when a_integer = 1 then 1 when a_integer > 2 then 2 end > ?";
PreparedStatement statement2 = conn.prepareStatement(query2);
ParameterMetaData pmd2 = statement2.getParameterMetaData();
assertEquals(1, pmd2.getParameterCount());
assertEquals(Integer.class.getName(), pmd2.getParameterClassName(1));
assertEquals(ParameterMetaData.parameterNullable, pmd2.isNullable(1));
}
@Test
public void testSubstrParameterMetaData() throws Exception {
String query = "SELECT a_string, b_string FROM atable WHERE substr(a_string,?,?) = ?";
Connection conn = DriverManager.getConnection(getUrl(), PropertiesUtil.deepCopy(TestUtil.TEST_PROPERTIES));
PreparedStatement statement = conn.prepareStatement(query);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(3, pmd.getParameterCount());
assertEquals(Long.class.getName(), pmd.getParameterClassName(1));
assertEquals(Long.class.getName(), pmd.getParameterClassName(2));
assertEquals(String.class.getName(), pmd.getParameterClassName(3));
}
@Test
public void testKeyPrefixParameterMetaData() throws Exception {
String query = "SELECT a_string, b_string FROM atable WHERE organization_id='000000000000000' and substr(entity_id,1,3)=? and a_string = 'foo'";
Connection conn = DriverManager.getConnection(getUrl(), PropertiesUtil.deepCopy(TestUtil.TEST_PROPERTIES));
PreparedStatement statement = conn.prepareStatement(query);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(1, pmd.getParameterCount());
assertEquals(String.class.getName(), pmd.getParameterClassName(1));
}
@Test
public void testDateSubstractExpressionMetaData1() throws Exception {
String query = "SELECT entity_id,a_string FROM atable where a_date-2.5-?=a_date";
Connection conn = DriverManager.getConnection(getUrl(), PropertiesUtil.deepCopy(TestUtil.TEST_PROPERTIES));
PreparedStatement statement = conn.prepareStatement(query);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(1, pmd.getParameterCount());
assertEquals(BigDecimal.class.getName(), pmd.getParameterClassName(1));
}
@Test
public void testDateSubstractExpressionMetaData2() throws Exception {
String query = "SELECT entity_id,a_string FROM atable where a_date-?=a_date";
Connection conn = DriverManager.getConnection(getUrl(), PropertiesUtil.deepCopy(TestUtil.TEST_PROPERTIES));
PreparedStatement statement = conn.prepareStatement(query);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(1, pmd.getParameterCount());
// FIXME: Should really be Date, but we currently don't know if we're
// comparing to a date or a number where this is being calculated
// (which would disambiguate it).
assertEquals(null, pmd.getParameterClassName(1));
}
@Test
public void testDateSubstractExpressionMetaData3() throws Exception {
String query = "SELECT entity_id,a_string FROM atable where a_date-?=a_integer";
Connection conn = DriverManager.getConnection(getUrl(), PropertiesUtil.deepCopy(TestUtil.TEST_PROPERTIES));
PreparedStatement statement = conn.prepareStatement(query);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(1, pmd.getParameterCount());
// FIXME: Should really be Integer, but we currently don't know if we're
// comparing to a date or a number where this is being calculated
// (which would disambiguate it).
assertEquals(null, pmd.getParameterClassName(1));
}
@Test
public void testTwoDateSubstractExpressionMetaData() throws Exception {
String query = "SELECT entity_id,a_string FROM atable where ?-a_date=1";
Connection conn = DriverManager.getConnection(getUrl(), PropertiesUtil.deepCopy(TestUtil.TEST_PROPERTIES));
PreparedStatement statement = conn.prepareStatement(query);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(1, pmd.getParameterCount());
// We know this must be date - anything else would be an error
assertEquals(Date.class.getName(), pmd.getParameterClassName(1));
}
@Test
public void testDateAdditionExpressionMetaData1() throws Exception {
String query = "SELECT entity_id,a_string FROM atable where 1+a_date+?>a_date";
Connection conn = DriverManager.getConnection(getUrl(), PropertiesUtil.deepCopy(TestUtil.TEST_PROPERTIES));
PreparedStatement statement = conn.prepareStatement(query);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(1, pmd.getParameterCount());
assertEquals(BigDecimal.class.getName(), pmd.getParameterClassName(1));
}
@Test
public void testDateAdditionExpressionMetaData2() throws Exception {
String query = "SELECT entity_id,a_string FROM atable where ?+a_date>a_date";
Connection conn = DriverManager.getConnection(getUrl(), PropertiesUtil.deepCopy(TestUtil.TEST_PROPERTIES));
PreparedStatement statement = conn.prepareStatement(query);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(1, pmd.getParameterCount());
assertEquals(BigDecimal.class.getName(), pmd.getParameterClassName(1));
}
@Test
public void testCoerceToDecimalArithmeticMetaData() throws Exception {
String[] ops = { "+", "-", "*", "/" };
for (String op : ops) {
String query = "SELECT entity_id,a_string FROM atable where a_integer" + op + "2.5" + op + "?=0";
Connection conn = DriverManager.getConnection(getUrl(), PropertiesUtil.deepCopy(TestUtil.TEST_PROPERTIES));
PreparedStatement statement = conn.prepareStatement(query);
statement.setInt(1, 4);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(1, pmd.getParameterCount());
assertEquals(BigDecimal.class.getName(), pmd.getParameterClassName(1));
}
}
@Test
public void testLongArithmeticMetaData() throws Exception {
String[] ops = { "+", "-", "*", "/" };
for (String op : ops) {
String query = "SELECT entity_id,a_string FROM atable where a_integer" + op + "2" + op + "?=0";
Connection conn = DriverManager.getConnection(getUrl(), PropertiesUtil.deepCopy(TestUtil.TEST_PROPERTIES));
PreparedStatement statement = conn.prepareStatement(query);
statement.setInt(1, 4);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(1, pmd.getParameterCount());
assertEquals(Long.class.getName(), pmd.getParameterClassName(1));
}
}
@Test
public void testBasicResultSetMetaData() throws Exception {
String query = "SELECT organization_id, a_string, b_string, a_integer i, a_date FROM atable WHERE organization_id='000000000000000' and substr(entity_id,1,3)=? and a_string = 'foo'";
Connection conn = DriverManager.getConnection(getUrl(), PropertiesUtil.deepCopy(TestUtil.TEST_PROPERTIES));
PreparedStatement statement = conn.prepareStatement(query);
ResultSetMetaData md = statement.getMetaData();
assertEquals(5, md.getColumnCount());
assertEquals("organization_id".toUpperCase(),md.getColumnName(1));
assertEquals("a_string".toUpperCase(),md.getColumnName(2));
assertEquals("b_string".toUpperCase(),md.getColumnName(3));
assertEquals("i".toUpperCase(),md.getColumnName(4));
assertEquals("a_date".toUpperCase(),md.getColumnName(5));
assertEquals(String.class.getName(),md.getColumnClassName(1));
assertEquals(String.class.getName(),md.getColumnClassName(2));
assertEquals(String.class.getName(),md.getColumnClassName(3));
assertEquals(Integer.class.getName(),md.getColumnClassName(4));
assertEquals(Date.class.getName(),md.getColumnClassName(5));
assertEquals("atable".toUpperCase(),md.getTableName(1));
assertEquals(java.sql.Types.INTEGER,md.getColumnType(4));
assertEquals(true,md.isReadOnly(1));
assertEquals(false,md.isDefinitelyWritable(1));
assertEquals("i".toUpperCase(),md.getColumnLabel(4));
assertEquals("a_date".toUpperCase(),md.getColumnLabel(5));
assertEquals(ResultSetMetaData.columnNoNulls,md.isNullable(1));
assertEquals(ResultSetMetaData.columnNullable,md.isNullable(5));
}
@Test
public void testStringConcatMetaData() throws Exception {
String query = "SELECT entity_id,a_string FROM atable where 2 || a_integer || ? like '2%'";
Connection conn = DriverManager.getConnection(getUrl(), PropertiesUtil.deepCopy(TestUtil.TEST_PROPERTIES));
PreparedStatement statement = conn.prepareStatement(query);
statement.setString(1, "foo");
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(1, pmd.getParameterCount());
assertEquals(String.class.getName(), pmd.getParameterClassName(1));
}
@Test
public void testRowValueConstructorBindParamMetaData() throws Exception {
String query = "SELECT a_integer, x_integer FROM aTable WHERE (a_integer, x_integer, a_string) = (?, ?, ?)";
Connection conn = DriverManager.getConnection(getUrl(), PropertiesUtil.deepCopy(TestUtil.TEST_PROPERTIES));
PreparedStatement statement = conn.prepareStatement(query);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(3, pmd.getParameterCount());
assertEquals(Integer.class.getName(), pmd.getParameterClassName(1));
assertEquals(Integer.class.getName(), pmd.getParameterClassName(2));
assertEquals(String.class.getName(), pmd.getParameterClassName(3));
}
@Test
public void testRowValueConstructorBindParamMetaDataWithMoreNumberOfBindArgs() throws Exception {
String query = "SELECT a_integer, x_integer FROM aTable WHERE (a_integer, x_integer) = (?, ?, ?)";
Connection conn = DriverManager.getConnection(getUrl(), PropertiesUtil.deepCopy(TestUtil.TEST_PROPERTIES));
PreparedStatement statement = conn.prepareStatement(query);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(3, pmd.getParameterCount());
assertEquals(Integer.class.getName(), pmd.getParameterClassName(1));
assertEquals(Integer.class.getName(), pmd.getParameterClassName(2));
assertEquals(null, pmd.getParameterClassName(3));
}
@Test
public void testRowValueConstructorBindParamMetaDataWithLessNumberOfBindArgs() throws Exception {
String query = "SELECT a_integer, x_integer FROM aTable WHERE (a_integer, x_integer, a_string) = (?, ?)";
Connection conn = DriverManager.getConnection(getUrl(), PropertiesUtil.deepCopy(TestUtil.TEST_PROPERTIES));
PreparedStatement statement = conn.prepareStatement(query);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(2, pmd.getParameterCount());
assertEquals(Integer.class.getName(), pmd.getParameterClassName(1));
assertEquals(Integer.class.getName(), pmd.getParameterClassName(2));
}
@Test
public void testRowValueConstructorBindParamMetaDataWithBindArgsAtSamePlacesOnLHSRHS() throws Exception {
String query = "SELECT a_integer, x_integer FROM aTable WHERE (a_integer, ?) = (a_integer, ?)";
Connection conn = DriverManager.getConnection(getUrl(), PropertiesUtil.deepCopy(TestUtil.TEST_PROPERTIES));
PreparedStatement statement = conn.prepareStatement(query);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(2, pmd.getParameterCount());
assertEquals(null, pmd.getParameterClassName(1));
assertEquals(null, pmd.getParameterClassName(2));
}
@Test
public void testRowValueConstructorBindParamMetaDataWithBindArgsAtDiffPlacesOnLHSRHS() throws Exception {
String query = "SELECT a_integer, x_integer FROM aTable WHERE (a_integer, ?) = (?, a_integer)";
Connection conn = DriverManager.getConnection(getUrl(), PropertiesUtil.deepCopy(TestUtil.TEST_PROPERTIES));
PreparedStatement statement = conn.prepareStatement(query);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(2, pmd.getParameterCount());
assertEquals(Integer.class.getName(), pmd.getParameterClassName(1));
assertEquals(Integer.class.getName(), pmd.getParameterClassName(2));
}
// @Test broken currently, as we'll end up with null = 7 which is never true
public void testRowValueConstructorBindParamMetaDataWithBindArgsOnLHSAndLiteralExprOnRHS() throws Exception {
String query = "SELECT a_integer, x_integer FROM aTable WHERE (?, ?) = 7";
Connection conn = DriverManager.getConnection(getUrl(), PropertiesUtil.deepCopy(TestUtil.TEST_PROPERTIES));
PreparedStatement statement = conn.prepareStatement(query);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(2, pmd.getParameterCount());
assertEquals(Integer.class.getName(), pmd.getParameterClassName(1));
assertEquals(null, pmd.getParameterClassName(2));
}
@Test
public void testRowValueConstructorBindParamMetaDataWithBindArgsOnRHSAndLiteralExprOnLHS() throws Exception {
String query = "SELECT a_integer, x_integer FROM aTable WHERE 7 = (?, ?)";
Connection conn = DriverManager.getConnection(getUrl(), PropertiesUtil.deepCopy(TestUtil.TEST_PROPERTIES));
PreparedStatement statement = conn.prepareStatement(query);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(2, pmd.getParameterCount());
assertEquals(Integer.class.getName(), pmd.getParameterClassName(1));
assertEquals(null, pmd.getParameterClassName(2));
}
@Test
public void testNonEqualityRowValueConstructorBindParamMetaDataWithBindArgsOnRHSAndLiteralExprOnLHS() throws Exception {
String query = "SELECT a_integer, x_integer FROM aTable WHERE 7 >= (?, ?)";
Connection conn = DriverManager.getConnection(getUrl(), PropertiesUtil.deepCopy(TestUtil.TEST_PROPERTIES));
PreparedStatement statement = conn.prepareStatement(query);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(2, pmd.getParameterCount());
assertEquals(Integer.class.getName(), pmd.getParameterClassName(1));
assertEquals(null, pmd.getParameterClassName(2));
}
@Test
public void testBindParamMetaDataForNestedRVC() throws Exception {
String query = "SELECT organization_id, entity_id, a_string FROM aTable WHERE (organization_id, (entity_id, a_string)) >= (?, (?, ?))";
Connection conn = DriverManager.getConnection(PHOENIX_JDBC_URL, PropertiesUtil.deepCopy(TestUtil.TEST_PROPERTIES));
PreparedStatement statement = conn.prepareStatement(query);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(3, pmd.getParameterCount());
assertEquals(String.class.getName(), pmd.getParameterClassName(1));
assertEquals(String.class.getName(), pmd.getParameterClassName(2));
assertEquals(String.class.getName(), pmd.getParameterClassName(3));
}
@Test
public void testBindParamMetaDataForCreateTable() throws Exception {
String ddl = "CREATE TABLE foo (k VARCHAR PRIMARY KEY) SPLIT ON (?, ?)";
Connection conn = DriverManager.getConnection(PHOENIX_JDBC_URL, PropertiesUtil.deepCopy(TestUtil.TEST_PROPERTIES));
PreparedStatement statement = conn.prepareStatement(ddl);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(2, pmd.getParameterCount());
assertEquals(byte[].class.getName(), pmd.getParameterClassName(1));
assertEquals(byte[].class.getName(), pmd.getParameterClassName(2));
}
}
| apache-2.0 |
rokn/Count_Words_2015 | testing/openjdk2/jdk/src/share/classes/javax/imageio/plugins/bmp/BMPImageWriteParam.java | 4743 | /*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio.plugins.bmp;
import java.util.Locale;
import javax.imageio.ImageWriteParam;
import com.sun.imageio.plugins.bmp.BMPConstants;
import com.sun.imageio.plugins.bmp.BMPCompressionTypes;
/**
* A subclass of <code>ImageWriteParam</code> for encoding images in
* the BMP format.
*
* <p> This class allows for the specification of various parameters
* while writing a BMP format image file. By default, the data layout
* is bottom-up, such that the pixels are stored in bottom-up order,
* the first scanline being stored last.
*
* <p>The particular compression scheme to be used can be specified by using
* the <code>setCompressionType()</code> method with the appropriate type
* string. The compression scheme specified will be honored if and only if it
* is compatible with the type of image being written. If the specified
* compression scheme is not compatible with the type of image being written
* then the <code>IOException</code> will be thrown by the BMP image writer.
* If the compression type is not set explicitly then <code>getCompressionType()</code>
* will return <code>null</code>. In this case the BMP image writer will select
* a compression type that supports encoding of the given image without loss
* of the color resolution.
* <p>The compression type strings and the image type(s) each supports are
* listed in the following
* table:
*
* <p><table border=1>
* <caption><b>Compression Types</b></caption>
* <tr><th>Type String</th> <th>Description</th> <th>Image Types</th></tr>
* <tr><td>BI_RGB</td> <td>Uncompressed RLE</td> <td>{@literal <= } 8-bits/sample</td></tr>
* <tr><td>BI_RLE8</td> <td>8-bit Run Length Encoding</td> <td>{@literal <=} 8-bits/sample</td></tr>
* <tr><td>BI_RLE4</td> <td>4-bit Run Length Encoding</td> <td>{@literal <=} 4-bits/sample</td></tr>
* <tr><td>BI_BITFIELDS</td> <td>Packed data</td> <td> 16 or 32 bits/sample</td></tr>
* </table>
*/
public class BMPImageWriteParam extends ImageWriteParam {
private boolean topDown = false;
/**
* Constructs a <code>BMPImageWriteParam</code> set to use a given
* <code>Locale</code> and with default values for all parameters.
*
* @param locale a <code>Locale</code> to be used to localize
* compression type names and quality descriptions, or
* <code>null</code>.
*/
public BMPImageWriteParam(Locale locale) {
super(locale);
// Set compression types ("BI_RGB" denotes uncompressed).
compressionTypes = BMPCompressionTypes.getCompressionTypes();
// Set compression flag.
canWriteCompressed = true;
compressionMode = MODE_COPY_FROM_METADATA;
compressionType = compressionTypes[BMPConstants.BI_RGB];
}
/**
* Constructs an <code>BMPImageWriteParam</code> object with default
* values for all parameters and a <code>null</code> <code>Locale</code>.
*/
public BMPImageWriteParam() {
this(null);
}
/**
* If set, the data will be written out in a top-down manner, the first
* scanline being written first.
*
* @param topDown whether the data are written in top-down order.
*/
public void setTopDown(boolean topDown) {
this.topDown = topDown;
}
/**
* Returns the value of the <code>topDown</code> parameter.
* The default is <code>false</code>.
*
* @return whether the data are written in top-down order.
*/
public boolean isTopDown() {
return topDown;
}
}
| mit |
rokn/Count_Words_2015 | testing/openjdk2/jdk/src/share/classes/com/sun/management/GcInfo.java | 9356 | /*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.management;
import java.lang.management.MemoryUsage;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataView;
import javax.management.openmbean.CompositeType;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import sun.management.GcInfoCompositeData;
import sun.management.GcInfoBuilder;
/**
* Garbage collection information. It contains the following
* information for one garbage collection as well as GC-specific
* attributes:
* <blockquote>
* <ul>
* <li>Start time</li>
* <li>End time</li>
* <li>Duration</li>
* <li>Memory usage before the collection starts</li>
* <li>Memory usage after the collection ends</li>
* </ul>
* </blockquote>
*
* <p>
* <tt>GcInfo</tt> is a {@link CompositeData CompositeData}
* The GC-specific attributes can be obtained via the CompositeData
* interface. This is a historical relic, and other classes should
* not copy this pattern. Use {@link CompositeDataView} instead.
*
* <h4>MXBean Mapping</h4>
* <tt>GcInfo</tt> is mapped to a {@link CompositeData CompositeData}
* with attributes as specified in the {@link #from from} method.
*
* @author Mandy Chung
* @since 1.5
*/
@jdk.Exported
public class GcInfo implements CompositeData, CompositeDataView {
private final long index;
private final long startTime;
private final long endTime;
private final Map<String, MemoryUsage> usageBeforeGc;
private final Map<String, MemoryUsage> usageAfterGc;
private final Object[] extAttributes;
private final CompositeData cdata;
private final GcInfoBuilder builder;
private GcInfo(GcInfoBuilder builder,
long index, long startTime, long endTime,
MemoryUsage[] muBeforeGc,
MemoryUsage[] muAfterGc,
Object[] extAttributes) {
this.builder = builder;
this.index = index;
this.startTime = startTime;
this.endTime = endTime;
String[] poolNames = builder.getPoolNames();
this.usageBeforeGc = new HashMap<String, MemoryUsage>(poolNames.length);
this.usageAfterGc = new HashMap<String, MemoryUsage>(poolNames.length);
for (int i = 0; i < poolNames.length; i++) {
this.usageBeforeGc.put(poolNames[i], muBeforeGc[i]);
this.usageAfterGc.put(poolNames[i], muAfterGc[i]);
}
this.extAttributes = extAttributes;
this.cdata = new GcInfoCompositeData(this, builder, extAttributes);
}
private GcInfo(CompositeData cd) {
GcInfoCompositeData.validateCompositeData(cd);
this.index = GcInfoCompositeData.getId(cd);
this.startTime = GcInfoCompositeData.getStartTime(cd);
this.endTime = GcInfoCompositeData.getEndTime(cd);
this.usageBeforeGc = GcInfoCompositeData.getMemoryUsageBeforeGc(cd);
this.usageAfterGc = GcInfoCompositeData.getMemoryUsageAfterGc(cd);
this.extAttributes = null;
this.builder = null;
this.cdata = cd;
}
/**
* Returns the identifier of this garbage collection which is
* the number of collections that this collector has done.
*
* @return the identifier of this garbage collection which is
* the number of collections that this collector has done.
*/
public long getId() {
return index;
}
/**
* Returns the start time of this GC in milliseconds
* since the Java virtual machine was started.
*
* @return the start time of this GC.
*/
public long getStartTime() {
return startTime;
}
/**
* Returns the end time of this GC in milliseconds
* since the Java virtual machine was started.
*
* @return the end time of this GC.
*/
public long getEndTime() {
return endTime;
}
/**
* Returns the elapsed time of this GC in milliseconds.
*
* @return the elapsed time of this GC in milliseconds.
*/
public long getDuration() {
return endTime - startTime;
}
/**
* Returns the memory usage of all memory pools
* at the beginning of this GC.
* This method returns
* a <tt>Map</tt> of the name of a memory pool
* to the memory usage of the corresponding
* memory pool before GC starts.
*
* @return a <tt>Map</tt> of memory pool names to the memory
* usage of a memory pool before GC starts.
*/
public Map<String, MemoryUsage> getMemoryUsageBeforeGc() {
return Collections.unmodifiableMap(usageBeforeGc);
}
/**
* Returns the memory usage of all memory pools
* at the end of this GC.
* This method returns
* a <tt>Map</tt> of the name of a memory pool
* to the memory usage of the corresponding
* memory pool when GC finishes.
*
* @return a <tt>Map</tt> of memory pool names to the memory
* usage of a memory pool when GC finishes.
*/
public Map<String, MemoryUsage> getMemoryUsageAfterGc() {
return Collections.unmodifiableMap(usageAfterGc);
}
/**
* Returns a <tt>GcInfo</tt> object represented by the
* given <tt>CompositeData</tt>. The given
* <tt>CompositeData</tt> must contain
* all the following attributes:
*
* <p>
* <blockquote>
* <table border>
* <tr>
* <th align=left>Attribute Name</th>
* <th align=left>Type</th>
* </tr>
* <tr>
* <td>index</td>
* <td><tt>java.lang.Long</tt></td>
* </tr>
* <tr>
* <td>startTime</td>
* <td><tt>java.lang.Long</tt></td>
* </tr>
* <tr>
* <td>endTime</td>
* <td><tt>java.lang.Long</tt></td>
* </tr>
* <tr>
* <td>memoryUsageBeforeGc</td>
* <td><tt>javax.management.openmbean.TabularData</tt></td>
* </tr>
* <tr>
* <td>memoryUsageAfterGc</td>
* <td><tt>javax.management.openmbean.TabularData</tt></td>
* </tr>
* </table>
* </blockquote>
*
* @throws IllegalArgumentException if <tt>cd</tt> does not
* represent a <tt>GcInfo</tt> object with the attributes
* described above.
*
* @return a <tt>GcInfo</tt> object represented by <tt>cd</tt>
* if <tt>cd</tt> is not <tt>null</tt>; <tt>null</tt> otherwise.
*/
public static GcInfo from(CompositeData cd) {
if (cd == null) {
return null;
}
if (cd instanceof GcInfoCompositeData) {
return ((GcInfoCompositeData) cd).getGcInfo();
} else {
return new GcInfo(cd);
}
}
// Implementation of the CompositeData interface
public boolean containsKey(String key) {
return cdata.containsKey(key);
}
public boolean containsValue(Object value) {
return cdata.containsValue(value);
}
public boolean equals(Object obj) {
return cdata.equals(obj);
}
public Object get(String key) {
return cdata.get(key);
}
public Object[] getAll(String[] keys) {
return cdata.getAll(keys);
}
public CompositeType getCompositeType() {
return cdata.getCompositeType();
}
public int hashCode() {
return cdata.hashCode();
}
public String toString() {
return cdata.toString();
}
public Collection values() {
return cdata.values();
}
/**
* <p>Return the {@code CompositeData} representation of this
* {@code GcInfo}, including any GC-specific attributes. The
* returned value will have at least all the attributes described
* in the {@link #from(CompositeData) from} method, plus optionally
* other attributes.
*
* @param ct the {@code CompositeType} that the caller expects.
* This parameter is ignored and can be null.
*
* @return the {@code CompositeData} representation.
*/
public CompositeData toCompositeData(CompositeType ct) {
return cdata;
}
}
| mit |
medicayun/medicayundicom | dcm4che14/trunk/src/java/org/dcm4cheri/image/ConfigurationUtils.java | 3263 | /* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is part of dcm4che, an implementation of DICOM(TM) in
* Java(TM), hosted at http://sourceforge.net/projects/dcm4che.
*
* The Initial Developer of the Original Code is
* Agfa Healthcare.
* Portions created by the Initial Developer are Copyright (C) 2006
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
package org.dcm4cheri.image;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Properties;
import org.dcm4che.util.SystemUtils;
/**
* @author Gunter Zeilinger<gunterze@gmail.com>
* @version $Id
* @since Jun 26, 2006
*/
class ConfigurationUtils {
public static void loadPropertiesForClass(Properties map, Class c) {
String key = c.getName();
String val = SystemUtils.getSystemProperty(key, null);
URL url;
if (val == null) {
val = key.replace('.','/') + ".properties";
url = getResource(c, val);
} else {
try {
url = new URL(val);
} catch (MalformedURLException e) {
url = getResource(c, val);
}
}
try {
InputStream is = url.openStream();
try {
map.load(is);
} finally {
is.close();
}
} catch (IOException e) {
throw new ConfigurationException("failed not load resource:", e);
}
}
private static URL getResource(Class c, String val) {
URL url;
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (cl == null || (url = cl.getResource(val)) == null) {
if ((url = c.getClassLoader().getResource(val)) == null) {
throw new ConfigurationException("missing resource: " + val);
}
}
return url;
}
}
| apache-2.0 |
mahaliachante/aws-sdk-java | aws-java-sdk-ec2/src/main/java/com/amazonaws/services/ec2/model/transform/CancelSpotFleetRequestsErrorStaxUnmarshaller.java | 2752 | /*
* Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.ec2.model.transform;
import java.util.Map;
import java.util.Map.Entry;
import javax.xml.stream.events.XMLEvent;
import com.amazonaws.services.ec2.model.*;
import com.amazonaws.transform.Unmarshaller;
import com.amazonaws.transform.MapEntry;
import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;
/**
* Cancel Spot Fleet Requests Error StAX Unmarshaller
*/
public class CancelSpotFleetRequestsErrorStaxUnmarshaller implements Unmarshaller<CancelSpotFleetRequestsError, StaxUnmarshallerContext> {
public CancelSpotFleetRequestsError unmarshall(StaxUnmarshallerContext context) throws Exception {
CancelSpotFleetRequestsError cancelSpotFleetRequestsError = new CancelSpotFleetRequestsError();
int originalDepth = context.getCurrentDepth();
int targetDepth = originalDepth + 1;
if (context.isStartOfDocument()) targetDepth += 1;
while (true) {
XMLEvent xmlEvent = context.nextEvent();
if (xmlEvent.isEndDocument()) return cancelSpotFleetRequestsError;
if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {
if (context.testExpression("code", targetDepth)) {
cancelSpotFleetRequestsError.setCode(StringStaxUnmarshaller.getInstance().unmarshall(context));
continue;
}
if (context.testExpression("message", targetDepth)) {
cancelSpotFleetRequestsError.setMessage(StringStaxUnmarshaller.getInstance().unmarshall(context));
continue;
}
} else if (xmlEvent.isEndElement()) {
if (context.getCurrentDepth() < originalDepth) {
return cancelSpotFleetRequestsError;
}
}
}
}
private static CancelSpotFleetRequestsErrorStaxUnmarshaller instance;
public static CancelSpotFleetRequestsErrorStaxUnmarshaller getInstance() {
if (instance == null) instance = new CancelSpotFleetRequestsErrorStaxUnmarshaller();
return instance;
}
}
| apache-2.0 |
amith01994/intellij-community | platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/EditVarConstraintsDialog.java | 23913 | package com.intellij.structuralsearch.plugin.ui;
import com.intellij.codeInsight.template.impl.Variable;
import com.intellij.find.impl.RegExHelpPopup;
import com.intellij.ide.highlighter.HighlighterFactory;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.EditorSettings;
import com.intellij.openapi.editor.colors.ex.DefaultColorSchemesManager;
import com.intellij.openapi.editor.event.DocumentAdapter;
import com.intellij.openapi.editor.event.DocumentEvent;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.fileTypes.FileTypes;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.help.HelpManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.ComponentWithBrowseButton;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiFileFactory;
import com.intellij.structuralsearch.*;
import com.intellij.structuralsearch.impl.matcher.CompiledPattern;
import com.intellij.structuralsearch.impl.matcher.predicates.ScriptSupport;
import com.intellij.structuralsearch.plugin.replace.ReplaceOptions;
import com.intellij.structuralsearch.plugin.replace.ui.ReplaceConfiguration;
import com.intellij.ui.ComboboxWithBrowseButton;
import com.intellij.ui.EditorTextField;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Collection;
import java.util.List;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
/**
* @author Maxim.Mossienko
* Date: Mar 25, 2004
* Time: 1:52:18 PM
*/
class EditVarConstraintsDialog extends DialogWrapper {
private static final Logger LOG = Logger.getInstance("#com.intellij.structuralsearch.plugin.ui.EditVarConstraintsDialog");
private JTextField maxoccurs;
private JCheckBox applyWithinTypeHierarchy;
private JCheckBox notRegexp;
private EditorTextField regexp;
private JTextField minoccurs;
private JPanel mainForm;
private JCheckBox notWrite;
private JCheckBox notRead;
private JCheckBox write;
private JCheckBox read;
private JList parameterList;
private JCheckBox partOfSearchResults;
private JCheckBox notExprType;
private EditorTextField regexprForExprType;
private final Configuration myConfiguration;
private JCheckBox exprTypeWithinHierarchy;
private final List<Variable> variables;
private Variable current;
private JCheckBox wholeWordsOnly;
private JCheckBox formalArgTypeWithinHierarchy;
private JCheckBox invertFormalArgType;
private EditorTextField formalArgType;
private ComponentWithBrowseButton<EditorTextField> customScriptCode;
private JCheckBox maxoccursUnlimited;
private ComboboxWithBrowseButton withinCombo;
private JPanel containedInConstraints;
private JCheckBox invertWithinIn;
private JPanel expressionConstraints;
private JPanel occurencePanel;
private JPanel textConstraintsPanel;
private JLabel myRegExHelpLabel;
private static Project myProject;
EditVarConstraintsDialog(final Project project, Configuration configuration, List<Variable> _variables, final FileType fileType) {
super(project, false);
variables = _variables;
myConfiguration = configuration;
setTitle(SSRBundle.message("editvarcontraints.edit.variables"));
regexp.getDocument().addDocumentListener(new MyDocumentListener(notRegexp, wholeWordsOnly));
regexp.getDocument().addDocumentListener(new DocumentAdapter() {
@Override
public void documentChanged(DocumentEvent e) {
applyWithinTypeHierarchy.setEnabled(e.getDocument().getTextLength() > 0 && fileType == StdFileTypes.JAVA);
}
});
read.addChangeListener(new MyChangeListener(notRead, false));
write.addChangeListener(new MyChangeListener(notWrite, false));
regexprForExprType.getDocument().addDocumentListener(new MyDocumentListener(exprTypeWithinHierarchy, notExprType));
formalArgType.getDocument().addDocumentListener(new MyDocumentListener(formalArgTypeWithinHierarchy, invertFormalArgType));
containedInConstraints.setVisible(false);
withinCombo.getComboBox().setEditable(true);
withinCombo.getButton().addActionListener(new ActionListener() {
public void actionPerformed(@NotNull final ActionEvent e) {
final SelectTemplateDialog dialog = new SelectTemplateDialog(project, false, false);
dialog.show();
if (dialog.getExitCode() == OK_EXIT_CODE) {
final Configuration[] selectedConfigurations = dialog.getSelectedConfigurations();
if (selectedConfigurations.length == 1) {
withinCombo.getComboBox().getEditor().setItem(selectedConfigurations[0].getMatchOptions().getSearchPattern()); // TODO:
}
}
}
});
boolean hasContextVar = false;
for(Variable var:variables) {
if (Configuration.CONTEXT_VAR_NAME.equals(var.getName())) {
hasContextVar = true; break;
}
}
if (!hasContextVar) {
variables.add(new Variable(Configuration.CONTEXT_VAR_NAME, "", "", true));
}
if (fileType == StdFileTypes.JAVA) {
formalArgTypeWithinHierarchy.setEnabled(true);
invertFormalArgType.setEnabled(true);
formalArgType.setEnabled(true);
exprTypeWithinHierarchy.setEnabled(true);
notExprType.setEnabled(true);
regexprForExprType.setEnabled(true);
read.setEnabled(true);
notRead.setEnabled(false);
write.setEnabled(true);
notWrite.setEnabled(false);
applyWithinTypeHierarchy.setEnabled(true);
} else {
formalArgTypeWithinHierarchy.setEnabled(false);
invertFormalArgType.setEnabled(false);
formalArgType.setEnabled(false);
exprTypeWithinHierarchy.setEnabled(false);
notExprType.setEnabled(false);
regexprForExprType.setEnabled(false);
read.setEnabled(false);
notRead.setEnabled(false);
write.setEnabled(false);
notWrite.setEnabled(false);
applyWithinTypeHierarchy.setEnabled(false);
}
parameterList.setModel(
new AbstractListModel() {
public Object getElementAt(int index) {
return variables.get(index);
}
public int getSize() {
return variables.size();
}
}
);
parameterList.setSelectionMode( ListSelectionModel.SINGLE_SELECTION );
parameterList.getSelectionModel().addListSelectionListener(
new ListSelectionListener() {
boolean rollingBackSelection;
public void valueChanged(@NotNull ListSelectionEvent e) {
if (e.getValueIsAdjusting()) return;
if (rollingBackSelection) {
rollingBackSelection=false;
return;
}
final Variable var = variables.get(parameterList.getSelectedIndex());
if (validateParameters()) {
if (current!=null) copyValuesFromUI(current);
ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { copyValuesToUI(var); }});
current = var;
} else {
rollingBackSelection = true;
parameterList.setSelectedIndex(e.getFirstIndex()==parameterList.getSelectedIndex()?e.getLastIndex():e.getFirstIndex());
}
}
}
);
parameterList.setCellRenderer(
new DefaultListCellRenderer() {
public Component getListCellRendererComponent(@NotNull JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
String name = ((Variable)value).getName();
if (Configuration.CONTEXT_VAR_NAME.equals(name)) name = SSRBundle.message("complete.match.variable.name");
if (isReplacementVariable(name)) {
name = stripReplacementVarDecoration(name);
}
return super.getListCellRendererComponent(list, name, index, isSelected, cellHasFocus);
}
}
);
maxoccursUnlimited.addChangeListener(new MyChangeListener(maxoccurs, true));
customScriptCode.getButton().addActionListener(new ActionListener() {
public void actionPerformed(@NotNull final ActionEvent e) {
final List<String> variableNames = ContainerUtil.newArrayList(myConfiguration.getMatchOptions().getVariableConstraintNames());
variableNames.remove(current.getName());
variableNames.remove(CompiledPattern.ALL_CLASS_UNMATCHED_CONTENT_VAR_ARTIFICIAL_NAME);
final EditScriptDialog dialog = new EditScriptDialog(project, customScriptCode.getChildComponent().getText(), variableNames);
dialog.show();
if (dialog.getExitCode() == OK_EXIT_CODE) {
customScriptCode.getChildComponent().setText(dialog.getScriptText());
}
}
});
init();
if (variables.size() > 0) parameterList.setSelectedIndex(0);
}
private static String stripReplacementVarDecoration(String name) {
name = name.substring(0, name.length() - ReplaceConfiguration.REPLACEMENT_VARIABLE_SUFFIX.length());
return name;
}
private static boolean isReplacementVariable(String name) {
return name.endsWith(ReplaceConfiguration.REPLACEMENT_VARIABLE_SUFFIX);
}
private boolean validateParameters() {
return validateRegExp(regexp) && validateRegExp(regexprForExprType) &&
validateIntOccurence(minoccurs) &&
validateScript(customScriptCode.getChildComponent()) &&
(maxoccursUnlimited.isSelected() || validateIntOccurence(maxoccurs));
}
protected JComponent createCenterPanel() {
return mainForm;
}
protected void doOKAction() {
if(validateParameters()) {
if (current!=null) copyValuesFromUI(current);
super.doOKAction();
}
}
void copyValuesFromUI(Variable var) {
final String varName = var.getName();
if (isReplacementVariable(varName)) {
saveScriptInfo(getOrAddReplacementVariableDefinition(varName, myConfiguration));
return;
}
final MatchVariableConstraint varInfo = UIUtil.getOrAddVariableConstraint(varName, myConfiguration);
varInfo.setInvertReadAccess(notRead.isSelected());
varInfo.setReadAccess(read.isSelected());
varInfo.setInvertWriteAccess(notWrite.isSelected());
varInfo.setWriteAccess(write.isSelected());
varInfo.setRegExp(regexp.getDocument().getText());
varInfo.setInvertRegExp(notRegexp.isSelected());
final int minCount = Integer.parseInt(minoccurs.getText());
varInfo.setMinCount(minCount);
final int maxCount = maxoccursUnlimited.isSelected() ? Integer.MAX_VALUE : Integer.parseInt(maxoccurs.getText());
varInfo.setMaxCount(maxCount);
varInfo.setWithinHierarchy(applyWithinTypeHierarchy.isSelected());
varInfo.setInvertRegExp(notRegexp.isSelected());
final boolean target = partOfSearchResults.isSelected();
if (target) {
final MatchOptions matchOptions = myConfiguration.getMatchOptions();
for (String name : matchOptions.getVariableConstraintNames()) {
if (!name.equals(varName)) {
matchOptions.getVariableConstraint(name).setPartOfSearchResults(false);
}
}
}
varInfo.setPartOfSearchResults(target);
varInfo.setInvertExprType(notExprType.isSelected());
varInfo.setNameOfExprType(regexprForExprType.getDocument().getText());
varInfo.setExprTypeWithinHierarchy(exprTypeWithinHierarchy.isSelected());
varInfo.setWholeWordsOnly(wholeWordsOnly.isSelected());
varInfo.setInvertFormalType(invertFormalArgType.isSelected());
varInfo.setFormalArgTypeWithinHierarchy(formalArgTypeWithinHierarchy.isSelected());
varInfo.setNameOfFormalArgType(formalArgType.getDocument().getText());
saveScriptInfo(varInfo);
final String withinConstraint = (String)withinCombo.getComboBox().getEditor().getItem();
varInfo.setWithinConstraint(withinConstraint.length() > 0 ? "\"" + withinConstraint +"\"":"");
varInfo.setInvertWithinConstraint(invertWithinIn.isSelected());
}
private static ReplacementVariableDefinition getOrAddReplacementVariableDefinition(String varName, Configuration configuration) {
ReplaceOptions replaceOptions = ((ReplaceConfiguration)configuration).getOptions();
String realVariableName = stripReplacementVarDecoration(varName);
ReplacementVariableDefinition variableDefinition = replaceOptions.getVariableDefinition(realVariableName);
if (variableDefinition == null) {
variableDefinition = new ReplacementVariableDefinition();
variableDefinition.setName(realVariableName);
replaceOptions.addVariableDefinition(variableDefinition);
}
return variableDefinition;
}
private void saveScriptInfo(NamedScriptableDefinition varInfo) {
varInfo.setScriptCodeConstraint("\"" + customScriptCode.getChildComponent().getText() + "\"");
}
private void copyValuesToUI(Variable var) {
final String varName = var.getName();
if (isReplacementVariable(varName)) {
final ReplacementVariableDefinition definition =
((ReplaceConfiguration)myConfiguration).getOptions().getVariableDefinition(stripReplacementVarDecoration(varName));
restoreScriptCode(definition);
setSearchConstraintsVisible(false);
return;
} else {
setSearchConstraintsVisible(true);
}
final MatchOptions matchOptions = myConfiguration.getMatchOptions();
final MatchVariableConstraint varInfo = matchOptions.getVariableConstraint(varName);
if (varInfo == null) {
notRead.setSelected(false);
notRegexp.setSelected(false);
read.setSelected(false);
notWrite.setSelected(false);
write.setSelected(false);
regexp.getDocument().setText("");
minoccurs.setText("1");
maxoccurs.setText("1");
maxoccursUnlimited.setSelected(false);
applyWithinTypeHierarchy.setSelected(false);
partOfSearchResults.setSelected(UIUtil.isTarget(varName, matchOptions));
regexprForExprType.getDocument().setText("");
notExprType.setSelected(false);
exprTypeWithinHierarchy.setSelected(false);
wholeWordsOnly.setSelected(false);
invertFormalArgType.setSelected(false);
formalArgTypeWithinHierarchy.setSelected(false);
formalArgType.getDocument().setText("");
customScriptCode.getChildComponent().setText("");
withinCombo.getComboBox().getEditor().setItem("");
invertWithinIn.setSelected(false);
} else {
notRead.setSelected(varInfo.isInvertReadAccess());
read.setSelected(varInfo.isReadAccess());
notWrite.setSelected(varInfo.isInvertWriteAccess());
write.setSelected(varInfo.isWriteAccess());
applyWithinTypeHierarchy.setSelected(varInfo.isWithinHierarchy());
regexp.getDocument().setText(varInfo.getRegExp());
//doProcessing(applyWithinTypeHierarchy,regexp);
notRegexp.setSelected(varInfo.isInvertRegExp());
minoccurs.setText(Integer.toString(varInfo.getMinCount()));
if(varInfo.getMaxCount() == Integer.MAX_VALUE) {
maxoccursUnlimited.setSelected(true);
maxoccurs.setText("");
} else {
maxoccursUnlimited.setSelected(false);
maxoccurs.setText(Integer.toString(varInfo.getMaxCount()));
}
partOfSearchResults.setSelected(UIUtil.isTarget(varName, matchOptions));
exprTypeWithinHierarchy.setSelected(varInfo.isExprTypeWithinHierarchy());
regexprForExprType.getDocument().setText(varInfo.getNameOfExprType());
notExprType.setSelected( varInfo.isInvertExprType() );
wholeWordsOnly.setSelected( varInfo.isWholeWordsOnly() );
invertFormalArgType.setSelected( varInfo.isInvertFormalType() );
formalArgTypeWithinHierarchy.setSelected(varInfo.isFormalArgTypeWithinHierarchy());
formalArgType.getDocument().setText(varInfo.getNameOfFormalArgType());
restoreScriptCode(varInfo);
withinCombo.getComboBox().getEditor().setItem(StringUtil.stripQuotesAroundValue(varInfo.getWithinConstraint()));
invertWithinIn.setSelected(varInfo.isInvertWithinConstraint());
}
final boolean contextVar = Configuration.CONTEXT_VAR_NAME.equals(var.getName());
containedInConstraints.setVisible(contextVar);
textConstraintsPanel.setVisible(!contextVar);
expressionConstraints.setVisible(!contextVar);
partOfSearchResults.setEnabled(!contextVar);
occurencePanel.setVisible(!contextVar);
}
private void setSearchConstraintsVisible(boolean b) {
textConstraintsPanel.setVisible(b);
occurencePanel.setVisible(b);
expressionConstraints.setVisible(b);
partOfSearchResults.setVisible(b);
containedInConstraints.setVisible(b);
}
private void restoreScriptCode(NamedScriptableDefinition varInfo) {
customScriptCode.getChildComponent().setText(
varInfo != null ? StringUtil.stripQuotesAroundValue(varInfo.getScriptCodeConstraint()) : "");
}
protected String getDimensionServiceKey() {
return "#com.intellij.structuralsearch.plugin.ui.EditVarConstraintsDialog";
}
private static boolean validateRegExp(EditorTextField field) {
final String s = field.getDocument().getText();
try {
if (s.length() > 0) {
Pattern.compile(s);
}
} catch(PatternSyntaxException ex) {
Messages.showErrorDialog(SSRBundle.message("invalid.regular.expression", ex.getMessage()),
SSRBundle.message("invalid.regular.expression.title"));
field.requestFocus();
return false;
}
return true;
}
private static boolean validateScript(EditorTextField field) {
final String text = field.getText();
if (text.length() > 0) {
final String message = ScriptSupport.checkValidScript(text);
if (message != null) {
Messages.showErrorDialog(message, SSRBundle.message("invalid.groovy.script"));
field.requestFocus();
return false;
}
}
return true;
}
private static boolean validateIntOccurence(JTextField field) {
try {
if (Integer.parseInt(field.getText()) < 0) throw new NumberFormatException();
} catch(NumberFormatException ex) {
Messages.showErrorDialog(SSRBundle.message("invalid.occurence.count"), SSRBundle.message("invalid.occurence.count"));
field.requestFocus();
return false;
}
return true;
}
@NotNull
protected Action[] createActions() {
return new Action[]{getOKAction(), getCancelAction(), getHelpAction()};
}
protected void doHelpAction() {
HelpManager.getInstance().invokeHelp("reference.dialogs.search.replace.structural.editvariable");
}
private void createUIComponents() {
regexp = createRegexComponent();
regexprForExprType = createRegexComponent();
formalArgType = createRegexComponent();
customScriptCode = new ComponentWithBrowseButton<EditorTextField>(createScriptComponent(), null);
myRegExHelpLabel = RegExHelpPopup.createRegExLink(SSRBundle.message("regular.expression.help.label"), regexp, LOG);
myRegExHelpLabel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));
}
private static EditorTextField createRegexComponent() {
@NonNls final String fileName = "1.regexp";
final FileType fileType = getFileType(fileName);
final Document doc = createDocument(fileName, fileType, "");
return new EditorTextField(doc, myProject, fileType);
}
private static EditorTextField createScriptComponent() {
@NonNls final String fileName = "1.groovy";
final FileType fileType = getFileType(fileName);
final Document doc = createDocument(fileName, fileType, "");
return new EditorTextField(doc, myProject, fileType);
}
private static Document createDocument(final String fileName, final FileType fileType, String text) {
final PsiFile file = PsiFileFactory.getInstance(myProject).createFileFromText(fileName, fileType, text, -1, true);
return PsiDocumentManager.getInstance(myProject).getDocument(file);
}
private static FileType getFileType(final String fileName) {
FileType fileType = FileTypeManager.getInstance().getFileTypeByFileName(fileName);
if (fileType == FileTypes.UNKNOWN) fileType = FileTypes.PLAIN_TEXT;
return fileType;
}
public static void setProject(final Project project) {
myProject = project;
}
private static class MyChangeListener implements ChangeListener {
private final JComponent component;
private final boolean inverted;
MyChangeListener(JComponent _component, boolean _inverted) {
component = _component;
inverted = _inverted;
}
public void stateChanged(@NotNull ChangeEvent e) {
final JCheckBox jCheckBox = (JCheckBox)e.getSource();
component.setEnabled(inverted ^ jCheckBox.isSelected());
}
}
private static class MyDocumentListener extends DocumentAdapter {
private final JComponent[] components;
private MyDocumentListener(JComponent... _components) {
components = _components;
}
@Override
public void documentChanged(DocumentEvent e) {
final boolean enable = e.getDocument().getTextLength() > 0;
for (JComponent component : components) {
component.setEnabled(enable);
}
}
}
private static Editor createEditor(final Project project, final String text, final String fileName) {
final FileType fileType = getFileType(fileName);
final Document doc = createDocument(fileName, fileType, text);
final Editor editor = EditorFactory.getInstance().createEditor(doc, project);
((EditorEx)editor).setEmbeddedIntoDialogWrapper(true);
final EditorSettings settings = editor.getSettings();
settings.setLineNumbersShown(false);
settings.setFoldingOutlineShown(false);
settings.setRightMarginShown(false);
settings.setLineMarkerAreaShown(false);
settings.setIndentGuidesShown(false);
((EditorEx)editor).setHighlighter(HighlighterFactory.createHighlighter(fileType, DefaultColorSchemesManager.getInstance().getFirstScheme(), project));
return editor;
}
private static class EditScriptDialog extends DialogWrapper {
private final Editor editor;
private final String title;
public EditScriptDialog(Project project, String text, Collection<String> names) {
super(project, true);
setTitle(SSRBundle.message("edit.groovy.script.constraint.title"));
editor = createEditor(project, text, "1.groovy");
title = names.size() > 0 ? "Available variables: " + StringUtil.join(names, ", ") : "";
init();
}
@Override
protected String getDimensionServiceKey() {
return getClass().getName();
}
@Override
public JComponent getPreferredFocusedComponent() {
return editor.getContentComponent();
}
protected JComponent createCenterPanel() {
final JPanel panel = new JPanel(new BorderLayout());
panel.add(editor.getComponent(), BorderLayout.CENTER);
if (!title.isEmpty()) {
panel.add(new JLabel(title), BorderLayout.SOUTH);
}
return panel;
}
String getScriptText() {
return editor.getDocument().getText();
}
@Override
protected void dispose() {
EditorFactory.getInstance().releaseEditor(editor);
super.dispose();
}
}
}
| apache-2.0 |
rokn/Count_Words_2015 | testing/openjdk2/jdk/test/javax/sound/midi/Gervill/SoftAudioBuffer/NewSoftAudioBuffer.java | 1904 | /*
* Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
@summary Test SoftAudioBuffer constructor */
import javax.sound.midi.Patch;
import javax.sound.sampled.*;
import com.sun.media.sound.*;
public class NewSoftAudioBuffer {
private static void assertEquals(Object a, Object b) throws Exception
{
if(!a.equals(b))
throw new RuntimeException("assertEquals fails!");
}
private static void assertTrue(boolean value) throws Exception
{
if(!value)
throw new RuntimeException("assertTrue fails!");
}
public static void main(String[] args) throws Exception {
AudioFormat frm = new AudioFormat(8000, 8, 1, true, false);
SoftAudioBuffer buff = new SoftAudioBuffer(377, frm);
assertEquals(buff.getSize(), 377);
assertEquals(buff.getFormat(), frm);
assertTrue(buff.isSilent());
}
}
| mit |
rokn/Count_Words_2015 | testing/openjdk2/jaxws/src/share/jaxws_classes/com/sun/tools/internal/xjc/api/Mapping.java | 3592 | /*
* Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.internal.xjc.api;
import java.util.List;
import javax.xml.namespace.QName;
/**
* JAXB-induced mapping between a Java class
* and an XML element declaration. A part of the compiler artifacts.
*
* <p>
* To be precise, this is a mapping between two Java classes and an
* XML element declaration. There's one Java class/interface that
* represents the element, and there's another Java class/interface that
* represents the type of the element.
*
* The former is called "element representation" and the latter is called
* "type representation".
*
* <p>
* The {@link Mapping} interface provides operation that lets the caller
* convert an instance of the element representation to that of the
* type representation or vice versa.
*
* @author
* Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
*/
public interface Mapping {
/**
* Name of the XML element.
*
* @return
* never be null.
*/
QName getElement();
/**
* Returns the fully-qualified name of the java class for the type of this element.
*
* TODO: does this method returns the name of the wrapper bean when it's qualified
* for the wrapper style? Seems no (consider <xs:element name='foo' type='xs:long' />),
* but then how does JAX-RPC captures that bean?
*
* @return
* never be null.
*/
TypeAndAnnotation getType();
/**
* If this element is a so-called "wrapper-style" element,
* obtains its member information.
*
* <p>
* The notion of the wrapper style should be defined by the JAXB spec,
* and ideally it should differ from that of the JAX-RPC only at
* the point where the JAX-RPC imposes additional restriction
* on the element name.
*
* <p>
* As of this writing the JAXB spec doesn't define "the wrapper style"
* and as such the exact definition of what XJC thinks
* "the wrapper style" isn't spec-ed.
*
* <p>
* Ths returned list includes {@link Property} defined not just
* in this class but in all its base classes.
*
* @return
* null if this isn't a wrapper-style element.
* Otherwise list of {@link Property}s. The order signifies
* the order they appeared inside a schema.
*/
List<? extends Property> getWrapperStyleDrilldown();
}
| mit |
fitzlee/JavaAlgorithmsDataStructure | src/com/solres/Medium/DecodeWays.java | 1914 | /**
* A message containing letters from A-Z is being encoded to numbers using the
* following mapping:
*
* 'A' -> 1
* 'B' -> 2
* ...
* 'Z' -> 26
*
* Given an encoded message containing digits, determine the total number of
* ways to decode it.
*
* For example,
* Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).
*
* The number of ways decoding "12" is 2.
*
* Tags: DP, String
*/
class DecodeWays {
public static void main(String[] args) {
DecodeWays d = new DecodeWays();
System.out.println(d.numDecodings("1029"));
}
/**
* Optimal, DP
* Reduce space to O(1)
*/
public int numDecodingsOptimal(String s) {
if (s == null || s.length() == 0) return 0;
int len = s.length();
int prev1 = 1;
int prev2 = s.charAt(0) == '0' ? 0 : 1;
for (int i = 2; i <= len; i++) {
int code1 = Integer.valueOf(s.substring(i - 1, i)); // 1 digit
int code2 = Integer.valueOf(s.substring(i - 2, i)); // 2 digits
int temp = prev2;
prev2 = (code1 != 0 ? prev2 : 0) + (code2 <= 26 && code2 > 9 ? prev1 : 0);
prev1 = temp;
}
return prev2;
}
/**
* Time O(n), Space O(n)
* note that there can be zeros in s
*/
public static int numDecodings(String s) {
if (s == null || s.length() == 0) return 0;
int len = s.length();
int[] ways = new int[len + 1];
ways[0] = 1;
ways[1] = s.charAt(0) == '0' ? 0 : 1;
for (int i = 2; i <= len; i++) {
int code1 = Integer.valueOf(s.substring(i - 1, i));
int code2 = Integer.valueOf(s.substring(i - 2, i));
// System.out.println(code2);
ways[i] = (code1 != 0 ? ways[i - 1] : 0) + (code2 <= 26 && code2 > 9 ? ways[i - 2] : 0);
}
return ways[len];
}
}
| apache-2.0 |
rokn/Count_Words_2015 | testing/openjdk2/jdk/src/share/classes/com/sun/jdi/connect/IllegalConnectorArgumentsException.java | 2951 | /*
* Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.jdi.connect;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
/**
* Thrown to indicate an invalid argument or
* inconsistent passed to a {@link Connector}.
*
* @author Gordon Hirsch
* @since 1.3
*/
@jdk.Exported
public class IllegalConnectorArgumentsException extends Exception {
private static final long serialVersionUID = -3042212603611350941L;
List<String> names;
/**
* Construct an <code>IllegalConnectorArgumentsException</code>
* with the specified detail message and the name of the argument
* which is invalid or inconsistent.
* @param s the detailed message.
* @param name the name of the invalid or inconsistent argument.
*/
public IllegalConnectorArgumentsException(String s,
String name) {
super(s);
names = new ArrayList<String>(1);
names.add(name);
}
/**
* Construct an <code>IllegalConnectorArgumentsException</code>
* with the specified detail message and a <code>List</code> of
* names of arguments which are invalid or inconsistent.
* @param s the detailed message.
* @param names a <code>List</code> containing the names of the
* invalid or inconsistent argument.
*/
public IllegalConnectorArgumentsException(String s, List<String> names) {
super(s);
this.names = new ArrayList<String>(names);
}
/**
* Return a <code>List</code> containing the names of the
* invalid or inconsistent arguments.
* @return a <code>List</code> of argument names.
*/
public List<String> argumentNames() {
return Collections.unmodifiableList(names);
}
}
| mit |
gingerwizard/elasticsearch | client/rest-high-level/src/test/java/org/elasticsearch/client/ml/GetJobStatsResponseTests.java | 1846 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.ml;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.client.ml.job.stats.JobStats;
import org.elasticsearch.client.ml.job.stats.JobStatsTests;
import org.elasticsearch.test.AbstractXContentTestCase;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class GetJobStatsResponseTests extends AbstractXContentTestCase<GetJobStatsResponse> {
@Override
protected GetJobStatsResponse createTestInstance() {
int count = randomIntBetween(1, 5);
List<JobStats> results = new ArrayList<>(count);
for(int i = 0; i < count; i++) {
results.add(JobStatsTests.createRandomInstance());
}
return new GetJobStatsResponse(results, count);
}
@Override
protected GetJobStatsResponse doParseInstance(XContentParser parser) throws IOException {
return GetJobStatsResponse.fromXContent(parser);
}
@Override
protected boolean supportsUnknownFields() {
return false;
}
}
| apache-2.0 |
wseyler/pentaho-kettle | ui/src/main/java/org/pentaho/di/ui/spoon/SpoonUiExtenderPluginInterface.java | 1152 | /*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.ui.spoon;
import java.util.Set;
import java.util.Map;
public interface SpoonUiExtenderPluginInterface {
public Map<Class<?>, Set<String>> respondsTo();
public void uiEvent( Object subject, String event );
}
| apache-2.0 |
kkashi01/appinventor-sources | appinventor/components/src/com/google/appinventor/components/annotations/SimpleObject.java | 918 | // -*- mode: java; c-basic-offset: 2; -*-
// Copyright 2009-2011 Google, All Rights reserved
// Copyright 2011-2012 MIT, All rights reserved
// Released under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
package com.google.appinventor.components.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation to mark Simple objects.
*
* <p>Note that the Simple compiler will only recognize Java classes marked
* with this annotation. All other classes will be ignored.
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface SimpleObject {
/**
* True if this component is an external component.
* Setting to True is mandatory for packing Extensions (aix)
*/
boolean external() default false;
}
| apache-2.0 |
madhawa-gunasekara/carbon-commons | components/application-mgt/org.wso2.carbon.application.mgt/src/main/java/org/wso2/carbon/application/mgt/ArtifactDeploymentStatus.java | 1413 | /*
* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.carbon.application.mgt;
import org.wso2.carbon.application.deployer.AppDeployerConstants;
/* This class is used in tracking the deployment status of individual artifacts in a CApp */
public class ArtifactDeploymentStatus {
private String artifactName;
private String deploymentStatus = AppDeployerConstants.DEPLOYMENT_STATUS_PENDING;
public String getArtifactName() {
return artifactName;
}
public void setArtifactName(String artifactName) {
this.artifactName = artifactName;
}
public String getDeploymentStatus() {
return deploymentStatus;
}
public void setDeploymentStatus(String deploymentStatus) {
this.deploymentStatus = deploymentStatus;
}
}
| apache-2.0 |
jimczi/elasticsearch | core/src/test/java/org/elasticsearch/search/functionscore/FunctionScoreFieldValueIT.java | 6350 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.search.functionscore;
import org.elasticsearch.action.search.SearchPhaseExecutionException;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.lucene.search.function.FieldValueFactorFunction;
import org.elasticsearch.test.ESIntegTestCase;
import java.io.IOException;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.index.query.QueryBuilders.functionScoreQuery;
import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
import static org.elasticsearch.index.query.QueryBuilders.simpleQueryStringQuery;
import static org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders.fieldValueFactorFunction;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertFailures;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertOrderedSearchHits;
/**
* Tests for the {@code field_value_factor} function in a function_score query.
*/
public class FunctionScoreFieldValueIT extends ESIntegTestCase {
public void testFieldValueFactor() throws IOException {
assertAcked(prepareCreate("test").addMapping(
"type1",
jsonBuilder()
.startObject()
.startObject("type1")
.startObject("properties")
.startObject("test")
.field("type", randomFrom(new String[]{"short", "float", "long", "integer", "double"}))
.endObject()
.startObject("body")
.field("type", "text")
.endObject()
.endObject()
.endObject()
.endObject()).get());
client().prepareIndex("test", "type1", "1").setSource("test", 5, "body", "foo").get();
client().prepareIndex("test", "type1", "2").setSource("test", 17, "body", "foo").get();
client().prepareIndex("test", "type1", "3").setSource("body", "bar").get();
refresh();
// document 2 scores higher because 17 > 5
SearchResponse response = client().prepareSearch("test")
.setExplain(randomBoolean())
.setQuery(functionScoreQuery(simpleQueryStringQuery("foo"), fieldValueFactorFunction("test")))
.get();
assertOrderedSearchHits(response, "2", "1");
// try again, but this time explicitly use the do-nothing modifier
response = client().prepareSearch("test")
.setExplain(randomBoolean())
.setQuery(functionScoreQuery(simpleQueryStringQuery("foo"),
fieldValueFactorFunction("test").modifier(FieldValueFactorFunction.Modifier.NONE)))
.get();
assertOrderedSearchHits(response, "2", "1");
// document 1 scores higher because 1/5 > 1/17
response = client().prepareSearch("test")
.setExplain(randomBoolean())
.setQuery(functionScoreQuery(simpleQueryStringQuery("foo"),
fieldValueFactorFunction("test").modifier(FieldValueFactorFunction.Modifier.RECIPROCAL)))
.get();
assertOrderedSearchHits(response, "1", "2");
// doc 3 doesn't have a "test" field, so an exception will be thrown
try {
response = client().prepareSearch("test")
.setExplain(randomBoolean())
.setQuery(functionScoreQuery(matchAllQuery(), fieldValueFactorFunction("test")))
.get();
assertFailures(response);
} catch (SearchPhaseExecutionException e) {
// We are expecting an exception, because 3 has no field
}
// doc 3 doesn't have a "test" field but we're defaulting it to 100 so it should be last
response = client().prepareSearch("test")
.setExplain(randomBoolean())
.setQuery(functionScoreQuery(matchAllQuery(),
fieldValueFactorFunction("test").modifier(FieldValueFactorFunction.Modifier.RECIPROCAL).missing(100)))
.get();
assertOrderedSearchHits(response, "1", "2", "3");
// field is not mapped but we're defaulting it to 100 so all documents should have the same score
response = client().prepareSearch("test")
.setExplain(randomBoolean())
.setQuery(functionScoreQuery(matchAllQuery(),
fieldValueFactorFunction("notmapped").modifier(FieldValueFactorFunction.Modifier.RECIPROCAL).missing(100)))
.get();
assertEquals(response.getHits().getAt(0).getScore(), response.getHits().getAt(2).getScore(), 0);
// n divided by 0 is infinity, which should provoke an exception.
try {
response = client().prepareSearch("test")
.setExplain(randomBoolean())
.setQuery(functionScoreQuery(simpleQueryStringQuery("foo"),
fieldValueFactorFunction("test").modifier(FieldValueFactorFunction.Modifier.RECIPROCAL).factor(0)))
.get();
assertFailures(response);
} catch (SearchPhaseExecutionException e) {
// This is fine, the query will throw an exception if executed
// locally, instead of just having failures
}
}
}
| apache-2.0 |
rokn/Count_Words_2015 | testing/openjdk/langtools/test/tools/javac/6567415/T6567415.java | 4937 | /*
* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 6567415
* @summary Test to ensure javac does not go into an infinite loop, while
* reading a classfile of a specific length.
* @compile -XDignore.symbol.file T6567415.java
* @run main T6567415
* @author ksrini
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
/*
* this test compiles Bar.java into a classfile and enlarges the file to the
* magic file length, then use this mutated file on the classpath to compile
* Foo.java which references Bar.java and Ka-boom. QED.
*/
public class T6567415 {
final static String TEST_FILE_NAME = "Bar";
final static String TEST_JAVA = TEST_FILE_NAME + ".java";
final static String TEST_CLASS = TEST_FILE_NAME + ".class";
final static String TEST2_FILE_NAME = "Foo";
final static String TEST2_JAVA = TEST2_FILE_NAME + ".java";
/*
* the following is the initial buffer length set in ClassReader.java
* thus this value needs to change if ClassReader buf length changes.
*/
final static int BAD_FILE_LENGTH =
com.sun.tools.javac.jvm.ClassReader.INITIAL_BUFFER_SIZE;
static void createClassFile() throws IOException {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(TEST_JAVA);
PrintStream ps = new PrintStream(fos);
ps.println("public class " + TEST_FILE_NAME + " {}");
} finally {
fos.close();
}
String cmds[] = {TEST_JAVA};
com.sun.tools.javac.Main.compile(cmds);
}
static void enlargeClassFile() throws IOException {
File f = new File(TEST_CLASS);
if (!f.exists()) {
System.out.println("file not found: " + TEST_CLASS);
System.exit(1);
}
File tfile = new File(f.getAbsolutePath() + ".tmp");
f.renameTo(tfile);
RandomAccessFile raf = null;
FileChannel wfc = null;
FileInputStream fis = null;
FileChannel rfc = null;
try {
raf = new RandomAccessFile(f, "rw");
wfc = raf.getChannel();
fis = new FileInputStream(tfile);
rfc = fis.getChannel();
ByteBuffer bb = MappedByteBuffer.allocate(BAD_FILE_LENGTH);
rfc.read(bb);
bb.rewind();
wfc.write(bb);
wfc.truncate(BAD_FILE_LENGTH);
} finally {
wfc.close();
raf.close();
rfc.close();
fis.close();
}
System.out.println("file length = " + f.length());
}
static void createJavaFile() throws IOException {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(TEST2_JAVA);
PrintStream ps = new PrintStream(fos);
ps.println("public class " + TEST2_FILE_NAME +
" {" + TEST_FILE_NAME + " b = new " +
TEST_FILE_NAME + " ();}");
} finally {
fos.close();
}
}
public static void main(String... args) throws Exception {
createClassFile();
enlargeClassFile();
createJavaFile();
Thread t = new Thread () {
@Override
public void run() {
String cmds[] = {"-verbose", "-cp", ".", TEST2_JAVA};
int ret = com.sun.tools.javac.Main.compile(cmds);
System.out.println("test compilation returns: " + ret);
}
};
t.start();
t.join(1000*10);
System.out.println(t.getState());
if (t.isAlive()) {
throw new RuntimeException("Error: compilation is looping");
}
}
}
| mit |
rokn/Count_Words_2015 | testing/openjdk/jdk/src/share/classes/java/beans/beancontext/BeanContextChild.java | 5486 | /*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.beans.beancontext;
import java.beans.PropertyChangeListener;
import java.beans.VetoableChangeListener;
import java.beans.PropertyVetoException;
import java.beans.beancontext.BeanContext;
/**
* <p>
* JavaBeans wishing to be nested within, and obtain a reference to their
* execution environment, or context, as defined by the BeanContext
* sub-interface shall implement this interface.
* </p>
* <p>
* Conformant BeanContexts shall as a side effect of adding a BeanContextChild
* object shall pass a reference to itself via the setBeanContext() method of
* this interface.
* </p>
* <p>
* Note that a BeanContextChild may refuse a change in state by throwing
* PropertyVetoedException in response.
* </p>
* <p>
* In order for persistence mechanisms to function properly on BeanContextChild
* instances across a broad variety of scenarios, implementing classes of this
* interface are required to define as transient, any or all fields, or
* instance variables, that may contain, or represent, references to the
* nesting BeanContext instance or other resources obtained
* from the BeanContext via any unspecified mechanisms.
* </p>
*
* @author Laurence P. G. Cable
* @since 1.2
*
* @see java.beans.beancontext.BeanContext
* @see java.beans.PropertyChangeEvent
* @see java.beans.PropertyChangeListener
* @see java.beans.PropertyVetoException
* @see java.beans.VetoableChangeListener
*/
public interface BeanContextChild {
/**
* <p>
* Objects that implement this interface,
* shall fire a java.beans.PropertyChangeEvent, with parameters:
*
* propertyName "beanContext", oldValue (the previous nesting
* <code>BeanContext</code> instance, or <code>null</code>),
* newValue (the current nesting
* <code>BeanContext</code> instance, or <code>null</code>).
* <p>
* A change in the value of the nesting BeanContext property of this
* BeanContextChild may be vetoed by throwing the appropriate exception.
* </p>
* @param bc The <code>BeanContext</code> with which
* to associate this <code>BeanContextChild</code>.
* @throws <code>PropertyVetoException</code> if the
* addition of the specified <code>BeanContext</code> is refused.
*/
void setBeanContext(BeanContext bc) throws PropertyVetoException;
/**
* Gets the <code>BeanContext</code> associated
* with this <code>BeanContextChild</code>.
* @return the <code>BeanContext</code> associated
* with this <code>BeanContextChild</code>.
*/
BeanContext getBeanContext();
/**
* Adds a <code>PropertyChangeListener</code>
* to this <code>BeanContextChild</code>
* in order to receive a <code>PropertyChangeEvent</code>
* whenever the specified property has changed.
* @param name the name of the property to listen on
* @param pcl the <code>PropertyChangeListener</code> to add
*/
void addPropertyChangeListener(String name, PropertyChangeListener pcl);
/**
* Removes a <code>PropertyChangeListener</code> from this
* <code>BeanContextChild</code> so that it no longer
* receives <code>PropertyChangeEvents</code> when the
* specified property is changed.
*
* @param name the name of the property that was listened on
* @param pcl the <code>PropertyChangeListener</code> to remove
*/
void removePropertyChangeListener(String name, PropertyChangeListener pcl);
/**
* Adds a <code>VetoableChangeListener</code> to
* this <code>BeanContextChild</code>
* to receive events whenever the specified property changes.
* @param name the name of the property to listen on
* @param vcl the <code>VetoableChangeListener</code> to add
*/
void addVetoableChangeListener(String name, VetoableChangeListener vcl);
/**
* Removes a <code>VetoableChangeListener</code> from this
* <code>BeanContextChild</code> so that it no longer receives
* events when the specified property changes.
* @param name the name of the property that was listened on.
* @param vcl the <code>VetoableChangeListener</code> to remove.
*/
void removeVetoableChangeListener(String name, VetoableChangeListener vcl);
}
| mit |
tasomaniac/u2020 | src/main/java/com/jakewharton/u2020/data/api/oauth/OauthService.java | 651 | package com.jakewharton.u2020.data.api.oauth;
import android.app.IntentService;
import android.content.Intent;
import com.jakewharton.u2020.data.Injector;
import dagger.ObjectGraph;
import javax.inject.Inject;
public final class OauthService extends IntentService {
@Inject OauthManager oauthManager;
public OauthService() {
super(OauthService.class.getSimpleName());
}
@Override public void onCreate() {
super.onCreate();
ObjectGraph appGraph = Injector.obtain(getApplication());
appGraph.inject(this);
}
@Override protected void onHandleIntent(Intent intent) {
oauthManager.handleResult(intent.getData());
}
}
| apache-2.0 |
OpenCollabZA/sakai | samigo/samigo-services/src/java/org/sakaiproject/tool/assessment/facade/FavoriteColChoicesFacadeQueriesAPI.java | 958 | /**
* Copyright (c) 2005-2012 The Apereo Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://opensource.org/licenses/ecl2
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sakaiproject.tool.assessment.facade;
import java.util.List;
import org.sakaiproject.tool.assessment.data.dao.assessment.FavoriteColChoices;
public interface FavoriteColChoicesFacadeQueriesAPI {
public List getFavoriteColChoicesByAgent(String siteAgentId);
public void saveOrUpdate(FavoriteColChoices list);
}
| apache-2.0 |
rokn/Count_Words_2015 | testing/openjdk2/jaxp/src/com/sun/org/apache/xerces/internal/impl/dv/dtd/NMTOKENDatatypeValidator.java | 1881 | /*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/*
* Copyright 1999-2002,2004,2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sun.org.apache.xerces.internal.impl.dv.dtd;
import com.sun.org.apache.xerces.internal.impl.dv.*;
import com.sun.org.apache.xerces.internal.util.XMLChar;
/**
* NMTOKEN datatype validator.
*
* @xerces.internal
*
* @author Jeffrey Rodriguez, IBM
* @author Sandy Gao, IBM
*
*/
public class NMTOKENDatatypeValidator implements DatatypeValidator {
// construct a NMTOKEN datatype validator
public NMTOKENDatatypeValidator() {
}
/**
* Checks that "content" string is valid NMTOKEN value.
* If invalid a Datatype validation exception is thrown.
*
* @param content the string value that needs to be validated
* @param context the validation context
* @throws InvalidDatatypeException if the content is
* invalid according to the rules for the validators
* @see InvalidDatatypeValueException
*/
public void validate(String content, ValidationContext context) throws InvalidDatatypeValueException {
if (!XMLChar.isValidNmtoken(content)) {
throw new InvalidDatatypeValueException("NMTOKENInvalid", new Object[]{content});
}
}
} // class NMTOKENDatatypeValidator
| mit |
taimos/openhab | bundles/io/org.openhab.io.myopenhab/src/main/java/org/openhab/io/myopenhab/internal/MyOHClient.java | 18913 | /**
* Copyright (c) 2010-2015, openHAB.org and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.io.myopenhab.internal;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.eclipse.jetty.client.ContentExchange;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.io.Buffer;
import org.eclipse.jetty.io.ByteArrayBuffer;
import org.eclipse.jetty.util.URIUtil;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.nkzawa.emitter.Emitter;
import com.github.nkzawa.engineio.client.Transport;
import com.github.nkzawa.socketio.client.IO;
import com.github.nkzawa.socketio.client.Manager;
import com.github.nkzawa.socketio.client.Socket;
/**
* This class provides communication between openHAB and my.openHAB service.
* It also implements async http proxy for serving requests from user to
* openHAB through my.openHAB. It uses Socket.IO connection to connect to
* my.openHAB service and Jetty Http client to send local http requests to
* openHAB.
*
* @author Victor Belov
* @since 1.3.0
*
*/
public class MyOHClient {
/*
* Logger for this class
*/
private static Logger logger = LoggerFactory.getLogger(MyOHClient.class);
/*
* This constant defines maximum number of HTTP connections per peer
* address for HTTP client which performs local connections to openHAB
*/
private static final int HTTP_CLIENT_MAX_CONNECTOPNS_PER_ADDRESS = 200;
/*
* This constant defines HTTP request timeout. It should be kept at about
* 30 seconds minimum to make it work for long polling requests
*/
private static final int HTTP_CLIENT_TIMEOUT = 30000;
/*
* This variable holds base URL for my.openHAB cloud connections, has a default
* value but can be changed
*/
private String mMyOHBaseUrl = "https://my.openhab.org/";
// openHAB UUID
/*
* This variable holds openHAB's UUID for authenticating and connecting to my.openHAB cloud
*/
private String mUUID;
/*
* This variable holds openHAB's secret for authenticating and connecting to my.openHAB cloud
*/
private String mSecret;
/*
* This variable holds local openHAB's base URL for connecting to local openHAB instance
*/
private String mOHBaseUrl = "http://localhost:8080";
/*
* This variable holds instance of Jetty HTTP client to make requests to local openHAB
*/
private HttpClient mJettyClient;
/*
* This hashmap holds HTTP requests to local openHAB which are currently running
*/
private HashMap<Integer, MyOHExchange> mRunningRequests;
/*
* This variable indicates if connection to my.openHAB cloud is currently in an established state
*/
private boolean mIsConnected;
/*
* This variable holds version of local openHAB
*/
private String mOpenHABVersion;
/*
* This variable holds instance of Socket.IO client class which provides communication
* with my.openHAB cloud
*/
private Socket mSocket;
/*
* This variable holds instance of MyOHClientListener which provides callbacks to communicate
* certain events from my.openHAB cloud back to openHAB
*/
private MyOHClientListener mListener;
/**
* Constructor of MyOHClient
*
* @param uuid openHAB's UUID to connect to my.openHAB
* @param secret openHAB's Secret to connect to my.openHAB
*
*/
public MyOHClient(String uuid, String secret) {
mUUID = uuid;
mSecret = secret;
mRunningRequests = new HashMap<Integer, MyOHExchange>();
mJettyClient = new HttpClient();
mJettyClient.setConnectorType(HttpClient.CONNECTOR_SELECT_CHANNEL);
mJettyClient.setMaxConnectionsPerAddress(HTTP_CLIENT_MAX_CONNECTOPNS_PER_ADDRESS);
mJettyClient.setTimeout(HTTP_CLIENT_TIMEOUT);
try {
mJettyClient.start();
} catch (Exception e) {
logger.error("Error starting JettyClient: {}", e.getMessage());
}
}
/**
* Connect to my.openHAB
*/
public void connect() {
try {
mSocket = IO.socket(mMyOHBaseUrl);
} catch (URISyntaxException e) {
logger.error("Error creating Socket.IO: {}", e.getMessage());
}
mSocket.io().on(Manager.EVENT_TRANSPORT,
new Emitter.Listener() {
@Override
public void call(Object... args) {
logger.debug("Manager.EVENT_TRANSPORT");
Transport transport = (Transport)args[0];
transport.on(Transport.EVENT_REQUEST_HEADERS, new Emitter.Listener() {
@Override
public void call(Object... args) {
logger.debug("Transport.EVENT_REQUEST_HEADERS");
Map<String, String> headers = (Map<String, String>) args[0];
headers.put("uuid", mUUID);
headers.put("secret", mSecret);
headers.put("openhabversion", mOpenHABVersion);
headers.put("myohversion", MyOpenHABServiceImpl.myohVersion);
}
});
}
}
);
mSocket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
@Override
public void call(Object... args) {
logger.debug("Socket.IO connected");
mIsConnected = true;
onConnect();
}
}).on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {
@Override
public void call(Object... args) {
logger.debug("Socket.IO disconnected");
mIsConnected = false;
onDisconnect();
}
}).on(Socket.EVENT_ERROR, new Emitter.Listener() {
@Override
public void call(Object... args) {
logger.error("Socket.IO error: " + args[0]);
}
}).on("request", new Emitter.Listener() {
@Override
public void call(Object... args) {
onEvent("request", (JSONObject)args[0]);
}
}).on("cancel", new Emitter.Listener() {
@Override
public void call(Object... args) {
onEvent("cancel", (JSONObject)args[0]);
}
}).on("command", new Emitter.Listener() {
@Override
public void call(Object... args) {
onEvent("command", (JSONObject)args[0]);
}
});
mSocket.connect();
}
/**
* Callback method for socket.io client which is called when connection is established
*/
public void onConnect() {
logger.info("Connected to my.openHAB service (UUID = {}, base URL = {})", this.mUUID, this.mOHBaseUrl);
mIsConnected = true;
}
/**
* Callback method for socket.io client which is called when disconnect occurs
*/
public void onDisconnect() {
logger.info("Disconnected from my.openHAB service (UUID = {}, base URL = {})", this.mUUID, this.mOHBaseUrl);
mIsConnected = false;
}
/**
* Callback method for socket.io client which is called when an error occurs
*/
public void onError(IOException error) {
logger.error(error.getMessage());
}
/**
* Callback method for socket.io client which is called when a message is received
*/
public void onEvent(String event, JSONObject data) {
logger.debug("on(): " + event);
if ("request".equals(event)) {
handleRequestEvent(data);
} else if ("cancel".equals(event)) {
handleCancelEvent(data);
} else if ("command".equals(event)) {
handleCommandEvent(data);
} else {
logger.warn("Unsupported event from my.openHAB: {}", event);
}
}
private void handleRequestEvent(JSONObject data) {
try {
// Get myOH uniq request Id
int requestId = data.getInt("id");
logger.debug("Got request {}", requestId);
// Get request path
String requestPath = data.getString("path");
// Get request method
String requestMethod = data.getString("method");
// Get request body
String requestBody = data.getString("body");
// Get JSONObject for request headers
JSONObject requestHeadersJson = data.getJSONObject("headers");
logger.debug(requestHeadersJson.toString());
// Get JSONObject for request query parameters
JSONObject requestQueryJson = data.getJSONObject("query");
Iterator<String> headersIterator = requestHeadersJson.keys();
// Create URI builder with base request URI of openHAB and path from request
String newPath = URIUtil.addPaths(mOHBaseUrl, requestPath);
Iterator<String> queryIterator = requestQueryJson.keys();
// Add query parameters to URI builder, if any
newPath +="?";
while (queryIterator.hasNext()) {
String queryName = queryIterator.next();
newPath += queryName;
newPath += "=";
newPath += URLEncoder.encode(requestQueryJson.getString(queryName), "UTF-8");
if (queryIterator.hasNext())
newPath += "&";
}
// Finally get the future request URI
URI requestUri = new URI(newPath);
// All preparations which are common for different methods are done
// Now perform the request to openHAB
// If method is GET
logger.debug("Request method is " + requestMethod);
MyOHExchange exchange = new MyOHExchange(requestId);
exchange.setURI(requestUri);
exchange.setRequestHeaders(requestHeadersJson);
exchange.setRequestHeader("X-Forwarded-Proto", "https");
if (requestMethod.equals("GET")) {
exchange.setMethod("GET");
} else if (requestMethod.equals("POST")) {
exchange.setMethod("POST");
Buffer requestContent = new ByteArrayBuffer(requestBody);
exchange.setRequestContent(requestContent);
} else if (requestMethod.equals("PUT")) {
exchange.setMethod("PUT");
Buffer requestContent = new ByteArrayBuffer(requestBody);
exchange.setRequestContent(requestContent);
} else {
// TODO: Reject unsupported methods
logger.error("Unsupported request method " + requestMethod);
return;
}
mJettyClient.send(exchange);
// If successfully submitted request to http client, add it to the list of currently
// running requests to be able to cancel it if needed
mRunningRequests.put(requestId, exchange);
} catch (JSONException e) {
logger.error(e.getMessage());
} catch (IOException e) {
logger.error(e.getMessage());
} catch (URISyntaxException e) {
logger.error(e.getMessage());
}
}
private void handleCancelEvent(JSONObject data) {
try {
int requestId = data.getInt("id");
logger.debug("Received cancel for request {}", requestId);
// Find and cancel running request
if (mRunningRequests.containsKey(requestId)) {
MyOHExchange requestExchange = mRunningRequests.get(requestId);
requestExchange.cancel();
mRunningRequests.remove(requestId);
}
} catch (JSONException e) {
logger.error(e.getMessage());
}
}
private void handleCommandEvent(JSONObject data) {
try {
logger.debug("Received command " + data.getString("command") + " for item " + data.getString("item"));
if (this.mListener != null)
this.mListener.sendCommand(data.getString("item"), data.getString("command"));
} catch (JSONException e) {
logger.error(e.getMessage());
}
}
/**
* This method sends notification to my.openHAB
*
* @param userId my.openHAB user id
* @param message notification message text
* @param icon name of the icon for this notification
* @param severity severity name for this notification
*
*/
public void sendNotification(String userId, String message, String icon, String severity) {
if (isConnected()) {
JSONObject notificationMessage = new JSONObject();
try {
notificationMessage.put("userId", userId);
notificationMessage.put("message", message);
notificationMessage.put("icon", icon);
notificationMessage.put("severity", severity);
mSocket.emit("notification", notificationMessage);
} catch (JSONException e) {
logger.error(e.getMessage());
}
} else {
logger.debug("No connection, notification is not sent");
}
}
/**
* Send SMS to my.openHAB
*
* @param phone number to send notification to
* @param message text to send
*
*/
public void sendSMS(String phone, String message) {
if (isConnected()) {
JSONObject smsMessage = new JSONObject();
try {
smsMessage.put("phone", phone);
smsMessage.put("message", message);
mSocket.emit("sms", smsMessage);
} catch (JSONException e) {
logger.error(e.getMessage());
}
} else {
logger.debug("No connection, SMS is not sent");
}
}
/**
* Send item update to my.openHAB
*
* @param itemName the name of the item
* @param itemStatus updated item status
*
*/
public void sendItemUpdate(String itemName, String itemStatus) {
if (isConnected()) {
JSONObject itemUpdateMessage = new JSONObject();
try {
itemUpdateMessage.put("itemName", itemName);
itemUpdateMessage.put("itemStatus", itemStatus);
mSocket.emit("itemupdate", itemUpdateMessage);
} catch (JSONException e) {
logger.error(e.getMessage());
}
} else {
logger.debug("No connection, Item update is not sent");
}
}
/**
* Returns true if my.openHAB connection is active
*/
public boolean isConnected() {
return mIsConnected;
}
/**
* Disconnect from my.openHAB
*/
public void shutdown() {
logger.info("Shutting down my.openHAB service connection");
try {
mJettyClient.stop();
} catch (Exception e) {
logger.error(e.getMessage());
}
mSocket.disconnect();
}
/**
* Set base URL of my.openHAB cloud
*
* @param myOHBaseUrl base URL in http://host:port form
*
*/
public void setMyOHBaseUrl(String myOHBaseUrl) {
mMyOHBaseUrl = myOHBaseUrl;
}
/**
* Set base local URL of openHAB
*
* @param ohBaseUrl base local URL of openHAB in http://host:port form
*
*/
public void setOHBaseUrl(String ohBaseUrl) {
this.mOHBaseUrl = ohBaseUrl;
}
public String getOpenHABVersion() {
return mOpenHABVersion;
}
public void setOpenHABVersion(String mOpenHABVersion) {
this.mOpenHABVersion = mOpenHABVersion;
}
public void setListener(MyOHClientListener mListener) {
this.mListener = mListener;
}
/*
* An internal class which extends ContentExchange and forwards response
* headers and data back to my.openHAB
*
*/
private class MyOHExchange extends ContentExchange {
private int mRequestId;
private HashMap<String, String> mResponseHeaders;
public MyOHExchange(int requestId) {
mRequestId = requestId;
mResponseHeaders = new HashMap<String, String>();
}
public void setRequestHeaders(JSONObject requestHeadersJson) {
Iterator<String> headersIterator = requestHeadersJson.keys();
// Convert JSONObject of headers into Header ArrayList
while (headersIterator.hasNext()) {
String headerName = headersIterator.next();
String headerValue;
try {
headerValue = requestHeadersJson.getString(headerName);
logger.debug("Jetty set header " + headerName + " = " + headerValue);
if (!headerName.equalsIgnoreCase("Content-Length")) {
this.setRequestHeader(headerName, headerValue);
}
} catch (JSONException e) {
logger.error("Error processing request headers: {}", e.getMessage());
}
}
}
public JSONObject getJSONHeaders() {
JSONObject headersJSON = new JSONObject();
try {
for (Map.Entry<String, String> responseHeader : mResponseHeaders.entrySet()) {
headersJSON.put(responseHeader.getKey(), responseHeader.getValue());
}
} catch (JSONException e) {
logger.error("Error forming response headers: {}", e.getMessage());
}
return headersJSON;
}
/*
* This is old onResponseContent which used base64 encoding, keep it here commented for some time
* The new onResponseContent uses 'responseContentBinary' to send response data
@Override
public void onResponseContent(Buffer content) {
logger.debug("Jetty received response content of size " + String.valueOf(content.length()));
JSONObject responseJson = new JSONObject();
String base64ResponseBody = Base64.encodeBytes(content.asArray());
try {
responseJson.put("id", mRequestId);
responseJson.put("body", base64ResponseBody);
if (this.getStatus() != STATUS_CANCELLING && this.getStatus() != STATUS_CANCELLED)
mSocket.emit("responseContent", responseJson);
logger.debug(String.format("Sent content to request %d", mRequestId));
} catch (JSONException e) {
e.printStackTrace();
}
}*/
/*
* This is a new onResponseContent which uses binary encoding
*/
@Override
public void onResponseContent(Buffer content) {
logger.debug("Jetty received response content of size " + String.valueOf(content.length()));
JSONObject responseJson = new JSONObject();
try {
responseJson.put("id", mRequestId);
responseJson.put("body", content.asArray());
if (this.getStatus() != STATUS_CANCELLING && this.getStatus() != STATUS_CANCELLED) {
mSocket.emit("responseContentBinary", responseJson);
}
logger.debug("Sent content to request {}", mRequestId);
} catch (JSONException e) {
logger.error(e.getMessage());
}
}
@Override
public void onResponseHeader(Buffer name, Buffer value) {
mResponseHeaders.put(name.toString(), value.toString());
logger.debug("Jetty received header " + name.toString() + " = " + value.toString());
}
@Override
public void onResponseHeaderComplete() {
logger.debug("Jetty finished receiving response header");
JSONObject responseJson = new JSONObject();
try {
responseJson.put("id", mRequestId);
responseJson.put("headers", getJSONHeaders());
responseJson.put("responseStatusCode", getResponseStatus());
responseJson.put("responseStatusText", "OK");
if (this.getStatus() != STATUS_CANCELLING && this.getStatus() != STATUS_CANCELLED) {
mSocket.emit("responseHeader", responseJson);
}
logger.debug("Sent headers to request {}", mRequestId);
} catch (JSONException e) {
logger.error(e.getMessage());
}
}
@Override
protected void onResponseComplete() {
int status = getResponseStatus();
logger.debug("Jetty request complete {} with status {}", mRequestId, status);
// Remove this request from list of running requests
mRunningRequests.remove(mRequestId);
JSONObject responseJson = new JSONObject();
try {
responseJson.put("id", mRequestId);
if (this.getStatus() != STATUS_CANCELLING && this.getStatus() != STATUS_CANCELLED) {
mSocket.emit("responseFinished", responseJson);
}
logger.debug("Finished responding to request {}", mRequestId);
} catch (JSONException e) {
// TODO Auto-generated catch block
logger.error(e.getMessage());
}
}
@Override
protected void onConnectionFailed(Throwable x) {
logger.error(x.getMessage());
JSONObject responseJson = new JSONObject();
try {
responseJson.put("id", mRequestId);
responseJson.put("responseStatusText", "openHAB connection error: " + x.getMessage());
if (this.getStatus() != STATUS_CANCELLING && this.getStatus() != STATUS_CANCELLED) {
mSocket.emit("responseError", responseJson);
}
} catch (JSONException e) {
logger.error(e.getMessage());
}
}
}
}
| epl-1.0 |
lctseng/NCTU-SDN-Project | src/test/java/com/bigswitch/floodlight/vendor/OFActionNiciraTtlDecrementTest.java | 1945 | package com.bigswitch.floodlight.vendor;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.junit.Test;
import org.openflow.protocol.action.OFAction;
import org.openflow.protocol.action.OFActionType;
import org.openflow.protocol.action.OFActionVendor;
import static org.junit.Assert.*;
public class OFActionNiciraTtlDecrementTest {
protected static byte[] expectedWireFormat = {
(byte) 0xff, (byte) 0xff, // action vendor
0x00, 0x10, // length
0x00, 0x00, 0x23, 0x20, // nicira
0x00, 0x12, // subtype 18 == 0x12
0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // pad
};
@Test
public void testAction() {
ChannelBuffer buf = ChannelBuffers.buffer(32);
OFActionNiciraTtlDecrement act = new OFActionNiciraTtlDecrement();
assertEquals(true, act instanceof OFActionNiciraVendor);
assertEquals(true, act instanceof OFActionVendor);
assertEquals(true, act instanceof OFAction);
act.writeTo(buf);
ChannelBuffer buf2 = buf.copy();
assertEquals(16, buf.readableBytes());
byte fromBuffer[] = new byte[16];
buf.readBytes(fromBuffer);
assertArrayEquals(expectedWireFormat, fromBuffer);
// Test parsing. TODO: we don't really have the proper parsing
// infrastructure....
OFActionNiciraVendor act2 = new OFActionNiciraTtlDecrement();
act2.readFrom(buf2);
assertEquals(act, act2);
assertNotSame(act, act2);
assertEquals(OFActionType.VENDOR, act2.getType());
assertEquals(16, act2.getLength());
assertEquals(OFActionNiciraVendor.NICIRA_VENDOR_ID, act2.getVendor());
assertEquals((short)18, act2.getSubtype());
}
}
| apache-2.0 |
McBen/ingress-intel-total-conversion | mobile_old/src/com/cradle/iitc_mobile/IITC_NotificationHelper.java | 3505 | package com.cradle.iitc_mobile;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
public class IITC_NotificationHelper {
public static final int NOTICE_HOWTO = 1 << 0;
public static final int NOTICE_INFO = 1 << 1;
public static final int NOTICE_PANES = 1 << 2;
public static final int NOTICE_EXTPLUGINS = 1 << 3;
public static final int NOTICE_SHARING = 1 << 4;
// next one would be 1<<5; (this results in 1,2,4,8,...)
private final Activity mActivity;
private final SharedPreferences mPrefs;
private int mDialogs = 0;
public IITC_NotificationHelper(final Activity activity) {
mActivity = activity;
mPrefs = PreferenceManager.getDefaultSharedPreferences(mActivity);
}
public void showNotice(final int which) {
if ((mPrefs.getInt("pref_messages", 0) & which) != 0 || (mDialogs & which) != 0) return;
String text;
switch (which) {
case NOTICE_HOWTO:
text = mActivity.getString(R.string.notice_how_to);
break;
case NOTICE_INFO:
text = mActivity.getString(R.string.notice_info);
break;
case NOTICE_PANES:
text = mActivity.getString(R.string.notice_panes);
break;
case NOTICE_EXTPLUGINS:
text = mActivity.getString(R.string.notice_extplugins);
text = String.format(text, Environment.getExternalStorageDirectory().getPath()
+ "/IITC_Mobile/plugins/");
break;
case NOTICE_SHARING:
text = mActivity.getString(R.string.notice_sharing);
break;
default:
return;
}
final View content = mActivity.getLayoutInflater().inflate(R.layout.dialog_notice, null);
final TextView message = (TextView) content.findViewById(R.id.tv_notice);
message.setText(Html.fromHtml(text));
message.setMovementMethod(LinkMovementMethod.getInstance());
final AlertDialog dialog = new AlertDialog.Builder(mActivity)
.setView(content)
.setCancelable(true)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface dialog, final int which) {
dialog.cancel();
}
})
.create();
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(final DialogInterface dialog) {
mDialogs &= ~which;
if (((CheckBox) content.findViewById(R.id.cb_do_not_show_again)).isChecked()) {
int value = mPrefs.getInt("pref_messages", 0);
value |= which;
mPrefs
.edit()
.putInt("pref_messages", value)
.commit();
}
}
});
mDialogs |= which;
dialog.show();
}
}
| isc |
rokn/Count_Words_2015 | testing/openjdk/langtools/test/tools/apt/Compile/HelloWorld.java | 150 | /* /nodynamiccopyright/ */
public class HelloWorld {
public static void main(String argv[]) {
System.out.println("Hello World.");
}
}
| mit |