repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
klopfdreh/wicket | wicket-core/src/main/java/org/apache/wicket/ajax/AjaxClientInfoBehavior.java | 4141 | /*
* 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.ajax;
import org.apache.wicket.Component;
import org.apache.wicket.Session;
import org.apache.wicket.ajax.attributes.AjaxRequestAttributes;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.JavaScriptHeaderItem;
import org.apache.wicket.markup.html.pages.BrowserInfoForm;
import org.apache.wicket.protocol.http.request.WebClientInfo;
import org.apache.wicket.request.IRequestParameters;
import org.apache.wicket.request.cycle.RequestCycle;
import org.apache.wicket.util.lang.Args;
import org.apache.wicket.util.time.Duration;
import org.danekja.java.util.function.serializable.SerializableBiConsumer;
/**
* An behavior that collects the information to populate
* WebClientInfo's ClientProperties by using Ajax
*
* @see #onClientInfo(AjaxRequestTarget, org.apache.wicket.protocol.http.request.WebClientInfo)
*/
public class AjaxClientInfoBehavior extends AbstractAjaxTimerBehavior
{
private static final long serialVersionUID = 1L;
/**
* Constructor.
*
* Auto fires after 50 millis.
*/
public AjaxClientInfoBehavior()
{
this(Duration.milliseconds(50));
}
/**
* Constructor. Auto fires after {@code duration}.
*
* @param duration the duration of the client info behavior
*/
public AjaxClientInfoBehavior(Duration duration)
{
super(duration);
}
@Override
protected final void onTimer(AjaxRequestTarget target)
{
stop(target);
RequestCycle requestCycle = RequestCycle.get();
IRequestParameters requestParameters = requestCycle.getRequest().getRequestParameters();
WebClientInfo clientInfo = newWebClientInfo(requestCycle);
clientInfo.getProperties().read(requestParameters);
Session.get().setClientInfo(clientInfo);
onClientInfo(target, clientInfo);
}
protected WebClientInfo newWebClientInfo(RequestCycle requestCycle)
{
return new WebClientInfo(requestCycle);
}
/**
* A callback method invoked when the client info is collected.
*
* @param target
* The Ajax request handler
* @param clientInfo
* The collected info for the client
*/
protected void onClientInfo(AjaxRequestTarget target, WebClientInfo clientInfo)
{
}
@Override
protected void updateAjaxAttributes(AjaxRequestAttributes attributes)
{
super.updateAjaxAttributes(attributes);
attributes.getDynamicExtraParameters().add("return Wicket.BrowserInfo.collect()");
}
@Override
public void renderHead(Component component, IHeaderResponse response)
{
super.renderHead(component, response);
response.render(JavaScriptHeaderItem.forReference(BrowserInfoForm.JS));
}
/**
* Creates an {@link AjaxClientInfoBehavior} based on lambda expressions
*
* @param onClientInfo
* the {@code SerializableBiConsumer} which accepts the {@link AjaxRequestTarget} and the
* {@link WebClientInfo}
* @return the {@link AjaxClientInfoBehavior}
*/
public static AjaxClientInfoBehavior onClientInfo(SerializableBiConsumer<AjaxRequestTarget, WebClientInfo> onClientInfo)
{
Args.notNull(onClientInfo, "onClientInfo");
return new AjaxClientInfoBehavior()
{
private static final long serialVersionUID = 1L;
@Override
protected void onClientInfo(AjaxRequestTarget target, WebClientInfo clientInfo)
{
onClientInfo.accept(target, clientInfo);
}
};
}
}
| apache-2.0 |
Phaneendra-Huawei/demo | protocols/ospf/ctl/src/test/java/org/onosproject/ospf/controller/area/OspfInterfaceImplTest.java | 16164 | /*
* Copyright 2016-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.ospf.controller.area;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.onlab.packet.Ip4Address;
import org.onosproject.ospf.controller.OspfNbr;
import org.onosproject.ospf.controller.TopologyForDeviceAndLink;
import org.onosproject.ospf.controller.impl.Controller;
import org.onosproject.ospf.controller.impl.OspfInterfaceChannelHandler;
import org.onosproject.ospf.controller.impl.OspfNbrImpl;
import org.onosproject.ospf.controller.impl.TopologyForDeviceAndLinkImpl;
import org.onosproject.ospf.protocol.lsa.OpaqueLsaHeader;
import org.onosproject.ospf.protocol.util.OspfInterfaceState;
import java.util.HashMap;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
/**
* Unit test class for OspfInterfaceImpl.
*/
public class OspfInterfaceImplTest {
private OspfInterfaceImpl ospfInterface;
private OspfNbrImpl ospfNbr;
private OpaqueLsaHeader opaqueLsaHeader;
private int result;
private HashMap<String, OspfNbr> ospfNbrHashMap;
private TopologyForDeviceAndLink topologyForDeviceAndLink;
@Before
public void setUp() throws Exception {
ospfInterface = new OspfInterfaceImpl();
topologyForDeviceAndLink = new TopologyForDeviceAndLinkImpl();
}
@After
public void tearDown() throws Exception {
ospfInterface = null;
ospfNbr = null;
opaqueLsaHeader = null;
ospfNbrHashMap = null;
}
/**
* Tests state() getter method.
*/
@Test
public void testGetState() throws Exception {
ospfInterface.setState(OspfInterfaceState.DROTHER);
assertThat(ospfInterface.state(), is(OspfInterfaceState.DROTHER));
}
/**
* Tests state() setter method.
*/
@Test
public void testSetState() throws Exception {
ospfInterface.setState(OspfInterfaceState.DROTHER);
assertThat(ospfInterface.state(), is(OspfInterfaceState.DROTHER));
}
/**
* Tests linkStateHeaders() method.
*/
@Test
public void testGetLinkStateHeaders() throws Exception {
assertThat(ospfInterface.linkStateHeaders().size(), is(0));
}
/**
* Tests ipNetworkMask() getter method.
*/
@Test
public void testGetIpNetworkMask() throws Exception {
ospfInterface.setIpNetworkMask(Ip4Address.valueOf("1.1.1.1"));
assertThat(ospfInterface.ipNetworkMask(), is(Ip4Address.valueOf("1.1.1.1")));
}
/**
* Tests ipNetworkMask() setter method.
*/
@Test
public void testSetIpNetworkMask() throws Exception {
ospfInterface.setIpNetworkMask(Ip4Address.valueOf("1.1.1.1"));
assertThat(ospfInterface.ipNetworkMask(), is(Ip4Address.valueOf("1.1.1.1")));
}
/**
* Tests addNeighbouringRouter() method.
*/
@Test
public void testAddNeighbouringRouter() throws Exception {
ospfNbr = new OspfNbrImpl(new OspfAreaImpl(), new OspfInterfaceImpl(),
Ip4Address.valueOf("1.1.1.1"), Ip4Address.valueOf("2.2.2.2"), 2,
new OspfInterfaceChannelHandler(new Controller(), new OspfAreaImpl(),
new OspfInterfaceImpl()),
topologyForDeviceAndLink);
ospfNbr.setNeighborId(Ip4Address.valueOf("111.111.111.111"));
ospfInterface.addNeighbouringRouter(ospfNbr);
assertThat(ospfInterface, is(notNullValue()));
}
/**
* Tests neighbouringRouter() method.
*/
@Test
public void testGetNeighbouringRouter() throws Exception {
ospfNbr = new OspfNbrImpl(new OspfAreaImpl(), new OspfInterfaceImpl(),
Ip4Address.valueOf("1.1.1.1"), Ip4Address.valueOf("2.2.2.2"), 2,
new OspfInterfaceChannelHandler(new Controller(), new OspfAreaImpl(),
new OspfInterfaceImpl()),
topologyForDeviceAndLink);
ospfNbr.setNeighborId(Ip4Address.valueOf("111.111.111.111"));
ospfInterface.addNeighbouringRouter(ospfNbr);
assertThat(ospfInterface.neighbouringRouter("111.111.111.111"), is(notNullValue()));
}
/**
* Tests addLsaHeaderForDelayAck() method.
*/
@Test
public void testAddLsaHeaderForDelayAck() throws Exception {
opaqueLsaHeader = new OpaqueLsaHeader();
opaqueLsaHeader.setLsType(10);
ospfInterface.addLsaHeaderForDelayAck(opaqueLsaHeader);
assertThat(ospfInterface, is(notNullValue()));
}
/**
* Tests removeLsaFromNeighborMap() method.
*/
@Test
public void testRemoveLsaFromNeighborMap() throws Exception {
ospfInterface.removeLsaFromNeighborMap("lsa10");
assertThat(ospfInterface, is(notNullValue()));
}
/**
* Tests isNeighborInList() method.
*/
@Test
public void testIsNeighborinList() throws Exception {
ospfNbr = new OspfNbrImpl(new OspfAreaImpl(), new OspfInterfaceImpl(),
Ip4Address.valueOf("1.1.1.1"), Ip4Address.valueOf("2.2.2.2"), 2,
new OspfInterfaceChannelHandler(new Controller(), new OspfAreaImpl(),
new OspfInterfaceImpl()),
topologyForDeviceAndLink);
ospfNbr.setNeighborId(Ip4Address.valueOf("111.111.111.111"));
ospfInterface.addNeighbouringRouter(ospfNbr);
assertThat(ospfInterface.isNeighborInList("111.111.111.111"), is(notNullValue()));
}
/**
* Tests listOfNeighbors() getter method.
*/
@Test
public void testGetListOfNeighbors() throws Exception {
ospfNbrHashMap = new HashMap();
ospfNbr = new OspfNbrImpl(new OspfAreaImpl(), new OspfInterfaceImpl(),
Ip4Address.valueOf("1.1.1.1"), Ip4Address.valueOf("2.2.2.2"), 2,
new OspfInterfaceChannelHandler(new Controller(),
new OspfAreaImpl(),
new OspfInterfaceImpl()),
topologyForDeviceAndLink);
ospfNbr.setNeighborId(Ip4Address.valueOf("111.111.111.111"));
ospfNbrHashMap.put("111.111.111.111", ospfNbr);
ospfInterface.setListOfNeighbors(ospfNbrHashMap);
assertThat(ospfInterface.listOfNeighbors().size(), is(1));
}
/**
* Tests listOfNeighbors() setter method.
*/
@Test
public void testSetListOfNeighbors() throws Exception {
ospfNbrHashMap = new HashMap();
ospfNbr = new OspfNbrImpl(new OspfAreaImpl(), new OspfInterfaceImpl(),
Ip4Address.valueOf("1.1.1.1"), Ip4Address.valueOf("2.2.2.2"), 2,
new OspfInterfaceChannelHandler(new Controller(), new OspfAreaImpl(),
new OspfInterfaceImpl()),
topologyForDeviceAndLink);
ospfNbr.setNeighborId(Ip4Address.valueOf("111.111.111.111"));
ospfNbrHashMap.put("111.111.111.111", ospfNbr);
ospfInterface.setListOfNeighbors(ospfNbrHashMap);
assertThat(ospfInterface.listOfNeighbors().size(), is(1));
}
/**
* Tests ipAddress() getter method.
*/
@Test
public void testGetIpAddress() throws Exception {
ospfInterface.setIpAddress(Ip4Address.valueOf("1.1.1.1"));
assertThat(ospfInterface.ipAddress(), is(Ip4Address.valueOf("1.1.1.1")));
}
/**
* Tests ipAddress() getter method.
*/
@Test
public void testSetIpAddress() throws Exception {
ospfInterface.setIpAddress(Ip4Address.valueOf("1.1.1.1"));
assertThat(ospfInterface.ipAddress(), is(Ip4Address.valueOf("1.1.1.1")));
}
/**
* Tests routerPriority() getter method.
*/
@Test
public void testGetRouterPriority() throws Exception {
ospfInterface.setRouterPriority(1);
Assert.assertEquals(1, ospfInterface.routerPriority());
}
/**
* Tests routerPriority() setter method.
*/
@Test
public void testSetRouterPriority() throws Exception {
ospfInterface.setRouterPriority(1);
assertThat(ospfInterface.routerPriority(), is(1));
}
/**
* Tests areaId() getter method.
*/
@Test
public void testGetAreaId() throws Exception {
ospfInterface.setAreaId(1);
assertThat(ospfInterface.areaId(), is(1));
}
/**
* Tests areaId() setter method.
*/
@Test
public void testSetAreaId() throws Exception {
ospfInterface.setAreaId(1);
assertThat(ospfInterface.areaId(), is(1));
}
/**
* Tests helloIntervalTime() getter method.
*/
@Test
public void testGetHelloIntervalTime() throws Exception {
ospfInterface.setHelloIntervalTime(10);
assertThat(ospfInterface.helloIntervalTime(), is(10));
}
/**
* Tests helloIntervalTime() setter method.
*/
@Test
public void testSetHelloIntervalTime() throws Exception {
ospfInterface.setHelloIntervalTime(10);
assertThat(ospfInterface.helloIntervalTime(), is(10));
}
/**
* Tests routerDeadIntervalTime() getter method.
*/
@Test
public void testGetRouterDeadIntervalTime() throws Exception {
ospfInterface.setRouterDeadIntervalTime(10);
assertThat(ospfInterface.routerDeadIntervalTime(), is(10));
}
/**
* Tests routerDeadIntervalTime() setter method.
*/
@Test
public void testSetRouterDeadIntervalTime() throws Exception {
ospfInterface.setRouterDeadIntervalTime(10);
assertThat(ospfInterface.routerDeadIntervalTime(), is(10));
}
/**
* Tests interfaceType() getter method.
*/
@Test
public void testGetInterfaceType() throws Exception {
ospfInterface.setInterfaceType(1);
assertThat(ospfInterface.interfaceType(), is(1));
}
/**
* Tests interfaceType() setter method.
*/
@Test
public void testSetInterfaceType() throws Exception {
ospfInterface.setInterfaceType(1);
assertThat(ospfInterface.interfaceType(), is(1));
}
/**
* Tests interfaceCost() getter method.
*/
@Test
public void testGetInterfaceCost() throws Exception {
ospfInterface.setInterfaceCost(100);
assertThat(ospfInterface.interfaceCost(), is(100));
}
/**
* Tests interfaceCost() setter method.
*/
@Test
public void testSetInterfaceCost() throws Exception {
ospfInterface.setInterfaceCost(100);
assertThat(ospfInterface.interfaceCost(), is(100));
}
/**
* Tests authType() getter method.
*/
@Test
public void testGetAuthType() throws Exception {
ospfInterface.setAuthType("00");
assertThat(ospfInterface.authType(), is("00"));
}
/**
* Tests authType() setter method.
*/
@Test
public void testSetAuthType() throws Exception {
ospfInterface.setAuthType("00");
assertThat(ospfInterface.authType(), is("00"));
}
/**
* Tests authKey() getter method.
*/
@Test
public void testGetAuthKey() throws Exception {
ospfInterface.setAuthKey("00");
assertThat(ospfInterface.authKey(), is("00"));
}
/**
* Tests authKey() setter method.
*/
@Test
public void testSetAuthKey() throws Exception {
ospfInterface.setAuthKey("00");
assertThat(ospfInterface.authKey(), is("00"));
}
/**
* Tests pollInterval() getter method.
*/
@Test
public void testGetPollInterval() throws Exception {
ospfInterface.setPollInterval(100);
assertThat(ospfInterface.pollInterval(), is(100));
}
/**
* Tests pollInterval() setter method.
*/
@Test
public void testSetPollInterval() throws Exception {
ospfInterface.setPollInterval(100);
assertThat(ospfInterface.pollInterval(), is(100));
}
/**
* Tests mtu() getter method.
*/
@Test
public void testGetMtu() throws Exception {
ospfInterface.setMtu(100);
assertThat(ospfInterface.mtu(), is(100));
}
/**
* Tests mtu() setter method.
*/
@Test
public void testSetMtu() throws Exception {
ospfInterface.setMtu(100);
assertThat(ospfInterface.mtu(), is(100));
}
/**
* Tests reTransmitInterval() getter method.
*/
@Test
public void testGetReTransmitInterval() throws Exception {
ospfInterface.setReTransmitInterval(100);
assertThat(ospfInterface.reTransmitInterval(), is(100));
}
/**
* Tests reTransmitInterval() setter method.
*/
@Test
public void testSetReTransmitInterval() throws Exception {
ospfInterface.setReTransmitInterval(100);
assertThat(ospfInterface.reTransmitInterval(), is(100));
}
/**
* Tests dr() getter method.
*/
@Test
public void testGetDr() throws Exception {
ospfInterface.setDr(Ip4Address.valueOf("1.1.1.1"));
assertThat(ospfInterface.dr(), is(Ip4Address.valueOf("1.1.1.1")));
}
/**
* Tests dr() setter method.
*/
@Test
public void testSetDr() throws Exception {
ospfInterface.setDr(Ip4Address.valueOf("1.1.1.1"));
assertThat(ospfInterface.dr(), is(Ip4Address.valueOf("1.1.1.1")));
}
/**
* Tests bdr() getter method.
*/
@Test
public void testGetBdr() throws Exception {
ospfInterface.setBdr(Ip4Address.valueOf("1.1.1.1"));
assertThat(ospfInterface.bdr(), is(Ip4Address.valueOf("1.1.1.1")));
}
/**
* Tests bdr() setter method.
*/
@Test
public void testSetBdr() throws Exception {
ospfInterface.setBdr(Ip4Address.valueOf("1.1.1.1"));
assertThat(ospfInterface.bdr(), is(Ip4Address.valueOf("1.1.1.1")));
}
/**
* Tests transmitDelay() getter method.
*/
@Test
public void testGetTransmitDelay() throws Exception {
ospfInterface.setTransmitDelay(100);
assertThat(ospfInterface.transmitDelay(), is(100));
}
/**
* Tests transmitDelay() setter method.
*/
@Test
public void testSetTransmitDelay() throws Exception {
ospfInterface.setTransmitDelay(100);
assertThat(ospfInterface.transmitDelay(), is(100));
}
/**
* Tests equals() method.
*/
@Test
public void testEquals() throws Exception {
assertThat(ospfInterface.equals(new OspfInterfaceImpl()), is(true));
}
/**
* Tests hashCode() method.
*/
@Test
public void testHashCode() throws Exception {
result = ospfInterface.hashCode();
assertThat(result, is(notNullValue()));
}
/**
* Tests to string method.
*/
@Test
public void testToString() throws Exception {
assertThat(ospfInterface.toString(), is(notNullValue()));
}
} | apache-2.0 |
DariusX/camel | components/camel-mina/src/test/java/org/apache/camel/component/mina/MinaSpringMinaEndpointUDPTest.java | 1703 | /*
* 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.mina;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.spring.CamelSpringTestSupport;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Unit test spring based mina endpoint configuration.
*/
public class MinaSpringMinaEndpointUDPTest extends CamelSpringTestSupport {
@Test
public void testMinaSpringEndpoint() throws Exception {
MockEndpoint result = getMockEndpoint("mock:result");
result.expectedMessageCount(1);
template.sendBody("myMinaEndpoint", "Hello World" + LS);
assertMockEndpointsSatisfied();
}
@Override
protected ClassPathXmlApplicationContext createApplicationContext() {
return new ClassPathXmlApplicationContext("org/apache/camel/component/mina/SpringMinaEndpointUDPTest-context.xml");
}
}
| apache-2.0 |
objectiser/camel | components/camel-cdi/src/main/java/org/apache/camel/cdi/BeanManagerHelper.java | 2125 | /*
* 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.cdi;
import java.lang.annotation.Annotation;
import java.util.Optional;
import java.util.Set;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
import static java.util.stream.Collectors.toSet;
@Vetoed
final class BeanManagerHelper {
private BeanManagerHelper() {
}
static <T> Set<T> getReferencesByType(BeanManager manager, Class<T> type, Annotation... qualifiers) {
return manager.getBeans(type, qualifiers).stream()
.map(bean -> getReference(manager, type, bean))
.collect(toSet());
}
static <T> Optional<T> getReferenceByName(BeanManager manager, String name, Class<T> type) {
return Optional.of(manager.getBeans(name))
.map(manager::resolve)
.map(bean -> getReference(manager, type, bean));
}
static <T> Optional<T> getReferenceByType(BeanManager manager, Class<T> type, Annotation... qualifiers) {
return Optional.of(manager.getBeans(type, qualifiers))
.map(manager::resolve)
.map(bean -> getReference(manager, type, bean));
}
static <T> T getReference(BeanManager manager, Class<T> type, Bean<?> bean) {
return type.cast(manager.getReference(bean, type, manager.createCreationalContext(bean)));
}
}
| apache-2.0 |
emre-aydin/hazelcast | hazelcast/src/test/java/com/hazelcast/query/impl/predicates/AndPredicateTest.java | 5143 | /*
* Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.query.impl.predicates;
import com.hazelcast.query.Predicate;
import com.hazelcast.query.impl.Indexes;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.annotation.ParallelJVMTest;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import static com.hazelcast.query.Predicates.and;
import static com.hazelcast.query.impl.predicates.PredicateTestUtils.createDelegatingVisitor;
import static com.hazelcast.query.impl.predicates.PredicateTestUtils.createMockNegatablePredicate;
import static com.hazelcast.query.impl.predicates.PredicateTestUtils.createMockVisitablePredicate;
import static com.hazelcast.query.impl.predicates.PredicateTestUtils.createPassthroughVisitor;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.sameInstance;
import static org.hamcrest.Matchers.arrayContainingInAnyOrder;
import static org.hamcrest.Matchers.arrayWithSize;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
@RunWith(HazelcastParallelClassRunner.class)
@Category({QuickTest.class, ParallelJVMTest.class})
public class AndPredicateTest {
@Test
public void negate_whenContainsNegatablePredicate_thenReturnOrPredicateWithNegationInside() {
// ~(foo and bar) --> (~foo or ~bar)
// this is testing the case where the inner predicate implements {@link Negatable}
Predicate negated = mock(Predicate.class);
Predicate negatable = createMockNegatablePredicate(negated);
AndPredicate and = (AndPredicate) and(negatable);
OrPredicate result = (OrPredicate) and.negate();
Predicate[] inners = result.predicates;
assertThat(inners, arrayWithSize(1));
assertThat(inners, arrayContainingInAnyOrder(negated));
}
@Test
public void negate_whenContainsNonNegatablePredicate_thenReturnOrPredicateWithNotInside() {
// ~(foo and bar) --> (~foo or ~bar)
// this is testing the case where the inner predicate does NOT implement {@link Negatable}
Predicate nonNegatable = mock(Predicate.class);
AndPredicate and = (AndPredicate) and(nonNegatable);
OrPredicate result = (OrPredicate) and.negate();
Predicate[] inners = result.predicates;
assertThat(inners, arrayWithSize(1));
NotPredicate notPredicate = (NotPredicate) inners[0];
assertThat(nonNegatable, sameInstance(notPredicate.predicate));
}
@Test
public void accept_whenEmptyPredicate_thenReturnItself() {
Visitor mockVisitor = createPassthroughVisitor();
Indexes mockIndexes = mock(Indexes.class);
AndPredicate andPredicate = new AndPredicate(new Predicate[0]);
AndPredicate result = (AndPredicate) andPredicate.accept(mockVisitor, mockIndexes);
assertThat(result, sameInstance(andPredicate));
}
@Test
public void accept_whenInnerPredicateChangedOnAccept_thenReturnAndNewAndPredicate() {
Visitor mockVisitor = createPassthroughVisitor();
Indexes mockIndexes = mock(Indexes.class);
Predicate transformed = mock(Predicate.class);
Predicate innerPredicate = createMockVisitablePredicate(transformed);
Predicate[] innerPredicates = new Predicate[1];
innerPredicates[0] = innerPredicate;
AndPredicate andPredicate = new AndPredicate(innerPredicates);
AndPredicate result = (AndPredicate) andPredicate.accept(mockVisitor, mockIndexes);
assertThat(result, not(sameInstance(andPredicate)));
Predicate[] newInnerPredicates = result.predicates;
assertThat(newInnerPredicates, arrayWithSize(1));
assertThat(newInnerPredicates[0], equalTo(transformed));
}
@Test
public void accept_whenVisitorReturnsNewInstance_thenReturnTheNewInstance() {
Predicate delegate = mock(Predicate.class);
Visitor mockVisitor = createDelegatingVisitor(delegate);
Indexes mockIndexes = mock(Indexes.class);
Predicate innerPredicate = mock(Predicate.class);
Predicate[] innerPredicates = new Predicate[1];
innerPredicates[0] = innerPredicate;
AndPredicate andPredicate = new AndPredicate(innerPredicates);
Predicate result = andPredicate.accept(mockVisitor, mockIndexes);
assertThat(result, sameInstance(delegate));
}
}
| apache-2.0 |
mehant/drill | exec/java-exec/src/main/java/org/apache/drill/exec/store/parquet/ParquetGroupScan.java | 30109 | /**
* 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.drill.exec.store.parquet;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.drill.common.exceptions.ExecutionSetupException;
import org.apache.drill.common.expression.SchemaPath;
import org.apache.drill.common.logical.FormatPluginConfig;
import org.apache.drill.common.logical.StoragePluginConfig;
import org.apache.drill.common.types.TypeProtos.MajorType;
import org.apache.drill.common.types.TypeProtos.MinorType;
import org.apache.drill.common.types.Types;
import org.apache.drill.exec.metrics.DrillMetrics;
import org.apache.drill.exec.physical.EndpointAffinity;
import org.apache.drill.exec.physical.PhysicalOperatorSetupException;
import org.apache.drill.exec.physical.base.AbstractFileGroupScan;
import org.apache.drill.exec.physical.base.FileGroupScan;
import org.apache.drill.exec.physical.base.GroupScan;
import org.apache.drill.exec.physical.base.PhysicalOperator;
import org.apache.drill.exec.physical.base.ScanStats;
import org.apache.drill.exec.physical.base.ScanStats.GroupScanProperty;
import org.apache.drill.exec.proto.CoordinationProtos.DrillbitEndpoint;
import org.apache.drill.exec.store.ParquetOutputRecordWriter;
import org.apache.drill.exec.store.StoragePluginRegistry;
import org.apache.drill.exec.store.TimedRunnable;
import org.apache.drill.exec.store.dfs.DrillFileSystem;
import org.apache.drill.exec.store.dfs.DrillPathFilter;
import org.apache.drill.exec.store.dfs.FileSelection;
import org.apache.drill.exec.store.dfs.ReadEntryFromHDFS;
import org.apache.drill.exec.store.dfs.ReadEntryWithPath;
import org.apache.drill.exec.store.dfs.easy.FileWork;
import org.apache.drill.exec.store.parquet.Metadata.ColumnMetadata;
import org.apache.drill.exec.store.parquet.Metadata.ParquetFileMetadata;
import org.apache.drill.exec.store.parquet.Metadata.ParquetTableMetadata_v1;
import org.apache.drill.exec.store.parquet.Metadata.RowGroupMetadata;
import org.apache.drill.exec.store.schedule.AffinityCreator;
import org.apache.drill.exec.store.schedule.AssignmentCreator;
import org.apache.drill.exec.store.schedule.BlockMapBuilder;
import org.apache.drill.exec.store.schedule.CompleteWork;
import org.apache.drill.exec.store.schedule.EndpointByteMap;
import org.apache.drill.exec.store.schedule.EndpointByteMapImpl;
import org.apache.drill.exec.util.ImpersonationUtil;
import org.apache.drill.exec.vector.NullableBigIntVector;
import org.apache.drill.exec.vector.NullableDateVector;
import org.apache.drill.exec.vector.NullableDecimal18Vector;
import org.apache.drill.exec.vector.NullableFloat4Vector;
import org.apache.drill.exec.vector.NullableFloat8Vector;
import org.apache.drill.exec.vector.NullableIntVector;
import org.apache.drill.exec.vector.NullableSmallIntVector;
import org.apache.drill.exec.vector.NullableTimeStampVector;
import org.apache.drill.exec.vector.NullableTimeVector;
import org.apache.drill.exec.vector.NullableTinyIntVector;
import org.apache.drill.exec.vector.NullableUInt1Vector;
import org.apache.drill.exec.vector.NullableUInt2Vector;
import org.apache.drill.exec.vector.NullableUInt4Vector;
import org.apache.drill.exec.vector.NullableVarBinaryVector;
import org.apache.drill.exec.vector.NullableVarCharVector;
import org.apache.drill.exec.vector.ValueVector;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.Path;
import org.joda.time.DateTimeUtils;
import org.apache.parquet.io.api.Binary;
import com.codahale.metrics.MetricRegistry;
import com.fasterxml.jackson.annotation.JacksonInject;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.google.common.base.Preconditions;
import com.google.common.base.Stopwatch;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Lists;
import org.apache.parquet.schema.OriginalType;
import org.apache.parquet.schema.PrimitiveType.PrimitiveTypeName;
@JsonTypeName("parquet-scan")
public class ParquetGroupScan extends AbstractFileGroupScan {
static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ParquetGroupScan.class);
static final MetricRegistry metrics = DrillMetrics.getInstance();
static final String READ_FOOTER_TIMER = MetricRegistry.name(ParquetGroupScan.class, "readFooter");
private final List<ReadEntryWithPath> entries;
private final Stopwatch watch = new Stopwatch();
private final ParquetFormatPlugin formatPlugin;
private final ParquetFormatConfig formatConfig;
private final DrillFileSystem fs;
private final String selectionRoot;
private boolean usedMetadataCache = false;
private List<EndpointAffinity> endpointAffinities;
private List<SchemaPath> columns;
private ListMultimap<Integer, RowGroupInfo> mappings;
private List<RowGroupInfo> rowGroupInfos;
/**
* The parquet table metadata may have already been read
* from a metadata cache file earlier; we can re-use during
* the ParquetGroupScan and avoid extra loading time.
*/
private ParquetTableMetadata_v1 parquetTableMetadata = null;
/*
* total number of rows (obtained from parquet footer)
*/
private long rowCount;
/*
* total number of non-null value for each column in parquet files.
*/
private Map<SchemaPath, Long> columnValueCounts;
@JsonCreator
public ParquetGroupScan( //
@JsonProperty("userName") String userName,
@JsonProperty("entries") List<ReadEntryWithPath> entries, //
@JsonProperty("storage") StoragePluginConfig storageConfig, //
@JsonProperty("format") FormatPluginConfig formatConfig, //
@JacksonInject StoragePluginRegistry engineRegistry, //
@JsonProperty("columns") List<SchemaPath> columns, //
@JsonProperty("selectionRoot") String selectionRoot //
) throws IOException, ExecutionSetupException {
super(ImpersonationUtil.resolveUserName(userName));
this.columns = columns;
if (formatConfig == null) {
formatConfig = new ParquetFormatConfig();
}
Preconditions.checkNotNull(storageConfig);
Preconditions.checkNotNull(formatConfig);
this.formatPlugin = (ParquetFormatPlugin) engineRegistry.getFormatPlugin(storageConfig, formatConfig);
Preconditions.checkNotNull(formatPlugin);
this.fs = ImpersonationUtil.createFileSystem(getUserName(), formatPlugin.getFsConf());
this.formatConfig = formatPlugin.getConfig();
this.entries = entries;
this.selectionRoot = selectionRoot;
init();
}
public ParquetGroupScan( //
String userName,
FileSelection selection, //
ParquetFormatPlugin formatPlugin, //
String selectionRoot,
List<SchemaPath> columns) //
throws IOException {
super(userName);
this.formatPlugin = formatPlugin;
this.columns = columns;
this.formatConfig = formatPlugin.getConfig();
this.fs = ImpersonationUtil.createFileSystem(userName, formatPlugin.getFsConf());
this.entries = Lists.newArrayList();
List<FileStatus> files = selection.getFileStatusList(fs);
for (FileStatus file : files) {
entries.add(new ReadEntryWithPath(file.getPath().toString()));
}
this.selectionRoot = selectionRoot;
this.parquetTableMetadata = selection.getParquetMetadata();
init();
}
/*
* This is used to clone another copy of the group scan.
*/
private ParquetGroupScan(ParquetGroupScan that) {
super(that);
this.columns = that.columns == null ? null : Lists.newArrayList(that.columns);
this.endpointAffinities = that.endpointAffinities == null ? null : Lists.newArrayList(that.endpointAffinities);
this.entries = that.entries == null ? null : Lists.newArrayList(that.entries);
this.formatConfig = that.formatConfig;
this.formatPlugin = that.formatPlugin;
this.fs = that.fs;
this.mappings = that.mappings == null ? null : ArrayListMultimap.create(that.mappings);
this.rowCount = that.rowCount;
this.rowGroupInfos = that.rowGroupInfos == null ? null : Lists.newArrayList(that.rowGroupInfos);
this.selectionRoot = that.selectionRoot;
this.columnValueCounts = that.columnValueCounts == null ? null : new HashMap(that.columnValueCounts);
this.columnTypeMap = that.columnTypeMap == null ? null : new HashMap(that.columnTypeMap);
this.partitionValueMap = that.partitionValueMap == null ? null : new HashMap(that.partitionValueMap);
this.fileSet = that.fileSet == null ? null : new HashSet(that.fileSet);
this.usedMetadataCache = that.usedMetadataCache;
this.parquetTableMetadata = that.parquetTableMetadata;
}
public List<ReadEntryWithPath> getEntries() {
return entries;
}
@JsonProperty("format")
public ParquetFormatConfig getFormatConfig() {
return this.formatConfig;
}
@JsonProperty("storage")
public StoragePluginConfig getEngineConfig() {
return this.formatPlugin.getStorageConfig();
}
public String getSelectionRoot() {
return selectionRoot;
}
public Set<String> getFileSet() {
return fileSet;
}
private Set<String> fileSet;
@JsonIgnore
private Map<SchemaPath,MajorType> columnTypeMap = Maps.newHashMap();
/**
* When reading the very first footer, any column is a potential partition column. So for the first footer, we check
* every column to see if it is single valued, and if so, add it to the list of potential partition columns. For the
* remaining footers, we will not find any new partition columns, but we may discover that what was previously a
* potential partition column now no longer qualifies, so it needs to be removed from the list.
* @return whether column is a potential partition column
*/
private boolean checkForPartitionColumn(ColumnMetadata columnMetadata, boolean first) {
SchemaPath schemaPath = columnMetadata.name;
if (first) {
if (hasSingleValue(columnMetadata)) {
columnTypeMap.put(schemaPath, getType(columnMetadata.primitiveType, columnMetadata.originalType));
return true;
} else {
return false;
}
} else {
if (!columnTypeMap.keySet().contains(schemaPath)) {
return false;
} else {
if (!hasSingleValue(columnMetadata)) {
columnTypeMap.remove(schemaPath);
return false;
}
if (!getType(columnMetadata.primitiveType, columnMetadata.originalType).equals(columnTypeMap.get(schemaPath))) {
columnTypeMap.remove(schemaPath);
return false;
}
}
}
return true;
}
private MajorType getType(PrimitiveTypeName type, OriginalType originalType) {
if (originalType != null) {
switch (originalType) {
case DECIMAL:
return Types.optional(MinorType.DECIMAL18);
case DATE:
return Types.optional(MinorType.DATE);
case TIME_MILLIS:
return Types.optional(MinorType.TIME);
case TIMESTAMP_MILLIS:
return Types.optional(MinorType.TIMESTAMP);
case UTF8:
return Types.optional(MinorType.VARCHAR);
case UINT_8:
return Types.optional(MinorType.UINT1);
case UINT_16:
return Types.optional(MinorType.UINT2);
case UINT_32:
return Types.optional(MinorType.UINT4);
case UINT_64:
return Types.optional(MinorType.UINT8);
case INT_8:
return Types.optional(MinorType.TINYINT);
case INT_16:
return Types.optional(MinorType.SMALLINT);
}
}
switch (type) {
case BOOLEAN:
return Types.optional(MinorType.BIT);
case INT32:
return Types.optional(MinorType.INT);
case INT64:
return Types.optional(MinorType.BIGINT);
case FLOAT:
return Types.optional(MinorType.FLOAT4);
case DOUBLE:
return Types.optional(MinorType.FLOAT8);
case BINARY:
case FIXED_LEN_BYTE_ARRAY:
case INT96:
return Types.optional(MinorType.VARBINARY);
default:
// Should never hit this
throw new UnsupportedOperationException("Unsupported type:" + type);
}
}
private boolean hasSingleValue(ColumnMetadata columnChunkMetaData) {
Object max = columnChunkMetaData.max;
Object min = columnChunkMetaData.min;
return max != null && max.equals(min);
/*
if (max != null && min != null) {
if (max instanceof byte[] && min instanceof byte[]) {
return Arrays.equals((byte[])max, (byte[])min);
}
return max.equals(min);
}
return false;
*/
}
@Override
public void modifyFileSelection(FileSelection selection) {
entries.clear();
fileSet = Sets.newHashSet();
for (String fileName : selection.getAsFiles()) {
entries.add(new ReadEntryWithPath(fileName));
fileSet.add(fileName);
}
List<RowGroupInfo> newRowGroupList = Lists.newArrayList();
for (RowGroupInfo rowGroupInfo : rowGroupInfos) {
if (fileSet.contains(rowGroupInfo.getPath())) {
newRowGroupList.add(rowGroupInfo);
}
}
this.rowGroupInfos = newRowGroupList;
}
public MajorType getTypeForColumn(SchemaPath schemaPath) {
return columnTypeMap.get(schemaPath);
}
private Map<String,Map<SchemaPath,Object>> partitionValueMap = Maps.newHashMap();
public void populatePruningVector(ValueVector v, int index, SchemaPath column, String file) {
String f = Path.getPathWithoutSchemeAndAuthority(new Path(file)).toString();
MinorType type = getTypeForColumn(column).getMinorType();
switch (type) {
case INT: {
NullableIntVector intVector = (NullableIntVector) v;
Integer value = (Integer) partitionValueMap.get(f).get(column);
intVector.getMutator().setSafe(index, value);
return;
}
case SMALLINT: {
NullableSmallIntVector smallIntVector = (NullableSmallIntVector) v;
Integer value = (Integer) partitionValueMap.get(f).get(column);
smallIntVector.getMutator().setSafe(index, value.shortValue());
return;
}
case TINYINT: {
NullableTinyIntVector tinyIntVector = (NullableTinyIntVector) v;
Integer value = (Integer) partitionValueMap.get(f).get(column);
tinyIntVector.getMutator().setSafe(index, value.byteValue());
return;
}
case UINT1: {
NullableUInt1Vector intVector = (NullableUInt1Vector) v;
Integer value = (Integer) partitionValueMap.get(f).get(column);
intVector.getMutator().setSafe(index, value.byteValue());
return;
}
case UINT2: {
NullableUInt2Vector intVector = (NullableUInt2Vector) v;
Integer value = (Integer) partitionValueMap.get(f).get(column);
intVector.getMutator().setSafe(index, (char) value.shortValue());
return;
}
case UINT4: {
NullableUInt4Vector intVector = (NullableUInt4Vector) v;
Integer value = (Integer) partitionValueMap.get(f).get(column);
intVector.getMutator().setSafe(index, value);
return;
}
case BIGINT: {
NullableBigIntVector bigIntVector = (NullableBigIntVector) v;
Long value = (Long) partitionValueMap.get(f).get(column);
bigIntVector.getMutator().setSafe(index, value);
return;
}
case FLOAT4: {
NullableFloat4Vector float4Vector = (NullableFloat4Vector) v;
Float value = (Float) partitionValueMap.get(f).get(column);
float4Vector.getMutator().setSafe(index, value);
return;
}
case FLOAT8: {
NullableFloat8Vector float8Vector = (NullableFloat8Vector) v;
Double value = (Double) partitionValueMap.get(f).get(column);
float8Vector.getMutator().setSafe(index, value);
return;
}
case VARBINARY: {
NullableVarBinaryVector varBinaryVector = (NullableVarBinaryVector) v;
Object s = partitionValueMap.get(f).get(column);
byte[] bytes;
if (s instanceof Binary) {
bytes = ((Binary) s).getBytes();
} else if (s instanceof String) {
bytes = ((String) s).getBytes();
} else if (s instanceof byte[]) {
bytes = (byte[])s;
} else {
throw new UnsupportedOperationException("Unable to create column data for type: " + type);
}
varBinaryVector.getMutator().setSafe(index, bytes, 0, bytes.length);
return;
}
case DECIMAL18: {
NullableDecimal18Vector decimalVector = (NullableDecimal18Vector) v;
Long value = (Long) partitionValueMap.get(f).get(column);
decimalVector.getMutator().setSafe(index, value);
return;
}
case DATE: {
NullableDateVector dateVector = (NullableDateVector) v;
Integer value = (Integer) partitionValueMap.get(f).get(column);
dateVector.getMutator().setSafe(index, DateTimeUtils.fromJulianDay(value - ParquetOutputRecordWriter.JULIAN_DAY_EPOC - 0.5));
return;
}
case TIME: {
NullableTimeVector timeVector = (NullableTimeVector) v;
Integer value = (Integer) partitionValueMap.get(f).get(column);
timeVector.getMutator().setSafe(index, value);
return;
}
case TIMESTAMP: {
NullableTimeStampVector timeStampVector = (NullableTimeStampVector) v;
Long value = (Long) partitionValueMap.get(f).get(column);
timeStampVector.getMutator().setSafe(index, value);
return;
}
case VARCHAR: {
NullableVarCharVector varCharVector = (NullableVarCharVector) v;
Object s = partitionValueMap.get(f).get(column);
byte[] bytes;
if (s instanceof String) { // if the metadata was read from a JSON cache file it maybe a string type
bytes = ((String) s).getBytes();
} else if (s instanceof Binary) {
bytes = ((Binary) s).getBytes();
} else if (s instanceof byte[]) {
bytes = (byte[])s;
} else {
throw new UnsupportedOperationException("Unable to create column data for type: " + type);
}
varCharVector.getMutator().setSafe(index, bytes, 0, bytes.length);
return;
}
default:
throw new UnsupportedOperationException("Unsupported type: " + type);
}
}
public static class RowGroupInfo extends ReadEntryFromHDFS implements CompleteWork, FileWork {
private EndpointByteMap byteMap;
private int rowGroupIndex;
private String root;
@JsonCreator
public RowGroupInfo(@JsonProperty("path") String path, @JsonProperty("start") long start,
@JsonProperty("length") long length, @JsonProperty("rowGroupIndex") int rowGroupIndex) {
super(path, start, length);
this.rowGroupIndex = rowGroupIndex;
}
public RowGroupReadEntry getRowGroupReadEntry() {
return new RowGroupReadEntry(this.getPath(), this.getStart(), this.getLength(), this.rowGroupIndex);
}
public int getRowGroupIndex() {
return this.rowGroupIndex;
}
@Override
public int compareTo(CompleteWork o) {
return Long.compare(getTotalBytes(), o.getTotalBytes());
}
@Override
public long getTotalBytes() {
return this.getLength();
}
@Override
public EndpointByteMap getByteMap() {
return byteMap;
}
public void setEndpointByteMap(EndpointByteMap byteMap) {
this.byteMap = byteMap;
}
}
private void init() throws IOException {
List<FileStatus> fileStatuses = null;
if (entries.size() == 1) {
Path p = Path.getPathWithoutSchemeAndAuthority(new Path(entries.get(0).getPath()));
Path metaPath = null;
if (fs.isDirectory(p)) {
// Using the metadata file makes sense when querying a directory; otherwise
// if querying a single file we can look up the metadata directly from the file
metaPath = new Path(p, Metadata.METADATA_FILENAME);
}
if (metaPath != null && fs.exists(metaPath)) {
usedMetadataCache = true;
if (parquetTableMetadata == null) {
parquetTableMetadata = Metadata.readBlockMeta(fs, metaPath.toString());
}
} else {
parquetTableMetadata = Metadata.getParquetTableMetadata(fs, p.toString());
}
} else {
Path p = Path.getPathWithoutSchemeAndAuthority(new Path(selectionRoot));
Path metaPath = new Path(p, Metadata.METADATA_FILENAME);
if (fs.isDirectory(new Path(selectionRoot)) && fs.exists(metaPath)) {
usedMetadataCache = true;
if (fileSet != null) {
if (parquetTableMetadata == null) {
parquetTableMetadata = removeUnneededRowGroups(Metadata.readBlockMeta(fs, metaPath.toString()));
} else {
parquetTableMetadata = removeUnneededRowGroups(parquetTableMetadata);
}
} else {
if (parquetTableMetadata == null) {
parquetTableMetadata = Metadata.readBlockMeta(fs, metaPath.toString());
}
}
} else {
fileStatuses = Lists.newArrayList();
for (ReadEntryWithPath entry : entries) {
getFiles(entry.getPath(), fileStatuses);
}
parquetTableMetadata = Metadata.getParquetTableMetadata(fs, fileStatuses);
}
}
if (fileSet == null) {
fileSet = Sets.newHashSet();
for (ParquetFileMetadata file : parquetTableMetadata.files) {
fileSet.add(file.path);
}
}
Map<String,DrillbitEndpoint> hostEndpointMap = Maps.newHashMap();
for (DrillbitEndpoint endpoint : formatPlugin.getContext().getBits()) {
hostEndpointMap.put(endpoint.getAddress(), endpoint);
}
rowGroupInfos = Lists.newArrayList();
for (ParquetFileMetadata file : parquetTableMetadata.files) {
int rgIndex = 0;
for (RowGroupMetadata rg : file.rowGroups) {
RowGroupInfo rowGroupInfo = new RowGroupInfo(file.path, rg.start, rg.length, rgIndex);
EndpointByteMap endpointByteMap = new EndpointByteMapImpl();
for (String host : rg.hostAffinity.keySet()) {
if (hostEndpointMap.containsKey(host)) {
endpointByteMap.add(hostEndpointMap.get(host), (long) (rg.hostAffinity.get(host) * rg.length));
}
}
rowGroupInfo.setEndpointByteMap(endpointByteMap);
rgIndex++;
rowGroupInfos.add(rowGroupInfo);
}
}
this.endpointAffinities = AffinityCreator.getAffinityMap(rowGroupInfos);
columnValueCounts = Maps.newHashMap();
this.rowCount = 0;
boolean first = true;
for (ParquetFileMetadata file : parquetTableMetadata.files) {
for (RowGroupMetadata rowGroup : file.rowGroups) {
long rowCount = rowGroup.rowCount;
for (ColumnMetadata column : rowGroup.columns) {
SchemaPath schemaPath = column.name;
Long previousCount = columnValueCounts.get(schemaPath);
if (previousCount != null) {
if (previousCount != GroupScan.NO_COLUMN_STATS) {
if (column.nulls != null) {
Long newCount = rowCount - column.nulls;
columnValueCounts.put(schemaPath, columnValueCounts.get(schemaPath) + newCount);
} else {
}
}
} else {
if (column.nulls != null) {
Long newCount = rowCount - column.nulls;
columnValueCounts.put(schemaPath, newCount);
} else {
columnValueCounts.put(schemaPath, GroupScan.NO_COLUMN_STATS);
}
}
boolean partitionColumn = checkForPartitionColumn(column, first);
if (partitionColumn) {
Map<SchemaPath,Object> map = partitionValueMap.get(file.path);
if (map == null) {
map = Maps.newHashMap();
partitionValueMap.put(file.path, map);
}
Object value = map.get(schemaPath);
Object currentValue = column.max;
// Object currentValue = column.getMax();
if (value != null) {
if (value != currentValue) {
columnTypeMap.remove(schemaPath);
}
} else {
map.put(schemaPath, currentValue);
}
} else {
columnTypeMap.remove(schemaPath);
}
}
this.rowCount += rowGroup.rowCount;
first = false;
}
}
}
private ParquetTableMetadata_v1 removeUnneededRowGroups(ParquetTableMetadata_v1 parquetTableMetadata) {
List<ParquetFileMetadata> newFileMetadataList = Lists.newArrayList();
for (ParquetFileMetadata file : parquetTableMetadata.files) {
if (fileSet.contains(file.path)) {
newFileMetadataList.add(file);
}
}
return new ParquetTableMetadata_v1(newFileMetadataList, new ArrayList<String>());
}
/**
* Calculates the affinity each endpoint has for this scan, by adding up the affinity each endpoint has for each
* rowGroup
*
* @return a list of EndpointAffinity objects
*/
@Override
public List<EndpointAffinity> getOperatorAffinity() {
return this.endpointAffinities;
}
private void getFiles(String path, List<FileStatus> fileStatuses) throws IOException {
Path p = Path.getPathWithoutSchemeAndAuthority(new Path(path));
FileStatus fileStatus = fs.getFileStatus(p);
if (fileStatus.isDirectory()) {
for (FileStatus f : fs.listStatus(p, new DrillPathFilter())) {
getFiles(f.getPath().toString(), fileStatuses);
}
} else {
fileStatuses.add(fileStatus);
}
}
private class BlockMapper extends TimedRunnable<Void> {
private final BlockMapBuilder bmb;
private final RowGroupInfo rgi;
public BlockMapper(BlockMapBuilder bmb, RowGroupInfo rgi) {
super();
this.bmb = bmb;
this.rgi = rgi;
}
@Override
protected Void runInner() throws Exception {
EndpointByteMap ebm = bmb.getEndpointByteMap(rgi);
rgi.setEndpointByteMap(ebm);
return null;
}
@Override
protected IOException convertToIOException(Exception e) {
return new IOException(String.format("Failure while trying to get block locations for file %s starting at %d.", rgi.getPath(), rgi.getStart()));
}
}
@Override
public void applyAssignments(List<DrillbitEndpoint> incomingEndpoints) throws PhysicalOperatorSetupException {
this.mappings = AssignmentCreator.getMappings(incomingEndpoints, rowGroupInfos, formatPlugin.getContext());
}
@Override
public ParquetRowGroupScan getSpecificScan(int minorFragmentId) {
assert minorFragmentId < mappings.size() : String.format(
"Mappings length [%d] should be longer than minor fragment id [%d] but it isn't.", mappings.size(),
minorFragmentId);
List<RowGroupInfo> rowGroupsForMinor = mappings.get(minorFragmentId);
Preconditions.checkArgument(!rowGroupsForMinor.isEmpty(),
String.format("MinorFragmentId %d has no read entries assigned", minorFragmentId));
return new ParquetRowGroupScan(
getUserName(), formatPlugin, convertToReadEntries(rowGroupsForMinor), columns, selectionRoot);
}
private List<RowGroupReadEntry> convertToReadEntries(List<RowGroupInfo> rowGroups) {
List<RowGroupReadEntry> entries = Lists.newArrayList();
for (RowGroupInfo rgi : rowGroups) {
RowGroupReadEntry entry = new RowGroupReadEntry(rgi.getPath(), rgi.getStart(), rgi.getLength(), rgi.getRowGroupIndex());
entries.add(entry);
}
return entries;
}
@Override
public int getMaxParallelizationWidth() {
return rowGroupInfos.size();
}
public List<SchemaPath> getColumns() {
return columns;
}
@Override
public ScanStats getScanStats() {
int columnCount = columns == null ? 20 : columns.size();
return new ScanStats(GroupScanProperty.EXACT_ROW_COUNT, rowCount, 1, rowCount * columnCount);
}
@Override
@JsonIgnore
public PhysicalOperator getNewWithChildren(List<PhysicalOperator> children) {
Preconditions.checkArgument(children.isEmpty());
return new ParquetGroupScan(this);
}
@Override
public String getDigest() {
return toString();
}
@Override
public String toString() {
return "ParquetGroupScan [entries=" + entries
+ ", selectionRoot=" + selectionRoot
+ ", numFiles=" + getEntries().size()
+ ", usedMetadataFile=" + usedMetadataCache
+ ", columns=" + columns + "]";
}
@Override
public GroupScan clone(List<SchemaPath> columns) {
ParquetGroupScan newScan = new ParquetGroupScan(this);
newScan.columns = columns;
return newScan;
}
@Override
public FileGroupScan clone(FileSelection selection) throws IOException {
ParquetGroupScan newScan = new ParquetGroupScan(this);
newScan.modifyFileSelection(selection);
newScan.init();
return newScan;
}
@Override
@JsonIgnore
public boolean canPushdownProjects(List<SchemaPath> columns) {
return true;
}
/**
* Return column value count for the specified column. If does not contain such column, return 0.
*/
@Override
public long getColumnValueCount(SchemaPath column) {
return columnValueCounts.containsKey(column) ? columnValueCounts.get(column) : 0;
}
@Override
public List<SchemaPath> getPartitionColumns() {
return new ArrayList(columnTypeMap.keySet());
}
}
| apache-2.0 |
prabushi/devstudio-tooling-esb | plugins/org.wso2.developerstudio.visualdatamapper.diagram/src/org/wso2/developerstudio/datamapper/diagram/edit/policies/RoundItemSemanticEditPolicy.java | 3053 | package org.wso2.developerstudio.datamapper.diagram.edit.policies;
import java.util.Iterator;
import org.eclipse.emf.ecore.EAnnotation;
import org.eclipse.gef.commands.Command;
import org.eclipse.gmf.runtime.common.core.command.ICompositeCommand;
import org.eclipse.gmf.runtime.diagram.core.commands.DeleteCommand;
import org.eclipse.gmf.runtime.emf.commands.core.command.CompositeTransactionalCommand;
import org.eclipse.gmf.runtime.emf.type.core.commands.DestroyElementCommand;
import org.eclipse.gmf.runtime.emf.type.core.requests.CreateElementRequest;
import org.eclipse.gmf.runtime.emf.type.core.requests.DestroyElementRequest;
import org.eclipse.gmf.runtime.notation.Node;
import org.eclipse.gmf.runtime.notation.View;
import org.wso2.developerstudio.datamapper.diagram.edit.commands.OperatorBasicContainerCreateCommand;
import org.wso2.developerstudio.datamapper.diagram.edit.parts.OperatorBasicContainerEditPart;
import org.wso2.developerstudio.datamapper.diagram.part.DataMapperVisualIDRegistry;
import org.wso2.developerstudio.datamapper.diagram.providers.DataMapperElementTypes;
/**
* @generated
*/
public class RoundItemSemanticEditPolicy extends DataMapperBaseItemSemanticEditPolicy {
/**
* @generated
*/
public RoundItemSemanticEditPolicy() {
super(DataMapperElementTypes.Round_2018);
}
/**
* @generated
*/
protected Command getCreateCommand(CreateElementRequest req) {
if (DataMapperElementTypes.OperatorBasicContainer_3012 == req.getElementType()) {
return getGEFWrapper(new OperatorBasicContainerCreateCommand(req));
}
return super.getCreateCommand(req);
}
/**
* @generated
*/
protected Command getDestroyElementCommand(DestroyElementRequest req) {
View view = (View) getHost().getModel();
CompositeTransactionalCommand cmd = new CompositeTransactionalCommand(getEditingDomain(), null);
cmd.setTransactionNestingEnabled(false);
EAnnotation annotation = view.getEAnnotation("Shortcut"); //$NON-NLS-1$
if (annotation == null) {
// there are indirectly referenced children, need extra commands: false
addDestroyChildNodesCommand(cmd);
addDestroyShortcutsCommand(cmd, view);
// delete host element
cmd.add(new DestroyElementCommand(req));
} else {
cmd.add(new DeleteCommand(getEditingDomain(), view));
}
return getGEFWrapper(cmd.reduce());
}
/**
* @generated
*/
private void addDestroyChildNodesCommand(ICompositeCommand cmd) {
View view = (View) getHost().getModel();
for (Iterator<?> nit = view.getChildren().iterator(); nit.hasNext();) {
Node node = (Node) nit.next();
switch (DataMapperVisualIDRegistry.getVisualID(node)) {
case OperatorBasicContainerEditPart.VISUAL_ID:
cmd.add(new DestroyElementCommand(
new DestroyElementRequest(getEditingDomain(), node.getElement(), false))); // directlyOwned: true
// don't need explicit deletion of node as parent's view deletion would clean child views as well
// cmd.add(new org.eclipse.gmf.runtime.diagram.core.commands.DeleteCommand(getEditingDomain(), node));
break;
}
}
}
}
| apache-2.0 |
n4ybn/yavijava | src/main/java/com/vmware/vim25/VirtualMachineVMCIDeviceFilterInfo.java | 888 | package com.vmware.vim25;
import lombok.Getter;
import lombok.Setter;
/**
* Created by Michael Rice on Sun May 24 16:15:35 CDT 2015
*
* Copyright 2015 Michael Rice
*
* 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.
* @since 6.0
*/
public class VirtualMachineVMCIDeviceFilterInfo extends DynamicData {
@Getter @Setter public VirtualMachineVMCIDeviceFilterSpec[] filters;
}
| bsd-3-clause |
ddugovic/raptor-chess-interface | raptor/src/raptor/action/game/MatchWinnerAction.java | 3928 | /**
* New BSD License
* http://www.opensource.org/licenses/bsd-license.php
* Copyright 2009-2011 RaptorProject (http://code.google.com/p/raptor-chess-interface/)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the RaptorProject 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package raptor.action.game;
import raptor.Raptor;
import raptor.RaptorWindowItem;
import raptor.action.AbstractRaptorAction;
import raptor.chess.Variant;
import raptor.swt.chess.ChessBoardController;
import raptor.swt.chess.ChessBoardWindowItem;
import raptor.swt.chess.controller.ObserveController;
import raptor.swt.chess.controller.ToolBarItemKey;
public class MatchWinnerAction extends AbstractRaptorAction {
public MatchWinnerAction() {
setName("Winners");
setDescription("Matches the winner of this game automatically when it is over.");
setCategory(Category.GameCommands);
}
public void run() {
boolean wasHandled = false;
if (getChessBoardControllerSource() != null) {
if (getChessBoardControllerSource() instanceof ObserveController) {
matchWinner(getChessBoardControllerSource());
}
wasHandled = true;
}
if (!wasHandled) {
RaptorWindowItem[] items = Raptor.getInstance().getWindow()
.getSelectedWindowItems(ChessBoardWindowItem.class);
for (RaptorWindowItem item : items) {
ChessBoardWindowItem chessBoardWindowItem = (ChessBoardWindowItem) item;
if (chessBoardWindowItem.getController() instanceof ObserveController) {
matchWinner(chessBoardWindowItem.getController());
}
}
}
}
protected void matchWinner(ChessBoardController controller) {
if (getChessBoardControllerSource().isToolItemSelected(
ToolBarItemKey.MATCH_WINNER)) {
if (controller.getGame().getVariant() == Variant.bughouse
|| controller.getGame().getVariant() == Variant.fischerRandomBughouse) {
getChessBoardControllerSource().getConnector().kibitz(
getChessBoardControllerSource().getGame(),
"Winners please");
} else {
getChessBoardControllerSource().getConnector().kibitz(
getChessBoardControllerSource().getGame(),
"Winner please");
}
} else {
if (controller.getGame().getVariant() == Variant.bughouse
|| controller.getGame().getVariant() == Variant.fischerRandomBughouse) {
getChessBoardControllerSource().getConnector().kibitz(
getChessBoardControllerSource().getGame(),
"No longer calling winners.");
} else {
getChessBoardControllerSource().getConnector().kibitz(
getChessBoardControllerSource().getGame(),
"No longer calling winner.");
}
}
}
} | bsd-3-clause |
Major-/apollo | game/src/main/org/apollo/game/message/impl/PrivacyOptionMessage.java | 1692 | package org.apollo.game.message.impl;
import org.apollo.game.model.entity.setting.PrivacyState;
import org.apollo.net.message.Message;
/**
* A {@link Message} sent both by and to the client to update the public chat, private (friend) chat, and trade chat
* privacy state.
*
* @author Kyle Stevenson
* @author Major
*/
public final class PrivacyOptionMessage extends Message {
/**
* The privacy state of the player's chat.
*/
private final PrivacyState chatPrivacy;
/**
* The privacy state of the player's friend chat.
*/
private final PrivacyState friendPrivacy;
/**
* The privacy state of the player's trade chat.
*/
private final PrivacyState tradePrivacy;
/**
* Creates a privacy option message.
*
* @param chatPrivacy The privacy state of the player's chat.
* @param friendPrivacy The privacy state of the player's friend chat.
* @param tradePrivacy The privacy state of the player's trade chat.
*/
public PrivacyOptionMessage(int chatPrivacy, int friendPrivacy, int tradePrivacy) {
this.chatPrivacy = PrivacyState.valueOf(chatPrivacy, true);
this.friendPrivacy = PrivacyState.valueOf(friendPrivacy, false);
this.tradePrivacy = PrivacyState.valueOf(tradePrivacy, false);
}
/**
* Gets the chat {@link PrivacyState}.
*
* @return The privacy state.
*/
public PrivacyState getChatPrivacy() {
return chatPrivacy;
}
/**
* Gets the friend {@link PrivacyState}.
*
* @return The privacy state.
*/
public PrivacyState getFriendPrivacy() {
return friendPrivacy;
}
/**
* Gets the trade {@link PrivacyState}.
*
* @return The privacy state.
*/
public PrivacyState getTradePrivacy() {
return tradePrivacy;
}
} | isc |
gaborkolozsy/XChange | xchange-poloniex/src/main/java/org/knowm/xchange/poloniex/dto/marketdata/PoloniexChartData.java | 2264 | package org.knowm.xchange.poloniex.dto.marketdata;
import java.math.BigDecimal;
import java.util.Date;
import org.knowm.xchange.poloniex.PoloniexUtils;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
public class PoloniexChartData {
private Date date;
private BigDecimal high;
private BigDecimal low;
private BigDecimal open;
private BigDecimal close;
private BigDecimal volume;
private BigDecimal quoteVolume;
private BigDecimal weightedAverage;
@JsonCreator
public PoloniexChartData(
@JsonProperty(value = "date", required = true) @JsonDeserialize(using = PoloniexUtils.UnixTimestampDeserializer.class) Date date,
@JsonProperty(value = "high", required = true) BigDecimal high, @JsonProperty(value = "low", required = true) BigDecimal low,
@JsonProperty(value = "open", required = true) BigDecimal open, @JsonProperty(value = "close", required = true) BigDecimal close,
@JsonProperty(value = "volume", required = true) BigDecimal volume,
@JsonProperty(value = "quoteVolume", required = true) BigDecimal quoteVolume,
@JsonProperty(value = "weightedAverage", required = true) BigDecimal weightedAverage) {
this.date = date;
this.high = high;
this.low = low;
this.open = open;
this.close = close;
this.volume = volume;
this.quoteVolume = quoteVolume;
this.weightedAverage = weightedAverage;
}
public Date getDate() {
return date;
}
public BigDecimal getHigh() {
return high;
}
public BigDecimal getLow() {
return low;
}
public BigDecimal getOpen() {
return open;
}
public BigDecimal getClose() {
return close;
}
public BigDecimal getVolume() {
return volume;
}
public BigDecimal getQuoteVolume() {
return quoteVolume;
}
public BigDecimal getWeightedAverage() {
return weightedAverage;
}
@Override
public String toString() {
return "PoloniexChartData [" + "date=" + date + ", high=" + high + ", low=" + low + ", open=" + open + ", close=" + close + ", volume=" + volume
+ ", quoteVolume=" + quoteVolume + ", weightedAverage=" + weightedAverage + ']';
}
}
| mit |
stephenc/jenkins | core/src/main/java/hudson/model/ItemGroupMixIn.java | 12594 | /*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.model;
import hudson.Util;
import hudson.XmlFile;
import hudson.model.listeners.ItemListener;
import hudson.security.AccessControlled;
import hudson.util.CopyOnWriteMap;
import hudson.util.Function1;
import hudson.util.Secret;
import jenkins.model.Jenkins;
import jenkins.util.xml.XMLUtils;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.TransformerException;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import jenkins.security.NotReallyRoleSensitiveCallable;
import org.acegisecurity.AccessDeniedException;
import org.xml.sax.SAXException;
/**
* Defines a bunch of static methods to be used as a "mix-in" for {@link ItemGroup}
* implementations. Not meant for a consumption from outside {@link ItemGroup}s.
*
* @author Kohsuke Kawaguchi
* @see ViewGroupMixIn
*/
public abstract class ItemGroupMixIn {
/**
* {@link ItemGroup} for which we are working.
*/
private final ItemGroup parent;
private final AccessControlled acl;
protected ItemGroupMixIn(ItemGroup parent, AccessControlled acl) {
this.parent = parent;
this.acl = acl;
}
/*
* Callback methods to be implemented by the ItemGroup implementation.
*/
/**
* Adds a newly created item to the parent.
*/
protected abstract void add(TopLevelItem item);
/**
* Assigns the root directory for a prospective item.
*/
protected abstract File getRootDirFor(String name);
/*
* The rest is the methods that provide meat.
*/
/**
* Loads all the child {@link Item}s.
*
* @param modulesDir
* Directory that contains sub-directories for each child item.
*/
public static <K,V extends Item> Map<K,V> loadChildren(ItemGroup parent, File modulesDir, Function1<? extends K,? super V> key) {
modulesDir.mkdirs(); // make sure it exists
File[] subdirs = modulesDir.listFiles(new FileFilter() {
public boolean accept(File child) {
return child.isDirectory();
}
});
CopyOnWriteMap.Tree<K,V> configurations = new CopyOnWriteMap.Tree<>();
for (File subdir : subdirs) {
try {
// Try to retain the identity of an existing child object if we can.
V item = (V) parent.getItem(subdir.getName());
if (item == null) {
XmlFile xmlFile = Items.getConfigFile(subdir);
if (xmlFile.exists()) {
item = (V) Items.load(parent, subdir);
} else {
Logger.getLogger(ItemGroupMixIn.class.getName()).log(Level.WARNING, "could not find file " + xmlFile.getFile());
continue;
}
} else {
item.onLoad(parent, subdir.getName());
}
configurations.put(key.call(item), item);
} catch (Exception e) {
Logger.getLogger(ItemGroupMixIn.class.getName()).log(Level.WARNING, "could not load " + subdir, e);
}
}
return configurations;
}
/**
* {@link Item} → name function.
*/
public static final Function1<String,Item> KEYED_BY_NAME = new Function1<String, Item>() {
public String call(Item item) {
return item.getName();
}
};
/**
* Creates a {@link TopLevelItem} for example from the submission of the {@code /lib/hudson/newFromList/form} tag
* or throws an exception if it fails.
*/
public synchronized TopLevelItem createTopLevelItem( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
acl.checkPermission(Item.CREATE);
TopLevelItem result;
String requestContentType = req.getContentType();
String mode = req.getParameter("mode");
if (requestContentType == null
&& !(mode != null && mode.equals("copy")))
throw new Failure("No Content-Type header set");
boolean isXmlSubmission = requestContentType != null
&& (requestContentType.startsWith("application/xml")
|| requestContentType.startsWith("text/xml"));
String name = req.getParameter("name");
if(name==null)
throw new Failure("Query parameter 'name' is required");
{// check if the name looks good
Jenkins.checkGoodName(name);
name = name.trim();
if(parent.getItem(name)!=null)
throw new Failure(Messages.Hudson_JobAlreadyExists(name));
}
if(mode!=null && mode.equals("copy")) {
String from = req.getParameter("from");
// resolve a name to Item
Item src = Jenkins.get().getItem(from, parent);
if(src==null) {
if(Util.fixEmpty(from)==null)
throw new Failure("Specify which job to copy");
else
throw new Failure("No such job: "+from);
}
if (!(src instanceof TopLevelItem))
throw new Failure(from+" cannot be copied");
result = copy((TopLevelItem) src,name);
} else {
if(isXmlSubmission) {
result = createProjectFromXML(name, req.getInputStream());
rsp.setStatus(HttpServletResponse.SC_OK);
return result;
} else {
if(mode==null)
throw new Failure("No mode given");
TopLevelItemDescriptor descriptor = Items.all().findByName(mode);
if (descriptor == null) {
throw new Failure("No item type ‘" + mode + "’ is known");
}
descriptor.checkApplicableIn(parent);
acl.getACL().checkCreatePermission(parent, descriptor);
// create empty job and redirect to the project config screen
result = createProject(descriptor, name, true);
}
}
rsp.sendRedirect2(redirectAfterCreateItem(req, result));
return result;
}
/**
* Computes the redirection target URL for the newly created {@link TopLevelItem}.
*/
protected String redirectAfterCreateItem(StaplerRequest req, TopLevelItem result) throws IOException {
return req.getContextPath()+'/'+result.getUrl()+"configure";
}
/**
* Copies an existing {@link TopLevelItem} to a new name.
*/
@SuppressWarnings({"unchecked"})
public synchronized <T extends TopLevelItem> T copy(T src, String name) throws IOException {
acl.checkPermission(Item.CREATE);
src.checkPermission(Item.EXTENDED_READ);
XmlFile srcConfigFile = Items.getConfigFile(src);
if (!src.hasPermission(Item.CONFIGURE)) {
Matcher matcher = AbstractItem.SECRET_PATTERN.matcher(srcConfigFile.asString());
while (matcher.find()) {
if (Secret.decrypt(matcher.group(1)) != null) {
// AccessDeniedException2 does not permit a custom message, and anyway redirecting the user to the login screen is obviously pointless.
throw new AccessDeniedException(Messages.ItemGroupMixIn_may_not_copy_as_it_contains_secrets_and_(src.getFullName(), Jenkins.getAuthentication().getName(), Item.PERMISSIONS.title, Item.EXTENDED_READ.name, Item.CONFIGURE.name));
}
}
}
src.getDescriptor().checkApplicableIn(parent);
acl.getACL().checkCreatePermission(parent, src.getDescriptor());
ItemListener.checkBeforeCopy(src, parent);
T result = (T)createProject(src.getDescriptor(),name,false);
// copy config
Files.copy(Util.fileToPath(srcConfigFile.getFile()), Util.fileToPath(Items.getConfigFile(result).getFile()),
StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING);
// reload from the new config
final File rootDir = result.getRootDir();
result = Items.whileUpdatingByXml(new NotReallyRoleSensitiveCallable<T,IOException>() {
@Override public T call() throws IOException {
return (T) Items.load(parent, rootDir);
}
});
result.onCopiedFrom(src);
add(result);
ItemListener.fireOnCopied(src,result);
Jenkins.get().rebuildDependencyGraphAsync();
return result;
}
public synchronized TopLevelItem createProjectFromXML(String name, InputStream xml) throws IOException {
acl.checkPermission(Item.CREATE);
Jenkins.get().getProjectNamingStrategy().checkName(name);
Items.verifyItemDoesNotAlreadyExist(parent, name, null);
// place it as config.xml
File configXml = Items.getConfigFile(getRootDirFor(name)).getFile();
final File dir = configXml.getParentFile();
dir.mkdirs();
boolean success = false;
try {
XMLUtils.safeTransform(new StreamSource(xml), new StreamResult(configXml));
// load it
TopLevelItem result = Items.whileUpdatingByXml(new NotReallyRoleSensitiveCallable<TopLevelItem,IOException>() {
@Override public TopLevelItem call() throws IOException {
return (TopLevelItem) Items.load(parent, dir);
}
});
success = acl.getACL().hasCreatePermission(Jenkins.getAuthentication(), parent, result.getDescriptor())
&& result.getDescriptor().isApplicableIn(parent);
add(result);
ItemListener.fireOnCreated(result);
Jenkins.get().rebuildDependencyGraphAsync();
return result;
} catch (TransformerException | SAXException e) {
success = false;
throw new IOException("Failed to persist config.xml", e);
} catch (IOException | RuntimeException e) {
success = false;
throw e;
} finally {
if (!success) {
// if anything fails, delete the config file to avoid further confusion
Util.deleteRecursive(dir);
}
}
}
public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name, boolean notify )
throws IOException {
acl.checkPermission(Item.CREATE);
type.checkApplicableIn(parent);
acl.getACL().checkCreatePermission(parent, type);
Jenkins.get().getProjectNamingStrategy().checkName(name);
Items.verifyItemDoesNotAlreadyExist(parent, name, null);
TopLevelItem item = type.newInstance(parent, name);
item.onCreatedFromScratch();
item.save();
add(item);
Jenkins.get().rebuildDependencyGraphAsync();
if (notify)
ItemListener.fireOnCreated(item);
return item;
}
}
| mit |
kaituo/sedge | trunk/test/org/apache/pig/test/TestOptimizeLimit.java | 8684 | /*
* 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.pig.test;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
import org.apache.pig.ExecType;
import org.apache.pig.PigServer;
import org.apache.pig.newplan.logical.optimizer.LogicalPlanOptimizer;
import org.apache.pig.newplan.logical.relational.LogicalPlan;
import org.apache.pig.newplan.logical.rules.LoadTypeCastInserter;
import org.apache.pig.newplan.logical.rules.LimitOptimizer;
import org.apache.pig.newplan.OperatorPlan;
import org.apache.pig.newplan.optimizer.PlanOptimizer;
import org.apache.pig.newplan.optimizer.Rule;
import org.apache.pig.backend.executionengine.ExecException;
import org.apache.pig.impl.PigContext;
import junit.framework.Assert;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class TestOptimizeLimit {
final String FILE_BASE_LOCATION = "test/org/apache/pig/test/data/DotFiles/" ;
static final int MAX_SIZE = 100000;
PigContext pc = new PigContext( ExecType.LOCAL, new Properties() );
PigServer pigServer;
@Before
public void setup() throws ExecException {
pigServer = new PigServer( pc );
}
@After
public void tearDown() {
}
void compareWithGoldenFile(LogicalPlan plan, String filename) throws Exception {
String actualPlan = printLimitGraph(plan);
System.out.println("We get:");
System.out.println(actualPlan);
FileInputStream fis = new FileInputStream(filename);
byte[] b = new byte[MAX_SIZE];
int len = fis.read(b);
String goldenPlan = new String(b, 0, len);
System.out.println("Expected:");
System.out.println(goldenPlan);
Assert.assertEquals(goldenPlan, actualPlan + "\n");
}
public static String printLimitGraph(LogicalPlan plan) throws IOException {
OptimizeLimitPlanPrinter printer = new OptimizeLimitPlanPrinter(plan) ;
String rep = "digraph graph1 {\n";
rep = rep + printer.printToString() ;
rep = rep + "}";
return rep;
}
@Test
// Merget limit into sort
public void testOPLimit1Optimizer() throws Exception {
String query = "A = load 'myfile';" +
"B = order A by $0;" +
"C = limit B 100;" +
"store C into 'empty';";
LogicalPlan newLogicalPlan = Util.buildLp(pigServer, query);;
optimizePlan(newLogicalPlan);
compareWithGoldenFile(newLogicalPlan, FILE_BASE_LOCATION + "new-optlimitplan1.dot");
}
@Test
// Merge limit into limit
public void testOPLimit2Optimizer() throws Exception {
String query = "A = load 'myfile';" +
"B = limit A 10;" +
"C = limit B 100;" + "store C into 'empty';";
LogicalPlan newLogicalPlan = Util.buildLp(pigServer, query);;
optimizePlan(newLogicalPlan);
compareWithGoldenFile(newLogicalPlan, FILE_BASE_LOCATION + "new-optlimitplan2.dot");
}
@Test
// Duplicate limit with two inputs
public void testOPLimit3Optimizer() throws Exception {
String query = "A = load 'myfile1';" +
"B = load 'myfile2';" +
"C = cross A, B;" +
"D = limit C 100;" + "store D into 'empty';";
LogicalPlan newLogicalPlan = Util.buildLp(pigServer, query);;
optimizePlan(newLogicalPlan);
compareWithGoldenFile(newLogicalPlan, FILE_BASE_LOCATION + "new-optlimitplan3.dot");
}
@Test
// Duplicte limit with one input
public void testOPLimit4Optimizer() throws Exception {
String query = "A = load 'myfile1';" +
"B = group A by $0;" + "C = foreach B generate flatten(A);" + "D = limit C 100;" +
"store D into 'empty';";
LogicalPlan newLogicalPlan = Util.buildLp(pigServer, query);;
optimizePlan(newLogicalPlan);
compareWithGoldenFile(newLogicalPlan, FILE_BASE_LOCATION + "new-optlimitplan4.dot");
}
@Test
// Move limit up
public void testOPLimit5Optimizer() throws Exception {
String query = "A = load 'myfile1';" +
"B = foreach A generate $0;" +
"C = limit B 100;" + "store C into 'empty';" ;
LogicalPlan newLogicalPlan = Util.buildLp(pigServer, query);;
optimizePlan(newLogicalPlan);
compareWithGoldenFile(newLogicalPlan, FILE_BASE_LOCATION + "new-optlimitplan5.dot");
}
@Test
// Multiple LOLimit
public void testOPLimit6Optimizer() throws Exception {
String query = "A = load 'myfile';" +
"B = limit A 50;" +
"C = limit B 20;" +
"D = limit C 100;" + "store D into 'empty';";
LogicalPlan newLogicalPlan = Util.buildLp(pigServer, query);;
optimizePlan(newLogicalPlan);
compareWithGoldenFile(newLogicalPlan, FILE_BASE_LOCATION + "new-optlimitplan6.dot");
}
@Test
// Limit stay the same for ForEach with a flatten
public void testOPLimit7Optimizer() throws Exception {
String query = "A = load 'myfile1';" +
"B = foreach A generate flatten($0);" +
"C = limit B 100;" + "store C into 'empty';";
LogicalPlan newLogicalPlan = Util.buildLp(pigServer, query);;
optimizePlan(newLogicalPlan);
compareWithGoldenFile(newLogicalPlan, FILE_BASE_LOCATION + "new-optlimitplan7.dot");
}
@Test
//Limit in the local mode, need to make sure limit stays after a sort
public void testOPLimit8Optimizer() throws Exception {
String query = "A = load 'myfile';" +
"B = order A by $0;" +
"C = limit B 10;" + "store C into 'empty';";
LogicalPlan newLogicalPlan = Util.buildLp(pigServer, query);;
optimizePlan(newLogicalPlan);
compareWithGoldenFile(newLogicalPlan, FILE_BASE_LOCATION + "new-optlimitplan8.dot");
}
@Test
public void testOPLimit9Optimizer() throws Exception {
String query = "A = load 'myfile';" +
"B = order A by $0;" +
"C = limit B 10;" + "store C into 'empty';";
LogicalPlan newLogicalPlan = Util.buildLp(pigServer, query);;
optimizePlan(newLogicalPlan);
compareWithGoldenFile(newLogicalPlan, FILE_BASE_LOCATION + "new-optlimitplan9.dot");
}
@Test
//See bug PIG-913
public void testOPLimit10Optimizer() throws Exception {
String query = "A = load 'myfile' AS (s:chararray);" +
"B = limit A 100;" + "C = GROUP B by $0;" + "store C into 'empty';";
LogicalPlan newLogicalPlan = Util.buildLp(pigServer, query);;
optimizePlan(newLogicalPlan);
compareWithGoldenFile(newLogicalPlan, FILE_BASE_LOCATION + "new-optlimitplan10.dot");
}
@Test
//See bug PIG-995
//We shall throw no exception here
public void testOPLimit11Optimizer() throws Exception {
String query = "B = foreach (limit (order (load 'myfile' AS (a0, a1, a2)) by $1) 10) generate $0;";
LogicalPlan plan = Util.buildLp(pigServer, query);
optimizePlan(plan);
}
public class MyPlanOptimizer extends LogicalPlanOptimizer {
protected MyPlanOptimizer(OperatorPlan p, int iterations) {
super( p, iterations, new HashSet<String>() );
}
protected List<Set<Rule>> buildRuleSets() {
List<Set<Rule>> ls = new ArrayList<Set<Rule>>();
Set<Rule> s = null;
Rule r = null;
s = new HashSet<Rule>();
r = new LoadTypeCastInserter( "TypeCastInserter");
s.add(r);
ls.add(s);
s = new HashSet<Rule>();
r = new LimitOptimizer("OptimizeLimit");
s.add(r);
ls.add(s);
return ls;
}
}
private LogicalPlan optimizePlan(LogicalPlan plan) throws IOException {
PlanOptimizer optimizer = new MyPlanOptimizer( plan, 3 );
optimizer.optimize();
return plan;
}
}
| mit |
caseif/SpongeAPI | src/main/java/org/spongepowered/api/event/entity/EntityInteractEvent.java | 1536 | /*
* This file is part of SpongeAPI, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.api.event.entity;
import org.spongepowered.api.entity.Entity;
import org.spongepowered.api.event.Cancellable;
/**
* Called when an {@link Entity} is interacting with something.
*/
public interface EntityInteractEvent extends EntityEvent, Cancellable {
}
| mit |
gaborkolozsy/XChange | xchange-anx/src/test/java/org/knowm/xchange/anx/v2/dto/trade/OpenOrdersJSONTest.java | 1672 | package org.knowm.xchange.anx.v2.dto.trade;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import org.junit.Assert;
import org.junit.Test;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* Test ANXOpenOrders JSON parsing
*/
public class OpenOrdersJSONTest {
@Test
public void testUnmarshal() throws IOException {
// Read in the JSON from the example resources
InputStream is = OpenOrdersJSONTest.class.getResourceAsStream("/v2/trade/example-openorders-data.json");
// Use Jackson to parse it
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
ANXOpenOrder[] anxOpenOrders = mapper.readValue(is, ANXOpenOrder[].class);
// System.out.println(new Date(anxOpenOrders[0].getTimestamp()));
// Verify that the example data was unmarshalled correctly
Assert.assertEquals("7eecf4b2-5785-4500-a5d4-f3f8c924395c", anxOpenOrders[1].getOid());
Assert.assertEquals("BTC", anxOpenOrders[1].getItem());
Assert.assertEquals("HKD", anxOpenOrders[1].getCurrency());
Assert.assertEquals("bid", anxOpenOrders[1].getType());
Assert.assertEquals("BTC", anxOpenOrders[1].getAmount().getCurrency());
Assert.assertEquals(new BigDecimal("10.00000000"), anxOpenOrders[1].getAmount().getValue());
Assert.assertEquals(new BigDecimal("412.34567"), anxOpenOrders[0].getPrice().getValue());
Assert.assertEquals(new BigDecimal("212.34567"), anxOpenOrders[1].getPrice().getValue());
Assert.assertEquals("open", anxOpenOrders[1].getStatus());
}
}
| mit |
bboyfeiyu/simple_net_framework | src/org/simple/net/requests/MultipartRequest.java | 2710 | /*
* The MIT License (MIT)
*
* Copyright (c) 2014-2015 bboyfeiyu@gmail.com, Inc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.simple.net.requests;
import android.util.Log;
import org.simple.net.base.Request;
import org.simple.net.base.Response;
import org.simple.net.entity.MultipartEntity;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
/**
* Multipart请求 ( 只能为POST请求 ),该请求可以搭载多种类型参数,比如文本、文件等,但是文件仅限于小文件,否则会出现OOM异常.
*
* @author mrsimple
*/
public class MultipartRequest extends Request<String> {
MultipartEntity mMultiPartEntity = new MultipartEntity();
public MultipartRequest(String url, RequestListener<String> listener) {
super(HttpMethod.POST, url, listener);
}
/**
* @return
*/
public MultipartEntity getMultiPartEntity() {
return mMultiPartEntity;
}
@Override
public String getBodyContentType() {
return mMultiPartEntity.getContentType().getValue();
}
@Override
public byte[] getBody() {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
// 将MultipartEntity中的参数写入到bos中
mMultiPartEntity.writeTo(bos);
} catch (IOException e) {
Log.e("", "IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
@Override
public String parseResponse(Response response) {
if (response != null && response.getRawData() != null) {
return new String(response.getRawData());
}
return "";
}
}
| mit |
RallySoftware/eclipselink.runtime | moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/oxm/inheritance/typetests/compositecollection/AddressesAsNestedNoRefClassTestCases.java | 1747 | /*******************************************************************************
* Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.testing.oxm.inheritance.typetests.compositecollection;
import org.eclipse.persistence.oxm.mappings.XMLCompositeCollectionMapping;
import org.eclipse.persistence.sessions.Project;
public class AddressesAsNestedNoRefClassTestCases extends AddressesAsNestedTestCases {
public AddressesAsNestedNoRefClassTestCases(String name) throws Exception {
super(name);
Project p = new COMCollectionTypeProject();
((XMLCompositeCollectionMapping)p.getDescriptor(Employee.class).getMappingForAttributeName("addresses")).setReferenceClass(null);
((XMLCompositeCollectionMapping)p.getDescriptor(Employee.class).getMappingForAttributeName("addresses")).setReferenceClassName(null);
setProject(p);
}
public static void main(String[] args) {
String[] arguments = { "-c", "org.eclipse.persistence.testing.oxm.inheritance.typetests.compositecollection.AddressesAsNestedNoRefClassTestCases" };
junit.textui.TestRunner.main(arguments);
}
}
| epl-1.0 |
veresh/tempo | wds-service/src/test/java/org/intalio/tempo/workflow/wds/core/WDSUtil.java | 1841 | /**
* Copyright (c) 2005-2008 Intalio inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Intalio inc. - initial API and implementation
*/
package org.intalio.tempo.workflow.wds.core;
import java.net.URI;
import java.util.Enumeration;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.ResourceBundle;
import org.intalio.tempo.workflow.task.PIPATask;
public class WDSUtil {
static final Random rand = new Random();
public static Properties convertBundleToProperties(ResourceBundle rb) {
Properties props = new Properties();
for (Enumeration<String> keys = rb.getKeys(); keys.hasMoreElements();) {
String key = (String) keys.nextElement();
props.put(key, rb.getString(key));
}
return props;
}
public static Map<?, ?> getJpaProperties() {
return convertBundleToProperties(ResourceBundle.getBundle("jpa"));
}
public static PIPATask getSamplePipa() {
PIPATask task1 = new PIPATask("abc", "http://localhost/" + rand.nextInt());
task1.setInitMessageNamespaceURI(URI.create("urn:ns"));
task1.setProcessEndpointFromString("http://localhost/process" + rand.nextInt());
task1.setInitOperationSOAPAction("initProcess" + rand.nextInt());
return task1;
}
public static Item getSampleItem() {
return new Item("AbscentRequest", "meta" + rand.nextInt(), new byte[] { 1, 2, 3 });
}
public static Item getXformItem() {
return new Item("http://www.task.xform", "meta" + rand.nextInt(), new byte[] { 1, 2, 3 });
}
} | epl-1.0 |
RallySoftware/eclipselink.runtime | moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/oxm/xmlmarshaller/structureValidation/group/EmployeeProject.java | 4254 | /*******************************************************************************
* Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.testing.oxm.xmlmarshaller.structureValidation.group;
import java.net.URL;
import javax.xml.namespace.QName;
import org.eclipse.persistence.oxm.XMLConstants;
import org.eclipse.persistence.oxm.XMLField;
import org.eclipse.persistence.oxm.mappings.XMLCompositeObjectMapping;
import org.eclipse.persistence.oxm.mappings.XMLDirectMapping;
import org.eclipse.persistence.oxm.XMLDescriptor;
import org.eclipse.persistence.oxm.schema.XMLSchemaReference;
import org.eclipse.persistence.oxm.schema.XMLSchemaURLReference;
import org.eclipse.persistence.sessions.Project;
public class EmployeeProject extends Project {
public EmployeeProject() {
addDescriptor(getEmployeeDescriptor());
addDescriptor(getPeriodDescriptor());
}
private XMLDescriptor getEmployeeDescriptor() {
XMLDescriptor descriptor = new XMLDescriptor();
descriptor.setJavaClass(org.eclipse.persistence.testing.oxm.xmlmarshaller.structureValidation.group.Employee.class);
descriptor.setDefaultRootElement("employee");
XMLCompositeObjectMapping periodMapping = new XMLCompositeObjectMapping();
periodMapping.setAttributeName("_G1");
periodMapping.setXPath(".");
periodMapping.setGetMethodName("getG1");
periodMapping.setSetMethodName("setG1");
periodMapping.setReferenceClass(org.eclipse.persistence.testing.oxm.xmlmarshaller.structureValidation.Period.class);
descriptor.addMapping(periodMapping);
URL schemaURL = ClassLoader.getSystemResource("org/eclipse/persistence/testing/oxm/xmlmarshaller/Employee_Group.xsd");
XMLSchemaURLReference schemaRef = new XMLSchemaURLReference(schemaURL);
schemaRef.setType(XMLSchemaReference.ELEMENT);
schemaRef.setSchemaContext("/employee");
descriptor.setSchemaReference(schemaRef);
return descriptor;
}
private XMLDescriptor getPeriodDescriptor() {
XMLDescriptor descriptor = new XMLDescriptor();
descriptor.setJavaClass(org.eclipse.persistence.testing.oxm.xmlmarshaller.structureValidation.Period.class);
XMLDirectMapping startDateMapping = new XMLDirectMapping();
startDateMapping.setAttributeName("_StartDate");
startDateMapping.setGetMethodName("getStartDate");
startDateMapping.setSetMethodName("setStartDate");
QName qname = new QName(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI, XMLConstants.DATE);
XMLField field = new XMLField("startDate/text()");
field.setSchemaType(qname);
startDateMapping.setField(field);
descriptor.addMapping(startDateMapping);
XMLDirectMapping endDateMapping = new XMLDirectMapping();
endDateMapping.setAttributeName("_EndDate");
endDateMapping.setGetMethodName("getEndDate");
endDateMapping.setSetMethodName("setEndDate");
qname = new QName(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI, XMLConstants.DATE);
field = new XMLField("endDate/text()");
field.setSchemaType(qname);
endDateMapping.setField(field);
descriptor.addMapping(endDateMapping);
URL schemaURL = ClassLoader.getSystemResource("org/eclipse/persistence/testing/oxm/xmlmarshaller/Employee_Group.xsd");
XMLSchemaURLReference schemaRef = new XMLSchemaURLReference(schemaURL);
schemaRef.setType(XMLSchemaReference.GROUP);
schemaRef.setSchemaContext("/G1");
descriptor.setSchemaReference(schemaRef);
return descriptor;
}
}
| epl-1.0 |
RallySoftware/eclipselink.runtime | moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/oxm/schemareference/unmarshal/EmployeeWithoutDefaultRootElementProject.java | 2027 | /*******************************************************************************
* Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.testing.oxm.schemareference.unmarshal;
import org.eclipse.persistence.oxm.NamespaceResolver;
import org.eclipse.persistence.oxm.XMLDescriptor;
import org.eclipse.persistence.oxm.mappings.XMLDirectMapping;
import org.eclipse.persistence.oxm.schema.XMLSchemaClassPathReference;
import org.eclipse.persistence.sessions.Project;
public class EmployeeWithoutDefaultRootElementProject extends Project {
public EmployeeWithoutDefaultRootElementProject() {
super();
this.addDescriptor(getEmployeeDescriptor());
}
private XMLDescriptor getEmployeeDescriptor() {
XMLDescriptor xmlDescriptor = new XMLDescriptor();
xmlDescriptor.setJavaClass(Employee.class);
XMLSchemaClassPathReference schemaReference = new XMLSchemaClassPathReference();
schemaReference.setSchemaContext("/ns:employee-type");
xmlDescriptor.setSchemaReference(schemaReference);
NamespaceResolver namespaceResolver = new NamespaceResolver();
namespaceResolver.put("ns", "urn:test");
xmlDescriptor.setNamespaceResolver(namespaceResolver);
XMLDirectMapping nameMapping = new XMLDirectMapping();
nameMapping.setAttributeName("name");
nameMapping.setXPath("ns:name/text()");
xmlDescriptor.addMapping(nameMapping);
return xmlDescriptor;
}
}
| epl-1.0 |
RallySoftware/eclipselink.runtime | moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/ObjectGraph.java | 3057 | /*******************************************************************************
* Copyright (c) 2011, 2015 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Matt MacIvor - 2.5 - initial implementation
******************************************************************************/
package org.eclipse.persistence.jaxb;
import java.util.List;
/**
* This type represents the root of an object graph that will be used
* as a template to define the attribute nodes and boundaries of a
* graph of JAXB objects and relationships. The root must be an
* root-level JAXB type.
*
* @see org.eclipse.persistence.jaxb.xmlmodel.XmlNamedObjectGraph
*
* @since EclipseLink 2.5
*/
public interface ObjectGraph {
/**
* Returns the name of the static EntityGraph. Will return null if the
* EntityGraph is not a named EntityGraph.
*/
public String getName();
/*
* Add an AttributeNode attribute to the entity graph.
*
* @throws IllegalArgumentException if the attribute is not an attribute of
* this entity.
* @throws IllegalStateException if this EntityGraph has been statically
* defined
*/
public void addAttributeNodes(String ... attributeName);
/*
* Used to add a node of the graph that corresponds to a managed type. This
* allows for construction of multi-node Entity graphs that include related
* managed types.
*
* @throws IllegalArgumentException if the attribute is not an attribute of
* this entity.
* @throws IllegalArgumentException if the attribute's target type is not a
* managed type
*
* @throws IllegalStateException if this EntityGraph has been statically
* defined
*/
public Subgraph addSubgraph(String attribute);
/**
* Used to add a node of the graph that corresponds to a managed type with
* inheritance. This allows for multiple subclass sub-graphs to be defined
* for this node of the entity graph. Subclass sub-graphs will include the
* specified attributes of superclass sub-graphs
*
* @throws IllegalArgumentException if the attribute is not an attribute of
* this managed type.
* @throws IllegalArgumentException
* if the attribute's target type is not a managed type
* @throws IllegalStateException
* if this EntityGraph has been statically defined
*/
public Subgraph addSubgraph(String attribute, Class type);
/*
* returns the attributes of this entity that are included in the entity
* graph
*/
public List<AttributeNode> getAttributeNodes();
}
| epl-1.0 |
gameduell/eclipselink.runtime | moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/oxm/mappings/compositeobject/nillable/CompositeObjectIsSetNodeNullPolicyFalseTestCases.java | 2846 | /*******************************************************************************
* Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.testing.oxm.mappings.compositeobject.nillable;
import org.eclipse.persistence.oxm.mappings.nullpolicy.AbstractNullPolicy;
import org.eclipse.persistence.oxm.mappings.nullpolicy.NullPolicy;
import org.eclipse.persistence.oxm.mappings.nullpolicy.IsSetNullPolicy;
import org.eclipse.persistence.oxm.mappings.nullpolicy.XMLNullRepresentationType;
import org.eclipse.persistence.oxm.mappings.XMLCompositeObjectMapping;
import org.eclipse.persistence.sessions.Project;
import org.eclipse.persistence.testing.oxm.mappings.XMLWithJSONMappingTestCases;
public class CompositeObjectIsSetNodeNullPolicyFalseTestCases extends XMLWithJSONMappingTestCases {
private final static String XML_RESOURCE = //
"org/eclipse/persistence/testing/oxm/mappings/compositeobject/nillable/CompositeObjectIsSetNodeNullPolicyFalse.xml";
private final static String JSON_RESOURCE = //
"org/eclipse/persistence/testing/oxm/mappings/compositeobject/nillable/CompositeObjectIsSetNodeNullPolicyFalse.json";
public CompositeObjectIsSetNodeNullPolicyFalseTestCases(String name) throws Exception {
super(name);
setControlDocument(XML_RESOURCE);
setControlJSON(JSON_RESOURCE);
AbstractNullPolicy aNullPolicy = new IsSetNullPolicy();
// alter unmarshal policy state
aNullPolicy.setNullRepresentedByEmptyNode(false);
aNullPolicy.setNullRepresentedByXsiNil(false);
// alter marshal policy state
aNullPolicy.setMarshalNullRepresentation(XMLNullRepresentationType.ABSENT_NODE);
((IsSetNullPolicy)aNullPolicy).setIsSetMethodName("isSetManager");
Project aProject = new CompositeObjectNodeNullPolicyProject(true);
XMLCompositeObjectMapping aMapping = (XMLCompositeObjectMapping)aProject.getDescriptor(Team.class)//
.getMappingForAttributeName("manager");
aMapping.setNullPolicy(aNullPolicy);
setProject(aProject);
}
protected Object getControlObject() {
Team aTeam = new Team();
aTeam.setId(123);
aTeam.setName("Eng");
return aTeam;
}
}
| epl-1.0 |
rex-xxx/mt6572_x201 | external/okhttp/android/main/java/libcore/util/Libcore.java | 7307 | /*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package libcore.util;
import javax.net.ssl.SSLSocket;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.Socket;
import java.net.SocketException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.ByteOrder;
import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;
/**
* APIs for interacting with Android's core library. The main purpose of this
* class is to access hidden methods on
*
* org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl
*
* via reflection.
*/
public final class Libcore {
private Libcore() {
}
private static final Class<?> openSslSocketClass;
private static final Method setUseSessionTickets;
private static final Method setHostname;
private static final Method setNpnProtocols;
private static final Method getNpnSelectedProtocol;
private static final Constructor<DeflaterOutputStream> deflaterOutputStreamConstructor;
static {
try {
openSslSocketClass = Class.forName(
"org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl");
setUseSessionTickets = openSslSocketClass.getMethod(
"setUseSessionTickets", boolean.class);
setHostname = openSslSocketClass.getMethod("setHostname", String.class);
setNpnProtocols = openSslSocketClass.getMethod("setNpnProtocols", byte[].class);
getNpnSelectedProtocol = openSslSocketClass.getMethod("getNpnSelectedProtocol");
deflaterOutputStreamConstructor = DeflaterOutputStream.class.getConstructor(
new Class[] { OutputStream.class, Deflater.class, boolean.class });
} catch (ClassNotFoundException cnfe) {
throw new RuntimeException(cnfe);
} catch (NoSuchMethodException nsme) {
throw new RuntimeException(nsme);
}
}
public static DeflaterOutputStream newDeflaterOutputStream(
OutputStream os, Deflater deflater, boolean syncFlush) {
try {
return deflaterOutputStreamConstructor.newInstance(os, deflater, syncFlush);
} catch (InstantiationException e) {
throw new RuntimeException("Unknown DeflaterOutputStream implementation.");
} catch (IllegalAccessException e) {
throw new RuntimeException("Unknown DeflaterOutputStream implementation.");
} catch (InvocationTargetException e) {
throw new RuntimeException("Unknown DeflaterOutputStream implementation.");
}
}
public static void makeTlsTolerant(SSLSocket socket, String socketHost, boolean tlsTolerant) {
if (!tlsTolerant) {
socket.setEnabledProtocols(new String[] {"SSLv3"});
return;
}
if (openSslSocketClass.isInstance(socket)) {
try {
setUseSessionTickets.invoke(socket, true);
setHostname.invoke(socket, socketHost);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new AssertionError(e);
}
} else {
throw new RuntimeException("Unknown socket implementation.");
}
}
/**
* Returns the negotiated protocol, or null if no protocol was negotiated.
*/
public static byte[] getNpnSelectedProtocol(SSLSocket socket) {
if (openSslSocketClass.isInstance(socket)) {
try {
return (byte[]) getNpnSelectedProtocol.invoke(socket);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new AssertionError(e);
}
} else {
throw new RuntimeException("Unknown socket implementation.");
}
}
public static void setNpnProtocols(SSLSocket socket, byte[] npnProtocols) {
if (openSslSocketClass.isInstance(socket)) {
try {
setNpnProtocols.invoke(socket, new Object[] {npnProtocols});
} catch (IllegalAccessException e) {
throw new AssertionError(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
} else {
throw new RuntimeException("Unknown socket implementation.");
}
}
public static void deleteIfExists(File file) throws IOException {
// okhttp-changed: was Libcore.os.remove() in a try/catch block
file.delete();
}
public static void logW(String warning) {
// okhttp-changed: was System.logw()
System.out.println(warning);
}
public static int getEffectivePort(URI uri) {
return getEffectivePort(uri.getScheme(), uri.getPort());
}
public static int getEffectivePort(URL url) {
return getEffectivePort(url.getProtocol(), url.getPort());
}
private static int getEffectivePort(String scheme, int specifiedPort) {
if (specifiedPort != -1) {
return specifiedPort;
}
if ("http".equalsIgnoreCase(scheme)) {
return 80;
} else if ("https".equalsIgnoreCase(scheme)) {
return 443;
} else {
return -1;
}
}
public static void checkOffsetAndCount(int arrayLength, int offset, int count) {
if ((offset | count) < 0 || offset > arrayLength || arrayLength - offset < count) {
throw new ArrayIndexOutOfBoundsException();
}
}
public static void tagSocket(Socket socket) {
}
public static void untagSocket(Socket socket) throws SocketException {
}
public static URI toUriLenient(URL url) throws URISyntaxException {
return url.toURI(); // this isn't as good as the built-in toUriLenient
}
public static void pokeInt(byte[] dst, int offset, int value, ByteOrder order) {
if (order == ByteOrder.BIG_ENDIAN) {
dst[offset++] = (byte) ((value >> 24) & 0xff);
dst[offset++] = (byte) ((value >> 16) & 0xff);
dst[offset++] = (byte) ((value >> 8) & 0xff);
dst[offset ] = (byte) ((value >> 0) & 0xff);
} else {
dst[offset++] = (byte) ((value >> 0) & 0xff);
dst[offset++] = (byte) ((value >> 8) & 0xff);
dst[offset++] = (byte) ((value >> 16) & 0xff);
dst[offset ] = (byte) ((value >> 24) & 0xff);
}
}
}
| gpl-2.0 |
md-5/jdk10 | test/jdk/java/lang/invoke/MethodHandlesGeneralTest.java | 104498 | /*
* Copyright (c) 2018, 2019, 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 8216558
* @summary unit tests for java.lang.invoke.MethodHandles
* @library /test/lib /java/lang/invoke/common
* @compile MethodHandlesTest.java MethodHandlesGeneralTest.java remote/RemoteExample.java
* @run junit/othervm/timeout=2500 -XX:+IgnoreUnrecognizedVMOptions
* -XX:-VerifyDependencies
* -esa
* test.java.lang.invoke.MethodHandlesGeneralTest
*/
package test.java.lang.invoke;
import org.junit.*;
import test.java.lang.invoke.lib.CodeCacheOverflowProcessor;
import test.java.lang.invoke.remote.RemoteExample;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandleProxies;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.invoke.WrongMethodTypeException;
import java.lang.invoke.MethodHandles.Lookup;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.UndeclaredThrowableException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Formatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static java.lang.invoke.MethodType.methodType;
import static org.junit.Assert.*;
public class MethodHandlesGeneralTest extends MethodHandlesTest {
@Test
public void testFirst() throws Throwable {
verbosity += 9;
try {
// left blank for debugging
} finally { printCounts(); verbosity -= 9; }
}
@Test
public void testFindStatic() throws Throwable {
CodeCacheOverflowProcessor.runMHTest(this::testFindStatic0);
}
public void testFindStatic0() throws Throwable {
if (CAN_SKIP_WORKING) return;
startTest("findStatic");
testFindStatic(PubExample.class, void.class, "s0");
testFindStatic(Example.class, void.class, "s0");
testFindStatic(Example.class, void.class, "pkg_s0");
testFindStatic(Example.class, void.class, "pri_s0");
testFindStatic(Example.class, void.class, "pro_s0");
testFindStatic(PubExample.class, void.class, "Pub/pro_s0");
testFindStatic(Example.class, Object.class, "s1", Object.class);
testFindStatic(Example.class, Object.class, "s2", int.class);
testFindStatic(Example.class, Object.class, "s3", long.class);
testFindStatic(Example.class, Object.class, "s4", int.class, int.class);
testFindStatic(Example.class, Object.class, "s5", long.class, int.class);
testFindStatic(Example.class, Object.class, "s6", int.class, long.class);
testFindStatic(Example.class, Object.class, "s7", float.class, double.class);
testFindStatic(false, PRIVATE, Example.class, void.class, "bogus");
testFindStatic(false, PRIVATE, Example.class, void.class, "<init>", int.class);
testFindStatic(false, PRIVATE, Example.class, void.class, "<init>", Void.class);
testFindStatic(false, PRIVATE, Example.class, void.class, "v0");
}
void testFindStatic(Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
for (Object[] ac : accessCases(defc, name)) {
testFindStatic((Boolean)ac[0], (Lookup)ac[1], defc, ret, name, params);
}
}
void testFindStatic(Lookup lookup, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
testFindStatic(true, lookup, defc, ret, name, params);
}
void testFindStatic(boolean positive, Lookup lookup, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
countTest(positive);
String methodName = name.substring(1 + name.indexOf('/')); // foo/bar => foo
MethodType type = MethodType.methodType(ret, params);
MethodHandle target = null;
Exception noAccess = null;
try {
if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
target = maybeMoveIn(lookup, defc).findStatic(defc, methodName, type);
} catch (ReflectiveOperationException ex) {
noAccess = ex;
assertExceptionClass(
(name.contains("bogus") || INIT_REF_CAUSES_NSME && name.contains("<init>"))
? NoSuchMethodException.class
: IllegalAccessException.class,
noAccess);
if (verbosity >= 5) ex.printStackTrace(System.out);
}
if (verbosity >= 3)
System.out.println("findStatic "+lookup+": "+defc.getName()+"."+name+"/"+type+" => "+target
+(noAccess == null ? "" : " !! "+noAccess));
if (positive && noAccess != null) throw noAccess;
assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
if (!positive) return; // negative test failed as expected
assertEquals(type, target.type());
assertNameStringContains(target, methodName);
Object[] args = randomArgs(params);
printCalled(target, name, args);
target.invokeWithArguments(args);
assertCalled(name, args);
if (verbosity >= 1)
System.out.print(':');
}
@Test
public void testFindVirtual() throws Throwable {
CodeCacheOverflowProcessor.runMHTest(this::testFindVirtual0);
}
public void testFindVirtual0() throws Throwable {
if (CAN_SKIP_WORKING) return;
startTest("findVirtual");
testFindVirtual(Example.class, void.class, "v0");
testFindVirtual(Example.class, void.class, "pkg_v0");
testFindVirtual(Example.class, void.class, "pri_v0");
testFindVirtual(Example.class, Object.class, "v1", Object.class);
testFindVirtual(Example.class, Object.class, "v2", Object.class, Object.class);
testFindVirtual(Example.class, Object.class, "v2", Object.class, int.class);
testFindVirtual(Example.class, Object.class, "v2", int.class, Object.class);
testFindVirtual(Example.class, Object.class, "v2", int.class, int.class);
testFindVirtual(Example.class, void.class, "pro_v0");
testFindVirtual(PubExample.class, void.class, "Pub/pro_v0");
testFindVirtual(false, PRIVATE, Example.class, Example.class, void.class, "bogus");
testFindVirtual(false, PRIVATE, Example.class, Example.class, void.class, "<init>", int.class);
testFindVirtual(false, PRIVATE, Example.class, Example.class, void.class, "<init>", Void.class);
testFindVirtual(false, PRIVATE, Example.class, Example.class, void.class, "s0");
// test dispatch
testFindVirtual(SubExample.class, SubExample.class, void.class, "Sub/v0");
testFindVirtual(SubExample.class, Example.class, void.class, "Sub/v0");
testFindVirtual(SubExample.class, IntExample.class, void.class, "Sub/v0");
testFindVirtual(SubExample.class, SubExample.class, void.class, "Sub/pkg_v0");
testFindVirtual(SubExample.class, Example.class, void.class, "Sub/pkg_v0");
testFindVirtual(Example.class, IntExample.class, void.class, "v0");
testFindVirtual(IntExample.Impl.class, IntExample.class, void.class, "Int/v0");
}
@Test
public void testFindVirtualClone() throws Throwable {
CodeCacheOverflowProcessor.runMHTest(this::testFindVirtualClone0);
}
public void testFindVirtualClone0() throws Throwable {
if (CAN_SKIP_WORKING) return;
// test some ad hoc system methods
testFindVirtual(false, PUBLIC, Object.class, Object.class, "clone");
// ##### FIXME - disable tests for clone until we figure out how they should work with modules
/*
testFindVirtual(true, PUBLIC, Object[].class, Object.class, "clone");
testFindVirtual(true, PUBLIC, int[].class, Object.class, "clone");
for (Class<?> cls : new Class<?>[]{ boolean[].class, long[].class, float[].class, char[].class })
testFindVirtual(true, PUBLIC, cls, Object.class, "clone");
*/
}
void testFindVirtual(Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
Class<?> rcvc = defc;
testFindVirtual(rcvc, defc, ret, name, params);
}
void testFindVirtual(Class<?> rcvc, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
for (Object[] ac : accessCases(defc, name)) {
testFindVirtual((Boolean)ac[0], (Lookup)ac[1], rcvc, defc, ret, name, params);
}
}
void testFindVirtual(Lookup lookup, Class<?> rcvc, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
testFindVirtual(true, lookup, rcvc, defc, ret, name, params);
}
void testFindVirtual(boolean positive, Lookup lookup, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
testFindVirtual(positive, lookup, defc, defc, ret, name, params);
}
void testFindVirtual(boolean positive, Lookup lookup, Class<?> rcvc, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
countTest(positive);
String methodName = name.substring(1 + name.indexOf('/')); // foo/bar => foo
MethodType type = MethodType.methodType(ret, params);
MethodHandle target = null;
Exception noAccess = null;
try {
if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
target = maybeMoveIn(lookup, defc).findVirtual(defc, methodName, type);
} catch (ReflectiveOperationException ex) {
noAccess = ex;
assertExceptionClass(
(name.contains("bogus") || INIT_REF_CAUSES_NSME && name.contains("<init>"))
? NoSuchMethodException.class
: IllegalAccessException.class,
noAccess);
if (verbosity >= 5) ex.printStackTrace(System.out);
}
if (verbosity >= 3)
System.out.println("findVirtual "+lookup+": "+defc.getName()+"."+name+"/"+type+" => "+target
+(noAccess == null ? "" : " !! "+noAccess));
if (positive && noAccess != null) throw noAccess;
assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
if (!positive) return; // negative test failed as expected
Class<?> selfc = defc;
// predict receiver type narrowing:
if (lookup == SUBCLASS &&
name.contains("pro_") &&
selfc.isAssignableFrom(lookup.lookupClass())) {
selfc = lookup.lookupClass();
if (name.startsWith("Pub/")) name = "Rem/"+name.substring(4);
}
Class<?>[] paramsWithSelf = cat(array(Class[].class, (Class)selfc), params);
MethodType typeWithSelf = MethodType.methodType(ret, paramsWithSelf);
assertEquals(typeWithSelf, target.type());
assertNameStringContains(target, methodName);
Object[] argsWithSelf = randomArgs(paramsWithSelf);
if (selfc.isAssignableFrom(rcvc) && rcvc != selfc) argsWithSelf[0] = randomArg(rcvc);
printCalled(target, name, argsWithSelf);
Object res = target.invokeWithArguments(argsWithSelf);
if (Example.class.isAssignableFrom(defc) || IntExample.class.isAssignableFrom(defc)) {
assertCalled(name, argsWithSelf);
} else if (name.equals("clone")) {
// Ad hoc method call outside Example. For Object[].clone.
printCalled(target, name, argsWithSelf);
assertEquals(MethodType.methodType(Object.class, rcvc), target.type());
Object orig = argsWithSelf[0];
assertEquals(orig.getClass(), res.getClass());
if (res instanceof Object[])
assertArrayEquals((Object[])res, (Object[])argsWithSelf[0]);
assert(Arrays.deepEquals(new Object[]{res}, new Object[]{argsWithSelf[0]}));
} else {
assert(false) : Arrays.asList(positive, lookup, rcvc, defc, ret, name, deepToString(params));
}
if (verbosity >= 1)
System.out.print(':');
}
@Test
public void testFindSpecial() throws Throwable {
CodeCacheOverflowProcessor.runMHTest(this::testFindSpecial0);
}
public void testFindSpecial0() throws Throwable {
if (CAN_SKIP_WORKING) return;
startTest("findSpecial");
testFindSpecial(SubExample.class, Example.class, void.class, false, "v0");
testFindSpecial(SubExample.class, Example.class, void.class, false, "pkg_v0");
testFindSpecial(RemoteExample.class, PubExample.class, void.class, false, "Pub/pro_v0");
testFindSpecial(Example.class, IntExample.class, void.class, true, "vd");
// Do some negative testing:
for (Lookup lookup : new Lookup[]{ PRIVATE, EXAMPLE, PACKAGE, PUBLIC }) {
testFindSpecial(false, lookup, Object.class, Example.class, void.class, "v0");
testFindSpecial(false, lookup, SubExample.class, Example.class, void.class, "bogus");
testFindSpecial(false, lookup, SubExample.class, Example.class, void.class, "<init>", int.class);
testFindSpecial(false, lookup, SubExample.class, Example.class, void.class, "<init>", Void.class);
testFindSpecial(false, lookup, SubExample.class, Example.class, void.class, "s0");
testFindSpecial(false, lookup, Example.class, IntExample.class, void.class, "v0");
}
}
void testFindSpecial(Class<?> specialCaller,
Class<?> defc, Class<?> ret, boolean dflt, String name, Class<?>... params) throws Throwable {
if (specialCaller == RemoteExample.class) {
testFindSpecial(false, EXAMPLE, specialCaller, defc, ret, name, params);
testFindSpecial(false, PRIVATE, specialCaller, defc, ret, name, params);
testFindSpecial(false, PACKAGE, specialCaller, defc, ret, name, params);
testFindSpecial(true, SUBCLASS, specialCaller, defc, ret, name, params);
testFindSpecial(false, PUBLIC, specialCaller, defc, ret, name, params);
return;
}
testFindSpecial(true, EXAMPLE, specialCaller, defc, ret, name, params);
testFindSpecial(true, PRIVATE, specialCaller, defc, ret, name, params);
testFindSpecial(false || dflt, PACKAGE, specialCaller, defc, ret, name, params);
testFindSpecial(false, SUBCLASS, specialCaller, defc, ret, name, params);
testFindSpecial(false, PUBLIC, specialCaller, defc, ret, name, params);
}
void testFindSpecial(boolean positive, Lookup lookup, Class<?> specialCaller,
Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
countTest(positive);
String methodName = name.substring(1 + name.indexOf('/')); // foo/bar => foo
MethodType type = MethodType.methodType(ret, params);
Lookup specialLookup = maybeMoveIn(lookup, specialCaller);
boolean specialAccessOK = (specialLookup.lookupClass() == specialCaller &&
(specialLookup.lookupModes() & Lookup.PRIVATE) != 0);
MethodHandle target = null;
Exception noAccess = null;
try {
if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
if (verbosity >= 5) System.out.println(" lookup => "+specialLookup);
target = specialLookup.findSpecial(defc, methodName, type, specialCaller);
} catch (ReflectiveOperationException ex) {
noAccess = ex;
assertExceptionClass(
(!specialAccessOK) // this check should happen first
? IllegalAccessException.class
: (name.contains("bogus") || INIT_REF_CAUSES_NSME && name.contains("<init>"))
? NoSuchMethodException.class
: IllegalAccessException.class,
noAccess);
if (verbosity >= 5) ex.printStackTrace(System.out);
}
if (verbosity >= 3)
System.out.println("findSpecial from "+specialCaller.getName()+" to "+defc.getName()+"."+name+"/"+type+" => "+target
+(target == null ? "" : target.type())
+(noAccess == null ? "" : " !! "+noAccess));
if (positive && noAccess != null) throw noAccess;
assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
if (!positive) return; // negative test failed as expected
assertEquals(specialCaller, target.type().parameterType(0));
assertEquals(type, target.type().dropParameterTypes(0,1));
Class<?>[] paramsWithSelf = cat(array(Class[].class, (Class)specialCaller), params);
MethodType typeWithSelf = MethodType.methodType(ret, paramsWithSelf);
assertNameStringContains(target, methodName);
Object[] args = randomArgs(paramsWithSelf);
printCalled(target, name, args);
target.invokeWithArguments(args);
assertCalled(name, args);
}
@Test
public void testFindConstructor() throws Throwable {
CodeCacheOverflowProcessor.runMHTest(this::testFindConstructor0);
}
public void testFindConstructor0() throws Throwable {
if (CAN_SKIP_WORKING) return;
startTest("findConstructor");
testFindConstructor(true, EXAMPLE, Example.class);
testFindConstructor(true, EXAMPLE, Example.class, int.class);
testFindConstructor(true, EXAMPLE, Example.class, int.class, int.class);
testFindConstructor(true, EXAMPLE, Example.class, int.class, long.class);
testFindConstructor(true, EXAMPLE, Example.class, int.class, float.class);
testFindConstructor(true, EXAMPLE, Example.class, int.class, double.class);
testFindConstructor(true, EXAMPLE, Example.class, String.class);
testFindConstructor(true, EXAMPLE, Example.class, int.class, int.class, int.class);
testFindConstructor(true, EXAMPLE, Example.class, int.class, int.class, int.class, int.class);
}
void testFindConstructor(boolean positive, Lookup lookup,
Class<?> defc, Class<?>... params) throws Throwable {
countTest(positive);
MethodType type = MethodType.methodType(void.class, params);
MethodHandle target = null;
Exception noAccess = null;
try {
if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" <init>"+type);
target = lookup.findConstructor(defc, type);
} catch (ReflectiveOperationException ex) {
noAccess = ex;
assertTrue(noAccess.getClass().getName(), noAccess instanceof IllegalAccessException);
}
if (verbosity >= 3)
System.out.println("findConstructor "+defc.getName()+".<init>/"+type+" => "+target
+(target == null ? "" : target.type())
+(noAccess == null ? "" : " !! "+noAccess));
if (positive && noAccess != null) throw noAccess;
assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
if (!positive) return; // negative test failed as expected
assertEquals(type.changeReturnType(defc), target.type());
Object[] args = randomArgs(params);
printCalled(target, defc.getSimpleName(), args);
Object obj = target.invokeWithArguments(args);
if (!(defc == Example.class && params.length < 2))
assertCalled(defc.getSimpleName()+".<init>", args);
assertTrue("instance of "+defc.getName(), defc.isInstance(obj));
}
@Test
public void testBind() throws Throwable {
CodeCacheOverflowProcessor.runMHTest(this::testBind0);
}
public void testBind0() throws Throwable {
if (CAN_SKIP_WORKING) return;
startTest("bind");
testBind(Example.class, void.class, "v0");
testBind(Example.class, void.class, "pkg_v0");
testBind(Example.class, void.class, "pri_v0");
testBind(Example.class, Object.class, "v1", Object.class);
testBind(Example.class, Object.class, "v2", Object.class, Object.class);
testBind(Example.class, Object.class, "v2", Object.class, int.class);
testBind(Example.class, Object.class, "v2", int.class, Object.class);
testBind(Example.class, Object.class, "v2", int.class, int.class);
testBind(false, PRIVATE, Example.class, void.class, "bogus");
testBind(false, PRIVATE, Example.class, void.class, "<init>", int.class);
testBind(false, PRIVATE, Example.class, void.class, "<init>", Void.class);
testBind(SubExample.class, void.class, "Sub/v0");
testBind(SubExample.class, void.class, "Sub/pkg_v0");
testBind(IntExample.Impl.class, void.class, "Int/v0");
}
void testBind(Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
for (Object[] ac : accessCases(defc, name)) {
testBind((Boolean)ac[0], (Lookup)ac[1], defc, ret, name, params);
}
}
void testBind(boolean positive, Lookup lookup, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
countTest(positive);
String methodName = name.substring(1 + name.indexOf('/')); // foo/bar => foo
MethodType type = MethodType.methodType(ret, params);
Object receiver = randomArg(defc);
MethodHandle target = null;
Exception noAccess = null;
try {
if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
target = maybeMoveIn(lookup, defc).bind(receiver, methodName, type);
} catch (ReflectiveOperationException ex) {
noAccess = ex;
assertExceptionClass(
(name.contains("bogus") || INIT_REF_CAUSES_NSME && name.contains("<init>"))
? NoSuchMethodException.class
: IllegalAccessException.class,
noAccess);
if (verbosity >= 5) ex.printStackTrace(System.out);
}
if (verbosity >= 3)
System.out.println("bind "+receiver+"."+name+"/"+type+" => "+target
+(noAccess == null ? "" : " !! "+noAccess));
if (positive && noAccess != null) throw noAccess;
assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
if (!positive) return; // negative test failed as expected
assertEquals(type, target.type());
Object[] args = randomArgs(params);
printCalled(target, name, args);
target.invokeWithArguments(args);
Object[] argsWithReceiver = cat(array(Object[].class, receiver), args);
assertCalled(name, argsWithReceiver);
if (verbosity >= 1)
System.out.print(':');
}
@Test
public void testUnreflect() throws Throwable {
CodeCacheOverflowProcessor.runMHTest(this::testUnreflect0);
}
public void testUnreflect0() throws Throwable {
if (CAN_SKIP_WORKING) return;
startTest("unreflect");
testUnreflect(Example.class, true, void.class, "s0");
testUnreflect(Example.class, true, void.class, "pro_s0");
testUnreflect(Example.class, true, void.class, "pkg_s0");
testUnreflect(Example.class, true, void.class, "pri_s0");
testUnreflect(Example.class, true, Object.class, "s1", Object.class);
testUnreflect(Example.class, true, Object.class, "s2", int.class);
testUnreflect(Example.class, true, Object.class, "s3", long.class);
testUnreflect(Example.class, true, Object.class, "s4", int.class, int.class);
testUnreflect(Example.class, true, Object.class, "s5", long.class, int.class);
testUnreflect(Example.class, true, Object.class, "s6", int.class, long.class);
testUnreflect(Example.class, false, void.class, "v0");
testUnreflect(Example.class, false, void.class, "pkg_v0");
testUnreflect(Example.class, false, void.class, "pri_v0");
testUnreflect(Example.class, false, Object.class, "v1", Object.class);
testUnreflect(Example.class, false, Object.class, "v2", Object.class, Object.class);
testUnreflect(Example.class, false, Object.class, "v2", Object.class, int.class);
testUnreflect(Example.class, false, Object.class, "v2", int.class, Object.class);
testUnreflect(Example.class, false, Object.class, "v2", int.class, int.class);
// Test a public final member in another package:
testUnreflect(RemoteExample.class, false, void.class, "Rem/fin_v0");
}
void testUnreflect(Class<?> defc, boolean isStatic, Class<?> ret, String name, Class<?>... params) throws Throwable {
for (Object[] ac : accessCases(defc, name)) {
testUnreflectMaybeSpecial(null, (Boolean)ac[0], (Lookup)ac[1], defc, (isStatic ? null : defc), ret, name, params);
}
}
void testUnreflect(Class<?> defc, Class<?> rcvc, Class<?> ret, String name, Class<?>... params) throws Throwable {
for (Object[] ac : accessCases(defc, name)) {
testUnreflectMaybeSpecial(null, (Boolean)ac[0], (Lookup)ac[1], defc, rcvc, ret, name, params);
}
}
void testUnreflectMaybeSpecial(Class<?> specialCaller,
boolean positive, Lookup lookup,
Class<?> defc, Class<?> rcvc, Class<?> ret, String name, Class<?>... params) throws Throwable {
countTest(positive);
String methodName = name.substring(1 + name.indexOf('/')); // foo/bar => foo
MethodType type = MethodType.methodType(ret, params);
Lookup specialLookup = (specialCaller != null ? maybeMoveIn(lookup, specialCaller) : null);
boolean specialAccessOK = (specialCaller != null &&
specialLookup.lookupClass() == specialCaller &&
(specialLookup.lookupModes() & Lookup.PRIVATE) != 0);
Method rmethod = defc.getDeclaredMethod(methodName, params);
MethodHandle target = null;
Exception noAccess = null;
boolean isStatic = (rcvc == null);
boolean isSpecial = (specialCaller != null);
try {
if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
if (isSpecial)
target = specialLookup.unreflectSpecial(rmethod, specialCaller);
else
target = maybeMoveIn(lookup, defc).unreflect(rmethod);
} catch (ReflectiveOperationException ex) {
noAccess = ex;
assertExceptionClass(
IllegalAccessException.class, // NSME is impossible, since it was already reflected
noAccess);
if (verbosity >= 5) ex.printStackTrace(System.out);
}
if (verbosity >= 3)
System.out.println("unreflect"+(isSpecial?"Special":"")+" "+defc.getName()+"."+name+"/"+type
+(!isSpecial ? "" : " specialCaller="+specialCaller)
+( isStatic ? "" : " receiver="+rcvc)
+" => "+target
+(noAccess == null ? "" : " !! "+noAccess));
if (positive && noAccess != null) throw noAccess;
assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
if (!positive) return; // negative test failed as expected
assertEquals(isStatic, Modifier.isStatic(rmethod.getModifiers()));
Class<?>[] paramsMaybeWithSelf = params;
if (!isStatic) {
paramsMaybeWithSelf = cat(array(Class[].class, (Class)rcvc), params);
}
MethodType typeMaybeWithSelf = MethodType.methodType(ret, paramsMaybeWithSelf);
if (isStatic) {
assertEquals(typeMaybeWithSelf, target.type());
} else {
if (isSpecial)
assertEquals(specialCaller, target.type().parameterType(0));
else
assertEquals(defc, target.type().parameterType(0));
assertEquals(typeMaybeWithSelf, target.type().changeParameterType(0, rcvc));
}
Object[] argsMaybeWithSelf = randomArgs(paramsMaybeWithSelf);
printCalled(target, name, argsMaybeWithSelf);
target.invokeWithArguments(argsMaybeWithSelf);
assertCalled(name, argsMaybeWithSelf);
if (verbosity >= 1)
System.out.print(':');
}
void testUnreflectSpecial(Class<?> defc, Class<?> rcvc, Class<?> ret, String name, Class<?>... params) throws Throwable {
for (Object[] ac : accessCases(defc, name, true)) {
Class<?> specialCaller = rcvc;
testUnreflectMaybeSpecial(specialCaller, (Boolean)ac[0], (Lookup)ac[1], defc, rcvc, ret, name, params);
}
}
@Test
public void testUnreflectSpecial() throws Throwable {
CodeCacheOverflowProcessor.runMHTest(this::testUnreflectSpecial0);
}
public void testUnreflectSpecial0() throws Throwable {
if (CAN_SKIP_WORKING) return;
startTest("unreflectSpecial");
testUnreflectSpecial(Example.class, Example.class, void.class, "v0");
testUnreflectSpecial(Example.class, SubExample.class, void.class, "v0");
testUnreflectSpecial(Example.class, Example.class, void.class, "pkg_v0");
testUnreflectSpecial(Example.class, SubExample.class, void.class, "pkg_v0");
testUnreflectSpecial(Example.class, Example.class, Object.class, "v2", int.class, int.class);
testUnreflectSpecial(Example.class, SubExample.class, Object.class, "v2", int.class, int.class);
testUnreflectMaybeSpecial(Example.class, false, PRIVATE, Example.class, Example.class, void.class, "s0");
}
@Test
public void testUnreflectGetter() throws Throwable {
CodeCacheOverflowProcessor.runMHTest(this::testUnreflectGetter0);
}
public void testUnreflectGetter0() throws Throwable {
if (CAN_SKIP_WORKING) return;
startTest("unreflectGetter");
testGetter(TEST_UNREFLECT);
}
@Test
public void testFindGetter() throws Throwable {
CodeCacheOverflowProcessor.runMHTest(this::testFindGetter0);
}
public void testFindGetter0() throws Throwable {
if (CAN_SKIP_WORKING) return;
startTest("findGetter");
testGetter(TEST_FIND_FIELD);
testGetter(TEST_FIND_FIELD | TEST_BOUND);
}
@Test
public void testFindStaticGetter() throws Throwable {
CodeCacheOverflowProcessor.runMHTest(this::testFindStaticGetter0);
}
public void testFindStaticGetter0() throws Throwable {
if (CAN_SKIP_WORKING) return;
startTest("findStaticGetter");
testGetter(TEST_FIND_STATIC);
}
public void testGetter(int testMode) throws Throwable {
Lookup lookup = PRIVATE; // FIXME: test more lookups than this one
for (Object[] c : HasFields.testCasesFor(testMode)) {
boolean positive = (c[1] != Error.class);
testGetter(positive, lookup, c[0], c[1], testMode);
if (positive)
testGetter(positive, lookup, c[0], c[1], testMode | TEST_NPE);
}
testGetter(true, lookup,
new Object[]{ true, System.class, "out", java.io.PrintStream.class },
System.out, testMode);
for (int isStaticN = 0; isStaticN <= 1; isStaticN++) {
testGetter(false, lookup,
new Object[]{ (isStaticN != 0), System.class, "bogus", char.class },
null, testMode);
}
}
public void testGetter(boolean positive, MethodHandles.Lookup lookup,
Object fieldRef, Object value, int testMode) throws Throwable {
testAccessor(positive, lookup, fieldRef, value, testMode);
}
public void testAccessor(boolean positive0, MethodHandles.Lookup lookup,
Object fieldRef, Object value, int testMode0) throws Throwable {
if (verbosity >= 4)
System.out.println("testAccessor"+Arrays.deepToString(new Object[]{positive0, lookup, fieldRef, value, testMode0}));
boolean isGetter = ((testMode0 & TEST_SETTER) == 0);
boolean doBound = ((testMode0 & TEST_BOUND) != 0);
boolean testNPE = ((testMode0 & TEST_NPE) != 0);
int testMode = testMode0 & ~(TEST_SETTER | TEST_BOUND | TEST_NPE);
boolean positive = positive0 && !testNPE;
boolean isStatic;
Class<?> fclass;
String fname;
Class<?> ftype;
Field f = (fieldRef instanceof Field ? (Field)fieldRef : null);
if (f != null) {
isStatic = Modifier.isStatic(f.getModifiers());
fclass = f.getDeclaringClass();
fname = f.getName();
ftype = f.getType();
} else {
Object[] scnt = (Object[]) fieldRef;
isStatic = (Boolean) scnt[0];
fclass = (Class<?>) scnt[1];
fname = (String) scnt[2];
ftype = (Class<?>) scnt[3];
try {
f = fclass.getDeclaredField(fname);
} catch (ReflectiveOperationException ex) {
f = null;
}
}
if (!testModeMatches(testMode, isStatic)) return;
if (f == null && testMode == TEST_UNREFLECT) return;
if (testNPE && isStatic) return;
countTest(positive);
MethodType expType;
if (isGetter)
expType = MethodType.methodType(ftype, HasFields.class);
else
expType = MethodType.methodType(void.class, HasFields.class, ftype);
if (isStatic) expType = expType.dropParameterTypes(0, 1);
Exception noAccess = null;
MethodHandle mh;
try {
switch (testMode0 & ~(TEST_BOUND | TEST_NPE)) {
case TEST_UNREFLECT: mh = lookup.unreflectGetter(f); break;
case TEST_FIND_FIELD: mh = lookup.findGetter(fclass, fname, ftype); break;
case TEST_FIND_STATIC: mh = lookup.findStaticGetter(fclass, fname, ftype); break;
case TEST_SETTER|
TEST_UNREFLECT: mh = lookup.unreflectSetter(f); break;
case TEST_SETTER|
TEST_FIND_FIELD: mh = lookup.findSetter(fclass, fname, ftype); break;
case TEST_SETTER|
TEST_FIND_STATIC: mh = lookup.findStaticSetter(fclass, fname, ftype); break;
default:
throw new InternalError("testMode="+testMode);
}
} catch (ReflectiveOperationException ex) {
mh = null;
noAccess = ex;
assertExceptionClass(
(fname.contains("bogus"))
? NoSuchFieldException.class
: IllegalAccessException.class,
noAccess);
if (verbosity >= 5) ex.printStackTrace(System.out);
}
if (verbosity >= 3)
System.out.format("%s%s %s.%s/%s => %s %s%n",
(testMode0 & TEST_UNREFLECT) != 0
? "unreflect"
: "find" + ((testMode0 & TEST_FIND_STATIC) != 0 ? "Static" : ""),
(isGetter ? "Getter" : "Setter"),
fclass.getName(), fname, ftype, mh,
(noAccess == null ? "" : " !! "+noAccess));
// negative test case and expected noAccess, then done.
if (!positive && noAccess != null) return;
// positive test case but found noAccess, then error
if (positive && !testNPE && noAccess != null) throw new RuntimeException(noAccess);
assertEquals(positive0 ? "positive test" : "negative test erroneously passed", positive0, mh != null);
if (!positive && !testNPE) return; // negative access test failed as expected
assertEquals((isStatic ? 0 : 1)+(isGetter ? 0 : 1), mh.type().parameterCount());
assertSame(mh.type(), expType);
//assertNameStringContains(mh, fname); // This does not hold anymore with LFs
HasFields fields = new HasFields();
HasFields fieldsForMH = fields;
if (testNPE) fieldsForMH = null; // perturb MH argument to elicit expected error
if (doBound)
mh = mh.bindTo(fieldsForMH);
Object sawValue;
Class<?> vtype = ftype;
if (ftype != int.class) vtype = Object.class;
if (isGetter) {
mh = mh.asType(mh.type().generic()
.changeReturnType(vtype));
} else {
int last = mh.type().parameterCount() - 1;
mh = mh.asType(mh.type().generic()
.changeReturnType(void.class)
.changeParameterType(last, vtype));
}
if (f != null && f.getDeclaringClass() == HasFields.class) {
assertEquals(f.get(fields), value); // clean to start with
}
Throwable caughtEx = null;
// non-final field and setAccessible(true) on instance field will have write access
boolean writeAccess = !Modifier.isFinal(f.getModifiers()) ||
(!Modifier.isStatic(f.getModifiers()) && f.isAccessible());
if (isGetter) {
Object expValue = value;
for (int i = 0; i <= 1; i++) {
sawValue = null; // make DA rules happy under try/catch
try {
if (isStatic || doBound) {
if (ftype == int.class)
sawValue = (int) mh.invokeExact(); // do these exactly
else
sawValue = mh.invokeExact();
} else {
if (ftype == int.class)
sawValue = (int) mh.invokeExact((Object) fieldsForMH);
else
sawValue = mh.invokeExact((Object) fieldsForMH);
}
} catch (RuntimeException ex) {
if (ex instanceof NullPointerException && testNPE) {
caughtEx = ex;
break;
}
}
assertEquals(sawValue, expValue);
if (f != null && f.getDeclaringClass() == HasFields.class && writeAccess) {
Object random = randomArg(ftype);
f.set(fields, random);
expValue = random;
} else {
break;
}
}
} else {
for (int i = 0; i <= 1; i++) {
Object putValue = randomArg(ftype);
try {
if (isStatic || doBound) {
if (ftype == int.class)
mh.invokeExact((int)putValue); // do these exactly
else
mh.invokeExact(putValue);
} else {
if (ftype == int.class)
mh.invokeExact((Object) fieldsForMH, (int)putValue);
else
mh.invokeExact((Object) fieldsForMH, putValue);
}
} catch (RuntimeException ex) {
if (ex instanceof NullPointerException && testNPE) {
caughtEx = ex;
break;
}
}
if (f != null && f.getDeclaringClass() == HasFields.class) {
assertEquals(f.get(fields), putValue);
}
}
}
if (f != null && f.getDeclaringClass() == HasFields.class && writeAccess) {
f.set(fields, value); // put it back if it has write access
}
if (testNPE) {
if (caughtEx == null || !(caughtEx instanceof NullPointerException))
throw new RuntimeException("failed to catch NPE exception"+(caughtEx == null ? " (caughtEx=null)" : ""), caughtEx);
caughtEx = null; // nullify expected exception
}
if (caughtEx != null) {
throw new RuntimeException("unexpected exception", caughtEx);
}
}
@Test
public void testUnreflectSetter() throws Throwable {
CodeCacheOverflowProcessor.runMHTest(this::testUnreflectSetter0);
}
public void testUnreflectSetter0() throws Throwable {
if (CAN_SKIP_WORKING) return;
startTest("unreflectSetter");
testSetter(TEST_UNREFLECT);
}
@Test
public void testFindSetter() throws Throwable {
CodeCacheOverflowProcessor.runMHTest(this::testFindSetter0);
}
public void testFindSetter0() throws Throwable {
if (CAN_SKIP_WORKING) return;
startTest("findSetter");
testSetter(TEST_FIND_FIELD);
testSetter(TEST_FIND_FIELD | TEST_BOUND);
}
@Test
public void testFindStaticSetter() throws Throwable {
CodeCacheOverflowProcessor.runMHTest(this::testFindStaticSetter0);
}
public void testFindStaticSetter0() throws Throwable {
if (CAN_SKIP_WORKING) return;
startTest("findStaticSetter");
testSetter(TEST_FIND_STATIC);
}
public void testSetter(int testMode) throws Throwable {
Lookup lookup = PRIVATE; // FIXME: test more lookups than this one
startTest("testSetter");
for (Object[] c : HasFields.testCasesFor(testMode|TEST_SETTER)) {
boolean positive = (c[1] != Error.class);
testSetter(positive, lookup, c[0], c[1], testMode);
if (positive)
testSetter(positive, lookup, c[0], c[1], testMode | TEST_NPE);
}
for (int isStaticN = 0; isStaticN <= 1; isStaticN++) {
testSetter(false, lookup,
new Object[]{ (isStaticN != 0), System.class, "bogus", char.class },
null, testMode);
}
}
public void testSetter(boolean positive, MethodHandles.Lookup lookup,
Object fieldRef, Object value, int testMode) throws Throwable {
testAccessor(positive, lookup, fieldRef, value, testMode | TEST_SETTER);
}
@Test
public void testArrayElementGetter() throws Throwable {
CodeCacheOverflowProcessor.runMHTest(this::testArrayElementGetter0);
}
public void testArrayElementGetter0() throws Throwable {
if (CAN_SKIP_WORKING) return;
startTest("arrayElementGetter");
testArrayElementGetterSetter(false);
}
@Test
public void testArrayElementSetter() throws Throwable {
CodeCacheOverflowProcessor.runMHTest(this::testArrayElementSetter0);
}
public void testArrayElementSetter0() throws Throwable {
if (CAN_SKIP_WORKING) return;
startTest("arrayElementSetter");
testArrayElementGetterSetter(true);
}
private static final int TEST_ARRAY_NONE = 0, TEST_ARRAY_NPE = 1, TEST_ARRAY_OOB = 2, TEST_ARRAY_ASE = 3;
public void testArrayElementGetterSetter(boolean testSetter) throws Throwable {
testArrayElementGetterSetter(testSetter, TEST_ARRAY_NONE);
}
@Test
public void testArrayElementErrors() throws Throwable {
CodeCacheOverflowProcessor.runMHTest(this::testArrayElementErrors0);
}
public void testArrayElementErrors0() throws Throwable {
if (CAN_SKIP_WORKING) return;
startTest("arrayElementErrors");
testArrayElementGetterSetter(false, TEST_ARRAY_NPE);
testArrayElementGetterSetter(true, TEST_ARRAY_NPE);
testArrayElementGetterSetter(false, TEST_ARRAY_OOB);
testArrayElementGetterSetter(true, TEST_ARRAY_OOB);
testArrayElementGetterSetter(new Object[10], true, TEST_ARRAY_ASE);
testArrayElementGetterSetter(new Example[10], true, TEST_ARRAY_ASE);
testArrayElementGetterSetter(new IntExample[10], true, TEST_ARRAY_ASE);
}
public void testArrayElementGetterSetter(boolean testSetter, int negTest) throws Throwable {
testArrayElementGetterSetter(new String[10], testSetter, negTest);
testArrayElementGetterSetter(new Iterable<?>[10], testSetter, negTest);
testArrayElementGetterSetter(new Example[10], testSetter, negTest);
testArrayElementGetterSetter(new IntExample[10], testSetter, negTest);
testArrayElementGetterSetter(new Object[10], testSetter, negTest);
testArrayElementGetterSetter(new boolean[10], testSetter, negTest);
testArrayElementGetterSetter(new byte[10], testSetter, negTest);
testArrayElementGetterSetter(new char[10], testSetter, negTest);
testArrayElementGetterSetter(new short[10], testSetter, negTest);
testArrayElementGetterSetter(new int[10], testSetter, negTest);
testArrayElementGetterSetter(new float[10], testSetter, negTest);
testArrayElementGetterSetter(new long[10], testSetter, negTest);
testArrayElementGetterSetter(new double[10], testSetter, negTest);
}
public void testArrayElementGetterSetter(Object array, boolean testSetter, int negTest) throws Throwable {
boolean positive = (negTest == TEST_ARRAY_NONE);
int length = Array.getLength(array);
Class<?> arrayType = array.getClass();
Class<?> elemType = arrayType.getComponentType();
Object arrayToMH = array;
// this stanza allows negative tests to make argument perturbations:
switch (negTest) {
case TEST_ARRAY_NPE:
arrayToMH = null;
break;
case TEST_ARRAY_OOB:
assert(length > 0);
arrayToMH = Array.newInstance(elemType, 0);
break;
case TEST_ARRAY_ASE:
assert(testSetter && !elemType.isPrimitive());
if (elemType == Object.class)
arrayToMH = new StringBuffer[length]; // very random subclass of Object!
else if (elemType == Example.class)
arrayToMH = new SubExample[length];
else if (elemType == IntExample.class)
arrayToMH = new SubIntExample[length];
else
return; // can't make an ArrayStoreException test
assert(arrayType.isInstance(arrayToMH))
: Arrays.asList(arrayType, arrayToMH.getClass(), testSetter, negTest);
break;
}
countTest(positive);
if (verbosity > 2) System.out.println("array type = "+array.getClass().getComponentType().getName()+"["+length+"]"+(positive ? "" : " negative test #"+negTest+" using "+Arrays.deepToString(new Object[]{arrayToMH})));
MethodType expType = !testSetter
? MethodType.methodType(elemType, arrayType, int.class)
: MethodType.methodType(void.class, arrayType, int.class, elemType);
MethodHandle mh = !testSetter
? MethodHandles.arrayElementGetter(arrayType)
: MethodHandles.arrayElementSetter(arrayType);
assertSame(mh.type(), expType);
if (elemType != int.class && elemType != boolean.class) {
MethodType gtype = mh.type().generic().changeParameterType(1, int.class);
if (testSetter) gtype = gtype.changeReturnType(void.class);
mh = mh.asType(gtype);
}
Object sawValue, expValue;
List<Object> model = array2list(array);
Throwable caughtEx = null;
for (int i = 0; i < length; i++) {
// update array element
Object random = randomArg(elemType);
model.set(i, random);
if (testSetter) {
try {
if (elemType == int.class)
mh.invokeExact((int[]) arrayToMH, i, (int)random);
else if (elemType == boolean.class)
mh.invokeExact((boolean[]) arrayToMH, i, (boolean)random);
else
mh.invokeExact(arrayToMH, i, random);
} catch (RuntimeException ex) {
caughtEx = ex;
break;
}
assertEquals(model, array2list(array));
} else {
Array.set(array, i, random);
}
if (verbosity >= 5) {
List<Object> array2list = array2list(array);
System.out.println("a["+i+"]="+random+" => "+array2list);
if (!array2list.equals(model))
System.out.println("*** != "+model);
}
// observe array element
sawValue = Array.get(array, i);
if (!testSetter) {
expValue = sawValue;
try {
if (elemType == int.class)
sawValue = (int) mh.invokeExact((int[]) arrayToMH, i);
else if (elemType == boolean.class)
sawValue = (boolean) mh.invokeExact((boolean[]) arrayToMH, i);
else
sawValue = mh.invokeExact(arrayToMH, i);
} catch (RuntimeException ex) {
caughtEx = ex;
break;
}
assertEquals(sawValue, expValue);
assertEquals(model, array2list(array));
}
}
if (!positive) {
if (caughtEx == null)
throw new RuntimeException("failed to catch exception for negTest="+negTest);
// test the kind of exception
Class<?> reqType = null;
switch (negTest) {
case TEST_ARRAY_ASE: reqType = ArrayStoreException.class; break;
case TEST_ARRAY_OOB: reqType = ArrayIndexOutOfBoundsException.class; break;
case TEST_ARRAY_NPE: reqType = NullPointerException.class; break;
default: assert(false);
}
if (reqType.isInstance(caughtEx)) {
caughtEx = null; // nullify expected exception
}
}
if (caughtEx != null) {
throw new RuntimeException("unexpected exception", caughtEx);
}
}
List<Object> array2list(Object array) {
int length = Array.getLength(array);
ArrayList<Object> model = new ArrayList<>(length);
for (int i = 0; i < length; i++)
model.add(Array.get(array, i));
return model;
}
@Test
public void testConvertArguments() throws Throwable {
CodeCacheOverflowProcessor.runMHTest(this::testConvertArguments0);
}
public void testConvertArguments0() throws Throwable {
if (CAN_SKIP_WORKING) return;
startTest("convertArguments");
testConvert(Callee.ofType(1), null, "id", int.class);
testConvert(Callee.ofType(1), null, "id", String.class);
testConvert(Callee.ofType(1), null, "id", Integer.class);
testConvert(Callee.ofType(1), null, "id", short.class);
testConvert(Callee.ofType(1), null, "id", char.class);
testConvert(Callee.ofType(1), null, "id", byte.class);
}
void testConvert(MethodHandle id, Class<?> rtype, String name, Class<?>... params) throws Throwable {
testConvert(true, id, rtype, name, params);
}
void testConvert(boolean positive,
MethodHandle id, Class<?> rtype, String name, Class<?>... params) throws Throwable {
countTest(positive);
MethodType idType = id.type();
if (rtype == null) rtype = idType.returnType();
for (int i = 0; i < params.length; i++) {
if (params[i] == null) params[i] = idType.parameterType(i);
}
// simulate the pairwise conversion
MethodType newType = MethodType.methodType(rtype, params);
Object[] args = randomArgs(newType.parameterArray());
Object[] convArgs = args.clone();
for (int i = 0; i < args.length; i++) {
Class<?> src = newType.parameterType(i);
Class<?> dst = idType.parameterType(i);
if (src != dst)
convArgs[i] = castToWrapper(convArgs[i], dst);
}
Object convResult = id.invokeWithArguments(convArgs);
{
Class<?> dst = newType.returnType();
Class<?> src = idType.returnType();
if (src != dst)
convResult = castToWrapper(convResult, dst);
}
MethodHandle target = null;
RuntimeException error = null;
try {
target = id.asType(newType);
} catch (WrongMethodTypeException ex) {
error = ex;
}
if (verbosity >= 3)
System.out.println("convert "+id+ " to "+newType+" => "+target
+(error == null ? "" : " !! "+error));
if (positive && error != null) throw error;
assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
if (!positive) return; // negative test failed as expected
assertEquals(newType, target.type());
printCalled(target, id.toString(), args);
Object result = target.invokeWithArguments(args);
assertCalled(name, convArgs);
assertEquals(convResult, result);
if (verbosity >= 1)
System.out.print(':');
}
@Test
public void testVarargsCollector() throws Throwable {
CodeCacheOverflowProcessor.runMHTest(this::testVarargsCollector0);
}
public void testVarargsCollector0() throws Throwable {
if (CAN_SKIP_WORKING) return;
startTest("varargsCollector");
MethodHandle vac0 = PRIVATE.findStatic(MethodHandlesTest.class, "called",
MethodType.methodType(Object.class, String.class, Object[].class));
vac0 = vac0.bindTo("vac");
MethodHandle vac = vac0.asVarargsCollector(Object[].class);
testConvert(true, vac.asType(MethodType.genericMethodType(0)), null, "vac");
testConvert(true, vac.asType(MethodType.genericMethodType(0)), null, "vac");
for (Class<?> at : new Class<?>[] { Object.class, String.class, Integer.class }) {
testConvert(true, vac.asType(MethodType.genericMethodType(1)), null, "vac", at);
testConvert(true, vac.asType(MethodType.genericMethodType(2)), null, "vac", at, at);
}
}
@Test
public void testFilterReturnValue() throws Throwable {
CodeCacheOverflowProcessor.runMHTest(this::testFilterReturnValue0);
}
public void testFilterReturnValue0() throws Throwable {
if (CAN_SKIP_WORKING) return;
startTest("filterReturnValue");
Class<?> classOfVCList = varargsList(1).invokeWithArguments(0).getClass();
assertTrue(List.class.isAssignableFrom(classOfVCList));
for (int nargs = 0; nargs <= 3; nargs++) {
for (Class<?> rtype : new Class<?>[] { Object.class,
List.class,
int.class,
byte.class,
long.class,
CharSequence.class,
String.class }) {
testFilterReturnValue(nargs, rtype);
}
}
}
void testFilterReturnValue(int nargs, Class<?> rtype) throws Throwable {
countTest();
MethodHandle target = varargsList(nargs, rtype);
MethodHandle filter;
if (List.class.isAssignableFrom(rtype) || rtype.isAssignableFrom(List.class))
filter = varargsList(1); // add another layer of list-ness
else
filter = MethodHandles.identity(rtype);
filter = filter.asType(MethodType.methodType(target.type().returnType(), rtype));
Object[] argsToPass = randomArgs(nargs, Object.class);
if (verbosity >= 3)
System.out.println("filter "+target+" to "+rtype.getSimpleName()+" with "+filter);
MethodHandle target2 = MethodHandles.filterReturnValue(target, filter);
if (verbosity >= 4)
System.out.println("filtered target: "+target2);
// Simulate expected effect of filter on return value:
Object unfiltered = target.invokeWithArguments(argsToPass);
Object expected = filter.invokeWithArguments(unfiltered);
if (verbosity >= 4)
System.out.println("unfiltered: "+unfiltered+" : "+unfiltered.getClass().getSimpleName());
if (verbosity >= 4)
System.out.println("expected: "+expected+" : "+expected.getClass().getSimpleName());
Object result = target2.invokeWithArguments(argsToPass);
if (verbosity >= 3)
System.out.println("result: "+result+" : "+result.getClass().getSimpleName());
if (!expected.equals(result))
System.out.println("*** fail at n/rt = "+nargs+"/"+rtype.getSimpleName()+": "+
Arrays.asList(argsToPass)+" => "+result+" != "+expected);
assertEquals(expected, result);
}
@Test
public void testFilterArguments() throws Throwable {
CodeCacheOverflowProcessor.runMHTest(this::testFilterArguments0);
}
public void testFilterArguments0() throws Throwable {
if (CAN_SKIP_WORKING) return;
startTest("filterArguments");
for (int nargs = 1; nargs <= 6; nargs++) {
for (int pos = 0; pos < nargs; pos++) {
testFilterArguments(nargs, pos);
}
}
}
void testFilterArguments(int nargs, int pos) throws Throwable {
countTest();
MethodHandle target = varargsList(nargs);
MethodHandle filter = varargsList(1);
filter = filter.asType(filter.type().generic());
Object[] argsToPass = randomArgs(nargs, Object.class);
if (verbosity >= 3)
System.out.println("filter "+target+" at "+pos+" with "+filter);
MethodHandle target2 = MethodHandles.filterArguments(target, pos, filter);
// Simulate expected effect of filter on arglist:
Object[] filteredArgs = argsToPass.clone();
filteredArgs[pos] = filter.invokeExact(filteredArgs[pos]);
List<Object> expected = Arrays.asList(filteredArgs);
Object result = target2.invokeWithArguments(argsToPass);
if (verbosity >= 3)
System.out.println("result: "+result);
if (!expected.equals(result))
System.out.println("*** fail at n/p = "+nargs+"/"+pos+": "+Arrays.asList(argsToPass)+" => "+result+" != "+expected);
assertEquals(expected, result);
}
@Test
public void testCollectArguments() throws Throwable {
CodeCacheOverflowProcessor.runMHTest(this::testCollectArguments0);
}
public void testCollectArguments0() throws Throwable {
if (CAN_SKIP_WORKING) return;
startTest("collectArguments");
testFoldOrCollectArguments(true, false);
}
@Test
public void testFoldArguments() throws Throwable {
CodeCacheOverflowProcessor.runMHTest(this::testFoldArguments0);
CodeCacheOverflowProcessor.runMHTest(this::testFoldArguments1);
}
public void testFoldArguments0() throws Throwable {
if (CAN_SKIP_WORKING) return;
startTest("foldArguments");
testFoldOrCollectArguments(false, false);
}
public void testFoldArguments1() throws Throwable {
if (CAN_SKIP_WORKING) return;
startTest("foldArguments/pos");
testFoldOrCollectArguments(false, true);
}
void testFoldOrCollectArguments(boolean isCollect, boolean withFoldPos) throws Throwable {
assert !(isCollect && withFoldPos); // exclude illegal argument combination
for (Class<?> lastType : new Class<?>[]{ Object.class, String.class, int.class }) {
for (Class<?> collectType : new Class<?>[]{ Object.class, String.class, int.class, void.class }) {
int maxArity = 10;
if (collectType != String.class) maxArity = 5;
if (lastType != Object.class) maxArity = 4;
for (int nargs = 0; nargs <= maxArity; nargs++) {
ArrayList<Class<?>> argTypes = new ArrayList<>(Collections.nCopies(nargs, Object.class));
int maxMix = 20;
if (collectType != Object.class) maxMix = 0;
Map<Object,Integer> argTypesSeen = new HashMap<>();
for (int mix = 0; mix <= maxMix; mix++) {
if (!mixArgs(argTypes, mix, argTypesSeen)) continue;
for (int collect = 0; collect <= nargs; collect++) {
for (int pos = 0; pos <= nargs - collect; pos++) {
testFoldOrCollectArguments(argTypes, pos, collect, collectType, lastType, isCollect, withFoldPos);
}
}
}
}
}
}
}
boolean mixArgs(List<Class<?>> argTypes, int mix, Map<Object,Integer> argTypesSeen) {
assert(mix >= 0);
if (mix == 0) return true; // no change
if ((mix >>> argTypes.size()) != 0) return false;
for (int i = 0; i < argTypes.size(); i++) {
if (i >= 31) break;
boolean bit = (mix & (1 << i)) != 0;
if (bit) {
Class<?> type = argTypes.get(i);
if (type == Object.class)
type = String.class;
else if (type == String.class)
type = int.class;
else
type = Object.class;
argTypes.set(i, type);
}
}
Integer prev = argTypesSeen.put(new ArrayList<>(argTypes), mix);
if (prev != null) {
if (verbosity >= 4) System.out.println("mix "+prev+" repeated "+mix+": "+argTypes);
return false;
}
if (verbosity >= 3) System.out.println("mix "+mix+" = "+argTypes);
return true;
}
void testFoldOrCollectArguments(List<Class<?>> argTypes, // argument types minus the inserted combineType
int pos, int fold, // position and length of the folded arguments
Class<?> combineType, // type returned from the combiner
Class<?> lastType, // type returned from the target
boolean isCollect,
boolean withFoldPos) throws Throwable {
int nargs = argTypes.size();
if (pos != 0 && !isCollect && !withFoldPos) return; // test MethodHandles.foldArguments(MH,MH) only for pos=0
countTest();
List<Class<?>> combineArgTypes = argTypes.subList(pos, pos + fold);
List<Class<?>> targetArgTypes = new ArrayList<>(argTypes);
if (isCollect) // does target see arg[pos..pos+cc-1]?
targetArgTypes.subList(pos, pos + fold).clear();
if (combineType != void.class)
targetArgTypes.add(pos, combineType);
MethodHandle target = varargsList(targetArgTypes, lastType);
MethodHandle combine = varargsList(combineArgTypes, combineType);
List<Object> argsToPass = Arrays.asList(randomArgs(argTypes));
if (verbosity >= 3)
System.out.println((isCollect ? "collect" : "fold")+" "+target+" with "+combine);
MethodHandle target2;
if (isCollect)
target2 = MethodHandles.collectArguments(target, pos, combine);
else
target2 = withFoldPos ? MethodHandles.foldArguments(target, pos, combine) : MethodHandles.foldArguments(target, combine);
// Simulate expected effect of combiner on arglist:
List<Object> expectedList = new ArrayList<>(argsToPass);
List<Object> argsToFold = expectedList.subList(pos, pos + fold);
if (verbosity >= 3)
System.out.println((isCollect ? "collect" : "fold")+": "+argsToFold+" into "+target2);
Object foldedArgs = combine.invokeWithArguments(argsToFold);
if (isCollect)
argsToFold.clear();
if (combineType != void.class)
argsToFold.add(0, foldedArgs);
Object result = target2.invokeWithArguments(argsToPass);
if (verbosity >= 3)
System.out.println("result: "+result);
Object expected = target.invokeWithArguments(expectedList);
if (!expected.equals(result))
System.out.println("*** fail at n/p/f = "+nargs+"/"+pos+"/"+fold+": "+argsToPass+" => "+result+" != "+expected);
assertEquals(expected, result);
}
@Test
public void testDropArguments() throws Throwable {
CodeCacheOverflowProcessor.runMHTest(this::testDropArguments0);
}
public void testDropArguments0() throws Throwable {
if (CAN_SKIP_WORKING) return;
startTest("dropArguments");
for (int nargs = 0; nargs <= 4; nargs++) {
for (int drop = 1; drop <= 4; drop++) {
for (int pos = 0; pos <= nargs; pos++) {
testDropArguments(nargs, pos, drop);
}
}
}
}
void testDropArguments(int nargs, int pos, int drop) throws Throwable {
countTest();
MethodHandle target = varargsArray(nargs);
Object[] args = randomArgs(target.type().parameterArray());
MethodHandle target2 = MethodHandles.dropArguments(target, pos,
Collections.nCopies(drop, Object.class).toArray(new Class<?>[0]));
List<Object> resList = Arrays.asList(args);
List<Object> argsToDrop = new ArrayList<>(resList);
for (int i = drop; i > 0; i--) {
argsToDrop.add(pos, "blort#"+i);
}
Object res2 = target2.invokeWithArguments(argsToDrop);
Object res2List = Arrays.asList((Object[])res2);
//if (!resList.equals(res2List))
// System.out.println("*** fail at n/p/d = "+nargs+"/"+pos+"/"+drop+": "+argsToDrop+" => "+res2List);
assertEquals(resList, res2List);
}
@Test
public void testGuardWithTest() throws Throwable {
CodeCacheOverflowProcessor.runMHTest(this::testGuardWithTest0);
}
public void testGuardWithTest0() throws Throwable {
if (CAN_SKIP_WORKING) return;
startTest("guardWithTest");
for (int nargs = 0; nargs <= 50; nargs++) {
if (CAN_TEST_LIGHTLY && nargs > 7) break;
testGuardWithTest(nargs, Object.class);
testGuardWithTest(nargs, String.class);
}
}
void testGuardWithTest(int nargs, Class<?> argClass) throws Throwable {
testGuardWithTest(nargs, 0, argClass);
if (nargs <= 5 || nargs % 10 == 3) {
for (int testDrops = 1; testDrops <= nargs; testDrops++)
testGuardWithTest(nargs, testDrops, argClass);
}
}
void testGuardWithTest(int nargs, int testDrops, Class<?> argClass) throws Throwable {
countTest();
int nargs1 = Math.min(3, nargs);
MethodHandle test = PRIVATE.findVirtual(Object.class, "equals", MethodType.methodType(boolean.class, Object.class));
MethodHandle target = PRIVATE.findStatic(MethodHandlesTest.class, "targetIfEquals", MethodType.genericMethodType(nargs1));
MethodHandle fallback = PRIVATE.findStatic(MethodHandlesTest.class, "fallbackIfNotEquals", MethodType.genericMethodType(nargs1));
while (test.type().parameterCount() > nargs)
// 0: test = constant(MISSING_ARG.equals(MISSING_ARG))
// 1: test = lambda (_) MISSING_ARG.equals(_)
test = MethodHandles.insertArguments(test, 0, MISSING_ARG);
if (argClass != Object.class) {
test = changeArgTypes(test, argClass);
target = changeArgTypes(target, argClass);
fallback = changeArgTypes(fallback, argClass);
}
int testArgs = nargs - testDrops;
assert(testArgs >= 0);
test = addTrailingArgs(test, Math.min(testArgs, nargs), argClass);
target = addTrailingArgs(target, nargs, argClass);
fallback = addTrailingArgs(fallback, nargs, argClass);
Object[][] argLists = {
{ },
{ "foo" }, { MethodHandlesTest.MISSING_ARG },
{ "foo", "foo" }, { "foo", "bar" },
{ "foo", "foo", "baz" }, { "foo", "bar", "baz" }
};
for (Object[] argList : argLists) {
Object[] argList1 = argList;
if (argList.length != nargs) {
if (argList.length != nargs1) continue;
argList1 = Arrays.copyOf(argList, nargs);
Arrays.fill(argList1, nargs1, nargs, MethodHandlesTest.MISSING_ARG_2);
}
MethodHandle test1 = test;
if (test1.type().parameterCount() > testArgs) {
int pc = test1.type().parameterCount();
test1 = MethodHandles.insertArguments(test, testArgs, Arrays.copyOfRange(argList1, testArgs, pc));
}
MethodHandle mh = MethodHandles.guardWithTest(test1, target, fallback);
assertEquals(target.type(), mh.type());
boolean equals;
switch (nargs) {
case 0: equals = true; break;
case 1: equals = MethodHandlesTest.MISSING_ARG.equals(argList[0]); break;
default: equals = argList[0].equals(argList[1]); break;
}
String willCall = (equals ? "targetIfEquals" : "fallbackIfNotEquals");
if (verbosity >= 3)
System.out.println(logEntry(willCall, argList));
Object result = mh.invokeWithArguments(argList1);
assertCalled(willCall, argList);
}
}
@Test
public void testGenericLoopCombinator() throws Throwable {
CodeCacheOverflowProcessor.runMHTest(this::testGenericLoopCombinator0);
}
public void testGenericLoopCombinator0() throws Throwable {
if (CAN_SKIP_WORKING) return;
startTest("loop");
// Test as follows:
// * Have an increasing number of loop-local state. Local state type diversity grows with the number.
// * Initializers set the starting value of loop-local state from the corresponding loop argument.
// * For each local state element, there is a predicate - for all state combinations, exercise all predicates.
// * Steps modify each local state element in each iteration.
// * Finalizers group all local state elements into a resulting array. Verify end values.
// * Exercise both pre- and post-checked loops.
// Local state types, start values, predicates, and steps:
// * int a, 0, a < 7, a = a + 1
// * double b, 7.0, b > 0.5, b = b / 2.0
// * String c, "start", c.length <= 9, c = c + a
final Class<?>[] argTypes = new Class<?>[] {int.class, double.class, String.class};
final Object[][] args = new Object[][] {
new Object[]{0 },
new Object[]{0, 7.0 },
new Object[]{0, 7.0, "start"}
};
// These are the expected final state tuples for argument type tuple / predicate combinations, for pre- and
// post-checked loops:
final Object[][] preCheckedResults = new Object[][] {
new Object[]{7 }, // (int) / int
new Object[]{7, 0.0546875 }, // (int,double) / int
new Object[]{5, 0.4375 }, // (int,double) / double
new Object[]{7, 0.0546875, "start1234567"}, // (int,double,String) / int
new Object[]{5, 0.4375, "start1234" }, // (int,double,String) / double
new Object[]{6, 0.109375, "start12345" } // (int,double,String) / String
};
final Object[][] postCheckedResults = new Object[][] {
new Object[]{7 }, // (int) / int
new Object[]{7, 0.109375 }, // (int,double) / int
new Object[]{4, 0.4375 }, // (int,double) / double
new Object[]{7, 0.109375, "start123456"}, // (int,double,String) / int
new Object[]{4, 0.4375, "start123" }, // (int,double,String) / double
new Object[]{5, 0.21875, "start12345" } // (int,double,String) / String
};
final Lookup l = MethodHandles.lookup();
final Class<?> MHT = MethodHandlesTest.class;
final Class<?> B = boolean.class;
final Class<?> I = int.class;
final Class<?> D = double.class;
final Class<?> S = String.class;
final MethodHandle hip = l.findStatic(MHT, "loopIntPred", methodType(B, I));
final MethodHandle hdp = l.findStatic(MHT, "loopDoublePred", methodType(B, I, D));
final MethodHandle hsp = l.findStatic(MHT, "loopStringPred", methodType(B, I, D, S));
final MethodHandle his = l.findStatic(MHT, "loopIntStep", methodType(I, I));
final MethodHandle hds = l.findStatic(MHT, "loopDoubleStep", methodType(D, I, D));
final MethodHandle hss = l.findStatic(MHT, "loopStringStep", methodType(S, I, D, S));
final MethodHandle[] preds = new MethodHandle[] {hip, hdp, hsp};
final MethodHandle[] steps = new MethodHandle[] {his, hds, hss};
for (int nargs = 1, useResultsStart = 0; nargs <= argTypes.length; useResultsStart += nargs++) {
Class<?>[] useArgTypes = Arrays.copyOf(argTypes, nargs, Class[].class);
MethodHandle[] usePreds = Arrays.copyOf(preds, nargs, MethodHandle[].class);
MethodHandle[] useSteps = Arrays.copyOf(steps, nargs, MethodHandle[].class);
Object[] useArgs = args[nargs - 1];
Object[][] usePreCheckedResults = new Object[nargs][];
Object[][] usePostCheckedResults = new Object[nargs][];
System.arraycopy(preCheckedResults, useResultsStart, usePreCheckedResults, 0, nargs);
System.arraycopy(postCheckedResults, useResultsStart, usePostCheckedResults, 0, nargs);
testGenericLoopCombinator(nargs, useArgTypes, usePreds, useSteps, useArgs, usePreCheckedResults,
usePostCheckedResults);
}
}
void testGenericLoopCombinator(int nargs, Class<?>[] argTypes, MethodHandle[] preds, MethodHandle[] steps,
Object[] args, Object[][] preCheckedResults, Object[][] postCheckedResults)
throws Throwable {
List<Class<?>> lArgTypes = Arrays.asList(argTypes);
// Predicate and step handles are passed in as arguments, initializer and finalizer handles are constructed here
// from the available information.
MethodHandle[] inits = new MethodHandle[nargs];
for (int i = 0; i < nargs; ++i) {
MethodHandle h;
// Initializers are meant to return whatever they are passed at a given argument position. This means that
// additional arguments may have to be appended and prepended.
h = MethodHandles.identity(argTypes[i]);
if (i < nargs - 1) {
h = MethodHandles.dropArguments(h, 1, lArgTypes.subList(i + 1, nargs));
}
if (i > 0) {
h = MethodHandles.dropArguments(h, 0, lArgTypes.subList(0, i));
}
inits[i] = h;
}
// Finalizers are all meant to collect all of the loop-local state in a single array and return that. Local
// state is passed before the loop args. Construct such a finalizer by first taking a varargsArray collector for
// the number of local state arguments, and then appending the loop args as to-be-dropped arguments.
MethodHandle[] finis = new MethodHandle[nargs];
MethodHandle genericFini = MethodHandles.dropArguments(
varargsArray(nargs).asType(methodType(Object[].class, lArgTypes)), nargs, lArgTypes);
Arrays.fill(finis, genericFini);
// The predicate and step handles' signatures need to be extended. They currently just accept local state args;
// append possibly missing local state args and loop args using dropArguments.
for (int i = 0; i < nargs; ++i) {
List<Class<?>> additionalLocalStateArgTypes = lArgTypes.subList(i + 1, nargs);
preds[i] = MethodHandles.dropArguments(
MethodHandles.dropArguments(preds[i], i + 1, additionalLocalStateArgTypes), nargs, lArgTypes);
steps[i] = MethodHandles.dropArguments(
MethodHandles.dropArguments(steps[i], i + 1, additionalLocalStateArgTypes), nargs, lArgTypes);
}
// Iterate over all of the predicates, using only one of them at a time.
for (int i = 0; i < nargs; ++i) {
MethodHandle[] usePreds;
if (nargs == 1) {
usePreds = preds;
} else {
// Create an all-null preds array, and only use one predicate in this iteration. The null entries will
// be substituted with true predicates by the loop combinator.
usePreds = new MethodHandle[nargs];
usePreds[i] = preds[i];
}
// Go for it.
if (verbosity >= 3) {
System.out.println("calling loop for argument types " + lArgTypes + " with predicate at index " + i);
if (verbosity >= 5) {
System.out.println("predicates: " + Arrays.asList(usePreds));
}
}
MethodHandle[] preInits = new MethodHandle[nargs + 1];
MethodHandle[] prePreds = new MethodHandle[nargs + 1];
MethodHandle[] preSteps = new MethodHandle[nargs + 1];
MethodHandle[] preFinis = new MethodHandle[nargs + 1];
System.arraycopy(inits, 0, preInits, 1, nargs);
System.arraycopy(usePreds, 0, prePreds, 0, nargs); // preds are offset by 1 for pre-checked loops
System.arraycopy(steps, 0, preSteps, 1, nargs);
System.arraycopy(finis, 0, preFinis, 0, nargs); // finis are also offset by 1 for pre-checked loops
// Convert to clause-major form.
MethodHandle[][] preClauses = new MethodHandle[nargs + 1][4];
MethodHandle[][] postClauses = new MethodHandle[nargs][4];
toClauseMajor(preClauses, preInits, preSteps, prePreds, preFinis);
toClauseMajor(postClauses, inits, steps, usePreds, finis);
MethodHandle pre = MethodHandles.loop(preClauses);
MethodHandle post = MethodHandles.loop(postClauses);
if (verbosity >= 6) {
System.out.println("pre-handle: " + pre);
}
Object[] preResults = (Object[]) pre.invokeWithArguments(args);
if (verbosity >= 4) {
System.out.println("pre-checked: expected " + Arrays.asList(preCheckedResults[i]) + ", actual " +
Arrays.asList(preResults));
}
if (verbosity >= 6) {
System.out.println("post-handle: " + post);
}
Object[] postResults = (Object[]) post.invokeWithArguments(args);
if (verbosity >= 4) {
System.out.println("post-checked: expected " + Arrays.asList(postCheckedResults[i]) + ", actual " +
Arrays.asList(postResults));
}
assertArrayEquals(preCheckedResults[i], preResults);
assertArrayEquals(postCheckedResults[i], postResults);
}
}
static void toClauseMajor(MethodHandle[][] clauses, MethodHandle[] init, MethodHandle[] step, MethodHandle[] pred, MethodHandle[] fini) {
for (int i = 0; i < clauses.length; ++i) {
clauses[i][0] = init[i];
clauses[i][1] = step[i];
clauses[i][2] = pred[i];
clauses[i][3] = fini[i];
}
}
@Test
public void testThrowException() throws Throwable {
CodeCacheOverflowProcessor.runMHTest(this::testThrowException0);
}
public void testThrowException0() throws Throwable {
if (CAN_SKIP_WORKING) return;
startTest("throwException");
testThrowException(int.class, new ClassCastException("testing"));
testThrowException(void.class, new java.io.IOException("testing"));
testThrowException(String.class, new LinkageError("testing"));
}
void testThrowException(Class<?> returnType, Throwable thrown) throws Throwable {
countTest();
Class<? extends Throwable> exType = thrown.getClass();
MethodHandle target = MethodHandles.throwException(returnType, exType);
//System.out.println("throwing with "+target+" : "+thrown);
MethodType expectedType = MethodType.methodType(returnType, exType);
assertEquals(expectedType, target.type());
target = target.asType(target.type().generic());
Throwable caught = null;
try {
Object res = target.invokeExact((Object) thrown);
fail("got "+res+" instead of throwing "+thrown);
} catch (Throwable ex) {
if (ex != thrown) {
if (ex instanceof Error) throw (Error)ex;
if (ex instanceof RuntimeException) throw (RuntimeException)ex;
}
caught = ex;
}
assertSame(thrown, caught);
}
@Test
public void testTryFinally() throws Throwable {
CodeCacheOverflowProcessor.runMHTest(this::testTryFinally0);
}
public void testTryFinally0() throws Throwable {
if (CAN_SKIP_WORKING) return;
startTest("tryFinally");
String inputMessage = "returned";
String augmentedMessage = "augmented";
String thrownMessage = "thrown";
String rethrownMessage = "rethrown";
// Test these cases:
// * target returns, cleanup passes through
// * target returns, cleanup augments
// * target throws, cleanup augments and returns
// * target throws, cleanup augments and rethrows
MethodHandle target = MethodHandles.identity(String.class);
MethodHandle targetThrow = MethodHandles.dropArguments(
MethodHandles.throwException(String.class, Exception.class).bindTo(new Exception(thrownMessage)), 0, String.class);
MethodHandle cleanupPassThrough = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0,
Throwable.class, String.class);
MethodHandle cleanupAugment = MethodHandles.dropArguments(MethodHandles.constant(String.class, augmentedMessage),
0, Throwable.class, String.class, String.class);
MethodHandle cleanupCatch = MethodHandles.dropArguments(MethodHandles.constant(String.class, thrownMessage), 0,
Throwable.class, String.class, String.class);
MethodHandle cleanupThrow = MethodHandles.dropArguments(MethodHandles.throwException(String.class, Exception.class).
bindTo(new Exception(rethrownMessage)), 0, Throwable.class, String.class, String.class);
testTryFinally(target, cleanupPassThrough, inputMessage, inputMessage, false);
testTryFinally(target, cleanupAugment, inputMessage, augmentedMessage, false);
testTryFinally(targetThrow, cleanupCatch, inputMessage, thrownMessage, true);
testTryFinally(targetThrow, cleanupThrow, inputMessage, rethrownMessage, true);
// Test the same cases as above for void targets and cleanups.
MethodHandles.Lookup lookup = MethodHandles.lookup();
Class<?> C = this.getClass();
MethodType targetType = methodType(void.class, String[].class);
MethodType cleanupType = methodType(void.class, Throwable.class, String[].class);
MethodHandle vtarget = lookup.findStatic(C, "vtarget", targetType);
MethodHandle vtargetThrow = lookup.findStatic(C, "vtargetThrow", targetType);
MethodHandle vcleanupPassThrough = lookup.findStatic(C, "vcleanupPassThrough", cleanupType);
MethodHandle vcleanupAugment = lookup.findStatic(C, "vcleanupAugment", cleanupType);
MethodHandle vcleanupCatch = lookup.findStatic(C, "vcleanupCatch", cleanupType);
MethodHandle vcleanupThrow = lookup.findStatic(C, "vcleanupThrow", cleanupType);
testTryFinally(vtarget, vcleanupPassThrough, inputMessage, inputMessage, false);
testTryFinally(vtarget, vcleanupAugment, inputMessage, augmentedMessage, false);
testTryFinally(vtargetThrow, vcleanupCatch, inputMessage, thrownMessage, true);
testTryFinally(vtargetThrow, vcleanupThrow, inputMessage, rethrownMessage, true);
}
void testTryFinally(MethodHandle target, MethodHandle cleanup, String input, String msg, boolean mustCatch)
throws Throwable {
countTest();
MethodHandle tf = MethodHandles.tryFinally(target, cleanup);
String result = null;
boolean isVoid = target.type().returnType() == void.class;
String[] argArray = new String[]{input};
try {
if (isVoid) {
tf.invoke(argArray);
} else {
result = (String) tf.invoke(input);
}
} catch (Throwable t) {
assertTrue(mustCatch);
assertEquals(msg, t.getMessage());
return;
}
assertFalse(mustCatch);
if (isVoid) {
assertEquals(msg, argArray[0]);
} else {
assertEquals(msg, result);
}
}
@Test
public void testAsInterfaceInstance() throws Throwable {
CodeCacheOverflowProcessor.runMHTest(this::testAsInterfaceInstance0);
}
public void testAsInterfaceInstance0() throws Throwable {
if (CAN_SKIP_WORKING) return;
startTest("asInterfaceInstance");
Lookup lookup = MethodHandles.lookup();
// test typical case: Runnable.run
{
countTest();
if (verbosity >= 2) System.out.println("Runnable");
MethodType mt = MethodType.methodType(void.class);
MethodHandle mh = lookup.findStatic(MethodHandlesGeneralTest.class, "runForRunnable", mt);
Runnable proxy = MethodHandleProxies.asInterfaceInstance(Runnable.class, mh);
proxy.run();
assertCalled("runForRunnable");
}
// well known single-name overloaded interface: Appendable.append
{
countTest();
if (verbosity >= 2) System.out.println("Appendable");
ArrayList<List<?>> appendResults = new ArrayList<>();
MethodHandle append = lookup.bind(appendResults, "add", MethodType.methodType(boolean.class, Object.class));
append = append.asType(MethodType.methodType(void.class, List.class)); // specialize the type
MethodHandle asList = lookup.findStatic(Arrays.class, "asList", MethodType.methodType(List.class, Object[].class));
MethodHandle mh = MethodHandles.filterReturnValue(asList, append).asVarargsCollector(Object[].class);
Appendable proxy = MethodHandleProxies.asInterfaceInstance(Appendable.class, mh);
proxy.append("one");
proxy.append("two", 3, 4);
proxy.append('5');
assertEquals(Arrays.asList(Arrays.asList("one"),
Arrays.asList("two", 3, 4),
Arrays.asList('5')),
appendResults);
if (verbosity >= 3) System.out.println("appendResults="+appendResults);
appendResults.clear();
Formatter formatter = new Formatter(proxy);
String fmt = "foo str=%s char='%c' num=%d";
Object[] fmtArgs = { "str!", 'C', 42 };
String expect = String.format(fmt, fmtArgs);
formatter.format(fmt, fmtArgs);
String actual = "";
if (verbosity >= 3) System.out.println("appendResults="+appendResults);
for (List<?> l : appendResults) {
Object x = l.get(0);
switch (l.size()) {
case 1: actual += x; continue;
case 3: actual += ((String)x).substring((int)(Object)l.get(1), (int)(Object)l.get(2)); continue;
}
actual += l;
}
if (verbosity >= 3) System.out.println("expect="+expect);
if (verbosity >= 3) System.out.println("actual="+actual);
assertEquals(expect, actual);
}
// test case of an single name which is overloaded: Fooable.foo(...)
{
if (verbosity >= 2) System.out.println("Fooable");
MethodHandle mh = lookup.findStatic(MethodHandlesGeneralTest.class, "fooForFooable",
MethodType.methodType(Object.class, String.class, Object[].class));
Fooable proxy = MethodHandleProxies.asInterfaceInstance(Fooable.class, mh);
for (Method m : Fooable.class.getDeclaredMethods()) {
countTest();
assertSame("foo", m.getName());
if (verbosity > 3)
System.out.println("calling "+m);
MethodHandle invoker = lookup.unreflect(m);
MethodType mt = invoker.type();
Class<?>[] types = mt.parameterArray();
types[0] = int.class; // placeholder
Object[] args = randomArgs(types);
args[0] = proxy;
if (verbosity > 3)
System.out.println("calling "+m+" on "+Arrays.asList(args));
Object result = invoker.invokeWithArguments(args);
if (verbosity > 4)
System.out.println("result = "+result);
String name = "fooForFooable/"+args[1];
Object[] argTail = Arrays.copyOfRange(args, 2, args.length);
assertCalled(name, argTail);
assertEquals(result, logEntry(name, argTail));
}
}
// test processing of thrown exceptions:
for (Throwable ex : new Throwable[] { new NullPointerException("ok"),
new InternalError("ok"),
new Throwable("fail"),
new Exception("fail"),
new MyCheckedException()
}) {
MethodHandle mh = MethodHandles.throwException(void.class, Throwable.class);
mh = MethodHandles.insertArguments(mh, 0, ex);
WillThrow proxy = MethodHandleProxies.asInterfaceInstance(WillThrow.class, mh);
try {
countTest();
proxy.willThrow();
System.out.println("Failed to throw: "+ex);
assertTrue(false);
} catch (Throwable ex1) {
if (verbosity > 3) {
System.out.println("throw "+ex);
System.out.println("catch "+(ex == ex1 ? "UNWRAPPED" : ex1));
}
if (ex instanceof RuntimeException ||
ex instanceof Error) {
assertSame("must pass unchecked exception out without wrapping", ex, ex1);
} else if (ex instanceof MyCheckedException) {
assertSame("must pass declared exception out without wrapping", ex, ex1);
} else {
assertNotSame("must pass undeclared checked exception with wrapping", ex, ex1);
if (!(ex1 instanceof UndeclaredThrowableException) || ex1.getCause() != ex) {
ex1.printStackTrace(System.out);
}
assertSame(ex, ex1.getCause());
UndeclaredThrowableException utex = (UndeclaredThrowableException) ex1;
}
}
}
// Test error checking on bad interfaces:
for (Class<?> nonSMI : new Class<?>[] { Object.class,
String.class,
CharSequence.class,
java.io.Serializable.class,
PrivateRunnable.class,
Example.class }) {
if (verbosity > 2) System.out.println(nonSMI.getName());
try {
countTest(false);
MethodHandleProxies.asInterfaceInstance(nonSMI, varargsArray(0));
assertTrue("Failed to throw on "+nonSMI.getName(), false);
} catch (IllegalArgumentException ex) {
if (verbosity > 2) System.out.println(nonSMI.getSimpleName()+": "+ex);
// Object: java.lang.IllegalArgumentException:
// not a public interface: java.lang.Object
// String: java.lang.IllegalArgumentException:
// not a public interface: java.lang.String
// CharSequence: java.lang.IllegalArgumentException:
// not a single-method interface: java.lang.CharSequence
// Serializable: java.lang.IllegalArgumentException:
// not a single-method interface: java.io.Serializable
// PrivateRunnable: java.lang.IllegalArgumentException:
// not a public interface: test.java.lang.invoke.MethodHandlesTest$PrivateRunnable
// Example: java.lang.IllegalArgumentException:
// not a public interface: test.java.lang.invoke.MethodHandlesTest$Example
}
}
// Test error checking on interfaces with the wrong method type:
for (Class<?> intfc : new Class<?>[] { Runnable.class /*arity 0*/,
Fooable.class /*arity 1 & 2*/ }) {
int badArity = 1; // known to be incompatible
if (verbosity > 2) System.out.println(intfc.getName());
try {
countTest(false);
MethodHandleProxies.asInterfaceInstance(intfc, varargsArray(badArity));
assertTrue("Failed to throw on "+intfc.getName(), false);
} catch (WrongMethodTypeException ex) {
if (verbosity > 2) System.out.println(intfc.getSimpleName()+": "+ex);
// Runnable: java.lang.invoke.WrongMethodTypeException:
// cannot convert MethodHandle(Object)Object[] to ()void
// Fooable: java.lang.invoke.WrongMethodTypeException:
// cannot convert MethodHandle(Object)Object[] to (Object,String)Object
}
}
}
@Test
public void testInterfaceCast() throws Throwable {
CodeCacheOverflowProcessor.runMHTest(this::testInterfaceCast0);
}
public void testInterfaceCast0() throws Throwable {
if (CAN_SKIP_WORKING) return;
startTest("interfaceCast");
assert( (((Object)"foo") instanceof CharSequence));
assert(!(((Object)"foo") instanceof Iterable));
for (MethodHandle mh : new MethodHandle[]{
MethodHandles.identity(String.class),
MethodHandles.identity(CharSequence.class),
MethodHandles.identity(Iterable.class)
}) {
if (verbosity > 0) System.out.println("-- mh = "+mh);
for (Class<?> ctype : new Class<?>[]{
Object.class, String.class, CharSequence.class,
Number.class, Iterable.class
}) {
if (verbosity > 0) System.out.println("---- ctype = "+ctype.getName());
// doret docast
testInterfaceCast(mh, ctype, false, false);
testInterfaceCast(mh, ctype, true, false);
testInterfaceCast(mh, ctype, false, true);
testInterfaceCast(mh, ctype, true, true);
}
}
}
private static Class<?> i2o(Class<?> c) {
return (c.isInterface() ? Object.class : c);
}
public void testInterfaceCast(MethodHandle mh, Class<?> ctype,
boolean doret, boolean docast) throws Throwable {
MethodHandle mh0 = mh;
if (verbosity > 1)
System.out.println("mh="+mh+", ctype="+ctype.getName()+", doret="+doret+", docast="+docast);
String normalRetVal = "normal return value";
MethodType mt = mh.type();
MethodType mt0 = mt;
if (doret) mt = mt.changeReturnType(ctype);
else mt = mt.changeParameterType(0, ctype);
if (docast) mh = MethodHandles.explicitCastArguments(mh, mt);
else mh = mh.asType(mt);
assertEquals(mt, mh.type());
MethodType mt1 = mt;
// this bit is needed to make the interface types disappear for invokeWithArguments:
mh = MethodHandles.explicitCastArguments(mh, mt.generic());
Class<?>[] step = {
mt1.parameterType(0), // param as passed to mh at first
mt0.parameterType(0), // param after incoming cast
mt0.returnType(), // return value before cast
mt1.returnType(), // return value after outgoing cast
};
// where might a checkCast occur?
boolean[] checkCast = new boolean[step.length];
// the string value must pass each step without causing an exception
if (!docast) {
if (!doret) {
if (step[0] != step[1])
checkCast[1] = true; // incoming value is cast
} else {
if (step[2] != step[3])
checkCast[3] = true; // outgoing value is cast
}
}
boolean expectFail = false;
for (int i = 0; i < step.length; i++) {
Class<?> c = step[i];
if (!checkCast[i]) c = i2o(c);
if (!c.isInstance(normalRetVal)) {
if (verbosity > 3)
System.out.println("expect failure at step "+i+" in "+Arrays.toString(step)+Arrays.toString(checkCast));
expectFail = true;
break;
}
}
countTest(!expectFail);
if (verbosity > 2)
System.out.println("expectFail="+expectFail+", mt="+mt);
Object res;
try {
res = mh.invokeWithArguments(normalRetVal);
} catch (Exception ex) {
res = ex;
}
boolean sawFail = !(res instanceof String);
if (sawFail != expectFail) {
System.out.println("*** testInterfaceCast: mh0 = "+mh0);
System.out.println(" retype using "+(docast ? "explicitCastArguments" : "asType")+" to "+mt+" => "+mh);
System.out.println(" call returned "+res);
System.out.println(" expected "+(expectFail ? "an exception" : normalRetVal));
}
if (!expectFail) {
assertFalse(res.toString(), sawFail);
assertEquals(normalRetVal, res);
} else {
assertTrue(res.toString(), sawFail);
}
}
static Example userMethod(Object o, String s, int i) {
called("userMethod", o, s, i);
return null;
}
@Test
public void testUserClassInSignature() throws Throwable {
CodeCacheOverflowProcessor.runMHTest(this::testUserClassInSignature0);
}
public void testUserClassInSignature0() throws Throwable {
if (CAN_SKIP_WORKING) return;
startTest("testUserClassInSignature");
Lookup lookup = MethodHandles.lookup();
String name; MethodType mt; MethodHandle mh;
Object[] args;
// Try a static method.
name = "userMethod";
mt = MethodType.methodType(Example.class, Object.class, String.class, int.class);
mh = lookup.findStatic(lookup.lookupClass(), name, mt);
assertEquals(mt, mh.type());
assertEquals(Example.class, mh.type().returnType());
args = randomArgs(mh.type().parameterArray());
mh.invokeWithArguments(args);
assertCalled(name, args);
// Try a virtual method.
name = "v2";
mt = MethodType.methodType(Object.class, Object.class, int.class);
mh = lookup.findVirtual(Example.class, name, mt);
assertEquals(mt, mh.type().dropParameterTypes(0,1));
assertTrue(mh.type().parameterList().contains(Example.class));
args = randomArgs(mh.type().parameterArray());
mh.invokeWithArguments(args);
assertCalled(name, args);
}
static void runForRunnable() {
called("runForRunnable");
}
public interface Fooable {
// overloads:
Object foo(Object x, String y);
List<?> foo(String x, int y);
Object foo(String x);
}
static Object fooForFooable(String x, Object... y) {
return called("fooForFooable/"+x, y);
}
@SuppressWarnings("serial") // not really a public API, just a test case
public static class MyCheckedException extends Exception {
}
public interface WillThrow {
void willThrow() throws MyCheckedException;
}
/*non-public*/ interface PrivateRunnable {
public void run();
}
@Test
public void testRunnableProxy() throws Throwable {
CodeCacheOverflowProcessor.runMHTest(this::testRunnableProxy0);
}
public void testRunnableProxy0() throws Throwable {
if (CAN_SKIP_WORKING) return;
startTest("testRunnableProxy");
MethodHandles.Lookup lookup = MethodHandles.lookup();
MethodHandle run = lookup.findStatic(lookup.lookupClass(), "runForRunnable", MethodType.methodType(void.class));
Runnable r = MethodHandleProxies.asInterfaceInstance(Runnable.class, run);
testRunnableProxy(r);
assertCalled("runForRunnable");
}
private static void testRunnableProxy(Runnable r) {
//7058630: JSR 292 method handle proxy violates contract for Object methods
r.run();
Object o = r;
r = null;
boolean eq = (o == o);
int hc = System.identityHashCode(o);
String st = o.getClass().getName() + "@" + Integer.toHexString(hc);
Object expect = Arrays.asList(st, eq, hc);
if (verbosity >= 2) System.out.println("expect st/eq/hc = "+expect);
Object actual = Arrays.asList(o.toString(), o.equals(o), o.hashCode());
if (verbosity >= 2) System.out.println("actual st/eq/hc = "+actual);
assertEquals(expect, actual);
}
}
| gpl-2.0 |
teamfx/openjfx-8u-dev-rt | modules/graphics/src/test/java/javafx/scene/effect/MotionBlur_properties_Test.java | 4789 | /*
* Copyright (c) 2011, 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 javafx.scene.effect;
import static com.sun.javafx.test.TestHelper.box;
import java.util.ArrayList;
import java.util.Collection;
import javafx.scene.Node;
import javafx.scene.shape.Rectangle;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import com.sun.javafx.test.BBoxComparator;
import com.sun.javafx.test.PropertiesTestBase;
@RunWith(Parameterized.class)
public final class MotionBlur_properties_Test extends PropertiesTestBase {
@Parameters
public static Collection data() {
ArrayList array = new ArrayList();
// simple property tests
final MotionBlur testMotionBlur = new MotionBlur();
array.add(config(testMotionBlur, "input", null, new BoxBlur()));
array.add(config(testMotionBlur, "radius", 20.0, 40.0));
array.add(config(testMotionBlur, "angle", 0.0, 45.0));
// bounding box calculation tests
Node testNode = createTestNode();
array.add(config(testNode.getEffect(),
"radius", 10.0, 20.0,
testNode,
"boundsInLocal",
box(-10.0, 0.0, 120.0, 100.0),
box(-20.0, 0.0, 140.0, 100.0),
new BBoxComparator(0.01)));
testNode = createTestNode();
array.add(config(testNode.getEffect(),
"angle", 0.0, 45.0,
testNode,
"boundsInLocal",
box(-10.0, 0.0, 120.0, 100.0),
box(-8.0, -8.0, 116.0, 116.0),
new BBoxComparator(0.01)));
testNode = createTestNode();
array.add(config(testNode.getEffect(),
"input", null, new BoxBlur(),
testNode,
"boundsInLocal",
box(-10.0, -0.0, 120.0, 100.0),
box(-12.0, -2.0, 124.0, 104.0),
new BBoxComparator(0.01)));
testNode = createTestNodeWithChainedEffect();
array.add(config(((ColorAdjust)testNode.getEffect()).getInput(),
"radius", 10.0, 20.0,
testNode,
"boundsInLocal",
box(-10.0, 0.0, 120.0, 100.0),
box(-20.0, 0.0, 140.0, 100.0),
new BBoxComparator(0.01)));
testNode = createTestNodeWithChainedEffect();
array.add(config(((ColorAdjust)testNode.getEffect()).getInput(),
"angle", 0.0, 45.0,
testNode,
"boundsInLocal",
box(-10.0, 0.0, 120.0, 100.0),
box(-8.0, -8.0, 116.0, 116.0),
new BBoxComparator(0.01)));
testNode = createTestNodeWithChainedEffect();
array.add(config(((ColorAdjust)testNode.getEffect()).getInput(),
"input", null, new BoxBlur(),
testNode,
"boundsInLocal",
box(-10.0, -0.0, 120.0, 100.0),
box(-12.0, -2.0, 124.0, 104.0),
new BBoxComparator(0.01)));
return array;
}
public MotionBlur_properties_Test(final Configuration configuration) {
super(configuration);
}
private static Rectangle createTestNode() {
Rectangle r = new Rectangle(100, 100);
r.setEffect(new MotionBlur());
return r;
}
private static Rectangle createTestNodeWithChainedEffect() {
Rectangle r = new Rectangle(100, 100);
ColorAdjust c = new ColorAdjust();
c.setInput(new MotionBlur());
r.setEffect(c);
return r;
}
}
| gpl-2.0 |
FauxFaux/jdk9-jdk | test/java/nio/file/WatchService/LotsOfEvents.java | 8134 | /*
* Copyright (c) 2010, 2011, 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 6907760 6929532
* @summary Tests WatchService behavior when lots of events are pending
* @library ..
* @run main/timeout=180 LotsOfEvents
* @key randomness
*/
import java.nio.file.*;
import static java.nio.file.StandardWatchEventKinds.*;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;
import java.util.concurrent.TimeUnit;
public class LotsOfEvents {
static final Random rand = new Random();
public static void main(String[] args) throws Exception {
Path dir = TestUtil.createTemporaryDirectory();
try {
testOverflowEvent(dir);
testModifyEventsQueuing(dir);
} finally {
TestUtil.removeAll(dir);
}
}
/**
* Tests that OVERFLOW events are not retreived with other events.
*/
static void testOverflowEvent(Path dir)
throws IOException, InterruptedException
{
try (WatchService watcher = dir.getFileSystem().newWatchService()) {
dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE);
// create a lot of files
int n = 1024;
Path[] files = new Path[n];
for (int i=0; i<n; i++) {
files[i] = Files.createFile(dir.resolve("foo" + i));
}
// give time for events to accumulate (improve chance of overflow)
Thread.sleep(1000);
// check that we see the create events (or overflow)
drainAndCheckOverflowEvents(watcher, ENTRY_CREATE, n);
// delete the files
for (int i=0; i<n; i++) {
Files.delete(files[i]);
}
// give time for events to accumulate (improve chance of overflow)
Thread.sleep(1000);
// check that we see the delete events (or overflow)
drainAndCheckOverflowEvents(watcher, ENTRY_DELETE, n);
}
}
static void drainAndCheckOverflowEvents(WatchService watcher,
WatchEvent.Kind<?> expectedKind,
int count)
throws IOException, InterruptedException
{
// wait for key to be signalled - the timeout is long to allow for
// polling implementations
WatchKey key = watcher.poll(15, TimeUnit.SECONDS);
if (key != null && count == 0)
throw new RuntimeException("Key was signalled (unexpected)");
if (key == null && count > 0)
throw new RuntimeException("Key not signalled (unexpected)");
int nread = 0;
boolean gotOverflow = false;
while (key != null) {
List<WatchEvent<?>> events = key.pollEvents();
for (WatchEvent<?> event: events) {
WatchEvent.Kind<?> kind = event.kind();
if (kind == expectedKind) {
// expected event kind
if (++nread > count)
throw new RuntimeException("More events than expected!!");
} else if (kind == OVERFLOW) {
// overflow event should not be retrieved with other events
if (events.size() > 1)
throw new RuntimeException("Overflow retrieved with other events");
gotOverflow = true;
} else {
throw new RuntimeException("Unexpected event '" + kind + "'");
}
}
if (!key.reset())
throw new RuntimeException("Key is no longer valid");
key = watcher.poll(2, TimeUnit.SECONDS);
}
// check that all expected events were received or there was an overflow
if (nread < count && !gotOverflow)
throw new RuntimeException("Insufficient events");
}
/**
* Tests that check that ENTRY_MODIFY events are queued efficiently
*/
static void testModifyEventsQueuing(Path dir)
throws IOException, InterruptedException
{
// this test uses a random number of files
final int nfiles = 5 + rand.nextInt(10);
DirectoryEntry[] entries = new DirectoryEntry[nfiles];
for (int i=0; i<nfiles; i++) {
entries[i] = new DirectoryEntry(dir.resolve("foo" + i));
// "some" of the files exist, some do not.
entries[i].deleteIfExists();
if (rand.nextBoolean())
entries[i].create();
}
try (WatchService watcher = dir.getFileSystem().newWatchService()) {
dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
// do several rounds of noise and test
for (int round=0; round<10; round++) {
// make some noise!!!
for (int i=0; i<100; i++) {
DirectoryEntry entry = entries[rand.nextInt(nfiles)];
int action = rand.nextInt(10);
switch (action) {
case 0 : entry.create(); break;
case 1 : entry.deleteIfExists(); break;
default: entry.modifyIfExists();
}
}
// process events and ensure that we don't get repeated modify
// events for the same file.
WatchKey key = watcher.poll(15, TimeUnit.SECONDS);
while (key != null) {
Set<Path> modified = new HashSet<>();
for (WatchEvent<?> event: key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
Path file = (kind == OVERFLOW) ? null : (Path)event.context();
if (kind == ENTRY_MODIFY) {
boolean added = modified.add(file);
if (!added) {
throw new RuntimeException(
"ENTRY_MODIFY events not queued efficiently");
}
} else {
if (file != null) modified.remove(file);
}
}
if (!key.reset())
throw new RuntimeException("Key is no longer valid");
key = watcher.poll(2, TimeUnit.SECONDS);
}
}
}
}
static class DirectoryEntry {
private final Path file;
DirectoryEntry(Path file) {
this.file = file;
}
void create() throws IOException {
if (Files.notExists(file))
Files.createFile(file);
}
void deleteIfExists() throws IOException {
Files.deleteIfExists(file);
}
void modifyIfExists() throws IOException {
if (Files.exists(file)) {
try (OutputStream out = Files.newOutputStream(file, StandardOpenOption.APPEND)) {
out.write("message".getBytes());
}
}
}
}
}
| gpl-2.0 |
md-5/jdk10 | test/jdk/java/awt/Robot/ModifierRobotKey/ModifierRobotEnhancedKeyTest.java | 9711 | /*
* Copyright (c) 2007, 2018, 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.
*/
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import static jdk.test.lib.Asserts.assertTrue;
/*
* NOTE: this is no intentionally a manual test (i.e. has no test tag) because
* even on Windows, the various tested key-combination may get partially
* intercepted by other applications and this can leave the whole system in an
* inconsistent state. For example on my Windows machine with Intel Graphics
* the key combinations "Ctl-Alt-F11" and "Ctl-Alt-F12" triggers some Intel
* Graphics utilities by default. If the test is run in such an environment,
* some key events of the test are intercepted by those utilities with the
* result that the test fails and no more keyboard input will be possible at
* all.
*
* To execute the test add a '@' before the 'test' keyword below to make it a tag.
*/
/*
* test 8155742
*
* @summary Make sure that modifier key mask is set when robot press
* some key with one or more modifiers.
* @library /lib/client/
* @library /test/lib
* @build ExtendedRobot
* @key headful
* @run main/timeout=600 ModifierRobotEnhancedKeyTest
*/
public class ModifierRobotEnhancedKeyTest extends KeyAdapter {
private boolean focusGained = false;
private boolean startTest = false;
private ExtendedRobot robot;
private Frame frame;
private Canvas canvas;
private volatile boolean tempPress = false;
private int[] textKeys, modifierKeys, inputMasks;
private boolean[] modifierStatus, textStatus;
private final static int waitDelay = 5000;
private Object tempLock = new Object();
private Object keyLock = new Object();
public static void main(String[] args) throws Exception {
String os = System.getProperty("os.name").toLowerCase();
if (!os.contains("windows")) {
System.out.println("*** this test is for windows only because some of the tested key combinations " +
"might be caught by the os and therefore don't reach the canvas ***");
return;
}
ModifierRobotEnhancedKeyTest test = new ModifierRobotEnhancedKeyTest();
test.doTest();
}
public ModifierRobotEnhancedKeyTest() throws Exception {
modifierKeys = new int[4];
modifierKeys[0] = KeyEvent.VK_SHIFT;
modifierKeys[1] = KeyEvent.VK_CONTROL;
modifierKeys[2] = KeyEvent.VK_ALT;
modifierKeys[3] = KeyEvent.VK_ALT_GRAPH;
inputMasks = new int[4];
inputMasks[0] = InputEvent.SHIFT_MASK;
inputMasks[1] = InputEvent.CTRL_MASK;
inputMasks[2] = InputEvent.ALT_MASK;
inputMasks[3] = InputEvent.ALT_GRAPH_MASK;
modifierStatus = new boolean[modifierKeys.length];
textKeys = new int[6];
textKeys[0] = KeyEvent.VK_A;
textKeys[1] = KeyEvent.VK_S;
textKeys[2] = KeyEvent.VK_DELETE;
textKeys[3] = KeyEvent.VK_HOME;
textKeys[4] = KeyEvent.VK_F12;
textKeys[5] = KeyEvent.VK_LEFT;
textStatus = new boolean[textKeys.length];
EventQueue.invokeAndWait( () -> { initializeGUI(); });
}
public void keyPressed(KeyEvent event) {
tempPress = true;
synchronized (tempLock) { tempLock.notifyAll(); }
if (! startTest) {
return;
}
for (int x = 0; x < inputMasks.length; x++) {
if ((event.getModifiers() & inputMasks[x]) != 0) {
System.out.println("Modifier set: " + event.getKeyModifiersText(inputMasks[x]));
modifierStatus[x] = true;
}
}
for (int x = 0; x < textKeys.length; x++) {
if (event.getKeyCode() == textKeys[x]) {
System.out.println("Text set: " + event.getKeyText(textKeys[x]));
textStatus[x] = true;
}
}
synchronized (keyLock) { keyLock.notifyAll(); }
}
private void initializeGUI() {
frame = new Frame("Test frame");
canvas = new Canvas();
canvas.addFocusListener(new FocusAdapter() {
public void focusGained(FocusEvent event) { focusGained = true; }
});
canvas.addKeyListener(this);
frame.setLayout(new BorderLayout());
frame.add(canvas);
frame.setSize(200, 200);
frame.setVisible(true);
}
public void doTest() throws Exception {
robot = new ExtendedRobot();
robot.mouseMove((int) frame.getLocationOnScreen().getX() + frame.getSize().width / 2,
(int) frame.getLocationOnScreen().getY() + frame.getSize().height / 2);
robot.click(MouseEvent.BUTTON1_MASK);
robot.waitForIdle();
assertTrue(focusGained, "FAIL: Canvas gained focus!");
for (int i = 0; i < modifierKeys.length; i++) {
for (int j = 0; j < textKeys.length; j++) {
tempPress = false;
robot.keyPress(modifierKeys[i]);
robot.waitForIdle();
if (! tempPress) {
synchronized (tempLock) { tempLock.wait(waitDelay); }
}
assertTrue(tempPress, "FAIL: keyPressed triggered for i=" + i);
resetStatus();
startTest = true;
robot.keyPress(textKeys[j]);
robot.waitForIdle();
if (! modifierStatus[i] || ! textStatus[j]) {
synchronized (keyLock) { keyLock.wait(waitDelay); }
}
assertTrue(modifierStatus[i] && textStatus[j],
"FAIL: KeyEvent not proper!"+
"Key checked: i=" + i + "; j=" + j+
"ModifierStatus = " + modifierStatus[i]+
"TextStatus = " + textStatus[j]);
startTest = false;
robot.keyRelease(textKeys[j]);
robot.waitForIdle();
robot.keyRelease(modifierKeys[i]);
robot.waitForIdle();
}
}
for (int i = 0; i < modifierKeys.length; i++) {
for (int j = i + 1; j < modifierKeys.length; j++) {
for (int k = 0; k < textKeys.length; k++) {
tempPress = false;
robot.keyPress(modifierKeys[i]);
robot.waitForIdle();
if (! tempPress) {
synchronized (tempLock) { tempLock.wait(waitDelay); }
}
assertTrue(tempPress, "FAIL: MultiKeyTest: keyPressed triggered for i=" + i);
tempPress = false;
robot.keyPress(modifierKeys[j]);
robot.waitForIdle();
if (! tempPress) {
synchronized (tempLock) { tempLock.wait(waitDelay); }
}
assertTrue(tempPress, "FAIL: MultiKeyTest keyPressed triggered for j=" + j);
resetStatus();
startTest = true;
robot.keyPress(textKeys[k]);
robot.waitForIdle();
if (! modifierStatus[i] || ! modifierStatus[j] || ! textStatus[k]) {
synchronized (keyLock) {
keyLock.wait(waitDelay);
}
}
assertTrue(modifierStatus[i] && modifierStatus[j] && textStatus[k],
"FAIL: KeyEvent not proper!"+
"Key checked: i=" + i + "; j=" + j + "; k=" + k+
"Modifier1Status = " + modifierStatus[i]+
"Modifier2Status = " + modifierStatus[j]+
"TextStatus = " + textStatus[k]);
startTest = false;
robot.keyRelease(textKeys[k]);
robot.waitForIdle();
robot.keyRelease(modifierKeys[j]);
robot.waitForIdle();
robot.keyRelease(modifierKeys[i]);
robot.waitForIdle();
}
}
}
frame.dispose();
}
private void resetStatus() {
for (int i = 0; i < modifierStatus.length; i++) {
modifierStatus[i] = false;
}
for (int i = 0; i < textStatus.length; i++) {
textStatus[i] = false;
}
}
}
| gpl-2.0 |
rgerkin/neuroConstruct | src/ucl/physiol/neuroconstruct/gui/DropDownObjectCellEditor.java | 2847 | /**
* neuroConstruct
* Software for developing large scale 3D networks of biologically realistic neurons
*
* Copyright (c) 2009 Padraig Gleeson
* UCL Department of Neuroscience, Physiology and Pharmacology
*
* Development of this software was made possible with funding from the
* Medical Research Council and the Wellcome Trust
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
package ucl.physiol.neuroconstruct.gui;
import javax.swing.*;
import java.awt.*;
import javax.swing.table.*;
import ucl.physiol.neuroconstruct.utils.*;
import java.util.*;
/**
* Implementation of AbstractCellEditor for drop down lost of generic objects.
* Object should have good toString implemented
*
* @author Padraig Gleeson
*
*/
@SuppressWarnings("serial")
public class DropDownObjectCellEditor extends AbstractCellEditor implements TableCellEditor
{
ClassLogger logger = new ClassLogger("DropDownObjectCellEditor");
JComboBox comboBox;
Vector<Object> allObjects = new Vector<Object>();
public DropDownObjectCellEditor()
{
logger.logComment("New DropDownObjectCellEditor created...");
comboBox = new JComboBox();
comboBox.setActionCommand("Choose");
}
public void addValue(Object obj)
{
logger.logComment("addValue called, object type: "+ obj.getClass().getName()+", value: "+ obj);
comboBox.addItem(obj);
allObjects.add(obj);
}
public Object getCellEditorValue()
{
logger.logComment("getCellEditorValue called");
int index = comboBox.getSelectedIndex();
return allObjects.elementAt(index);
}
public Component getTableCellEditorComponent(JTable table,
Object value,
boolean isSelected,
int row,
int column)
{
logger.logComment("getTableCellEditorComponent called, object type: "+ value.getClass().getName()+", value: "+ value);
comboBox.setSelectedItem(value);
return comboBox;
}
}
| gpl-2.0 |
iwabuchiken/freemind_1.0.0_20140624_214725 | freemind/modes/mindmapmode/hooks/MindMapNodeHookAdapter.java | 1261 | /*FreeMind - A Program for creating and viewing Mindmaps
*Copyright (C) 2005 Christian Foltin <christianfoltin@users.sourceforge.net>
*See COPYING for Details
*
*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 2
*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, write to the Free Software
*Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package freemind.modes.mindmapmode.hooks;
import freemind.extensions.NodeHookAdapter;
import freemind.modes.mindmapmode.MindMapController;
/** */
public class MindMapNodeHookAdapter extends NodeHookAdapter {
/**
*
*/
public MindMapNodeHookAdapter() {
super();
}
public MindMapController getMindMapController() {
return (MindMapController) getController();
}
}
| gpl-2.0 |
andreynovikov/androzic-library | src/main/java/com/jhlabs/map/proj/Apian1Projection.java | 1692 | /*
Copyright 2010 Bernhard Jenny
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.jhlabs.map.proj;
import com.jhlabs.Point2D;
/**
* Apian I Globular projection.
* Code from proj4.
* @author Bernhard Jenny, Institute of Cartography, ETH Zurich
*/
public class Apian1Projection extends Projection {
private static final double HLFPI2 = 2.46740110027233965467;
private static final double EPS = 1e-10;
public Apian1Projection() {
}
public Point2D.Double project(double lplam, double lpphi, Point2D.Double out) {
double ax = Math.abs(lplam);
out.y = lpphi;
if (ax >= EPS) {
double f = 0.5 * (HLFPI2 / ax + ax);
out.x = ax - f + Math.sqrt(f * f - lpphi * lpphi);
if (lplam < 0.) {
out.x = -out.x;
}
} else {
out.x = 0.;
}
return out;
}
@Override
public Point2D.Double projectInverse(double x, double y, Point2D.Double out) {
binarySearchInverse(x, y, out);
return out;
}
@Override
public boolean hasInverse() {
return true;
}
public String toString() {
return "Apian Globular I";
}
}
| gpl-3.0 |
akeranen/the-one | src/report/TotalContactTimeReport.java | 2268 | /*
* Copyright 2010 Aalto University, ComNet
* Released under GPLv3. See LICENSE.txt for details.
*/
package report;
import java.util.List;
import core.DTNHost;
import core.UpdateListener;
/**
* Report for total amount of contact times among hosts. Reports how long all
* nodes have been in contact with some other node. Supports
* {@link ContactTimesReport#GRANULARITY} setting. If update interval is
* smaller than 1.0 seconds, time stamps may start to drift. Reported values
* still correspond to reported times. Connections that started during the
* warmup period are ignored.
*/
public class TotalContactTimeReport extends ContactTimesReport implements
UpdateListener {
/** The header of every report file */
public static final String HEADER = "# time totalContactTime";
/** cumulative contact times of all disconnected contacts */
private double oldContactTimes;
/** sim time of last report writing */
private double lastWrite;
/** last reported time count (to suppress duplicates) */
private double lastReportedTime;
public void init() {
super.init();
write(HEADER);
this.oldContactTimes = 0;
this.lastReportedTime = 0;
this.lastWrite = getSimTime();
}
@Override
public void hostsDisconnected(DTNHost host1, DTNHost host2) {
newEvent();
ConnectionInfo ci = removeConnection(host1, host2);
if (ci == null) {
return; // connection started during the warm up period
}
oldContactTimes += ci.getConnectionTime();
}
/**
* Reports total contact time if more time than defined with setting
* {@link ContactTimesReport#GRANULARITY} has passed. Method is called
* on every update cycle.
*/
public void updated(List<DTNHost> hosts) {
double simTime = getSimTime();
if (simTime - lastWrite < granularity || isWarmup()) {
return; // shouldn't report yet
}
lastWrite = simTime;
// count also the times for connections that are still up
double othersTime = 0;
for (ConnectionInfo oth : this.connections.values()) {
othersTime += oth.getConnectionTime();
}
double totalTime = oldContactTimes + othersTime;
if (lastReportedTime == totalTime) {
return; // don't report duplicate times
}
write(format(simTime) + " " + format(totalTime));
lastReportedTime = totalTime;
}
}
| gpl-3.0 |
s20121035/rk3288_android5.1_repo | cts/tools/vm-tests-tf/src/dot/junit/opcodes/sput/TestStubs.java | 818 | /*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dot.junit.opcodes.sput;
public class TestStubs {
// used by testVFE9
static int TestStubField = 0;
// used by testE5
public static final int TestStubFieldFinal = 0;
}
| gpl-3.0 |
jtux270/translate | ovirt/3.6_source/backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/utils/GlusterGeoRepUtil.java | 7431 | package org.ovirt.engine.core.bll.utils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Singleton;
import org.ovirt.engine.core.bll.Backend;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.gluster.GlusterGeoRepNonEligibilityReason;
import org.ovirt.engine.core.common.businessentities.gluster.GlusterGeoRepSession;
import org.ovirt.engine.core.common.businessentities.gluster.GlusterStatus;
import org.ovirt.engine.core.common.businessentities.gluster.GlusterVolumeEntity;
import org.ovirt.engine.core.common.vdscommands.VDSCommandType;
import org.ovirt.engine.core.common.vdscommands.VDSReturnValue;
import org.ovirt.engine.core.common.vdscommands.gluster.GlusterVolumeVDSParameters;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.Version;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
import org.ovirt.engine.core.dao.VdsGroupDao;
import org.ovirt.engine.core.dao.gluster.GlusterGeoRepDao;
import org.ovirt.engine.core.utils.linq.Predicate;
@Singleton
public class GlusterGeoRepUtil {
public Map<GlusterGeoRepNonEligibilityReason, Predicate<GlusterVolumeEntity>> getEligibilityPredicates(final GlusterVolumeEntity masterVolume) {
Map<GlusterGeoRepNonEligibilityReason, Predicate<GlusterVolumeEntity>> eligibilityPredicates = new HashMap<>();
final List<Guid> existingSessionSlavesIds = getSessionSlaveVolumeIds();
eligibilityPredicates.put(GlusterGeoRepNonEligibilityReason.SLAVE_VOLUME_SHOULD_BE_UP, new Predicate<GlusterVolumeEntity>() {
@Override
public boolean eval(GlusterVolumeEntity slaveVolume) {
return slaveVolume.getStatus() == GlusterStatus.UP;
}
});
eligibilityPredicates.put(GlusterGeoRepNonEligibilityReason.SLAVE_AND_MASTER_VOLUMES_SHOULD_NOT_BE_IN_SAME_CLUSTER, new Predicate<GlusterVolumeEntity>() {
@Override
public boolean eval(GlusterVolumeEntity slaveVolume) {
return ! masterVolume.getClusterId().equals(slaveVolume.getClusterId());
}
});
final Predicate<GlusterVolumeEntity> nonNullSlaveSizePredicate = new Predicate<GlusterVolumeEntity>() {
@Override
public boolean eval(GlusterVolumeEntity slaveVolume) {
return slaveVolume.getAdvancedDetails().getCapacityInfo() != null;
}
};
eligibilityPredicates.put(GlusterGeoRepNonEligibilityReason.SLAVE_VOLUME_SIZE_TO_BE_AVAILABLE, nonNullSlaveSizePredicate);
final Predicate<GlusterVolumeEntity> nonNullMasterSizePredicate = new Predicate<GlusterVolumeEntity>() {
@Override
public boolean eval(GlusterVolumeEntity slaveVolume) {
return masterVolume.getAdvancedDetails().getCapacityInfo() != null;
}
};
eligibilityPredicates.put(GlusterGeoRepNonEligibilityReason.MASTER_VOLUME_SIZE_TO_BE_AVAILABLE, nonNullMasterSizePredicate);
Predicate<GlusterVolumeEntity> masterSlaveSizePredicate = new Predicate<GlusterVolumeEntity>() {
@Override
public boolean eval(GlusterVolumeEntity slaveVolume) {
boolean eligible = nonNullSlaveSizePredicate.eval(slaveVolume) && nonNullMasterSizePredicate.eval(masterVolume);
if (eligible) {
eligible = slaveVolume.getAdvancedDetails().getCapacityInfo().getTotalSize() >= masterVolume.getAdvancedDetails().getCapacityInfo().getTotalSize();
}
return eligible;
}
};
eligibilityPredicates.put(GlusterGeoRepNonEligibilityReason.SLAVE_VOLUME_SIZE_SHOULD_BE_GREATER_THAN_MASTER_VOLUME_SIZE, masterSlaveSizePredicate);
eligibilityPredicates.put(GlusterGeoRepNonEligibilityReason.SLAVE_VOLUME_SHOULD_NOT_BE_SLAVE_OF_ANOTHER_GEO_REP_SESSION, new Predicate<GlusterVolumeEntity>() {
@Override
public boolean eval(GlusterVolumeEntity slaveVolume) {
return !existingSessionSlavesIds.contains(slaveVolume.getId());
}
});
eligibilityPredicates.put(GlusterGeoRepNonEligibilityReason.SLAVE_CLUSTER_AND_MASTER_CLUSTER_COMPATIBILITY_VERSIONS_DO_NOT_MATCH, new Predicate<GlusterVolumeEntity>() {
@Override
public boolean eval(GlusterVolumeEntity slaveVolume) {
VdsGroupDao vdsGroupDao = getVdsGroupDao();
Version slaveCompatibilityVersion = vdsGroupDao.get(slaveVolume.getClusterId()).getCompatibilityVersion();
Version masterCompatibilityVersion = vdsGroupDao.get(masterVolume.getClusterId()).getCompatibilityVersion();
return masterCompatibilityVersion.equals(slaveCompatibilityVersion);
}
});
eligibilityPredicates.put(GlusterGeoRepNonEligibilityReason.NO_UP_SLAVE_SERVER,
new Predicate<GlusterVolumeEntity>() {
@Override
public boolean eval(GlusterVolumeEntity slaveVolume) {
Guid slaveUpserverId = getUpServerId(slaveVolume.getClusterId());
if (slaveUpserverId == null) {
return false;
}
return true;
}
});
eligibilityPredicates.put(GlusterGeoRepNonEligibilityReason.SLAVE_VOLUME_TO_BE_EMPTY,
new Predicate<GlusterVolumeEntity>() {
@Override
public boolean eval(GlusterVolumeEntity slaveVolume) {
Guid slaveUpserverId = getUpServerId(slaveVolume.getClusterId());
if(slaveUpserverId == null) {
return false;
}
return checkEmptyGlusterVolume(slaveUpserverId, slaveVolume.getName());
}
});
return eligibilityPredicates;
}
private List<Guid> getSessionSlaveVolumeIds() {
List<GlusterGeoRepSession> existingSessions = getGeoRepDao().getAllSessions();
List<Guid> sessionSlavesIds = new ArrayList<>();
for(GlusterGeoRepSession currentSession : existingSessions) {
sessionSlavesIds.add(currentSession.getSlaveVolumeId());
}
return sessionSlavesIds;
}
public boolean checkEmptyGlusterVolume(Guid slaveUpserverId, String slaveVolumeName) {
VDSReturnValue returnValue =
Backend.getInstance()
.getResourceManager()
.RunVdsCommand(VDSCommandType.CheckEmptyGlusterVolume,
new GlusterVolumeVDSParameters(slaveUpserverId, slaveVolumeName));
if (!returnValue.getSucceeded()) {
return false;
}
return (boolean) returnValue.getReturnValue();
}
public Guid getUpServerId(Guid clusterId) {
VDS randomUpServer = ClusterUtils.getInstance().getRandomUpServer(clusterId);
return randomUpServer == null ? null : randomUpServer.getId();
}
public VdsGroupDao getVdsGroupDao() {
return DbFacade.getInstance().getVdsGroupDao();
}
public GlusterGeoRepDao getGeoRepDao() {
return DbFacade.getInstance().getGlusterGeoRepDao();
}
}
| gpl-3.0 |
sbandur84/micro-Blagajna | src-pos/com/openbravo/pos/imports/JPanelCSVImport.java | 82832 | // uniCenta oPOS - Touch Friendly Point Of Sale
// Copyright (c) 2009-2014 uniCenta & previous Openbravo POS works
// http://www.unicenta.com
//
// This file is part of uniCenta oPOS
//
// uniCenta oPOS 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.
//
// uniCenta oPOS 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 uniCenta oPOS. If not, see <http://www.gnu.org/licenses/>.
// CSV Import Panel added by JDL - February 2013
// Additonal library required - javacsv
package com.openbravo.pos.imports;
import com.csvreader.CsvReader;
import com.openbravo.basic.BasicException;
import com.openbravo.data.gui.ComboBoxValModel;
import com.openbravo.data.loader.SentenceList;
import com.openbravo.data.loader.Session;
import com.openbravo.data.user.SaveProvider;
import com.openbravo.pos.forms.*;
import com.openbravo.pos.inventory.TaxCategoryInfo;
import com.openbravo.pos.sales.TaxesLogic;
import com.openbravo.pos.ticket.ProductInfoExt;
import java.io.*;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.filechooser.FileNameExtensionFilter;
import org.apache.commons.lang.StringUtils;
/**
* Graphical User Interface and code for importing data from a CSV file allowing
* adding or updating many products quickly and easily.
*
* @author John L - Version 1.0
* @author Walter Wojcik - Version 2.0+
* @version 2.0 - Added functionality to remember the last folder opened and
* importing categories from CVS.
* @version 2.1 complete re-write of the core code, to make use of the core
* classes available within Unicenta
*/
public class JPanelCSVImport extends JPanel implements JPanelView {
private ArrayList<String> Headers = new ArrayList<>();
private Session s;
private Connection con;
private String csvFileName;
private Double dOriginalRate;
private String dCategory;
private String csvMessage = "";
private CsvReader products;
private double oldSellPrice = 0;
private double oldBuyPrice = 0;
private int currentRecord;
private int rowCount = 0;
private String last_folder;
private File config_file;
private static String category_disable_text = "[ USE DEFAULT CATEGORY ]";
private static String reject_bad_categories_text = "[ REJECT ITEMS WITH BAD CATEGORIES ]";
private DataLogicSales m_dlSales;
private DataLogicSystem m_dlSystem;
/**
*
*/
protected SaveProvider spr;
private String productReference;
private String productBarcode;
private String productName;
private String Category;
private Double productBuyPrice;
private Double productSellPrice;
private SentenceList m_sentcat;
private ComboBoxValModel m_CategoryModel;
private SentenceList taxcatsent;
private ComboBoxValModel taxcatmodel;
private SentenceList taxsent;
private TaxesLogic taxeslogic;
private DocumentListener documentListener;
private HashMap cat_list = new HashMap();
private ArrayList badCategories = new ArrayList();
private ProductInfoExt prodInfo;
private String recordType = null;
private int newRecords = 0;
private int invalidRecords = 0;
private int priceUpdates = 0;
private int missingData = 0;
private int noChanges = 0;
private int badPrice = 0;
private double dTaxRate;
/**
* Constructs a new JPanelCSVImport object
*
* @param oApp AppView
*/
public JPanelCSVImport(AppView oApp) {
this(oApp.getProperties());
}
/**
* Constructs a new JPanelCSVImport object
*
* @param props AppProperties
*/
@SuppressWarnings("empty-statement")
public JPanelCSVImport(AppProperties props) {
initComponents();
// Open Database session
try {
s = AppViewConnection.createSession(props);
con = s.getConnection();
} catch (BasicException | SQLException e) {;
}
/*
* Create new datalogocsales & DataLogicSystem instances to allow access to sql routines.
*/
m_dlSales = new DataLogicSales();
m_dlSales.init(s);
m_dlSystem = new DataLogicSystem();
m_dlSystem.init(s);
spr = new SaveProvider(
m_dlSales.getProductCatUpdate(),
m_dlSales.getProductCatInsert(),
m_dlSales.getProductCatDelete());
// Save Last file for later use.
last_folder = props.getProperty("CSV.last_folder");
config_file = props.getConfigFile();
jFileName.getDocument().addDocumentListener(documentListener);
documentListener = new DocumentListener() {
@Override
public void changedUpdate(DocumentEvent documentEvent) {
jHeaderRead.setEnabled(true);
}
@Override
public void insertUpdate(DocumentEvent documentEvent) {
if (!"".equals(jFileName.getText().trim())) {
jHeaderRead.setEnabled(true);
}
}
@Override
public void removeUpdate(DocumentEvent documentEvent) {
if (jFileName.getText().trim().equals("")) {
jHeaderRead.setEnabled(false);
}
}
};
jFileName.getDocument().addDocumentListener(documentListener);
}
/**
* Reads the headers from the CSV file and initializes subsequent form
* fields. This function first reads the headers from the CSVFileName file,
* then puts them into the header combo boxes and enables the other form
* inputs.
*
* @todo Simplify this method by stripping the file reading and writing
* functionality out into it's own class. Also make the enabling fields
* section into it's own function and return the 'Headers' to the calling
* function to be added there.
*
* @param CSVFileName Name of the file (including the path) to open and read
* CSV data from
* @throws IOException If there is an issue reading the CSV file
*/
private void GetheadersFromFile(String CSVFileName) throws IOException {
File f = new File(CSVFileName);
if (f.exists()) {
products = new CsvReader(CSVFileName);
products.setDelimiter(((String) jComboSeparator.getSelectedItem()).charAt(0));
products.readHeaders();
// We need a minimum of 5 columns to map all required fields
if (products.getHeaderCount() < 5) {
JOptionPane.showMessageDialog(null,
"Insufficient headers found in file",
"Invalid Header Count.",
JOptionPane.WARNING_MESSAGE);
products.close();
return;
}
rowCount = 0;
int i = 0;
Headers.clear();
Headers.add("");
jComboName.addItem("");
jComboReference.addItem("");
jComboBarcode.addItem("");
jComboBuy.addItem("");
jComboSell.addItem("");
jComboCategory.addItem("");
/**
* @todo Return header list for processing elsewhere
*/
while (i < products.getHeaderCount()) {
jComboName.addItem(products.getHeader(i));
jComboReference.addItem(products.getHeader(i));
jComboBarcode.addItem(products.getHeader(i));
jComboBuy.addItem(products.getHeader(i));
jComboSell.addItem(products.getHeader(i));
jComboCategory.addItem(products.getHeader(i));
Headers.add(products.getHeader(i));
++i;
}
//enable all the chsck boxes ready for use
enableCheckBoxes();
//Count the records found
while (products.readRecord()) {
++rowCount;
}
jTextRecords.setText(Long.toString(rowCount));
// close the file we will open again when required
products.close();
} else {
JOptionPane.showMessageDialog(null, "Unable to locate "
+ CSVFileName,
"File not found",
JOptionPane.WARNING_MESSAGE);
}
}
/**
* Enables all the selection options on the for to allow the user to
* interact with the routine.
*
*/
private void enableCheckBoxes() {
jHeaderRead.setEnabled(false);
jImport.setEnabled(false);
jComboReference.setEnabled(true);
jComboName.setEnabled(true);
jComboBarcode.setEnabled(true);
jComboBuy.setEnabled(true);
jComboSell.setEnabled(true);
jComboCategory.setEnabled(true);
jComboDefaultCategory.setEnabled(true);
jComboTax.setEnabled(true);
jCheckInCatalogue.setEnabled(true);
jCheckSellIncTax.setEnabled(true);
}
/**
* Imports the CVS File using specifications from the form.
*
* @param CSVFileName Name of the file (including path) to import.
* @throws IOException If there are file reading issues.
*/
private void ImportCsvFile(String CSVFileName) throws IOException {
File f = new File(CSVFileName);
if (f.exists()) {
// Read file
products = new CsvReader(CSVFileName);
products.setDelimiter(((String) jComboSeparator.getSelectedItem()).charAt(0));
products.readHeaders();
currentRecord = 0;
while (products.readRecord()) {
productReference = products.get((String) jComboReference.getSelectedItem());
productName = products.get((String) jComboName.getSelectedItem());
productBarcode = products.get((String) jComboBarcode.getSelectedItem());
String BuyPrice = products.get((String) jComboBuy.getSelectedItem());
String SellPrice = products.get((String) jComboSell.getSelectedItem());
Category = products.get((String) jComboCategory.getSelectedItem());
currentRecord++;
// Strip Currency Symbols
BuyPrice = StringUtils.replaceChars(BuyPrice, "$", ""); // Remove currency symbol
SellPrice = StringUtils.replaceChars(SellPrice, "$", ""); // Remove currency symbol
dCategory = getCategory();
// set the csvMessage to a default value
if ("Bad Category".equals(dCategory)) {
csvMessage = "Bad category details";
} else {
csvMessage = "Missing data or Invalid number";
}
// Validate and convert the prices or change them to null
if (validateNumber(BuyPrice)) {
productBuyPrice = Double.parseDouble(BuyPrice);
} else {
productBuyPrice = null;
}
if (validateNumber(SellPrice)) {
productSellPrice = getSellPrice(SellPrice);
} else {
productSellPrice = null;
}
/**
* Check to make sure our entries aren't bad or blank or the
* category is not bad
*
*/
if ("".equals(productReference)
| "".equals(productName)
| "".equals(productBarcode)
| "".equals(BuyPrice)
| "".equals(SellPrice)
| productBuyPrice == null
| productSellPrice == null
| "Bad Category".equals(dCategory)) {
if (productBuyPrice == null | productSellPrice == null) {
badPrice++;
} else {
missingData++;
}
createCSVEntry(csvMessage, null, null);
} else {
// We know that the data passes the basic checks, so get more details about the product
recordType = getRecord();
switch (recordType) {
case "new":
createProduct("new");
newRecords++;
createCSVEntry("New product", null, null);
break;
case "name error":
case "barcode error":
case "reference error":
case "Duplicate Reference found.":
case "Duplicate Barcode found.":
case "Duplicate Description found.":
case "Exception":
invalidRecords++;
createCSVEntry(recordType, null, null);
break;
default:
updateRecord(recordType);
break;
}
}
}
} else {
JOptionPane.showMessageDialog(null, "Unable to locate " + CSVFileName, "File not found", JOptionPane.WARNING_MESSAGE);
}
// update the record fields on the form
jTextNew.setText(Integer.toString(newRecords));
jTextUpdate.setText(Integer.toString(priceUpdates));
jTextInvalid.setText(Integer.toString(invalidRecords));
jTextMissing.setText(Integer.toString(missingData));
jTextNoChange.setText(Integer.toString(noChanges));
jTextBadPrice.setText(Integer.toString(badPrice));
jTextBadCats.setText(Integer.toString(badCategories.size()));
}
/**
* Tests
* <code>testString</code> for validity as a number
*
* @param testString the string to be checked
* @return <code>True<code> if a real number <code>False<code> if not
*/
private Boolean validateNumber(String testString) {
try {
Double res = Double.parseDouble(testString);
return (true);
} catch (NumberFormatException e) {
return (false);
}
}
/*
* Get the category to be used for the new product
* returns category id as string
*/
private String getCategory() {
// get the category to be used for the product
if (jComboCategory.getSelectedItem() != category_disable_text) {
// get the category ID of the catergory passed
String cat = (String) cat_list.get(Category);
// only if we have a valid category
if (cat != null) {
return (cat);
}
}
if (!badCategories.contains(Category)) {
badCategories.add(Category.trim()); // Save a list of the bad categories so we can tell the user later
}
return ((jComboDefaultCategory.getSelectedItem() == reject_bad_categories_text) ? "Bad Category" : (String) cat_list.get(m_CategoryModel.getSelectedText()));
}
/**
* Adjusts the sell price for included taxes if needed and converted to
* <code>double</code>
*
* @param pSellPrice sell price to be converted
* @return sell price after adjustment for included taxes and converted to <code>double</double>
*/
private Double getSellPrice(String pSellPrice) {
// Check if the selling price icludes taxes
dTaxRate = taxeslogic.getTaxRate((TaxCategoryInfo) taxcatmodel.getSelectedItem());
if (jCheckSellIncTax.isSelected()) {
return ((Double.parseDouble(pSellPrice)) / (1 + dTaxRate));
} else {
return (Double.parseDouble(pSellPrice));
}
}
/**
* Updated the record in the database with the new prices and category if
* needed.
*
* @param pID Unique product id of the record to be updated It then creates
* an updated record for the product, subject to the prices be different
*
*/
private void updateRecord(String pID) {
prodInfo = new ProductInfoExt();
try {
prodInfo = m_dlSales.getProductInfo(pID);
dOriginalRate = taxeslogic.getTaxRate(prodInfo.getTaxCategoryID());
dCategory = (String) cat_list.get(prodInfo.getCategoryID());
oldBuyPrice = prodInfo.getPriceBuy();
oldSellPrice = prodInfo.getPriceSell();
productSellPrice *= (1 + dOriginalRate);
if ((oldBuyPrice != productBuyPrice) || (oldSellPrice != productSellPrice)) {
createCSVEntry("Updated Price Details", oldBuyPrice, oldSellPrice * (1 + dOriginalRate));
createProduct("update");
priceUpdates++;
} else {
noChanges++;
}
} catch (BasicException ex) {
Logger.getLogger(JPanelCSVImport.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Gets the title of the current panel
*
* @return The name of the panel
*/
@Override
public String getTitle() {
return AppLocal.getIntString("Menu.CSVImport");
}
/**
* Returns this object
* @return
*/
@Override
public JComponent getComponent() {
return this;
}
/**
* Loads Tax and category data into their combo boxes.
* @throws com.openbravo.basic.BasicException
*/
@Override
public void activate() throws BasicException {
// Get tax details and logic
taxsent = m_dlSales.getTaxList(); //get details taxes table
taxeslogic = new TaxesLogic(taxsent.list());
taxcatsent = m_dlSales.getTaxCategoriesList();
taxcatmodel = new ComboBoxValModel(taxcatsent.list());
jComboTax.setModel(taxcatmodel);
// Get categories list
m_sentcat = m_dlSales.getCategoriesList();
m_CategoryModel = new ComboBoxValModel(m_sentcat.list());
m_CategoryModel.add(reject_bad_categories_text);
jComboDefaultCategory.setModel(m_CategoryModel);
// Build the cat_list for later use
cat_list = new HashMap<>();
for (Object category : m_sentcat.list()) {
m_CategoryModel.setSelectedItem(category);
cat_list.put(category.toString(), m_CategoryModel.getSelectedKey().toString());
}
// reset the selected to the first in the list
m_CategoryModel.setSelectedItem(null);
taxcatmodel.setSelectedFirst();
// Set the column delimiter
jComboSeparator.removeAllItems();
jComboSeparator.addItem(",");
jComboSeparator.addItem(";");
jComboSeparator.addItem("~");
jComboSeparator.addItem("^");
}
/**
* Resets all the form fields
*/
public void resetFields() {
// Clear the form
jComboReference.removeAllItems();
jComboReference.setEnabled(false);
jComboName.removeAllItems();
jComboName.setEnabled(false);
jComboBarcode.removeAllItems();
jComboBarcode.setEnabled(false);
jComboBuy.removeAllItems();
jComboBuy.setEnabled(false);
jComboSell.removeAllItems();
jComboSell.setEnabled(false);
jComboCategory.removeAllItems();
jComboCategory.setEnabled(false);
jComboDefaultCategory.setEnabled(false);
jComboTax.setEnabled(false);
jImport.setEnabled(false);
jHeaderRead.setEnabled(false);
jCheckInCatalogue.setSelected(false);
jCheckInCatalogue.setEnabled(false);
jCheckSellIncTax.setSelected(false);
jCheckSellIncTax.setEnabled(false);
jFileName.setText(null);
csvFileName = "";
jTextNew.setText("");
jTextUpdate.setText("");
jTextInvalid.setText("");
jTextMissing.setText("");
jTextNoChange.setText("");
jTextRecords.setText("");
jTextBadPrice.setText("");
Headers.clear();
}
/**
* Checks the field mappings to ensure all compulsory fields have been
* completed to allow import to proceed
*/
public void checkFieldMapping() {
if (jComboReference.getSelectedItem() != "" & jComboName.getSelectedItem() != "" & jComboBarcode.getSelectedItem() != ""
& jComboBuy.getSelectedItem() != "" & jComboSell.getSelectedItem() != "" & jComboCategory.getSelectedItem() != ""
& m_CategoryModel.getSelectedText() != null) {
jImport.setEnabled(true);
} else {
jImport.setEnabled(false);
}
}
/**
* Deactivates and resets all form fields.
*
* @return
*/
@Override
public boolean deactivate() {
resetFields();
return (true);
}
/**
*
* @param pType
*/
public void createProduct(String pType) {
// create a new product and save it using DalaLogicSales
Object[] myprod = new Object[25];
myprod[0] = UUID.randomUUID().toString(); // ID string
myprod[1] = productReference; // Reference string
myprod[2] = productBarcode; // Barcode String
myprod[3] = productName; // Name string
myprod[4] = false; // IScomment flag (Attribute modifier)
myprod[5] = false; // ISscale flag
myprod[6] = productBuyPrice; // Buy price double
myprod[7] = productSellPrice; // Sell price double
myprod[8] = dCategory; // Category string
myprod[9] = taxcatmodel.getSelectedKey(); // Tax string
myprod[10] = null; // Attributeset string
myprod[11] = null; // Image
myprod[12] = null; // Stock cost double
myprod[13] = null; // Stock volume double
myprod[14] = jCheckInCatalogue.isSelected(); // In catalog flag
myprod[15] = null; // catalog order
myprod[16] = null; //
myprod[17] = false; // IsKitchen flag
myprod[18] = false; // isService flag
myprod[19] = "<HTML>" + productName; //
myprod[20] = false; // isVariable price flag
myprod[21] = false; // Compulsory Att flag
myprod[22] = productName; // Text tip string
myprod[23] = false; // Warranty flag
myprod[24] = 0.0; // StockUnits
try {
if (pType == "new") {
spr.insertData(myprod);
} else {
spr.updateData(myprod);
}
} catch (BasicException ex) {
Logger.getLogger(JPanelCSVImport.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
*
* @param csvError
* @param PreviousBuy
* @param previousSell
*/
public void createCSVEntry(String csvError, Double PreviousBuy, Double previousSell) {
// create a new csv entry and save it using DataLogicSystem
Object[] myprod = new Object[11];
myprod[0] = UUID.randomUUID().toString(); // ID string
myprod[1] = Integer.toString(currentRecord); // Record number
myprod[2] = csvError; // Error description
myprod[3] = productReference; // Reference string
myprod[4] = productBarcode; // Barcode String
myprod[5] = productName; // Name string
myprod[6] = productBuyPrice; // Buy price
myprod[7] = productSellPrice; // Sell price
myprod[8] = PreviousBuy; // Previous Buy price double
myprod[9] = previousSell; // Previous Sell price double
myprod[10] = Category;
try {
m_dlSystem.execAddCSVEntry(myprod);
} catch (BasicException ex) {
Logger.getLogger(JPanelCSVImport.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
*
* @return
*/
public String getRecord() {
// Get record type using using DataLogicSystem
Object[] myprod = new Object[3];
myprod[0] = productReference;
myprod[1] = productBarcode;
myprod[2] = productName;
try {
return (m_dlSystem.getProductRecordType(myprod));
} catch (BasicException ex) {
Logger.getLogger(JPanelCSVImport.class.getName()).log(Level.SEVERE, null, ex);
}
return "Exception";
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jFileChooserPanel = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jFileName = new javax.swing.JTextField();
jbtnDbDriverLib = new javax.swing.JButton();
jPanel1 = new javax.swing.JPanel();
jComboReference = new javax.swing.JComboBox();
jComboBarcode = new javax.swing.JComboBox();
jComboName = new javax.swing.JComboBox();
jComboBuy = new javax.swing.JComboBox();
jComboSell = new javax.swing.JComboBox();
jComboDefaultCategory = new javax.swing.JComboBox();
jComboTax = new javax.swing.JComboBox();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
jLabel11 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jCheckInCatalogue = new javax.swing.JCheckBox();
jLabel8 = new javax.swing.JLabel();
jCheckSellIncTax = new javax.swing.JCheckBox();
jLabel12 = new javax.swing.JLabel();
jComboCategory = new javax.swing.JComboBox();
jLabel20 = new javax.swing.JLabel();
jLabel17 = new javax.swing.JLabel();
jLabel18 = new javax.swing.JLabel();
jHeaderRead = new javax.swing.JButton();
jPanel2 = new javax.swing.JPanel();
jLabel9 = new javax.swing.JLabel();
jLabel14 = new javax.swing.JLabel();
jLabel16 = new javax.swing.JLabel();
jTextUpdates = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel15 = new javax.swing.JLabel();
jLabel13 = new javax.swing.JLabel();
jTextRecords = new javax.swing.JTextField();
jTextNew = new javax.swing.JTextField();
jTextInvalid = new javax.swing.JTextField();
jTextUpdate = new javax.swing.JTextField();
jTextMissing = new javax.swing.JTextField();
jTextBadPrice = new javax.swing.JTextField();
jTextNoChange = new javax.swing.JTextField();
jLabel19 = new javax.swing.JLabel();
jTextBadCats = new javax.swing.JTextField();
jComboSeparator = new javax.swing.JComboBox();
jImport = new javax.swing.JButton();
setOpaque(false);
setPreferredSize(new java.awt.Dimension(630, 430));
jLabel1.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("pos_messages"); // NOI18N
jLabel1.setText(bundle.getString("label.csvfile")); // NOI18N
jLabel1.setPreferredSize(new java.awt.Dimension(100, 30));
jFileName.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jFileName.setPreferredSize(new java.awt.Dimension(275, 30));
jFileName.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jFileNameActionPerformed(evt);
}
});
jbtnDbDriverLib.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/fileopen.png"))); // NOI18N
jbtnDbDriverLib.setMaximumSize(new java.awt.Dimension(64, 32));
jbtnDbDriverLib.setMinimumSize(new java.awt.Dimension(64, 32));
jbtnDbDriverLib.setPreferredSize(new java.awt.Dimension(64, 32));
jbtnDbDriverLib.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbtnDbDriverLibActionPerformed(evt);
}
});
javax.swing.GroupLayout jFileChooserPanelLayout = new javax.swing.GroupLayout(jFileChooserPanel);
jFileChooserPanel.setLayout(jFileChooserPanelLayout);
jFileChooserPanelLayout.setHorizontalGroup(
jFileChooserPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jFileChooserPanelLayout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jFileName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jbtnDbDriverLib, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(116, 116, 116))
);
jFileChooserPanelLayout.setVerticalGroup(
jFileChooserPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jFileChooserPanelLayout.createSequentialGroup()
.addGroup(jFileChooserPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jFileName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(jbtnDbDriverLib, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jComboReference.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
jComboReference.setEnabled(false);
jComboReference.setMinimumSize(new java.awt.Dimension(32, 25));
jComboReference.setOpaque(false);
jComboReference.setPreferredSize(new java.awt.Dimension(275, 30));
jComboReference.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jComboReferenceItemStateChanged(evt);
}
});
jComboReference.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jComboReferenceFocusGained(evt);
}
});
jComboBarcode.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
jComboBarcode.setEnabled(false);
jComboBarcode.setMinimumSize(new java.awt.Dimension(32, 25));
jComboBarcode.setPreferredSize(new java.awt.Dimension(275, 30));
jComboBarcode.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jComboBarcodeItemStateChanged(evt);
}
});
jComboBarcode.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jComboBarcodeFocusGained(evt);
}
});
jComboName.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
jComboName.setEnabled(false);
jComboName.setMinimumSize(new java.awt.Dimension(32, 25));
jComboName.setPreferredSize(new java.awt.Dimension(275, 30));
jComboName.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jComboNameItemStateChanged(evt);
}
});
jComboName.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jComboNameFocusGained(evt);
}
});
jComboBuy.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
jComboBuy.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "" }));
jComboBuy.setSelectedIndex(-1);
jComboBuy.setEnabled(false);
jComboBuy.setMinimumSize(new java.awt.Dimension(32, 25));
jComboBuy.setPreferredSize(new java.awt.Dimension(275, 30));
jComboBuy.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jComboBuyItemStateChanged(evt);
}
});
jComboBuy.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jComboBuyFocusGained(evt);
}
});
jComboSell.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
jComboSell.setEnabled(false);
jComboSell.setMinimumSize(new java.awt.Dimension(32, 25));
jComboSell.setPreferredSize(new java.awt.Dimension(275, 30));
jComboSell.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jComboSellItemStateChanged(evt);
}
});
jComboSell.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jComboSellFocusGained(evt);
}
});
jComboDefaultCategory.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
jComboDefaultCategory.setEnabled(false);
jComboDefaultCategory.setMinimumSize(new java.awt.Dimension(32, 25));
jComboDefaultCategory.setPreferredSize(new java.awt.Dimension(275, 30));
jComboDefaultCategory.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jComboDefaulrCategoryItemStateChanged(evt);
}
});
jComboDefaultCategory.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboDefaultCategoryActionPerformed(evt);
}
});
jComboTax.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
jComboTax.setEnabled(false);
jComboTax.setPreferredSize(new java.awt.Dimension(275, 30));
jLabel3.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel3.setText(bundle.getString("label.prodref")); // NOI18N
jLabel3.setPreferredSize(new java.awt.Dimension(100, 30));
jLabel4.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel4.setText(bundle.getString("label.prodbarcode")); // NOI18N
jLabel4.setPreferredSize(new java.awt.Dimension(100, 30));
jLabel5.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel5.setText(bundle.getString("label.prodname")); // NOI18N
jLabel5.setPreferredSize(new java.awt.Dimension(100, 30));
jLabel10.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel10.setText(bundle.getString("label.prodpricebuy")); // NOI18N
jLabel10.setPreferredSize(new java.awt.Dimension(100, 30));
jLabel11.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel11.setText(bundle.getString("label.prodcategory")); // NOI18N
jLabel11.setPreferredSize(new java.awt.Dimension(100, 30));
jLabel6.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel6.setText(bundle.getString("label.proddefaultcategory")); // NOI18N
jLabel6.setPreferredSize(new java.awt.Dimension(100, 30));
jLabel7.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel7.setText(bundle.getString("label.prodtaxcode")); // NOI18N
jLabel7.setPreferredSize(new java.awt.Dimension(100, 30));
jCheckInCatalogue.setEnabled(false);
jLabel8.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel8.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jLabel8.setText(bundle.getString("label.prodincatalog")); // NOI18N
jCheckSellIncTax.setEnabled(false);
jLabel12.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel12.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jLabel12.setText(bundle.getString("label.csvsellingintax")); // NOI18N
jComboCategory.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
jComboCategory.setEnabled(false);
jComboCategory.setMinimumSize(new java.awt.Dimension(32, 25));
jComboCategory.setName(""); // NOI18N
jComboCategory.setPreferredSize(new java.awt.Dimension(275, 30));
jComboCategory.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jComboCategoryItemStateChanged(evt);
}
});
jComboCategory.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jComboCategoryFocusGained(evt);
}
});
jLabel20.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel20.setText(bundle.getString("label.prodpricesell")); // NOI18N
jLabel20.setPreferredSize(new java.awt.Dimension(100, 30));
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jComboDefaultCategory, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboTax, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(1, 1, 1)
.addComponent(jCheckInCatalogue, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jCheckSellIncTax, javax.swing.GroupLayout.Alignment.TRAILING))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, Short.MAX_VALUE))))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel20, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jComboCategory, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboReference, 0, 454, Short.MAX_VALUE)
.addComponent(jComboBarcode, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboName, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBuy, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboSell, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(2, 2, 2)
.addComponent(jComboReference, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBarcode, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboName, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBuy, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jComboSell, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel20, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jComboCategory, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel6, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboDefaultCategory, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboTax, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jCheckInCatalogue)
.addGap(10, 10, 10))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jCheckSellIncTax))
.addGap(54, 54, 54))
);
jLabel17.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
jLabel17.setText("Import Version V2.1");
jLabel18.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel18.setText(bundle.getString("label.csvdelimit")); // NOI18N
jLabel18.setPreferredSize(new java.awt.Dimension(100, 30));
jHeaderRead.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
jHeaderRead.setText(bundle.getString("label.csvread")); // NOI18N
jHeaderRead.setEnabled(false);
jHeaderRead.setPreferredSize(new java.awt.Dimension(120, 30));
jHeaderRead.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jHeaderReadActionPerformed(evt);
}
});
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(153, 153, 153), 1, true), bundle.getString("title.CSVImport"), javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Arial", 1, 12), new java.awt.Color(102, 102, 102))); // NOI18N
jLabel9.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel9.setText(bundle.getString("label.csvrecordsfound")); // NOI18N
jLabel9.setPreferredSize(new java.awt.Dimension(100, 25));
jLabel14.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel14.setText(bundle.getString("label.csvnewproducts")); // NOI18N
jLabel14.setMaximumSize(new java.awt.Dimension(77, 14));
jLabel14.setMinimumSize(new java.awt.Dimension(77, 14));
jLabel14.setPreferredSize(new java.awt.Dimension(100, 25));
jLabel16.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel16.setText(bundle.getString("label.cvsinvalid")); // NOI18N
jLabel16.setPreferredSize(new java.awt.Dimension(100, 25));
jTextUpdates.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jTextUpdates.setText(bundle.getString("label.csvpriceupdated")); // NOI18N
jTextUpdates.setPreferredSize(new java.awt.Dimension(100, 25));
jLabel2.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel2.setText(bundle.getString("label.csvmissing")); // NOI18N
jLabel2.setPreferredSize(new java.awt.Dimension(100, 25));
jLabel15.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel15.setText(bundle.getString("label.csvbad")); // NOI18N
jLabel15.setPreferredSize(new java.awt.Dimension(100, 25));
jLabel13.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel13.setText(bundle.getString("label.cvsnotchanged")); // NOI18N
jLabel13.setPreferredSize(new java.awt.Dimension(100, 25));
jTextRecords.setBackground(new java.awt.Color(224, 223, 227));
jTextRecords.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
jTextRecords.setForeground(new java.awt.Color(102, 102, 102));
jTextRecords.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
jTextRecords.setBorder(null);
jTextRecords.setDisabledTextColor(new java.awt.Color(0, 0, 0));
jTextRecords.setEnabled(false);
jTextRecords.setPreferredSize(new java.awt.Dimension(70, 25));
jTextNew.setBackground(new java.awt.Color(224, 223, 227));
jTextNew.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
jTextNew.setForeground(new java.awt.Color(102, 102, 102));
jTextNew.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
jTextNew.setBorder(null);
jTextNew.setDisabledTextColor(new java.awt.Color(0, 0, 0));
jTextNew.setEnabled(false);
jTextNew.setPreferredSize(new java.awt.Dimension(70, 25));
jTextInvalid.setBackground(new java.awt.Color(224, 223, 227));
jTextInvalid.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
jTextInvalid.setForeground(new java.awt.Color(102, 102, 102));
jTextInvalid.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
jTextInvalid.setBorder(null);
jTextInvalid.setDisabledTextColor(new java.awt.Color(0, 0, 0));
jTextInvalid.setEnabled(false);
jTextInvalid.setPreferredSize(new java.awt.Dimension(70, 25));
jTextUpdate.setBackground(new java.awt.Color(224, 223, 227));
jTextUpdate.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
jTextUpdate.setForeground(new java.awt.Color(102, 102, 102));
jTextUpdate.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
jTextUpdate.setBorder(null);
jTextUpdate.setDisabledTextColor(new java.awt.Color(0, 0, 0));
jTextUpdate.setEnabled(false);
jTextUpdate.setPreferredSize(new java.awt.Dimension(70, 25));
jTextMissing.setBackground(new java.awt.Color(224, 223, 227));
jTextMissing.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
jTextMissing.setForeground(new java.awt.Color(102, 102, 102));
jTextMissing.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
jTextMissing.setBorder(null);
jTextMissing.setDisabledTextColor(new java.awt.Color(0, 0, 0));
jTextMissing.setEnabled(false);
jTextMissing.setPreferredSize(new java.awt.Dimension(70, 25));
jTextBadPrice.setBackground(new java.awt.Color(224, 223, 227));
jTextBadPrice.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
jTextBadPrice.setForeground(new java.awt.Color(102, 102, 102));
jTextBadPrice.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
jTextBadPrice.setBorder(null);
jTextBadPrice.setDisabledTextColor(new java.awt.Color(0, 0, 0));
jTextBadPrice.setEnabled(false);
jTextBadPrice.setPreferredSize(new java.awt.Dimension(70, 25));
jTextNoChange.setBackground(new java.awt.Color(224, 223, 227));
jTextNoChange.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
jTextNoChange.setForeground(new java.awt.Color(102, 102, 102));
jTextNoChange.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
jTextNoChange.setBorder(null);
jTextNoChange.setDisabledTextColor(new java.awt.Color(0, 0, 0));
jTextNoChange.setEnabled(false);
jTextNoChange.setPreferredSize(new java.awt.Dimension(70, 25));
jLabel19.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel19.setText(bundle.getString("label.cvsbadcats")); // NOI18N
jLabel19.setPreferredSize(new java.awt.Dimension(100, 25));
jTextBadCats.setBackground(new java.awt.Color(224, 223, 227));
jTextBadCats.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
jTextBadCats.setForeground(new java.awt.Color(102, 102, 102));
jTextBadCats.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
jTextBadCats.setBorder(null);
jTextBadCats.setDisabledTextColor(new java.awt.Color(0, 0, 0));
jTextBadCats.setEnabled(false);
jTextBadCats.setPreferredSize(new java.awt.Dimension(70, 25));
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextRecords, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jLabel19, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel13, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel16, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jTextUpdates, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel15, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel14, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextBadCats, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextNew, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextInvalid, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextUpdate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextMissing, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextBadPrice, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextNoChange, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap(26, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(0, 0, 0)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextRecords, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel14, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextNew, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel16, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextInvalid, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextUpdates, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextUpdate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextMissing, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel15, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextBadPrice, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel13, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextNoChange, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel19, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextBadCats, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jComboSeparator.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jComboSeparator.setPreferredSize(new java.awt.Dimension(50, 30));
jImport.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
jImport.setText(bundle.getString("label.csvimpostbtn")); // NOI18N
jImport.setEnabled(false);
jImport.setPreferredSize(new java.awt.Dimension(120, 30));
jImport.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jImportActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel17))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(jFileChooserPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(jLabel18, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jComboSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(106, 106, 106)
.addComponent(jHeaderRead, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jImport, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(8, 8, 8)))
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel17)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jFileChooserPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jComboSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel18, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jHeaderRead, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 359, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(53, 53, 53)
.addComponent(jImport, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
private void jHeaderReadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jHeaderReadActionPerformed
try {
GetheadersFromFile(jFileName.getText());
} catch (IOException ex) {
Logger.getLogger(JPanelCSVImport.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jHeaderReadActionPerformed
private void jImportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jImportActionPerformed
// prevent any more key presses
jImport.setEnabled(false);
try {
ImportCsvFile(jFileName.getText());
} catch (IOException ex) {
Logger.getLogger(JPanelCSVImport.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jImportActionPerformed
private void jFileNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jFileNameActionPerformed
jImport.setEnabled(false);
jHeaderRead.setEnabled(true);
}//GEN-LAST:event_jFileNameActionPerformed
private void jbtnDbDriverLibActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnDbDriverLibActionPerformed
resetFields();
// If CSV.last_file is null then use c:\ otherwise use saved dir
JFileChooser chooser = new JFileChooser(last_folder == null ? "C:\\" : last_folder);
FileNameExtensionFilter filter = new FileNameExtensionFilter("csv files", "csv");
chooser.setFileFilter(filter);
chooser.showOpenDialog(null);
File csvFile = chooser.getSelectedFile();
// check if a file was selected
if (csvFile == null) {
return;
}
File current_folder = chooser.getCurrentDirectory();
// If we have a file lets save the directory for later use if it's different from the old
if (last_folder == null || !last_folder.equals(current_folder.getAbsolutePath())) {
AppConfig CSVConfig = new AppConfig(config_file);
CSVConfig.load();
CSVConfig.setProperty("CSV.last_folder", current_folder.getAbsolutePath());
last_folder = current_folder.getAbsolutePath();
try {
CSVConfig.save();
} catch (IOException ex) {
Logger.getLogger(JPanelCSVImport.class.getName()).log(Level.SEVERE, null, ex);
}
}
String csv = csvFile.getName();
if (!(csv.trim().equals(""))) {
csvFileName = csvFile.getAbsolutePath();
jFileName.setText(csvFileName);
}
}//GEN-LAST:event_jbtnDbDriverLibActionPerformed
private void jComboDefaultCategoryActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboDefaultCategoryActionPerformed
checkFieldMapping();
}//GEN-LAST:event_jComboDefaultCategoryActionPerformed
private void jComboSellFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jComboSellFocusGained
jComboSell.removeAllItems();
int i = 1;
jComboSell.addItem("");
while (i < Headers.size()) {
if ((Headers.get(i) != jComboCategory.getSelectedItem()) & (Headers.get(i) != jComboReference.getSelectedItem()) & (Headers.get(i) != jComboName.getSelectedItem()) & (Headers.get(i) != jComboBuy.getSelectedItem()) & (Headers.get(i) != jComboBarcode.getSelectedItem())) {
jComboSell.addItem(Headers.get(i));
}
++i;
}
}//GEN-LAST:event_jComboSellFocusGained
private void jComboSellItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboSellItemStateChanged
checkFieldMapping();
}//GEN-LAST:event_jComboSellItemStateChanged
private void jComboBuyFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jComboBuyFocusGained
jComboBuy.removeAllItems();
int i = 1;
jComboBuy.addItem("");
while (i < Headers.size()) {
if ((Headers.get(i) != jComboCategory.getSelectedItem()) & (Headers.get(i) != jComboReference.getSelectedItem()) & (Headers.get(i) != jComboName.getSelectedItem()) & (Headers.get(i) != jComboBarcode.getSelectedItem()) & (Headers.get(i) != jComboSell.getSelectedItem())) {
jComboBuy.addItem(Headers.get(i));
}
++i;
}
}//GEN-LAST:event_jComboBuyFocusGained
private void jComboBuyItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboBuyItemStateChanged
checkFieldMapping();
}//GEN-LAST:event_jComboBuyItemStateChanged
private void jComboNameFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jComboNameFocusGained
jComboName.removeAllItems();
int i = 1;
jComboName.addItem("");
while (i < Headers.size()) {
if ((Headers.get(i) != jComboCategory.getSelectedItem()) & (Headers.get(i) != jComboReference.getSelectedItem()) & (Headers.get(i) != jComboBarcode.getSelectedItem()) & (Headers.get(i) != jComboBuy.getSelectedItem()) & (Headers.get(i) != jComboSell.getSelectedItem())) {
jComboName.addItem(Headers.get(i));
}
++i;
}
}//GEN-LAST:event_jComboNameFocusGained
private void jComboNameItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboNameItemStateChanged
checkFieldMapping();
}//GEN-LAST:event_jComboNameItemStateChanged
private void jComboBarcodeFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jComboBarcodeFocusGained
jComboBarcode.removeAllItems();
int i = 1;
jComboBarcode.addItem("");
while (i < Headers.size()) {
if ((Headers.get(i) != jComboCategory.getSelectedItem()) & (Headers.get(i) != jComboReference.getSelectedItem()) & (Headers.get(i) != jComboName.getSelectedItem()) & (Headers.get(i) != jComboBuy.getSelectedItem()) & (Headers.get(i) != jComboSell.getSelectedItem())) {
jComboBarcode.addItem(Headers.get(i));
}
++i;
}
}//GEN-LAST:event_jComboBarcodeFocusGained
private void jComboBarcodeItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboBarcodeItemStateChanged
checkFieldMapping();
}//GEN-LAST:event_jComboBarcodeItemStateChanged
private void jComboReferenceFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jComboReferenceFocusGained
jComboReference.removeAllItems();
int i = 1;
jComboReference.addItem("");
while (i < Headers.size()) {
if ((Headers.get(i) != jComboCategory.getSelectedItem()) & (Headers.get(i) != jComboBarcode.getSelectedItem()) & (Headers.get(i) != jComboName.getSelectedItem()) & (Headers.get(i) != jComboBuy.getSelectedItem()) & (Headers.get(i) != jComboSell.getSelectedItem())) {
jComboReference.addItem(Headers.get(i));
}
++i;
}
}//GEN-LAST:event_jComboReferenceFocusGained
private void jComboReferenceItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboReferenceItemStateChanged
checkFieldMapping();
}//GEN-LAST:event_jComboReferenceItemStateChanged
private void jComboCategoryItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboCategoryItemStateChanged
// if we have not selected [ USE DEFAULT CATEGORY ] allow the [ REJECT ITEMS WITH BAD CATEGORIES ] to be used in default category combo box
try {
if (jComboCategory.getSelectedItem() == "[ USE DEFAULT CATEGORY ]") {
m_CategoryModel = new ComboBoxValModel(m_sentcat.list());
jComboDefaultCategory.setModel(m_CategoryModel);
} else {
m_CategoryModel = new ComboBoxValModel(m_sentcat.list());
m_CategoryModel.add(reject_bad_categories_text);
jComboDefaultCategory.setModel(m_CategoryModel);
}
} catch (BasicException ex) {
Logger.getLogger(JPanelCSVImport.class.getName()).log(Level.SEVERE, null, ex);
}
checkFieldMapping();
}//GEN-LAST:event_jComboCategoryItemStateChanged
private void jComboCategoryFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jComboCategoryFocusGained
jComboCategory.removeAllItems();
int i = 1;
jComboCategory.addItem("");
while (i < Headers.size()) {
if ((Headers.get(i) != jComboBarcode.getSelectedItem()) & (Headers.get(i) != jComboReference.getSelectedItem())
& (Headers.get(i) != jComboName.getSelectedItem()) & (Headers.get(i) != jComboBuy.getSelectedItem())
& (Headers.get(i) != jComboSell.getSelectedItem())) {
jComboCategory.addItem(Headers.get(i));
}
++i;
}
jComboCategory.addItem(category_disable_text);
}//GEN-LAST:event_jComboCategoryFocusGained
private void jComboDefaulrCategoryItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboDefaulrCategoryItemStateChanged
// TODO add your handling code here:
}//GEN-LAST:event_jComboDefaulrCategoryItemStateChanged
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JCheckBox jCheckInCatalogue;
private javax.swing.JCheckBox jCheckSellIncTax;
private javax.swing.JComboBox jComboBarcode;
private javax.swing.JComboBox jComboBuy;
private javax.swing.JComboBox jComboCategory;
private javax.swing.JComboBox jComboDefaultCategory;
private javax.swing.JComboBox jComboName;
private javax.swing.JComboBox jComboReference;
private javax.swing.JComboBox jComboSell;
private javax.swing.JComboBox jComboSeparator;
private javax.swing.JComboBox jComboTax;
private javax.swing.JPanel jFileChooserPanel;
private javax.swing.JTextField jFileName;
private javax.swing.JButton jHeaderRead;
private javax.swing.JButton jImport;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel17;
private javax.swing.JLabel jLabel18;
private javax.swing.JLabel jLabel19;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel20;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JTextField jTextBadCats;
private javax.swing.JTextField jTextBadPrice;
private javax.swing.JTextField jTextInvalid;
private javax.swing.JTextField jTextMissing;
private javax.swing.JTextField jTextNew;
private javax.swing.JTextField jTextNoChange;
private javax.swing.JTextField jTextRecords;
private javax.swing.JTextField jTextUpdate;
private javax.swing.JLabel jTextUpdates;
private javax.swing.JButton jbtnDbDriverLib;
// End of variables declaration//GEN-END:variables
}
| gpl-3.0 |
s20121035/rk3288_android5.1_repo | cts/tools/vm-tests-tf/src/dot/junit/opcodes/sget_short/d/T_sget_short_9.java | 747 | /*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dot.junit.opcodes.sget_short.d;
public class T_sget_short_9 {
public short run(){
return 0;
}
}
| gpl-3.0 |
kingtang/spring-learn | spring-orm/src/main/java/org/springframework/orm/jpa/JpaObjectRetrievalFailureException.java | 1230 | /*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.orm.jpa;
import javax.persistence.EntityNotFoundException;
import org.springframework.orm.ObjectRetrievalFailureException;
/**
* JPA-specific subclass of ObjectRetrievalFailureException.
* Converts JPA's EntityNotFoundException.
*
* @author Juergen Hoeller
* @since 2.0
* @see EntityManagerFactoryUtils#convertJpaAccessExceptionIfPossible
*/
@SuppressWarnings("serial")
public class JpaObjectRetrievalFailureException extends ObjectRetrievalFailureException {
public JpaObjectRetrievalFailureException(EntityNotFoundException ex) {
super(ex.getMessage(), ex);
}
}
| gpl-3.0 |
guardianproject/InformaCore | src/org/witness/informacam/informa/suckers/EnvironmentalSucker.java | 5828 | package org.witness.informacam.informa.suckers;
import java.util.List;
import java.util.TimerTask;
import org.witness.informacam.informa.SensorLogger;
import org.witness.informacam.json.JSONException;
import org.witness.informacam.models.j3m.ILogPack;
import org.witness.informacam.models.utils.PressureServiceUpdater;
import org.witness.informacam.utils.Constants.Suckers;
import org.witness.informacam.utils.Constants.Suckers.Environment;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.AsyncTask;
import android.util.Log;
@SuppressWarnings("rawtypes")
public class EnvironmentalSucker extends SensorLogger implements SensorEventListener {
SensorManager sm;
List<Sensor> availableSensors;
org.witness.informacam.models.j3m.ILogPack currentAmbientTemp, currentDeviceTemp, currentHumidity, currentPressure, currentLight;
float mPressureSeaLevel = SensorManager.PRESSURE_STANDARD_ATMOSPHERE;
private final static String LOG = Suckers.LOG;
@SuppressWarnings({ "unchecked", "deprecation" })
public EnvironmentalSucker(Context context) {
super(context);
setSucker(this);
sm = (SensorManager)context.getApplicationContext().getSystemService(Context.SENSOR_SERVICE);
availableSensors = sm.getSensorList(Sensor.TYPE_ALL);
for(Sensor s : availableSensors) {
switch(s.getType()) {
case Sensor.TYPE_AMBIENT_TEMPERATURE:
sm.registerListener(this, s, SensorManager.SENSOR_DELAY_NORMAL);
break;
case Sensor.TYPE_RELATIVE_HUMIDITY:
sm.registerListener(this, s, SensorManager.SENSOR_DELAY_NORMAL);
break;
case Sensor.TYPE_PRESSURE:
sm.registerListener(this, s, SensorManager.SENSOR_DELAY_NORMAL);
break;
case Sensor.TYPE_LIGHT:
sm.registerListener(this, s, SensorManager.SENSOR_DELAY_NORMAL);
break;
case Sensor.TYPE_TEMPERATURE:
sm.registerListener(this, s, SensorManager.SENSOR_DELAY_NORMAL);
break;
}
}
setTask(new TimerTask() {
@Override
public void run() {
if(currentAmbientTemp != null)
sendToBuffer(currentAmbientTemp);
if(currentDeviceTemp != null)
sendToBuffer(currentDeviceTemp);
if(currentHumidity != null)
sendToBuffer(currentHumidity);
if(currentPressure != null)
sendToBuffer(currentPressure);
if(currentLight != null)
sendToBuffer(currentLight);
}
});
getTimer().schedule(getTask(), 0, Environment.LOG_RATE);
}
public ILogPack forceReturn() throws JSONException {
ILogPack fr = new ILogPack();
if (currentAmbientTemp != null)
fr.put(Environment.Keys.AMBIENT_TEMP, currentAmbientTemp);
if (currentDeviceTemp != null)
fr.put(Environment.Keys.DEVICE_TEMP, currentDeviceTemp);
if (currentHumidity != null)
fr.put(Environment.Keys.HUMIDITY, currentHumidity);
if (currentPressure != null)
fr.put(Environment.Keys.PRESSURE, currentPressure);
if (currentLight != null)
fr.put(Environment.Keys.LIGHT, currentLight);
return fr;
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {}
/**
*
Sensor Sensor event data Units of measure Data description
TYPE_AMBIENT_TEMPERATURE event.values[0] °C Ambient air temperature.
TYPE_LIGHT event.values[0] lx Illuminance.
TYPE_PRESSURE event.values[0] hPa or mbar Ambient air pressure.
TYPE_RELATIVE_HUMIDITY event.values[0] % Ambient relative humidity.
TYPE_TEMPERATURE event.values[0] °C Device temperature.1
*/
@SuppressWarnings("deprecation")
@Override
public void onSensorChanged(SensorEvent event) {
synchronized(this) {
if(getIsRunning()) {
ILogPack sVals = new ILogPack();
try {
switch(event.sensor.getType()) {
case Sensor.TYPE_AMBIENT_TEMPERATURE:
sVals.put(Environment.Keys.AMBIENT_TEMP_CELSIUS, event.values[0]);
currentAmbientTemp = sVals;
break;
case Sensor.TYPE_TEMPERATURE:
sVals.put(Environment.Keys.DEVICE_TEMP_CELSIUS, event.values[0]);
currentDeviceTemp = sVals;
break;
case Sensor.TYPE_RELATIVE_HUMIDITY:
sVals.put(Environment.Keys.HUMIDITY_PERC,event.values[0]);
currentHumidity = sVals;
break;
case Sensor.TYPE_PRESSURE:
sVals.put(Environment.Keys.PRESSURE_MBAR, event.values[0]);
//TODO we need to get real local sea level pressure here from a dynamic source
//as the default value doesn't cut it
float altitudeFromPressure = SensorManager.getAltitude(mPressureSeaLevel, event.values[0]);
sVals.put(Environment.Keys.PRESSURE_ALTITUDE, altitudeFromPressure);
currentPressure = sVals;
break;
case Sensor.TYPE_LIGHT:
sVals.put(Environment.Keys.LIGHT_METER_VALUE, event.values[0]);
currentLight = sVals;
break;
}
} catch(JSONException e) {}
}
}
}
public void stopUpdates() {
setIsRunning(false);
sm.unregisterListener(this);
Log.d(LOG, "shutting down EnviroSucker...");
}
public void updateSeaLevelPressure (final double latitude, final double longitude)
{
new AsyncTask<Double, Void, Float>() {
@Override
protected Float doInBackground(Double... params) {
return PressureServiceUpdater.GetRefPressure(params[0],params[1]);
}
@Override
protected void onPostExecute(Float result) {
mPressureSeaLevel = result.floatValue();
Log.d("Pressure","got updated sea level pressure: " + mPressureSeaLevel);
}
@Override
protected void onPreExecute() {
}
@Override
protected void onProgressUpdate(Void... values) {
}
}.execute(latitude, longitude);
}
} | gpl-3.0 |
open-health-hub/openMAXIMS | openmaxims_workspace/ValueObjects/src/ims/therapies/vo/beans/StretchingDetailsVoBean.java | 4034 | //#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.therapies.vo.beans;
public class StretchingDetailsVoBean extends ims.vo.ValueObjectBean
{
public StretchingDetailsVoBean()
{
}
public StretchingDetailsVoBean(ims.therapies.vo.StretchingDetailsVo vo)
{
this.id = vo.getBoId();
this.version = vo.getBoVersion();
this.stretchingarea = vo.getStretchingArea() == null ? null : (ims.vo.LookupInstanceBean)vo.getStretchingArea().getBean();
this.active = vo.getActive();
this.passive = vo.getPassive();
this.comment = vo.getComment();
}
public void populate(ims.vo.ValueObjectBeanMap map, ims.therapies.vo.StretchingDetailsVo vo)
{
this.id = vo.getBoId();
this.version = vo.getBoVersion();
this.stretchingarea = vo.getStretchingArea() == null ? null : (ims.vo.LookupInstanceBean)vo.getStretchingArea().getBean();
this.active = vo.getActive();
this.passive = vo.getPassive();
this.comment = vo.getComment();
}
public ims.therapies.vo.StretchingDetailsVo buildVo()
{
return this.buildVo(new ims.vo.ValueObjectBeanMap());
}
public ims.therapies.vo.StretchingDetailsVo buildVo(ims.vo.ValueObjectBeanMap map)
{
ims.therapies.vo.StretchingDetailsVo vo = null;
if(map != null)
vo = (ims.therapies.vo.StretchingDetailsVo)map.getValueObject(this);
if(vo == null)
{
vo = new ims.therapies.vo.StretchingDetailsVo();
map.addValueObject(this, vo);
vo.populate(map, this);
}
return vo;
}
public Integer getId()
{
return this.id;
}
public void setId(Integer value)
{
this.id = value;
}
public int getVersion()
{
return this.version;
}
public void setVersion(int value)
{
this.version = value;
}
public ims.vo.LookupInstanceBean getStretchingArea()
{
return this.stretchingarea;
}
public void setStretchingArea(ims.vo.LookupInstanceBean value)
{
this.stretchingarea = value;
}
public Boolean getActive()
{
return this.active;
}
public void setActive(Boolean value)
{
this.active = value;
}
public Boolean getPassive()
{
return this.passive;
}
public void setPassive(Boolean value)
{
this.passive = value;
}
public String getComment()
{
return this.comment;
}
public void setComment(String value)
{
this.comment = value;
}
private Integer id;
private int version;
private ims.vo.LookupInstanceBean stretchingarea;
private Boolean active;
private Boolean passive;
private String comment;
}
| agpl-3.0 |
open-health-hub/openMAXIMS | openmaxims_workspace/ValueObjects/src/ims/emergency/vo/beans/PendingEmergencyAdmissionForDischargeVoBean.java | 7240 | //#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.emergency.vo.beans;
public class PendingEmergencyAdmissionForDischargeVoBean extends ims.vo.ValueObjectBean
{
public PendingEmergencyAdmissionForDischargeVoBean()
{
}
public PendingEmergencyAdmissionForDischargeVoBean(ims.emergency.vo.PendingEmergencyAdmissionForDischargeVo vo)
{
this.id = vo.getBoId();
this.version = vo.getBoVersion();
this.admissionstatus = vo.getAdmissionStatus() == null ? null : (ims.vo.LookupInstanceBean)vo.getAdmissionStatus().getBean();
this.conclusiondate = vo.getConclusionDate() == null ? null : (ims.framework.utils.beans.DateTimeBean)vo.getConclusionDate().getBean();
this.pasevent = vo.getPasEvent() == null ? null : (ims.core.vo.beans.PasEventShortVoBean)vo.getPasEvent().getBean();
this.dtadatetime = vo.getDTADateTime() == null ? null : (ims.framework.utils.beans.DateTimeBean)vo.getDTADateTime().getBean();
this.currentlocation = vo.getCurrentLocation() == null ? null : (ims.core.vo.beans.LocationLiteVoBean)vo.getCurrentLocation().getBean();
this.admissiontype = vo.getAdmissionType() == null ? null : (ims.vo.LookupInstanceBean)vo.getAdmissionType().getBean();
this.bedtyperequested = vo.getBedTypeRequested() == null ? null : (ims.vo.LookupInstanceBean)vo.getBedTypeRequested().getBean();
this.allocatedward = vo.getAllocatedWard() == null ? null : new ims.vo.RefVoBean(vo.getAllocatedWard().getBoId(), vo.getAllocatedWard().getBoVersion());
}
public void populate(ims.vo.ValueObjectBeanMap map, ims.emergency.vo.PendingEmergencyAdmissionForDischargeVo vo)
{
this.id = vo.getBoId();
this.version = vo.getBoVersion();
this.admissionstatus = vo.getAdmissionStatus() == null ? null : (ims.vo.LookupInstanceBean)vo.getAdmissionStatus().getBean();
this.conclusiondate = vo.getConclusionDate() == null ? null : (ims.framework.utils.beans.DateTimeBean)vo.getConclusionDate().getBean();
this.pasevent = vo.getPasEvent() == null ? null : (ims.core.vo.beans.PasEventShortVoBean)vo.getPasEvent().getBean(map);
this.dtadatetime = vo.getDTADateTime() == null ? null : (ims.framework.utils.beans.DateTimeBean)vo.getDTADateTime().getBean();
this.currentlocation = vo.getCurrentLocation() == null ? null : (ims.core.vo.beans.LocationLiteVoBean)vo.getCurrentLocation().getBean(map);
this.admissiontype = vo.getAdmissionType() == null ? null : (ims.vo.LookupInstanceBean)vo.getAdmissionType().getBean();
this.bedtyperequested = vo.getBedTypeRequested() == null ? null : (ims.vo.LookupInstanceBean)vo.getBedTypeRequested().getBean();
this.allocatedward = vo.getAllocatedWard() == null ? null : new ims.vo.RefVoBean(vo.getAllocatedWard().getBoId(), vo.getAllocatedWard().getBoVersion());
}
public ims.emergency.vo.PendingEmergencyAdmissionForDischargeVo buildVo()
{
return this.buildVo(new ims.vo.ValueObjectBeanMap());
}
public ims.emergency.vo.PendingEmergencyAdmissionForDischargeVo buildVo(ims.vo.ValueObjectBeanMap map)
{
ims.emergency.vo.PendingEmergencyAdmissionForDischargeVo vo = null;
if(map != null)
vo = (ims.emergency.vo.PendingEmergencyAdmissionForDischargeVo)map.getValueObject(this);
if(vo == null)
{
vo = new ims.emergency.vo.PendingEmergencyAdmissionForDischargeVo();
map.addValueObject(this, vo);
vo.populate(map, this);
}
return vo;
}
public Integer getId()
{
return this.id;
}
public void setId(Integer value)
{
this.id = value;
}
public int getVersion()
{
return this.version;
}
public void setVersion(int value)
{
this.version = value;
}
public ims.vo.LookupInstanceBean getAdmissionStatus()
{
return this.admissionstatus;
}
public void setAdmissionStatus(ims.vo.LookupInstanceBean value)
{
this.admissionstatus = value;
}
public ims.framework.utils.beans.DateTimeBean getConclusionDate()
{
return this.conclusiondate;
}
public void setConclusionDate(ims.framework.utils.beans.DateTimeBean value)
{
this.conclusiondate = value;
}
public ims.core.vo.beans.PasEventShortVoBean getPasEvent()
{
return this.pasevent;
}
public void setPasEvent(ims.core.vo.beans.PasEventShortVoBean value)
{
this.pasevent = value;
}
public ims.framework.utils.beans.DateTimeBean getDTADateTime()
{
return this.dtadatetime;
}
public void setDTADateTime(ims.framework.utils.beans.DateTimeBean value)
{
this.dtadatetime = value;
}
public ims.core.vo.beans.LocationLiteVoBean getCurrentLocation()
{
return this.currentlocation;
}
public void setCurrentLocation(ims.core.vo.beans.LocationLiteVoBean value)
{
this.currentlocation = value;
}
public ims.vo.LookupInstanceBean getAdmissionType()
{
return this.admissiontype;
}
public void setAdmissionType(ims.vo.LookupInstanceBean value)
{
this.admissiontype = value;
}
public ims.vo.LookupInstanceBean getBedTypeRequested()
{
return this.bedtyperequested;
}
public void setBedTypeRequested(ims.vo.LookupInstanceBean value)
{
this.bedtyperequested = value;
}
public ims.vo.RefVoBean getAllocatedWard()
{
return this.allocatedward;
}
public void setAllocatedWard(ims.vo.RefVoBean value)
{
this.allocatedward = value;
}
private Integer id;
private int version;
private ims.vo.LookupInstanceBean admissionstatus;
private ims.framework.utils.beans.DateTimeBean conclusiondate;
private ims.core.vo.beans.PasEventShortVoBean pasevent;
private ims.framework.utils.beans.DateTimeBean dtadatetime;
private ims.core.vo.beans.LocationLiteVoBean currentlocation;
private ims.vo.LookupInstanceBean admissiontype;
private ims.vo.LookupInstanceBean bedtyperequested;
private ims.vo.RefVoBean allocatedward;
}
| agpl-3.0 |
open-health-hub/openMAXIMS | openmaxims_workspace/ValueObjects/src/ims/nursing/vo/lookups/SkinExudateType.java | 4749 | //#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.nursing.vo.lookups;
import ims.framework.cn.data.TreeNode;
import java.util.ArrayList;
import ims.framework.utils.Image;
import ims.framework.utils.Color;
public class SkinExudateType extends ims.vo.LookupInstVo implements TreeNode
{
private static final long serialVersionUID = 1L;
public SkinExudateType()
{
super();
}
public SkinExudateType(int id)
{
super(id, "", true);
}
public SkinExudateType(int id, String text, boolean active)
{
super(id, text, active, null, null, null);
}
public SkinExudateType(int id, String text, boolean active, SkinExudateType parent, Image image)
{
super(id, text, active, parent, image);
}
public SkinExudateType(int id, String text, boolean active, SkinExudateType parent, Image image, Color color)
{
super(id, text, active, parent, image, color);
}
public SkinExudateType(int id, String text, boolean active, SkinExudateType parent, Image image, Color color, int order)
{
super(id, text, active, parent, image, color, order);
}
public static SkinExudateType buildLookup(ims.vo.LookupInstanceBean bean)
{
return new SkinExudateType(bean.getId(), bean.getText(), bean.isActive());
}
public String toString()
{
if(getText() != null)
return getText();
return "";
}
public TreeNode getParentNode()
{
return (SkinExudateType)super.getParentInstance();
}
public SkinExudateType getParent()
{
return (SkinExudateType)super.getParentInstance();
}
public void setParent(SkinExudateType parent)
{
super.setParentInstance(parent);
}
public TreeNode[] getChildren()
{
ArrayList children = super.getChildInstances();
SkinExudateType[] typedChildren = new SkinExudateType[children.size()];
for (int i = 0; i < children.size(); i++)
{
typedChildren[i] = (SkinExudateType)children.get(i);
}
return typedChildren;
}
public int addChild(TreeNode child)
{
if (child instanceof SkinExudateType)
{
super.addChild((SkinExudateType)child);
}
return super.getChildInstances().size();
}
public int removeChild(TreeNode child)
{
if (child instanceof SkinExudateType)
{
super.removeChild((SkinExudateType)child);
}
return super.getChildInstances().size();
}
public Image getExpandedImage()
{
return super.getImage();
}
public Image getCollapsedImage()
{
return super.getImage();
}
public static ims.framework.IItemCollection getNegativeInstancesAsIItemCollection()
{
SkinExudateTypeCollection result = new SkinExudateTypeCollection();
return result;
}
public static SkinExudateType[] getNegativeInstances()
{
return new SkinExudateType[] {};
}
public static String[] getNegativeInstanceNames()
{
return new String[] {};
}
public static SkinExudateType getNegativeInstance(String name)
{
if(name == null)
return null;
// No negative instances found
return null;
}
public static SkinExudateType getNegativeInstance(Integer id)
{
if(id == null)
return null;
// No negative instances found
return null;
}
public int getTypeId()
{
return TYPE_ID;
}
public static final int TYPE_ID = 1001032;
}
| agpl-3.0 |
open-health-hub/openMAXIMS | openmaxims_workspace/RefMan/src/ims/RefMan/forms/clinicalnotes/BaseAccessLogic.java | 3488 | // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.RefMan.forms.clinicalnotes;
import java.io.Serializable;
import ims.framework.Context;
import ims.framework.FormName;
import ims.framework.FormAccessLogic;
public class BaseAccessLogic extends FormAccessLogic implements Serializable
{
private static final long serialVersionUID = 1L;
public final void setContext(Context context, FormName formName)
{
form = new CurrentForm(new GlobalContext(context), new CurrentForms());
engine = new CurrentEngine(formName);
}
public boolean isAccessible()
{
if(!form.getGlobalContext().RefMan.getCatsReferralIsNotNull())
return false;
if(!form.getGlobalContext().Core.getPatientShortIsNotNull())
return false;
if(!form.getGlobalContext().Core.getCurrentCareContextIsNotNull())
return false;
if(!form.getGlobalContext().Core.getEpisodeofCareShortIsNotNull())
return false;
return true;
}
public boolean isReadOnly()
{
return false;
}
public CurrentEngine engine;
public CurrentForm form;
public final static class CurrentForm implements Serializable
{
private static final long serialVersionUID = 1L;
CurrentForm(GlobalContext globalcontext, CurrentForms forms)
{
this.globalcontext = globalcontext;
this.forms = forms;
}
public final GlobalContext getGlobalContext()
{
return globalcontext;
}
public final CurrentForms getForms()
{
return forms;
}
private GlobalContext globalcontext;
private CurrentForms forms;
}
public final static class CurrentEngine implements Serializable
{
private static final long serialVersionUID = 1L;
CurrentEngine(FormName formName)
{
this.formName = formName;
}
public final FormName getFormName()
{
return formName;
}
private FormName formName;
}
public static final class CurrentForms implements Serializable
{
private static final long serialVersionUID = 1L;
protected final class LocalFormName extends FormName
{
private static final long serialVersionUID = 1L;
protected LocalFormName(int value)
{
super(value);
}
}
private CurrentForms()
{
RefMan = new RefManForms();
Core = new CoreForms();
}
public final class RefManForms implements Serializable
{
private static final long serialVersionUID = 1L;
private RefManForms()
{
ClinicalNoteDialog = new LocalFormName(134195);
PatientDiagnosisDialog = new LocalFormName(134201);
PatientProcedureDialog = new LocalFormName(134202);
PreviousReferralsDialog = new LocalFormName(134204);
AppointmentPatientDiagnosisDialog = new LocalFormName(134211);
AppointmentPatientProcedureDialog = new LocalFormName(134212);
}
public final FormName ClinicalNoteDialog;
public final FormName PatientDiagnosisDialog;
public final FormName PatientProcedureDialog;
public final FormName PreviousReferralsDialog;
public final FormName AppointmentPatientDiagnosisDialog;
public final FormName AppointmentPatientProcedureDialog;
}
public final class CoreForms implements Serializable
{
private static final long serialVersionUID = 1L;
private CoreForms()
{
PatientDocumentView = new LocalFormName(102335);
}
public final FormName PatientDocumentView;
}
public RefManForms RefMan;
public CoreForms Core;
}
}
| agpl-3.0 |
open-health-hub/openMAXIMS | openmaxims_workspace/ValueObjects/src/ims/ocrr/vo/beans/InvestigationShortVoBean.java | 3955 | //#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.ocrr.vo.beans;
public class InvestigationShortVoBean extends ims.vo.ValueObjectBean
{
public InvestigationShortVoBean()
{
}
public InvestigationShortVoBean(ims.ocrr.vo.InvestigationShortVo vo)
{
this.id = vo.getBoId();
this.version = vo.getBoVersion();
this.activestatus = vo.getActiveStatus() == null ? null : (ims.vo.LookupInstanceBean)vo.getActiveStatus().getBean();
this.investigationindex = vo.getInvestigationIndex() == null ? null : (ims.ocrr.vo.beans.InvestigationIndexVoBean)vo.getInvestigationIndex().getBean();
}
public void populate(ims.vo.ValueObjectBeanMap map, ims.ocrr.vo.InvestigationShortVo vo)
{
this.id = vo.getBoId();
this.version = vo.getBoVersion();
this.activestatus = vo.getActiveStatus() == null ? null : (ims.vo.LookupInstanceBean)vo.getActiveStatus().getBean();
this.investigationindex = vo.getInvestigationIndex() == null ? null : (ims.ocrr.vo.beans.InvestigationIndexVoBean)vo.getInvestigationIndex().getBean(map);
}
public ims.ocrr.vo.InvestigationShortVo buildVo()
{
return this.buildVo(new ims.vo.ValueObjectBeanMap());
}
public ims.ocrr.vo.InvestigationShortVo buildVo(ims.vo.ValueObjectBeanMap map)
{
ims.ocrr.vo.InvestigationShortVo vo = null;
if(map != null)
vo = (ims.ocrr.vo.InvestigationShortVo)map.getValueObject(this);
if(vo == null)
{
vo = new ims.ocrr.vo.InvestigationShortVo();
map.addValueObject(this, vo);
vo.populate(map, this);
}
return vo;
}
public Integer getId()
{
return this.id;
}
public void setId(Integer value)
{
this.id = value;
}
public int getVersion()
{
return this.version;
}
public void setVersion(int value)
{
this.version = value;
}
public ims.vo.LookupInstanceBean getActiveStatus()
{
return this.activestatus;
}
public void setActiveStatus(ims.vo.LookupInstanceBean value)
{
this.activestatus = value;
}
public ims.ocrr.vo.beans.InvestigationIndexVoBean getInvestigationIndex()
{
return this.investigationindex;
}
public void setInvestigationIndex(ims.ocrr.vo.beans.InvestigationIndexVoBean value)
{
this.investigationindex = value;
}
private Integer id;
private int version;
private ims.vo.LookupInstanceBean activestatus;
private ims.ocrr.vo.beans.InvestigationIndexVoBean investigationindex;
}
| agpl-3.0 |
open-health-hub/openMAXIMS | openmaxims_workspace/ValueObjects/src/ims/RefMan/vo/CatsReferralForClinicListVo.java | 4680 | // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.RefMan.vo;
/**
* Linked to RefMan.CatsReferral business object (ID: 1004100035).
*/
public class CatsReferralForClinicListVo extends ims.RefMan.vo.CatsReferralRefVo implements ims.vo.ImsCloneable, Comparable
{
private static final long serialVersionUID = 1L;
public CatsReferralForClinicListVo()
{
}
public CatsReferralForClinicListVo(Integer id, int version)
{
super(id, version);
}
public CatsReferralForClinicListVo(ims.RefMan.vo.beans.CatsReferralForClinicListVoBean bean)
{
this.id = bean.getId();
this.version = bean.getVersion();
this.hasdnaapptsforreview = bean.getHasDNAApptsForReview();
}
public void populate(ims.vo.ValueObjectBeanMap map, ims.RefMan.vo.beans.CatsReferralForClinicListVoBean bean)
{
this.id = bean.getId();
this.version = bean.getVersion();
this.hasdnaapptsforreview = bean.getHasDNAApptsForReview();
}
public ims.vo.ValueObjectBean getBean()
{
return this.getBean(new ims.vo.ValueObjectBeanMap());
}
public ims.vo.ValueObjectBean getBean(ims.vo.ValueObjectBeanMap map)
{
ims.RefMan.vo.beans.CatsReferralForClinicListVoBean bean = null;
if(map != null)
bean = (ims.RefMan.vo.beans.CatsReferralForClinicListVoBean)map.getValueObjectBean(this);
if (bean == null)
{
bean = new ims.RefMan.vo.beans.CatsReferralForClinicListVoBean();
map.addValueObjectBean(this, bean);
bean.populate(map, this);
}
return bean;
}
public Object getFieldValueByFieldName(String fieldName)
{
if(fieldName == null)
throw new ims.framework.exceptions.CodingRuntimeException("Invalid field name");
fieldName = fieldName.toUpperCase();
if(fieldName.equals("HASDNAAPPTSFORREVIEW"))
return getHasDNAApptsForReview();
return super.getFieldValueByFieldName(fieldName);
}
public boolean getHasDNAApptsForReviewIsNotNull()
{
return this.hasdnaapptsforreview != null;
}
public Boolean getHasDNAApptsForReview()
{
return this.hasdnaapptsforreview;
}
public void setHasDNAApptsForReview(Boolean value)
{
this.isValidated = false;
this.hasdnaapptsforreview = value;
}
public boolean isValidated()
{
if(this.isBusy)
return true;
this.isBusy = true;
if(!this.isValidated)
{
this.isBusy = false;
return false;
}
this.isBusy = false;
return true;
}
public String[] validate()
{
return validate(null);
}
public String[] validate(String[] existingErrors)
{
if(this.isBusy)
return null;
this.isBusy = true;
java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>();
if(existingErrors != null)
{
for(int x = 0; x < existingErrors.length; x++)
{
listOfErrors.add(existingErrors[x]);
}
}
int errorCount = listOfErrors.size();
if(errorCount == 0)
{
this.isBusy = false;
this.isValidated = true;
return null;
}
String[] result = new String[errorCount];
for(int x = 0; x < errorCount; x++)
result[x] = (String)listOfErrors.get(x);
this.isBusy = false;
this.isValidated = false;
return result;
}
public void clearIDAndVersion()
{
this.id = null;
this.version = 0;
}
public Object clone()
{
if(this.isBusy)
return this;
this.isBusy = true;
CatsReferralForClinicListVo clone = new CatsReferralForClinicListVo(this.id, this.version);
clone.hasdnaapptsforreview = this.hasdnaapptsforreview;
clone.isValidated = this.isValidated;
this.isBusy = false;
return clone;
}
public int compareTo(Object obj)
{
return compareTo(obj, true);
}
public int compareTo(Object obj, boolean caseInsensitive)
{
if (obj == null)
{
return -1;
}
if(caseInsensitive); // this is to avoid eclipse warning only.
if (!(CatsReferralForClinicListVo.class.isAssignableFrom(obj.getClass())))
{
throw new ClassCastException("A CatsReferralForClinicListVo object cannot be compared an Object of type " + obj.getClass().getName());
}
if (this.id == null)
return 1;
if (((CatsReferralForClinicListVo)obj).getBoId() == null)
return -1;
return this.id.compareTo(((CatsReferralForClinicListVo)obj).getBoId());
}
public synchronized static int generateValueObjectUniqueID()
{
return ims.vo.ValueObject.generateUniqueID();
}
public int countFieldsWithValue()
{
int count = 0;
if(this.hasdnaapptsforreview != null)
count++;
return count;
}
public int countValueObjectFields()
{
return 1;
}
protected Boolean hasdnaapptsforreview;
private boolean isValidated = false;
private boolean isBusy = false;
}
| agpl-3.0 |
cfallin/soot | src/soot/coffi/Instruction_Faload.java | 2477 | /* Soot - a J*va Optimization Framework
* Copyright (C) 1997 Clark Verbrugge
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/*
* Modified by the Sable Research Group and others 1997-1999.
* See the 'credits' file distributed with Soot for the complete list of
* contributors. (Soot is distributed at http://www.sable.mcgill.ca/soot)
*/
package soot.coffi;
/** Instruction subclasses are used to represent parsed bytecode; each
* bytecode operation has a corresponding subclass of Instruction.
* <p>
* Each subclass is derived from one of
* <ul><li>Instruction</li>
* <li>Instruction_noargs (an Instruction with no embedded arguments)</li>
* <li>Instruction_byte (an Instruction with a single byte data argument)</li>
* <li>Instruction_bytevar (a byte argument specifying a local variable)</li>
* <li>Instruction_byteindex (a byte argument specifying a constant pool index)</li>
* <li>Instruction_int (an Instruction with a single short data argument)</li>
* <li>Instruction_intvar (a short argument specifying a local variable)</li>
* <li>Instruction_intindex (a short argument specifying a constant pool index)</li>
* <li>Instruction_intbranch (a short argument specifying a code offset)</li>
* <li>Instruction_longbranch (an int argument specifying a code offset)</li>
* </ul>
* @author Clark Verbrugge
* @see Instruction
* @see Instruction_noargs
* @see Instruction_byte
* @see Instruction_bytevar
* @see Instruction_byteindex
* @see Instruction_int
* @see Instruction_intvar
* @see Instruction_intindex
* @see Instruction_intbranch
* @see Instruction_longbranch
* @see Instruction_Unknown
*/
class Instruction_Faload extends Instruction_noargs {
public Instruction_Faload() { super((byte)ByteCode.FALOAD); name = "faload"; }
}
| lgpl-2.1 |
JSansalone/JFreeChart | tests/org/jfree/data/xy/junit/XYDataItemTests.java | 3858 | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2011, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library 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 Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.]
*
* --------------------
* XYDataItemTests.java
* --------------------
* (C) Copyright 2003-2009, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 23-Dec-2003 : Version 1 (DG);
*
*/
package org.jfree.data.xy.junit;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.jfree.data.xy.XYDataItem;
/**
* Tests for the {@link XYDataItem} class.
*/
public class XYDataItemTests extends TestCase {
/**
* Returns the tests as a test suite.
*
* @return The test suite.
*/
public static Test suite() {
return new TestSuite(XYDataItemTests.class);
}
/**
* Constructs a new set of tests.
*
* @param name the name of the tests.
*/
public XYDataItemTests(String name) {
super(name);
}
/**
* Confirm that the equals method can distinguish all the required fields.
*/
public void testEquals() {
XYDataItem i1 = new XYDataItem(1.0, 1.1);
XYDataItem i2 = new XYDataItem(1.0, 1.1);
assertTrue(i1.equals(i2));
assertTrue(i2.equals(i1));
i1.setY(new Double(9.9));
assertFalse(i1.equals(i2));
i2.setY(new Double(9.9));
assertTrue(i1.equals(i2));
}
/**
* Confirm that cloning works.
*/
public void testCloning() {
XYDataItem i1 = new XYDataItem(1.0, 1.1);
XYDataItem i2 = null;
i2 = (XYDataItem) i1.clone();
assertTrue(i1 != i2);
assertTrue(i1.getClass() == i2.getClass());
assertTrue(i1.equals(i2));
}
/**
* Serialize an instance, restore it, and check for equality.
*/
public void testSerialization() {
XYDataItem i1 = new XYDataItem(1.0, 1.1);
XYDataItem i2 = null;
try {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(buffer);
out.writeObject(i1);
out.close();
ObjectInput in = new ObjectInputStream(
new ByteArrayInputStream(buffer.toByteArray()));
i2 = (XYDataItem) in.readObject();
in.close();
}
catch (Exception e) {
e.printStackTrace();
}
assertEquals(i1, i2);
}
}
| lgpl-2.1 |
topicusonderwijs/jdiff | test/new/ChangedPackage/ChangedClassModifiers.java | 4306 | package ChangedPackage;
import java.io.*;
/**
* NEW: The changes in this class are to do with changes in deprecation,
* modifiers, or exceptions.
*/
public abstract class ChangedClassModifiers {
/** This constructor should remain unchanged. */
public ChangedClassModifiers() {
}
/**
* This constructor should have been changed from protected to public.
*/
public ChangedClassModifiers(int removed) {
}
/**
* This constructor should have been deprecated.
*
* @deprecated Deprecated to test JDiff.
*/
public ChangedClassModifiers(int a, int b) {
}
/**
* This constructor should have been changed from deprecated to
* non-deprecated.
*/
public ChangedClassModifiers(int a, String b) {
}
/**
* This constructor should have removed exceptions.
*/
public ChangedClassModifiers(long a) {
}
/** This constructor should have added exceptions. */
public ChangedClassModifiers(long a, long b) throws Exception, IOException, FileNotFoundException {
}
/** This constructor should have changed exceptions. */
public ChangedClassModifiers(long a, long b, long c) throws Exception, IOException {
}
/** This method should remain unchanged. */
public void UnchangedMethod() {
}
/** This method should have been changed from static to non-static. */
public void MethodBecomesNonStatic() {
}
/** This method should have been changed from non-static to static. */
public static void MethodBecomesStatic() {
}
/** This method should have been changed from abstract to non-abstract. */
public void MethodBecomesNonAbstract() {
}
/** This method should have been changed from non-abstract to abstract. */
public abstract void MethodBecomesAbstract();
/** This method should have removed exceptions. */
public void MethodRemovesExceptions() {
}
/** This method should have added exceptions. */
public void MethodAddsExceptions() throws Exception, IOException, FileNotFoundException {
}
/**
* This method should have changed exceptions. In fact, the
* exceptions' order was just reversed.
*/
public void MethodChangesExceptions() throws IOException, Exception {
}
/** This method should have changed exceptions. */
public void MethodChangesExceptions2() throws Exception, IOException {
}
/** This method should have changed from native to non-native. */
public void MethodChangesNativeToNonNative() {
}
/** This method should have changed from non-native to native. */
public native void MethodChangesNonNativeToNative();
/** This method should have changed from synchronized to non-synchronized. */
public void MethodChangesSynchronizedToNonSynchronized() {
}
/** This method should have changed from non-synchronized to synchronized. */
public synchronized void MethodChangesNonSynchronizedToSynchronized() {
}
/** This field should remain unchanged. */
public boolean unchanged;
/** This field should have been changed from final to non-final. */
public boolean changedFinalToNonFinal = false;
/** This field should have been changed from final to non-final. */
public final boolean changedNonFinalToFinal = false;
/** This field should have been changed from public to protected. */
protected String fromPublicToProtected;
/** This field should have been changed from protected to public. */
public String fromProtectedToPublic;
/** This field should have been changed from static to non-static. */
String fromStaticToNonStatic;
/** This field should have been changed from non-static to static. */
static String fromNonStaticToStatic;
/** This field should have been changed from transient to non-transient. */
String fromTransientToNonTransient;
/** This field should have been changed from non-transient to transient. */
transient String fromNonTransientToTransient;
/** This field should have been changed from volatile to non-volatile. */
String fromVolatileToNonVolatile;
/** This field should have been changed from non-volatile to volatile. */
volatile String fromNonVolatileToVolatile;
}
| lgpl-2.1 |
HomescuLiviu/OmegaDeveloper-shopizer | sm-shop/src/main/java/com/salesmanager/shop/model/customer/attribute/CustomerOptionEntity.java | 645 | package com.salesmanager.shop.model.customer.attribute;
import java.io.Serializable;
public class CustomerOptionEntity extends CustomerOption implements
Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private int order;
private String code;
private String type;//TEXT|SELECT|RADIO|CHECKBOX
public void setOrder(int order) {
this.order = order;
}
public int getOrder() {
return order;
}
public void setCode(String code) {
this.code = code;
}
public String getCode() {
return code;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
| lgpl-2.1 |
gpickin/Lucee4 | lucee-java/lucee-core/src/lucee/runtime/functions/arrays/ArrayMedian.java | 1382 | /**
*
* Copyright (c) 2014, the Railo Company Ltd. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
**/
package lucee.runtime.functions.arrays;
import lucee.runtime.PageContext;
import lucee.runtime.exp.ExpressionException;
import lucee.runtime.exp.PageException;
import lucee.runtime.functions.BIF;
import lucee.runtime.op.Caster;
import lucee.runtime.type.Array;
import lucee.runtime.type.util.ArrayUtil;
public class ArrayMedian extends BIF {
public static double call(PageContext pc , Array array) throws ExpressionException {
return ArrayUtil.median(array);
}
@Override
public Object invoke(PageContext pc, Object[] args) throws PageException {
return call(pc, Caster.toArray(args[0]));
}
}
| lgpl-2.1 |
stoksey69/googleads-java-lib | modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201411/CreateAdUnitsResponse.java | 1825 |
package com.google.api.ads.dfp.jaxws.v201411;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="rval" type="{https://www.google.com/apis/ads/publisher/v201411}AdUnit" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"rval"
})
@XmlRootElement(name = "createAdUnitsResponse")
public class CreateAdUnitsResponse {
protected List<AdUnit> rval;
/**
* Gets the value of the rval property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the rval property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getRval().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link AdUnit }
*
*
*/
public List<AdUnit> getRval() {
if (rval == null) {
rval = new ArrayList<AdUnit>();
}
return this.rval;
}
}
| apache-2.0 |
chathurace/carbon-business-process | components/bpel/org.wso2.carbon.bpel/src/main/java/org/wso2/carbon/bpel/core/Axis2ConfigurationContextObserverImpl.java | 2216 | /**
* 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.bpel.core;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.bpel.core.ode.integration.BPELServerImpl;
import org.wso2.carbon.bpel.core.ode.integration.store.ProcessStoreImpl;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.utils.AbstractAxis2ConfigurationContextObserver;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
/**
* Listen to Axis2ConfigurationContext life cycle events and do the necessary tasks to register
* BPEL Deployer and unregister BPEL Deployer.
*/
public class Axis2ConfigurationContextObserverImpl extends
AbstractAxis2ConfigurationContextObserver {
private static Log log = LogFactory.getLog(Axis2ConfigurationContextObserverImpl.class);
private BPELServerImpl bpelServer;
public Axis2ConfigurationContextObserverImpl(){
bpelServer = BPELServerImpl.getInstance();
}
public void createdConfigurationContext(ConfigurationContext configurationContext) {
}
public void terminatingConfigurationContext(ConfigurationContext configurationContext) {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
log.info("Unloading TenantProcessStore for tenant " + tenantId + ".");
((ProcessStoreImpl)bpelServer.getMultiTenantProcessStore()).unloadTenantProcessStore(tenantId);
}
}
| apache-2.0 |
tatamiya3/redpen | redpen-core/src/main/java/cc/redpen/validator/package-info.java | 89 | /**
* Validators and the factory classes are provided.
*/
package cc.redpen.validator;
| apache-2.0 |
skjolber/camunda-bpm-platform | engine/src/main/java/org/camunda/bpm/engine/impl/metrics/dmn/MetricsDecisionTableListener.java | 1486 | /* 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.metrics.dmn;
import org.camunda.bpm.dmn.engine.delegate.DmnDecisionTableEvaluationEvent;
import org.camunda.bpm.dmn.engine.delegate.DmnDecisionTableEvaluationListener;
import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.camunda.bpm.engine.impl.context.Context;
import org.camunda.bpm.engine.management.Metrics;
public class MetricsDecisionTableListener implements DmnDecisionTableEvaluationListener {
public void notify(DmnDecisionTableEvaluationEvent evaluationEvent) {
ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();
if (processEngineConfiguration != null && processEngineConfiguration.isMetricsEnabled()) {
processEngineConfiguration
.getMetricsRegistry()
.markOccurrence(Metrics.EXECUTED_DECISION_ELEMENTS, evaluationEvent.getExecutedDecisionElements());
}
}
}
| apache-2.0 |
facebook/buck | src/com/facebook/buck/util/WeakMemoizer.java | 1667 | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.buck.util;
import java.lang.ref.WeakReference;
import java.util.function.Supplier;
import javax.annotation.Nullable;
/**
* Memoizes a value with a weak reference, supporting passing in a supplier when getting the value,
* unlike {@link MoreSuppliers.WeakMemoizingSupplier}
*/
public class WeakMemoizer<T> {
private WeakReference<T> valueRef = new WeakReference<>(null);
/**
* Get the value and memoize the result. Constructs the value if it hasn't been memoized before,
* or if the previously memoized value has been collected.
*
* @param delegate delegate for constructing the value
* @return the value
*/
public T get(Supplier<T> delegate) {
@Nullable T value = valueRef.get();
if (value == null) {
synchronized (this) {
// Check again in case someone else has populated the cache.
value = valueRef.get();
if (value == null) {
value = delegate.get();
valueRef = new WeakReference<>(value);
}
}
}
return value;
}
}
| apache-2.0 |
supersven/intellij-community | java/java-impl/src/com/intellij/codeInsight/editorActions/smartEnter/MethodCallFixer.java | 4446 | /*
* 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.codeInsight.editorActions.smartEnter;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.DumbService;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.jsp.jspJava.JspMethodCall;
import com.intellij.psi.infos.CandidateInfo;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.text.CharArrayUtil;
import org.jetbrains.annotations.Nullable;
/**
* Created by IntelliJ IDEA.
* User: max
* Date: Sep 5, 2003
* Time: 3:35:49 PM
* To change this template use Options | File Templates.
*/
public class MethodCallFixer implements Fixer {
@Override
public void apply(Editor editor, JavaSmartEnterProcessor processor, PsiElement psiElement) throws IncorrectOperationException {
PsiExpressionList args = null;
if (psiElement instanceof PsiMethodCallExpression && !(psiElement instanceof JspMethodCall)) {
args = ((PsiMethodCallExpression) psiElement).getArgumentList();
} else if (psiElement instanceof PsiNewExpression) {
args = ((PsiNewExpression) psiElement).getArgumentList();
}
if (args != null && !hasRParenth(args)) {
int caret = editor.getCaretModel().getOffset();
PsiCallExpression innermostCall = PsiTreeUtil.findElementOfClassAtOffset(psiElement.getContainingFile(), caret, PsiCallExpression.class, false);
if (innermostCall == null) return;
args = innermostCall.getArgumentList();
if (args == null) return;
int endOffset = -1;
PsiElement child = args.getFirstChild();
while (child != null) {
if (child instanceof PsiErrorElement) {
final PsiErrorElement errorElement = (PsiErrorElement)child;
if (errorElement.getErrorDescription().contains("')'")) {
endOffset = errorElement.getTextRange().getStartOffset();
break;
}
}
child = child.getNextSibling();
}
if (endOffset == -1) {
endOffset = args.getTextRange().getEndOffset();
}
final PsiExpression[] params = args.getExpressions();
if (params.length > 0 &&
startLine(editor, args) != startLine(editor, params[0]) &&
caret < params[0].getTextRange().getStartOffset()) {
endOffset = args.getTextRange().getStartOffset() + 1;
}
if (!DumbService.isDumb(args.getProject())) {
Integer argCount = getUnambiguousParameterCount(innermostCall);
if (argCount != null && argCount > 0 && argCount < params.length) {
endOffset = Math.min(endOffset, params[argCount - 1].getTextRange().getEndOffset());
}
}
endOffset = CharArrayUtil.shiftBackward(editor.getDocument().getCharsSequence(), endOffset - 1, " \t\n") + 1;
editor.getDocument().insertString(endOffset, ")");
}
}
private static boolean hasRParenth(PsiExpressionList args) {
PsiElement parenth = args.getLastChild();
return parenth != null && ")".equals(parenth.getText());
}
@Nullable
private static Integer getUnambiguousParameterCount(PsiCallExpression call) {
int argCount = -1;
for (CandidateInfo candidate : PsiResolveHelper.SERVICE.getInstance(call.getProject()).getReferencedMethodCandidates(call, false)) {
PsiElement element = candidate.getElement();
if (!(element instanceof PsiMethod)) return null;
if (((PsiMethod)element).isVarArgs()) return null;
int count = ((PsiMethod)element).getParameterList().getParametersCount();
if (argCount == -1) {
argCount = count;
} else if (argCount != count) {
return null;
}
}
return argCount;
}
private static int startLine(Editor editor, PsiElement psiElement) {
return editor.getDocument().getLineNumber(psiElement.getTextRange().getStartOffset());
}
}
| apache-2.0 |
hbarnard/fcrepo-phaidra | fcrepo-server/src/main/java/org/fcrepo/server/journal/managementmethods/PurgeRelationshipMethod.java | 1178 | /* The contents of this file are subject to the license and copyright terms
* detailed in the license directory at the root of the source tree (also
* available online at http://fedora-commons.org/license/).
*/
package org.fcrepo.server.journal.managementmethods;
import org.fcrepo.server.errors.ServerException;
import org.fcrepo.server.journal.entry.JournalEntry;
import org.fcrepo.server.management.ManagementDelegate;
/**
* Adapter class for Management.purgeRelationship().
*
* @author Jim Blake
*/
public class PurgeRelationshipMethod
extends ManagementMethod {
public PurgeRelationshipMethod(JournalEntry parent) {
super(parent);
}
@Override
public Object invoke(ManagementDelegate delegate) throws ServerException {
return delegate.purgeRelationship(parent.getContext(), parent
.getStringArgument(ARGUMENT_NAME_PID), parent
.getStringArgument(ARGUMENT_NAME_RELATIONSHIP), parent
.getStringArgument(ARGUMENT_NAME_OBJECT), parent
.getBooleanArgument(ARGUMENT_NAME_IS_LITERAL), parent
.getStringArgument(ARGUMENT_NAME_DATATYPE));
}
}
| apache-2.0 |
yuruki/camel | components/camel-test-spring/src/main/java/org/apache/camel/test/spring/CamelSpringBootExecutionListener.java | 3544 | /**
* 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.spring;
import org.apache.camel.CamelContext;
import org.apache.camel.spring.SpringCamelContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.test.context.TestContext;
import org.springframework.test.context.support.AbstractTestExecutionListener;
public class CamelSpringBootExecutionListener extends AbstractTestExecutionListener {
private static final Logger LOG = LoggerFactory.getLogger(CamelSpringBootExecutionListener.class);
@Override
public void prepareTestInstance(TestContext testContext) throws Exception {
LOG.info("@RunWith(CamelSpringBootJUnit4ClassRunner.class) preparing: {}", testContext.getTestClass());
Class<?> testClass = testContext.getTestClass();
// we are customizing the Camel context with
// CamelAnnotationsHandler so we do not want to start it
// automatically, which would happen when SpringCamelContext
// is added to Spring ApplicationContext, so we set the flag
// not to start it just yet
SpringCamelContext.setNoStart(true);
ConfigurableApplicationContext context = (ConfigurableApplicationContext) testContext.getApplicationContext();
// Post CamelContext(s) instantiation but pre CamelContext(s) start setup
CamelAnnotationsHandler.handleProvidesBreakpoint(context, testClass);
CamelAnnotationsHandler.handleShutdownTimeout(context, testClass);
CamelAnnotationsHandler.handleMockEndpoints(context, testClass);
CamelAnnotationsHandler.handleMockEndpointsAndSkip(context, testClass);
CamelAnnotationsHandler.handleUseOverridePropertiesWithPropertiesComponent(context, testClass);
SpringCamelContext.setNoStart(false);
CamelContext camelContext = context.getBean(CamelContext.class);
// after our customizations we should start the CamelContext
camelContext.start();
}
@Override
public void beforeTestMethod(TestContext testContext) throws Exception {
LOG.info("@RunWith(CamelSpringBootJUnit4ClassRunner.class) before: {}.{}", testContext.getTestClass(), testContext.getTestMethod().getName());
Class<?> testClass = testContext.getTestClass();
ConfigurableApplicationContext context = (ConfigurableApplicationContext) testContext.getApplicationContext();
// mark Camel to be startable again and start Camel
System.clearProperty("skipStartingCamelContext");
LOG.info("Initialized CamelSpringBootJUnit4ClassRunner now ready to start CamelContext");
CamelAnnotationsHandler.handleCamelContextStartup(context, testClass);
}
}
| apache-2.0 |
artiya4u/buck | src/com/facebook/buck/android/ExopackageInstaller.java | 33621 | /*
* Copyright 2014-present Facebook, 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.facebook.buck.android;
import com.android.ddmlib.AdbCommandRejectedException;
import com.android.ddmlib.CollectingOutputReceiver;
import com.android.ddmlib.IDevice;
import com.android.ddmlib.InstallException;
import com.facebook.buck.android.agent.util.AgentUtil;
import com.facebook.buck.event.BuckEventBus;
import com.facebook.buck.event.ConsoleEvent;
import com.facebook.buck.event.InstallEvent;
import com.facebook.buck.event.TraceEventLogger;
import com.facebook.buck.io.ProjectFilesystem;
import com.facebook.buck.log.Logger;
import com.facebook.buck.rules.ExopackageInfo;
import com.facebook.buck.rules.InstallableApk;
import com.facebook.buck.step.ExecutionContext;
import com.facebook.buck.util.NamedTemporaryFile;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Charsets;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicates;
import com.google.common.base.Splitter;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
/**
* ExopackageInstaller manages the installation of apps with the "exopackage" flag set to true.
*/
public class ExopackageInstaller {
private static final Logger LOG = Logger.get(ExopackageInstaller.class);
/**
* Prefix of the path to the agent apk on the device.
*/
private static final String AGENT_DEVICE_PATH = "/data/app/" + AgentUtil.AGENT_PACKAGE_NAME;
/**
* Command line to invoke the agent on the device.
*/
private static final String JAVA_AGENT_COMMAND =
"dalvikvm -classpath " +
AGENT_DEVICE_PATH + "-1.apk:" + AGENT_DEVICE_PATH + "-2.apk:" +
AGENT_DEVICE_PATH + "-1/base.apk:" + AGENT_DEVICE_PATH + "-2/base.apk " +
"com.facebook.buck.android.agent.AgentMain ";
/**
* Maximum length of commands that can be passed to "adb shell".
*/
private static final int MAX_ADB_COMMAND_SIZE = 1019;
private static final Path SECONDARY_DEX_DIR = Paths.get("secondary-dex");
private static final Path NATIVE_LIBS_DIR = Paths.get("native-libs");
@VisibleForTesting
static final Pattern DEX_FILE_PATTERN = Pattern.compile("secondary-([0-9a-f]+)\\.[\\w.-]*");
@VisibleForTesting
static final Pattern NATIVE_LIB_PATTERN = Pattern.compile("native-([0-9a-f]+)\\.so");
private final ProjectFilesystem projectFilesystem;
private final BuckEventBus eventBus;
private final AdbHelper adbHelper;
private final InstallableApk apkRule;
private final String packageName;
private final Path dataRoot;
private final ExopackageInfo exopackageInfo;
/**
* The next port number to use for communicating with the agent on a device.
* This resets for every instance of ExopackageInstaller,
* but is incremented for every device we are installing on when using "-x".
*/
private final AtomicInteger nextAgentPort = new AtomicInteger(2828);
@VisibleForTesting
static class PackageInfo {
final String apkPath;
final String nativeLibPath;
final String versionCode;
private PackageInfo(String apkPath, String nativeLibPath, String versionCode) {
this.nativeLibPath = nativeLibPath;
this.apkPath = apkPath;
this.versionCode = versionCode;
}
}
public ExopackageInstaller(
ExecutionContext context,
AdbHelper adbHelper,
InstallableApk apkRule) {
this.adbHelper = adbHelper;
this.projectFilesystem = apkRule.getProjectFilesystem();
this.eventBus = context.getBuckEventBus();
this.apkRule = apkRule;
this.packageName = AdbHelper.tryToExtractPackageNameFromManifest(apkRule);
this.dataRoot = Paths.get("/data/local/tmp/exopackage/").resolve(packageName);
Preconditions.checkArgument(AdbHelper.PACKAGE_NAME_PATTERN.matcher(packageName).matches());
Optional<ExopackageInfo> exopackageInfo = apkRule.getExopackageInfo();
Preconditions.checkArgument(exopackageInfo.isPresent());
this.exopackageInfo = exopackageInfo.get();
}
/**
* Installs the app specified in the constructor. This object should be discarded afterward.
*/
public synchronized boolean install(boolean quiet) throws InterruptedException {
InstallEvent.Started started = InstallEvent.started(apkRule.getBuildTarget());
eventBus.post(started);
boolean success = adbHelper.adbCall(
new AdbHelper.AdbCallable() {
@Override
public boolean call(IDevice device) throws Exception {
try {
return new SingleDeviceInstaller(device, nextAgentPort.getAndIncrement()).doInstall();
} catch (Exception e) {
throw new RuntimeException("Failed to install exopackage on " + device, e);
}
}
@Override
public String toString() {
return "install exopackage";
}
},
quiet);
eventBus.post(InstallEvent.finished(
started,
success,
Optional.<Long>absent()));
return success;
}
/**
* Helper class to manage the state required to install on a single device.
*/
private class SingleDeviceInstaller {
/**
* Device that we are installing onto.
*/
private final IDevice device;
/**
* Port to use for sending files to the agent.
*/
private final int agentPort;
/**
* True iff we should use the native agent.
*/
private boolean useNativeAgent = true;
/**
* Set after the agent is installed.
*/
@Nullable
private String nativeAgentPath;
private SingleDeviceInstaller(IDevice device, int agentPort) {
this.device = device;
this.agentPort = agentPort;
}
boolean doInstall() throws Exception {
Optional<PackageInfo> agentInfo = installAgentIfNecessary();
if (!agentInfo.isPresent()) {
return false;
}
nativeAgentPath = agentInfo.get().nativeLibPath;
determineBestAgent();
final File apk = apkRule.getApkPath().toFile();
// TODO(user): Support SD installation.
final boolean installViaSd = false;
if (shouldAppBeInstalled()) {
try (TraceEventLogger ignored = TraceEventLogger.start(eventBus, "install_exo_apk")) {
boolean success = adbHelper.installApkOnDevice(device, apk, installViaSd, false);
if (!success) {
return false;
}
}
}
if (exopackageInfo.getDexInfo().isPresent()) {
installSecondaryDexFiles();
}
if (exopackageInfo.getNativeLibsInfo().isPresent()) {
installNativeLibraryFiles();
}
// TODO(user): Make this work on Gingerbread.
try (TraceEventLogger ignored = TraceEventLogger.start(eventBus, "kill_app")) {
AdbHelper.executeCommandWithErrorChecking(device, "am force-stop " + packageName);
}
return true;
}
private void installSecondaryDexFiles() throws Exception {
final ImmutableMap<String, Path> hashToSources = getRequiredDexFiles();
final ImmutableSet<String> requiredHashes = hashToSources.keySet();
final ImmutableSet<String> presentHashes = prepareSecondaryDexDir(requiredHashes);
final Set<String> hashesToInstall = Sets.difference(requiredHashes, presentHashes);
Map<String, Path> filesToInstallByHash =
Maps.filterKeys(hashToSources, Predicates.in(hashesToInstall));
// This is a bit gross. It was a late addition. Ideally, we could eliminate this, but
// it wouldn't be terrible if we don't. We store the dexed jars on the device
// with the full SHA-1 hashes in their names. This is the format that the loader uses
// internally, so ideally we would just load them in place. However, the code currently
// expects to be able to copy the jars from a directory that matches the name in the
// metadata file, like "secondary-1.dex.jar". We don't want to give up putting the
// hashes in the file names (because we use that to skip re-uploads), so just hack
// the metadata file to have hash-like names.
String metadataContents = com.google.common.io.Files.toString(
exopackageInfo.getDexInfo().get().getMetadata().toFile(),
Charsets.UTF_8)
.replaceAll(
"secondary-(\\d+)\\.dex\\.jar (\\p{XDigit}{40}) ",
"secondary-$2.dex.jar $2 ");
installFiles(
"secondary_dex",
ImmutableMap.copyOf(filesToInstallByHash),
metadataContents,
"secondary-%s.dex.jar",
SECONDARY_DEX_DIR);
}
private ImmutableList<String> getDeviceAbis() throws Exception {
ImmutableList.Builder<String> abis = ImmutableList.builder();
// Rare special indigenous to Lollipop devices
String abiListProperty = getProperty("ro.product.cpu.abilist");
if (!abiListProperty.isEmpty()) {
abis.addAll(Splitter.on(',').splitToList(abiListProperty));
} else {
String abi1 = getProperty("ro.product.cpu.abi");
if (abi1.isEmpty()) {
throw new RuntimeException("adb returned empty result for ro.product.cpu.abi property.");
}
abis.add(abi1);
String abi2 = getProperty("ro.product.cpu.abi2");
if (!abi2.isEmpty()) {
abis.add(abi2);
}
}
return abis.build();
}
private void installNativeLibraryFiles() throws Exception {
ImmutableMultimap<String, Path> allLibraries = getAllLibraries();
ImmutableSet.Builder<String> providedLibraries = ImmutableSet.builder();
for (String abi : getDeviceAbis()) {
ImmutableMap<String, Path> libraries =
getRequiredLibrariesForAbi(allLibraries, abi, providedLibraries.build());
installNativeLibrariesForAbi(abi, libraries);
providedLibraries.addAll(libraries.keySet());
}
}
private void installNativeLibrariesForAbi(String abi, ImmutableMap<String, Path> libraries)
throws Exception {
if (libraries.isEmpty()) {
return;
}
ImmutableSet<String> requiredHashes = libraries.keySet();
ImmutableSet<String> presentHashes = prepareNativeLibsDir(abi, requiredHashes);
Map<String, Path> filesToInstallByHash =
Maps.filterKeys(libraries, Predicates.not(Predicates.in(presentHashes)));
String metadataContents = Joiner.on('\n').join(
FluentIterable.from(libraries.entrySet()).transform(
new Function<Map.Entry<String, Path>, String>() {
@Override
public String apply(Map.Entry<String, Path> input) {
String hash = input.getKey();
String filename = input.getValue().getFileName().toString();
int index = filename.indexOf('.');
String libname = index == -1 ? filename : filename.substring(0, index);
return String.format("%s native-%s.so", libname, hash);
}
}));
installFiles(
"native_library",
ImmutableMap.copyOf(filesToInstallByHash),
metadataContents,
"native-%s.so",
NATIVE_LIBS_DIR.resolve(abi));
}
/**
* Sets {@link #useNativeAgent} to true on pre-L devices, because our native agent is built
* without -fPIC. The java agent works fine on L as long as we don't use it for mkdir.
*/
private void determineBestAgent() throws Exception {
String value = getProperty("ro.build.version.sdk");
try {
if (Integer.valueOf(value.trim()) > 19) {
useNativeAgent = false;
}
} catch (NumberFormatException exn) {
useNativeAgent = false;
}
}
private String getAgentCommand() {
if (useNativeAgent) {
return nativeAgentPath + "/libagent.so ";
} else {
return JAVA_AGENT_COMMAND;
}
}
private Optional<PackageInfo> getPackageInfo(final String packageName) throws Exception {
try (TraceEventLogger ignored = TraceEventLogger.start(
eventBus,
"get_package_info",
ImmutableMap.of("package", packageName))) {
/* "dumpsys package <package>" produces output that looks like
Package [com.facebook.katana] (4229ce68):
userId=10145 gids=[1028, 1015, 3003]
pkg=Package{42690b80 com.facebook.katana}
codePath=/data/app/com.facebook.katana-1.apk
resourcePath=/data/app/com.facebook.katana-1.apk
nativeLibraryPath=/data/app-lib/com.facebook.katana-1
versionCode=1640376 targetSdk=14
versionName=8.0.0.0.23
...
*/
// We call "pm path" because "dumpsys package" returns valid output if an app has been
// uninstalled using the "--keepdata" option. "pm path", on the other hand, returns an empty
// output in that case.
String lines = AdbHelper.executeCommandWithErrorChecking(
device,
String.format("pm path %s; dumpsys package %s", packageName, packageName));
return parsePathAndPackageInfo(packageName, lines);
}
}
/**
* @return PackageInfo for the agent, or absent if installation failed.
*/
private Optional<PackageInfo> installAgentIfNecessary() throws Exception {
Optional<PackageInfo> agentInfo = getPackageInfo(AgentUtil.AGENT_PACKAGE_NAME);
if (!agentInfo.isPresent()) {
LOG.debug("Agent not installed. Installing.");
return installAgentApk();
}
LOG.debug("Agent version: %s", agentInfo.get().versionCode);
if (!agentInfo.get().versionCode.equals(AgentUtil.AGENT_VERSION_CODE)) {
// Always uninstall before installing. We might be downgrading, which requires
// an uninstall, or we might just want a clean installation.
uninstallAgent();
return installAgentApk();
}
return agentInfo;
}
private void uninstallAgent() throws InstallException {
try (TraceEventLogger ignored = TraceEventLogger.start(eventBus, "uninstall_old_agent")) {
device.uninstallPackage(AgentUtil.AGENT_PACKAGE_NAME);
}
}
private Optional<PackageInfo> installAgentApk() throws Exception {
try (TraceEventLogger ignored = TraceEventLogger.start(eventBus, "install_agent_apk")) {
String apkFileName = System.getProperty("buck.android_agent_path");
if (apkFileName == null) {
throw new RuntimeException("Android agent apk path not specified in properties");
}
File apkPath = new File(apkFileName);
boolean success = adbHelper.installApkOnDevice(
device,
apkPath,
/* installViaSd */ false,
/* quiet */ false);
if (!success) {
return Optional.absent();
}
return getPackageInfo(AgentUtil.AGENT_PACKAGE_NAME);
}
}
private boolean shouldAppBeInstalled() throws Exception {
Optional<PackageInfo> appPackageInfo = getPackageInfo(packageName);
if (!appPackageInfo.isPresent()) {
eventBus.post(ConsoleEvent.info("App not installed. Installing now."));
return true;
}
LOG.debug("App path: %s", appPackageInfo.get().apkPath);
String installedAppSignature = getInstalledAppSignature(appPackageInfo.get().apkPath);
String localAppSignature = AgentUtil.getJarSignature(apkRule.getApkPath().toString());
LOG.debug("Local app signature: %s", localAppSignature);
LOG.debug("Remote app signature: %s", installedAppSignature);
if (!installedAppSignature.equals(localAppSignature)) {
LOG.debug("App signatures do not match. Must re-install.");
return true;
}
LOG.debug("App signatures match. No need to install.");
return false;
}
private String getInstalledAppSignature(final String packagePath) throws Exception {
try (TraceEventLogger ignored = TraceEventLogger.start(eventBus, "get_app_signature")) {
String command = getAgentCommand() + "get-signature " + packagePath;
LOG.debug("Executing %s", command);
String output = AdbHelper.executeCommandWithErrorChecking(device, command);
String result = output.trim();
if (result.contains("\n") || result.contains("\r")) {
throw new IllegalStateException("Unexpected return from get-signature:\n" + output);
}
return result;
}
}
private ImmutableMap<String, Path> getRequiredDexFiles() throws IOException {
ExopackageInfo.DexInfo dexInfo = exopackageInfo.getDexInfo().get();
ImmutableMultimap<String, Path> multimap = parseExopackageInfoMetadata(
dexInfo.getMetadata(),
dexInfo.getDirectory(),
projectFilesystem);
// Convert multimap to a map, because every key should have only one value.
ImmutableMap.Builder<String, Path> builder = ImmutableMap.builder();
for (Map.Entry<String, Path> entry : multimap.entries()) {
builder.put(entry);
}
return builder.build();
}
private ImmutableSet<String> prepareSecondaryDexDir(ImmutableSet<String> requiredHashes)
throws Exception {
return prepareDirectory("secondary-dex", DEX_FILE_PATTERN, requiredHashes);
}
private ImmutableSet<String> prepareNativeLibsDir(
String abi,
ImmutableSet<String> requiredHashes) throws Exception {
return prepareDirectory("native-libs/" + abi, NATIVE_LIB_PATTERN, requiredHashes);
}
private ImmutableSet<String> prepareDirectory(
String dirname,
Pattern filePattern,
ImmutableSet<String> requiredHashes) throws Exception {
try (TraceEventLogger ignored = TraceEventLogger.start(eventBus, "prepare_" + dirname)) {
String dirPath = dataRoot.resolve(dirname).toString();
mkDirP(dirPath);
String output = AdbHelper.executeCommandWithErrorChecking(device, "ls " + dirPath);
ImmutableSet.Builder<String> foundHashes = ImmutableSet.builder();
ImmutableSet.Builder<String> filesToDelete = ImmutableSet.builder();
processLsOutput(output, filePattern, requiredHashes, foundHashes, filesToDelete);
String commandPrefix = "cd " + dirPath + " && rm ";
// Add a fudge factor for separators and error checking.
final int overhead = commandPrefix.length() + 100;
for (List<String> rmArgs :
chunkArgs(filesToDelete.build(), MAX_ADB_COMMAND_SIZE - overhead)) {
String command = commandPrefix + Joiner.on(' ').join(rmArgs);
LOG.debug("Executing %s", command);
AdbHelper.executeCommandWithErrorChecking(device, command);
}
return foundHashes.build();
}
}
private void installFiles(
String filesType,
ImmutableMap<String, Path> filesToInstallByHash,
String metadataFileContents,
String filenameFormat,
Path destinationDirRelativeToDataRoot) throws Exception {
try (TraceEventLogger ignored1 =
TraceEventLogger.start(eventBus, "multi_install_" + filesType)) {
device.createForward(agentPort, agentPort);
try {
for (Map.Entry<String, Path> entry : filesToInstallByHash.entrySet()) {
Path destination = destinationDirRelativeToDataRoot.resolve(
String.format(filenameFormat, entry.getKey()));
Path source = entry.getValue();
try (TraceEventLogger ignored2 =
TraceEventLogger.start(eventBus, "install_" + filesType)) {
installFile(device, agentPort, destination, source);
}
}
try (TraceEventLogger ignored3 =
TraceEventLogger.start(eventBus, "install_" + filesType + "_metadata")) {
try (NamedTemporaryFile temp = new NamedTemporaryFile("metadata", "tmp")) {
com.google.common.io.Files.write(
metadataFileContents.getBytes(Charsets.UTF_8),
temp.get().toFile());
installFile(
device,
agentPort,
destinationDirRelativeToDataRoot.resolve("metadata.txt"),
temp.get());
}
}
} finally {
try {
device.removeForward(agentPort, agentPort);
} catch (AdbCommandRejectedException e) {
LOG.warn(e, "Failed to remove adb forward on port %d for device %s", agentPort, device);
eventBus.post(
ConsoleEvent.warning(
"Failed to remove adb forward %d. This is not necessarily a problem\n" +
"because it will be recreated during the next exopackage installation.\n" +
"See the log for the full exception.",
agentPort));
}
}
}
}
private void installFile(
IDevice device,
final int port,
Path pathRelativeToDataRoot,
final Path source) throws Exception {
CollectingOutputReceiver receiver = new CollectingOutputReceiver() {
private boolean sentPayload = false;
@Override
public void addOutput(byte[] data, int offset, int length) {
super.addOutput(data, offset, length);
if (!sentPayload && getOutput().length() >= AgentUtil.TEXT_SECRET_KEY_SIZE) {
LOG.verbose("Got key: %s", getOutput().trim());
sentPayload = true;
try (Socket clientSocket = new Socket("localhost", port)) {
LOG.verbose("Connected");
OutputStream outToDevice = clientSocket.getOutputStream();
outToDevice.write(
getOutput().substring(
0,
AgentUtil.TEXT_SECRET_KEY_SIZE).getBytes());
LOG.verbose("Wrote key");
com.google.common.io.Files.asByteSource(source.toFile()).copyTo(outToDevice);
LOG.verbose("Wrote file");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
};
String targetFileName = dataRoot.resolve(pathRelativeToDataRoot).toString();
String command =
"umask 022 && " +
getAgentCommand() +
"receive-file " + port + " " + Files.size(source) + " " +
targetFileName +
" ; echo -n :$?";
LOG.debug("Executing %s", command);
// If we fail to execute the command, stash the exception. My experience during development
// has been that the exception from checkReceiverOutput is more actionable.
Exception shellException = null;
try {
device.executeShellCommand(command, receiver);
} catch (Exception e) {
shellException = e;
}
try {
AdbHelper.checkReceiverOutput(command, receiver);
} catch (Exception e) {
if (shellException != null) {
e.addSuppressed(shellException);
}
throw e;
}
if (shellException != null) {
throw shellException;
}
// The standard Java libraries on Android always create new files un-readable by other users.
// We use the shell user or root to create these files, so we need to explicitly set the mode
// to allow the app to read them. Ideally, the agent would do this automatically, but
// there's no easy way to do this in Java. We can drop this if we drop support for the
// Java agent.
AdbHelper.executeCommandWithErrorChecking(device, "chmod 644 " + targetFileName);
}
private String getProperty(String property) throws Exception {
return AdbHelper.executeCommandWithErrorChecking(device, "getprop " + property).trim();
}
private void mkDirP(String dirpath) throws Exception {
// Kind of a hack here. The java agent can't force the proper permissions on the
// directories it creates, so we use the command-line "mkdir -p" instead of the java agent.
// Fortunately, "mkdir -p" seems to work on all devices where we use use the java agent.
String mkdirP = useNativeAgent ? getAgentCommand() + "mkdir-p" : "mkdir -p";
AdbHelper.executeCommandWithErrorChecking(device, "umask 022 && " + mkdirP + " " + dirpath);
}
}
private ImmutableMultimap<String, Path> getAllLibraries() throws IOException {
ExopackageInfo.NativeLibsInfo nativeLibsInfo = exopackageInfo.getNativeLibsInfo().get();
return parseExopackageInfoMetadata(
nativeLibsInfo.getMetadata(),
nativeLibsInfo.getDirectory(),
projectFilesystem);
}
private ImmutableMap<String, Path> getRequiredLibrariesForAbi(
ImmutableMultimap<String, Path> allLibraries,
String abi,
ImmutableSet<String> ignoreLibraries) throws IOException {
return filterLibrariesForAbi(
exopackageInfo.getNativeLibsInfo().get().getDirectory(),
allLibraries,
abi,
ignoreLibraries);
}
@VisibleForTesting
static ImmutableMap<String, Path> filterLibrariesForAbi(
Path nativeLibsDir,
ImmutableMultimap<String, Path> allLibraries,
String abi,
ImmutableSet<String> ignoreLibraries) {
ImmutableMap.Builder<String, Path> filteredLibraries = ImmutableMap.builder();
for (Map.Entry<String, Path> entry : allLibraries.entries()) {
Path relativePath = nativeLibsDir.relativize(entry.getValue());
// relativePath is of the form libs/x86/foo.so, or assetLibs/x86/foo.so etc.
Preconditions.checkState(relativePath.getNameCount() == 3);
Preconditions.checkState(
relativePath.getName(0).toString().equals("libs") ||
relativePath.getName(0).toString().equals("assetLibs"));
String libAbi = relativePath.getParent().getFileName().toString();
String libName = relativePath.getFileName().toString();
if (libAbi.equals(abi) && !ignoreLibraries.contains(libName)) {
filteredLibraries.put(entry);
}
}
return filteredLibraries.build();
}
/**
* Parses a text file which is supposed to be in the following format:
* "file_path_without_spaces file_hash ...." i.e. it parses the first two columns of each line
* and ignores the rest of it.
*
* @return A multi map from the file hash to its path, which equals the raw path resolved against
* {@code resolvePathAgainst}.
*/
@VisibleForTesting
static ImmutableMultimap<String, Path> parseExopackageInfoMetadata(
Path metadataTxt,
Path resolvePathAgainst,
ProjectFilesystem filesystem) throws IOException {
ImmutableMultimap.Builder<String, Path> builder = ImmutableMultimap.builder();
for (String line : filesystem.readLines(metadataTxt)) {
List<String> parts = Splitter.on(' ').splitToList(line);
if (parts.size() < 2) {
throw new RuntimeException("Illegal line in metadata file: " + line);
}
builder.put(parts.get(1), resolvePathAgainst.resolve(parts.get(0)));
}
return builder.build();
}
@VisibleForTesting
static Optional<PackageInfo> parsePathAndPackageInfo(String packageName, String rawOutput) {
Iterable<String> lines = Splitter.on("\r\n").omitEmptyStrings().split(rawOutput);
String pmPathPrefix = "package:";
String pmPath = Iterables.getFirst(lines, null);
if (pmPath == null || !pmPath.startsWith(pmPathPrefix)) {
return Optional.absent();
}
final String packagePrefix = " Package [" + packageName + "] (";
final String otherPrefix = " Package [";
boolean sawPackageLine = false;
final Splitter splitter = Splitter.on('=').limit(2);
String codePath = null;
String resourcePath = null;
String nativeLibPath = null;
String versionCode = null;
for (String line : lines) {
// Just ignore everything until we see the line that says we are in the right package.
if (line.startsWith(packagePrefix)) {
sawPackageLine = true;
continue;
}
// This should never happen, but if we do see a different package, stop parsing.
if (line.startsWith(otherPrefix)) {
break;
}
// Ignore lines before our package.
if (!sawPackageLine) {
continue;
}
// Parse key-value pairs.
List<String> parts = splitter.splitToList(line.trim());
if (parts.size() != 2) {
continue;
}
switch (parts.get(0)) {
case "codePath":
codePath = parts.get(1);
break;
case "resourcePath":
resourcePath = parts.get(1);
break;
case "nativeLibraryPath":
nativeLibPath = parts.get(1);
break;
// Lollipop uses this name. Not sure what's "legacy" about it yet.
// Maybe something to do with 64-bit?
// Might need to update if people report failures.
case "legacyNativeLibraryDir":
nativeLibPath = parts.get(1);
break;
case "versionCode":
// Extra split to get rid of the SDK thing.
versionCode = parts.get(1).split(" ", 2)[0];
break;
default:
break;
}
}
if (!sawPackageLine) {
return Optional.absent();
}
Preconditions.checkNotNull(codePath, "Could not find codePath");
Preconditions.checkNotNull(resourcePath, "Could not find resourcePath");
Preconditions.checkNotNull(nativeLibPath, "Could not find nativeLibraryPath");
Preconditions.checkNotNull(versionCode, "Could not find versionCode");
if (!codePath.equals(resourcePath)) {
throw new IllegalStateException("Code and resource path do not match");
}
// Lollipop doesn't give the full path to the apk anymore. Not sure why it's "base.apk".
if (!codePath.endsWith(".apk")) {
codePath += "/base.apk";
}
return Optional.of(new PackageInfo(codePath, nativeLibPath, versionCode));
}
/**
* @param output Output of "ls" command.
* @param filePattern A {@link Pattern} that is used to check if a file is valid, and if it
* matches, {@code filePattern.group(1)} should return the hash in the file name.
* @param requiredHashes Hashes of dex files required for this apk.
* @param foundHashes Builder to receive hashes that we need and were found.
* @param toDelete Builder to receive files that we need to delete.
*/
@VisibleForTesting
static void processLsOutput(
String output,
Pattern filePattern,
ImmutableSet<String> requiredHashes,
ImmutableSet.Builder<String> foundHashes,
ImmutableSet.Builder<String> toDelete) {
for (String line : Splitter.on("\r\n").omitEmptyStrings().split(output)) {
if (line.equals("lock")) {
continue;
}
Matcher m = filePattern.matcher(line);
if (m.matches()) {
if (requiredHashes.contains(m.group(1))) {
foundHashes.add(m.group(1));
} else {
toDelete.add(line);
}
} else {
toDelete.add(line);
}
}
}
/**
* Breaks a list of strings into groups whose total size is within some limit.
* Kind of like the xargs command that groups arguments to avoid maximum argument length limits.
* Except that the limit in adb is about 1k instead of 512k or 2M on Linux.
*/
@VisibleForTesting
static ImmutableList<ImmutableList<String>> chunkArgs(Iterable<String> args, int sizeLimit) {
ImmutableList.Builder<ImmutableList<String>> topLevelBuilder = ImmutableList.builder();
ImmutableList.Builder<String> chunkBuilder = ImmutableList.builder();
int chunkSize = 0;
for (String arg : args) {
if (chunkSize + arg.length() > sizeLimit) {
topLevelBuilder.add(chunkBuilder.build());
chunkBuilder = ImmutableList.builder();
chunkSize = 0;
}
// We don't check for an individual arg greater than the limit.
// We just put it in its own chunk and hope for the best.
chunkBuilder.add(arg);
chunkSize += arg.length();
}
ImmutableList<String> tail = chunkBuilder.build();
if (!tail.isEmpty()) {
topLevelBuilder.add(tail);
}
return topLevelBuilder.build();
}
}
| apache-2.0 |
apache/cassandra | src/java/org/apache/cassandra/auth/AuthCache.java | 18012 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.auth;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.BiPredicate;
import java.util.function.BooleanSupplier;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.IntConsumer;
import java.util.function.IntSupplier;
import java.util.function.Supplier;
import com.google.common.util.concurrent.Uninterruptibles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.github.benmanes.caffeine.cache.Policy;
import org.apache.cassandra.concurrent.ExecutorPlus;
import org.apache.cassandra.concurrent.ScheduledExecutors;
import org.apache.cassandra.concurrent.Shutdownable;
import org.apache.cassandra.utils.ExecutorUtils;
import org.apache.cassandra.utils.MBeanWrapper;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.apache.cassandra.concurrent.ExecutorFactory.Global.executorFactory;
public class AuthCache<K, V> implements AuthCacheMBean, Shutdownable
{
private static final Logger logger = LoggerFactory.getLogger(AuthCache.class);
public static final String MBEAN_NAME_BASE = "org.apache.cassandra.auth:type=";
// We expect default values on cache retries and interval to be sufficient for everyone but have this escape hatch
// just in case.
static final String CACHE_LOAD_RETRIES_PROPERTY = "cassandra.auth_cache.warming.max_retries";
static final String CACHE_LOAD_RETRY_INTERVAL_PROPERTY = "cassandra.auth_cache.warming.retry_interval_ms";
private volatile ScheduledFuture cacheRefresher = null;
// Keep a handle on created instances so their executors can be terminated cleanly
private static final Set<Shutdownable> REGISTRY = new HashSet<>(4);
public static void shutdownAllAndWait(long timeout, TimeUnit unit) throws InterruptedException, TimeoutException
{
ExecutorUtils.shutdownNowAndWait(timeout, unit, REGISTRY);
}
/**
* Underlying cache. LoadingCache will call underlying load function on {@link #get} if key is not present
*/
protected volatile LoadingCache<K, V> cache;
private ExecutorPlus cacheRefreshExecutor;
private final String name;
private final IntConsumer setValidityDelegate;
private final IntSupplier getValidityDelegate;
private final IntConsumer setUpdateIntervalDelegate;
private final IntSupplier getUpdateIntervalDelegate;
private final IntConsumer setMaxEntriesDelegate;
private final IntSupplier getMaxEntriesDelegate;
private final Consumer<Boolean> setActiveUpdate;
private final BooleanSupplier getActiveUpdate;
private final Function<K, V> loadFunction;
private final Supplier<Map<K, V>> bulkLoadFunction;
private final BooleanSupplier enableCache;
// Determines whether the presence of a specific value should trigger the invalidation of
// the supplied key. Used by CredentialsCache & CacheRefresher to identify when the
// credentials for a role couldn't be loaded without throwing an exception or serving stale
// values until the natural expiry time.
private final BiPredicate<K, V> invalidateCondition;
/**
* @param name Used for MBean
* @param setValidityDelegate Used to set cache validity period. See {@link Policy#expireAfterWrite()}
* @param getValidityDelegate Getter for validity period
* @param setUpdateIntervalDelegate Used to set cache update interval. See {@link Policy#refreshAfterWrite()}
* @param getUpdateIntervalDelegate Getter for update interval
* @param setMaxEntriesDelegate Used to set max # entries in cache. See {@link com.github.benmanes.caffeine.cache.Policy.Eviction#setMaximum(long)}
* @param getMaxEntriesDelegate Getter for max entries.
* @param setActiveUpdate Method to process config to actively update the auth cache prior to configured cache expiration
* @param getActiveUpdate Getter for active update
* @param loadFunction Function to load the cache. Called on {@link #get(Object)}
* @param cacheEnabledDelegate Used to determine if cache is enabled.
*/
protected AuthCache(String name,
IntConsumer setValidityDelegate,
IntSupplier getValidityDelegate,
IntConsumer setUpdateIntervalDelegate,
IntSupplier getUpdateIntervalDelegate,
IntConsumer setMaxEntriesDelegate,
IntSupplier getMaxEntriesDelegate,
Consumer<Boolean> setActiveUpdate,
BooleanSupplier getActiveUpdate,
Function<K, V> loadFunction,
Supplier<Map<K, V>> bulkLoadFunction,
BooleanSupplier cacheEnabledDelegate)
{
this(name,
setValidityDelegate,
getValidityDelegate,
setUpdateIntervalDelegate,
getUpdateIntervalDelegate,
setMaxEntriesDelegate,
getMaxEntriesDelegate,
setActiveUpdate,
getActiveUpdate,
loadFunction,
bulkLoadFunction,
cacheEnabledDelegate,
(k, v) -> false);
}
/**
* @param name Used for MBean
* @param setValidityDelegate Used to set cache validity period. See {@link Policy#expireAfterWrite()}
* @param getValidityDelegate Getter for validity period
* @param setUpdateIntervalDelegate Used to set cache update interval. See {@link Policy#refreshAfterWrite()}
* @param getUpdateIntervalDelegate Getter for update interval
* @param setMaxEntriesDelegate Used to set max # entries in cache. See {@link com.github.benmanes.caffeine.cache.Policy.Eviction#setMaximum(long)}
* @param getMaxEntriesDelegate Getter for max entries.
* @param setActiveUpdate Actively update the cache before expiry
* @param getActiveUpdate Getter for active update
* @param loadFunction Function to load the cache. Called on {@link #get(Object)}
* @param cacheEnabledDelegate Used to determine if cache is enabled.
* @param invalidationCondition Used during active updates to determine if a refreshed value indicates a missing
* entry in the underlying table. If satisfied, the key will be invalidated.
*/
protected AuthCache(String name,
IntConsumer setValidityDelegate,
IntSupplier getValidityDelegate,
IntConsumer setUpdateIntervalDelegate,
IntSupplier getUpdateIntervalDelegate,
IntConsumer setMaxEntriesDelegate,
IntSupplier getMaxEntriesDelegate,
Consumer<Boolean> setActiveUpdate,
BooleanSupplier getActiveUpdate,
Function<K, V> loadFunction,
Supplier<Map<K, V>> bulkLoadFunction,
BooleanSupplier cacheEnabledDelegate,
BiPredicate<K, V> invalidationCondition)
{
this.name = checkNotNull(name);
this.setValidityDelegate = checkNotNull(setValidityDelegate);
this.getValidityDelegate = checkNotNull(getValidityDelegate);
this.setUpdateIntervalDelegate = checkNotNull(setUpdateIntervalDelegate);
this.getUpdateIntervalDelegate = checkNotNull(getUpdateIntervalDelegate);
this.setMaxEntriesDelegate = checkNotNull(setMaxEntriesDelegate);
this.getMaxEntriesDelegate = checkNotNull(getMaxEntriesDelegate);
this.setActiveUpdate = checkNotNull(setActiveUpdate);
this.getActiveUpdate = checkNotNull(getActiveUpdate);
this.loadFunction = checkNotNull(loadFunction);
this.bulkLoadFunction = checkNotNull(bulkLoadFunction);
this.enableCache = checkNotNull(cacheEnabledDelegate);
this.invalidateCondition = checkNotNull(invalidationCondition);
init();
}
/**
* Do setup for the cache and MBean.
*/
protected void init()
{
this.cacheRefreshExecutor = executorFactory().sequential(name + "Refresh");
cache = initCache(null);
MBeanWrapper.instance.registerMBean(this, getObjectName());
REGISTRY.add(this);
}
protected void unregisterMBean()
{
MBeanWrapper.instance.unregisterMBean(getObjectName(), MBeanWrapper.OnException.LOG);
}
protected String getObjectName()
{
return MBEAN_NAME_BASE + name;
}
/**
* Retrieve all cached entries. Will call {@link LoadingCache#asMap()} which does not trigger "load".
* @return a map of cached key-value pairs
*/
public Map<K, V> getAll()
{
if (cache == null)
return Collections.emptyMap();
return Collections.unmodifiableMap(cache.asMap());
}
/**
* Retrieve a value from the cache. Will call {@link LoadingCache#get(Object)} which will
* "load" the value if it's not present, thus populating the key.
* @param k
* @return The current value of {@code K} if cached or loaded.
*
* See {@link LoadingCache#get(Object)} for possible exceptions.
*/
public V get(K k)
{
if (cache == null)
return loadFunction.apply(k);
return cache.get(k);
}
/**
* Invalidate the entire cache.
*/
public synchronized void invalidate()
{
cache = initCache(null);
}
/**
* Invalidate a key.
* @param k key to invalidate
*/
public void invalidate(K k)
{
if (cache != null)
cache.invalidate(k);
}
/**
* Time in milliseconds that a value in the cache will expire after.
* @param validityPeriod in milliseconds
*/
public synchronized void setValidity(int validityPeriod)
{
if (Boolean.getBoolean("cassandra.disable_auth_caches_remote_configuration"))
throw new UnsupportedOperationException("Remote configuration of auth caches is disabled");
setValidityDelegate.accept(validityPeriod);
cache = initCache(cache);
}
public int getValidity()
{
return getValidityDelegate.getAsInt();
}
/**
* Time in milliseconds after which an entry in the cache should be refreshed (it's load function called again)
* @param updateInterval in milliseconds
*/
public synchronized void setUpdateInterval(int updateInterval)
{
if (Boolean.getBoolean("cassandra.disable_auth_caches_remote_configuration"))
throw new UnsupportedOperationException("Remote configuration of auth caches is disabled");
setUpdateIntervalDelegate.accept(updateInterval);
cache = initCache(cache);
}
public int getUpdateInterval()
{
return getUpdateIntervalDelegate.getAsInt();
}
/**
* Set maximum number of entries in the cache.
* @param maxEntries
*/
public synchronized void setMaxEntries(int maxEntries)
{
if (Boolean.getBoolean("cassandra.disable_auth_caches_remote_configuration"))
throw new UnsupportedOperationException("Remote configuration of auth caches is disabled");
setMaxEntriesDelegate.accept(maxEntries);
cache = initCache(cache);
}
public int getMaxEntries()
{
return getMaxEntriesDelegate.getAsInt();
}
public boolean getActiveUpdate()
{
return getActiveUpdate.getAsBoolean();
}
public synchronized void setActiveUpdate(boolean update)
{
if (Boolean.getBoolean("cassandra.disable_auth_caches_remote_configuration"))
throw new UnsupportedOperationException("Remote configuration of auth caches is disabled");
setActiveUpdate.accept(update);
cache = initCache(cache);
}
public long getEstimatedSize()
{
return cache == null ? 0L : cache.estimatedSize();
}
/**
* (Re-)initialise the underlying cache. Will update validity, max entries, and update interval if
* any have changed. The underlying {@link LoadingCache} will be initiated based on the provided {@code loadFunction}.
* Note: If you need some unhandled cache setting to be set you should extend {@link AuthCache} and override this method.
* @param existing If not null will only update cache update validity, max entries, and update interval.
* @return New {@link LoadingCache} if existing was null, otherwise the existing {@code cache}
*/
protected LoadingCache<K, V> initCache(LoadingCache<K, V> existing)
{
if (!enableCache.getAsBoolean())
return null;
if (getValidity() <= 0)
return null;
boolean activeUpdate = getActiveUpdate();
logger.info("(Re)initializing {} (validity period/update interval/max entries/active update) ({}/{}/{}/{})",
name, getValidity(), getUpdateInterval(), getMaxEntries(), activeUpdate);
LoadingCache<K, V> updatedCache;
if (existing == null)
{
updatedCache = Caffeine.newBuilder().refreshAfterWrite(activeUpdate ? getValidity() : getUpdateInterval(), TimeUnit.MILLISECONDS)
.expireAfterWrite(getValidity(), TimeUnit.MILLISECONDS)
.maximumSize(getMaxEntries())
.executor(cacheRefreshExecutor)
.build(loadFunction::apply);
}
else
{
updatedCache = cache;
// Always set as mandatory
cache.policy().refreshAfterWrite().ifPresent(policy ->
policy.setExpiresAfter(activeUpdate ? getValidity() : getUpdateInterval(), TimeUnit.MILLISECONDS));
cache.policy().expireAfterWrite().ifPresent(policy -> policy.setExpiresAfter(getValidity(), TimeUnit.MILLISECONDS));
cache.policy().eviction().ifPresent(policy -> policy.setMaximum(getMaxEntries()));
}
if (cacheRefresher != null)
{
cacheRefresher.cancel(false); // permit the two refreshers to race until the old one dies, should be harmless.
cacheRefresher = null;
}
if (activeUpdate)
{
cacheRefresher = ScheduledExecutors.optionalTasks.scheduleAtFixedRate(CacheRefresher.create(name,
updatedCache,
invalidateCondition),
getUpdateInterval(),
getUpdateInterval(),
TimeUnit.MILLISECONDS);
}
return updatedCache;
}
@Override
public boolean isTerminated()
{
return cacheRefreshExecutor.isTerminated();
}
@Override
public void shutdown()
{
cacheRefreshExecutor.shutdown();
}
@Override
public Object shutdownNow()
{
return cacheRefreshExecutor.shutdownNow();
}
@Override
public boolean awaitTermination(long timeout, TimeUnit units) throws InterruptedException
{
return cacheRefreshExecutor.awaitTermination(timeout, units);
}
public void warm()
{
if (cache == null)
{
logger.info("{} cache not enabled, skipping pre-warming", name);
return;
}
int retries = Integer.getInteger(CACHE_LOAD_RETRIES_PROPERTY, 10);
long retryInterval = Long.getLong(CACHE_LOAD_RETRY_INTERVAL_PROPERTY, 1000);
while (retries-- > 0)
{
try
{
Map<K, V> entries = bulkLoadFunction.get();
cache.putAll(entries);
break;
}
catch (Exception e)
{
Uninterruptibles.sleepUninterruptibly(retryInterval, TimeUnit.MILLISECONDS);
}
}
}
/*
* Implemented when we can provide an efficient way to bulk load all entries for a cache. This isn't a
* @FunctionalInterface due to the default impl, which is for IRoleManager, IAuthorizer, and INetworkAuthorizer.
* They all extend this interface so that implementations only need to provide an override if it's useful.
* IAuthenticator doesn't implement this interface because CredentialsCache is more tightly coupled to
* PasswordAuthenticator, which does expose a bulk loader.
*/
public interface BulkLoader<K, V>
{
default Supplier<Map<K, V>> bulkLoader()
{
return Collections::emptyMap;
}
}
}
| apache-2.0 |
Addepar/buck | src/com/facebook/buck/io/windowspipe/WindowsNamedPipeLibrary.java | 2210 | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.buck.io.windowspipe;
import com.sun.jna.Library;
import com.sun.jna.Memory;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.platform.win32.WinBase;
import com.sun.jna.platform.win32.WinNT;
import com.sun.jna.ptr.IntByReference;
import com.sun.jna.win32.W32APIOptions;
import java.nio.ByteBuffer;
@SuppressWarnings("checkstyle:methodname")
public interface WindowsNamedPipeLibrary extends WinNT, Library {
WindowsNamedPipeLibrary INSTANCE =
Native.loadLibrary("kernel32", WindowsNamedPipeLibrary.class, W32APIOptions.UNICODE_OPTIONS);
boolean GetOverlappedResult(
WinNT.HANDLE hFile,
Pointer lpOverlapped,
IntByReference lpNumberOfBytesTransferred,
boolean wait);
boolean ReadFile(
WinNT.HANDLE hFile,
Memory pointer,
int nNumberOfBytesToRead,
IntByReference lpNumberOfBytesRead,
Pointer lpOverlapped);
WinNT.HANDLE CreateFile(
String lpFileName,
int dwDesiredAccess,
int dwShareMode,
WinBase.SECURITY_ATTRIBUTES lpSecurityAttributes,
int dwCreationDisposition,
int dwFlagsAndAttributes,
WinNT.HANDLE hTemplateFile);
WinNT.HANDLE CreateEvent(
WinBase.SECURITY_ATTRIBUTES lpEventAttributes,
boolean bManualReset,
boolean bInitialState,
String lpName);
boolean CloseHandle(WinNT.HANDLE hObject);
boolean WriteFile(
WinNT.HANDLE hFile,
ByteBuffer lpBuffer,
int nNumberOfBytesToWrite,
IntByReference lpNumberOfBytesWritten,
Pointer lpOverlapped);
int GetLastError();
}
| apache-2.0 |
jbertouch/elasticsearch | core/src/main/java/org/elasticsearch/search/aggregations/metrics/percentiles/hdr/HDRPercentilesAggregator.java | 3022 | /*
* 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.percentiles.hdr;
import org.HdrHistogram.DoubleHistogram;
import org.elasticsearch.search.aggregations.Aggregator;
import org.elasticsearch.search.aggregations.InternalAggregation;
import org.elasticsearch.search.aggregations.pipeline.PipelineAggregator;
import org.elasticsearch.search.aggregations.support.AggregationContext;
import org.elasticsearch.search.aggregations.support.ValuesSource.Numeric;
import org.elasticsearch.search.aggregations.support.format.ValueFormatter;
import java.io.IOException;
import java.util.List;
import java.util.Map;
/**
*
*/
public class HDRPercentilesAggregator extends AbstractHDRPercentilesAggregator {
public HDRPercentilesAggregator(String name, Numeric valuesSource, AggregationContext context, Aggregator parent, double[] percents,
int numberOfSignificantValueDigits, boolean keyed, ValueFormatter formatter,
List<PipelineAggregator> pipelineAggregators, Map<String, Object> metaData) throws IOException {
super(name, valuesSource, context, parent, percents, numberOfSignificantValueDigits, keyed, formatter,
pipelineAggregators, metaData);
}
@Override
public InternalAggregation buildAggregation(long owningBucketOrdinal) {
DoubleHistogram state = getState(owningBucketOrdinal);
if (state == null) {
return buildEmptyAggregation();
} else {
return new InternalHDRPercentiles(name, keys, state, keyed, formatter, pipelineAggregators(), metaData());
}
}
@Override
public double metric(String name, long bucketOrd) {
DoubleHistogram state = getState(bucketOrd);
if (state == null) {
return Double.NaN;
} else {
return state.getValueAtPercentile(Double.parseDouble(name));
}
}
@Override
public InternalAggregation buildEmptyAggregation() {
DoubleHistogram state;
state = new DoubleHistogram(numberOfSignificantValueDigits);
state.setAutoResize(true);
return new InternalHDRPercentiles(name, keys, state,
keyed,
formatter, pipelineAggregators(), metaData());
}
}
| apache-2.0 |
pspaude/uPortal | uportal-war/src/main/java/org/jasig/portal/rendering/PortletRenderingIncorporationComponent.java | 7211 | /**
* Licensed to Jasig under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Jasig 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.jasig.portal.rendering;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jasig.portal.character.stream.CharacterEventReader;
import org.jasig.portal.character.stream.FilteringCharacterEventReader;
import org.jasig.portal.character.stream.events.CharacterDataEventImpl;
import org.jasig.portal.character.stream.events.CharacterEvent;
import org.jasig.portal.character.stream.events.PortletContentPlaceholderEvent;
import org.jasig.portal.character.stream.events.PortletHeaderPlaceholderEvent;
import org.jasig.portal.character.stream.events.PortletLinkPlaceholderEvent;
import org.jasig.portal.character.stream.events.PortletNewItemCountPlaceholderEvent;
import org.jasig.portal.character.stream.events.PortletTitlePlaceholderEvent;
import org.jasig.portal.portlet.om.IPortletWindowId;
import org.jasig.portal.portlet.rendering.IPortletExecutionManager;
import org.jasig.portal.utils.cache.CacheKey;
import org.springframework.beans.factory.annotation.Autowired;
/**
* Inserts the results of portlet's rendering into the character stream
*
* @author Eric Dalquist
* @version $Revision$
*/
public class PortletRenderingIncorporationComponent extends CharacterPipelineComponentWrapper {
private IPortletExecutionManager portletExecutionManager;
@Autowired
public void setPortletExecutionManager(IPortletExecutionManager portletExecutionManager) {
this.portletExecutionManager = portletExecutionManager;
}
/* (non-Javadoc)
* @see org.jasig.portal.rendering.PipelineComponent#getCacheKey(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
@Override
public CacheKey getCacheKey(HttpServletRequest request, HttpServletResponse response) {
/*
* TODO do all the portlet cache keys need to be included here?
* Probably for this to be useful
*/
return this.wrappedComponent.getCacheKey(request, response);
}
/* (non-Javadoc)
* @see org.jasig.portal.rendering.PipelineComponent#getEventReader(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
@Override
public PipelineEventReader<CharacterEventReader, CharacterEvent> getEventReader(HttpServletRequest request, HttpServletResponse response) {
final PipelineEventReader<CharacterEventReader, CharacterEvent> pipelineEventReader = this.wrappedComponent.getEventReader(request, response);
final CharacterEventReader eventReader = pipelineEventReader.getEventReader();
final PortletIncorporatingEventReader portletIncorporatingEventReader = new PortletIncorporatingEventReader(eventReader, request, response);
final Map<String, String> outputProperties = pipelineEventReader.getOutputProperties();
return new PipelineEventReaderImpl<CharacterEventReader, CharacterEvent>(portletIncorporatingEventReader, outputProperties);
}
private class PortletIncorporatingEventReader extends FilteringCharacterEventReader {
private final HttpServletRequest request;
private final HttpServletResponse response;
public PortletIncorporatingEventReader(CharacterEventReader delegate, HttpServletRequest request, HttpServletResponse response) {
super(delegate);
this.request = request;
this.response = response;
}
@Override
protected CharacterEvent filterEvent(CharacterEvent event, boolean peek) {
switch (event.getEventType()) {
case PORTLET_HEADER: {
final PortletHeaderPlaceholderEvent headerPlaceholderEvent = (PortletHeaderPlaceholderEvent) event;
final IPortletWindowId portletWindowId = headerPlaceholderEvent.getPortletWindowId();
final String output = portletExecutionManager.getPortletHeadOutput(portletWindowId, this.request, this.response);
return CharacterDataEventImpl.create(output);
}
case PORTLET_CONTENT: {
final PortletContentPlaceholderEvent contentPlaceholderEvent = (PortletContentPlaceholderEvent)event;
final IPortletWindowId portletWindowId = contentPlaceholderEvent.getPortletWindowId();
final String output = portletExecutionManager.getPortletOutput(portletWindowId, this.request, this.response);
return CharacterDataEventImpl.create(output);
}
case PORTLET_TITLE: {
final PortletTitlePlaceholderEvent titlePlaceholderEvent = (PortletTitlePlaceholderEvent)event;
final IPortletWindowId portletWindowId = titlePlaceholderEvent.getPortletWindowId();
final String title = portletExecutionManager.getPortletTitle(portletWindowId, this.request, this.response);
return CharacterDataEventImpl.create(title);
}
case PORTLET_NEW_ITEM_COUNT: {
final PortletNewItemCountPlaceholderEvent newItemCountPlaceholderEvent = (PortletNewItemCountPlaceholderEvent)event;
final IPortletWindowId portletWindowId = newItemCountPlaceholderEvent.getPortletWindowId();
final int newItemCount = portletExecutionManager.getPortletNewItemCount(portletWindowId, this.request, this.response);
return CharacterDataEventImpl.create(String.valueOf(newItemCount));
}
case PORTLET_LINK: {
final PortletLinkPlaceholderEvent linkPlaceholderEvent = (PortletLinkPlaceholderEvent)event;
final IPortletWindowId portletWindowId = linkPlaceholderEvent.getPortletWindowId();
final String defaultPortletUrl = linkPlaceholderEvent.getDefaultPortletUrl();
final String link = portletExecutionManager.getPortletLink(portletWindowId, defaultPortletUrl, this.request, this.response);
return CharacterDataEventImpl.create(link);
}
default: {
return event;
}
}
}
}
}
| apache-2.0 |
gabby2212/gs-collections | unit-tests/src/test/java/com/gs/collections/impl/list/mutable/ListAdapterTest.java | 3453 | /*
* Copyright 2014 Goldman Sachs.
*
* 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.gs.collections.impl.list.mutable;
import java.util.Arrays;
import java.util.LinkedList;
import com.gs.collections.api.list.MutableList;
import com.gs.collections.impl.test.Verify;
import org.junit.Assert;
import org.junit.Test;
/**
* JUnit test for {@link ListAdapter}.
*/
public class ListAdapterTest extends AbstractListTestCase
{
@Override
protected <T> ListAdapter<T> newWith(T... littleElements)
{
return new ListAdapter<>(new LinkedList<>(FastList.newListWith(littleElements)));
}
@Test(expected = NullPointerException.class)
public void null_throws()
{
new ListAdapter<>(null);
}
@Override
@Test
public void testClone()
{
MutableList<Integer> list = this.newWith(1, 2, 3);
MutableList<Integer> list2 = list.clone();
Verify.assertListsEqual(list, list2);
}
@Test
@Override
public void subList()
{
// Not serializable
MutableList<String> list = this.newWith("A", "B", "C", "D");
MutableList<String> sublist = list.subList(1, 3);
Verify.assertEqualsAndHashCode(sublist, sublist);
Verify.assertSize(2, sublist);
Verify.assertContainsAll(sublist, "B", "C");
sublist.add("X");
Verify.assertSize(3, sublist);
Verify.assertContainsAll(sublist, "B", "C", "X");
Verify.assertSize(5, list);
Verify.assertContainsAll(list, "A", "B", "C", "X", "D");
sublist.remove("X");
Verify.assertContainsAll(sublist, "B", "C");
Verify.assertContainsAll(list, "A", "B", "C", "D");
Assert.assertEquals("C", sublist.set(1, "R"));
Verify.assertContainsAll(sublist, "B", "R");
Verify.assertContainsAll(list, "A", "B", "R", "D");
sublist.addAll(Arrays.asList("W", "G"));
Verify.assertContainsAll(sublist, "B", "R", "W", "G");
Verify.assertContainsAll(list, "A", "B", "R", "W", "G", "D");
sublist.clear();
Verify.assertEmpty(sublist);
Verify.assertContainsAll(list, "A", "D");
}
@Override
@Test
public void withMethods()
{
super.withMethods();
Verify.assertContainsAll(this.newWith(1).with(2, 3), 1, 2, 3);
Verify.assertContainsAll(this.newWith(1).with(2, 3, 4), 1, 2, 3, 4);
Verify.assertContainsAll(this.newWith(1).with(2, 3, 4, 5), 1, 2, 3, 4, 5);
}
@Override
@Test
public void getWithArrayIndexOutOfBoundsException()
{
Object item = new Object();
Verify.assertThrows(IndexOutOfBoundsException.class, () -> this.newWith(item).get(-1));
}
@Test
public void adaptNull()
{
Verify.assertThrows(NullPointerException.class, () -> new ListAdapter<>(null));
Verify.assertThrows(NullPointerException.class, () -> ListAdapter.adapt(null));
}
}
| apache-2.0 |
apache/accumulo | server/tserver/src/main/java/org/apache/accumulo/tserver/log/DfsLogger.java | 23806 | /*
* 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.accumulo.tserver.log;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Collections.singletonList;
import static org.apache.accumulo.tserver.logger.LogEvents.COMPACTION_FINISH;
import static org.apache.accumulo.tserver.logger.LogEvents.COMPACTION_START;
import static org.apache.accumulo.tserver.logger.LogEvents.DEFINE_TABLET;
import static org.apache.accumulo.tserver.logger.LogEvents.MANY_MUTATIONS;
import static org.apache.accumulo.tserver.logger.LogEvents.MUTATION;
import static org.apache.accumulo.tserver.logger.LogEvents.OPEN;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.channels.ClosedChannelException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.accumulo.core.Constants;
import org.apache.accumulo.core.client.Durability;
import org.apache.accumulo.core.conf.AccumuloConfiguration;
import org.apache.accumulo.core.conf.Property;
import org.apache.accumulo.core.crypto.CryptoEnvironmentImpl;
import org.apache.accumulo.core.crypto.CryptoServiceFactory;
import org.apache.accumulo.core.crypto.CryptoServiceFactory.ClassloaderType;
import org.apache.accumulo.core.crypto.CryptoUtils;
import org.apache.accumulo.core.crypto.streams.NoFlushOutputStream;
import org.apache.accumulo.core.data.Mutation;
import org.apache.accumulo.core.spi.crypto.CryptoEnvironment;
import org.apache.accumulo.core.spi.crypto.CryptoEnvironment.Scope;
import org.apache.accumulo.core.spi.crypto.CryptoService;
import org.apache.accumulo.core.spi.crypto.FileDecrypter;
import org.apache.accumulo.core.spi.crypto.FileEncrypter;
import org.apache.accumulo.core.spi.crypto.NoCryptoService;
import org.apache.accumulo.core.util.Pair;
import org.apache.accumulo.core.util.threads.Threads;
import org.apache.accumulo.server.ServerContext;
import org.apache.accumulo.server.fs.VolumeChooserEnvironmentImpl;
import org.apache.accumulo.server.fs.VolumeManager;
import org.apache.accumulo.tserver.TabletMutations;
import org.apache.accumulo.tserver.logger.LogFileKey;
import org.apache.accumulo.tserver.logger.LogFileValue;
import org.apache.accumulo.tserver.tablet.CommitSession;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.DFSOutputStream;
import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
/**
* Wrap a connection to a logger.
*
*/
public class DfsLogger implements Comparable<DfsLogger> {
// older version supported for upgrade
public static final String LOG_FILE_HEADER_V3 = "--- Log File Header (v3) ---";
/**
* Simplified encryption technique supported in V4.
*
* @since 2.0
*/
public static final String LOG_FILE_HEADER_V4 = "--- Log File Header (v4) ---";
private static final Logger log = LoggerFactory.getLogger(DfsLogger.class);
private static final DatanodeInfo[] EMPTY_PIPELINE = new DatanodeInfo[0];
public static class LogClosedException extends IOException {
private static final long serialVersionUID = 1L;
public LogClosedException() {
super("LogClosed");
}
}
/**
* A well-timed tabletserver failure could result in an incomplete header written to a write-ahead
* log. This exception is thrown when the header cannot be read from a WAL which should only
* happen when the tserver dies as described.
*/
public static class LogHeaderIncompleteException extends Exception {
private static final long serialVersionUID = 1L;
public LogHeaderIncompleteException(EOFException cause) {
super(cause);
}
}
public interface ServerResources {
AccumuloConfiguration getConfiguration();
VolumeManager getVolumeManager();
}
private final LinkedBlockingQueue<DfsLogger.LogWork> workQueue = new LinkedBlockingQueue<>();
private final Object closeLock = new Object();
private static final DfsLogger.LogWork CLOSED_MARKER =
new DfsLogger.LogWork(null, Durability.FLUSH);
private static final LogFileValue EMPTY = new LogFileValue();
private boolean closed = false;
private class LogSyncingTask implements Runnable {
private int expectedReplication = 0;
@Override
public void run() {
ArrayList<DfsLogger.LogWork> work = new ArrayList<>();
boolean sawClosedMarker = false;
while (!sawClosedMarker) {
work.clear();
try {
work.add(workQueue.take());
} catch (InterruptedException ex) {
continue;
}
workQueue.drainTo(work);
Optional<Boolean> shouldHSync = Optional.empty();
loop: for (LogWork logWork : work) {
switch (logWork.durability) {
case DEFAULT:
case NONE:
case LOG:
// shouldn't make it to the work queue
throw new IllegalArgumentException("unexpected durability " + logWork.durability);
case SYNC:
shouldHSync = Optional.of(Boolean.TRUE);
break loop;
case FLUSH:
if (shouldHSync.isEmpty()) {
shouldHSync = Optional.of(Boolean.FALSE);
}
break;
}
}
long start = System.currentTimeMillis();
try {
if (shouldHSync.isPresent()) {
if (shouldHSync.get()) {
logFile.hsync();
syncCounter.incrementAndGet();
} else {
logFile.hflush();
flushCounter.incrementAndGet();
}
}
} catch (IOException | RuntimeException ex) {
fail(work, ex, "synching");
}
long duration = System.currentTimeMillis() - start;
if (duration > slowFlushMillis) {
String msg = new StringBuilder(128).append("Slow sync cost: ").append(duration)
.append(" ms, current pipeline: ").append(Arrays.toString(getPipeLine())).toString();
log.info(msg);
if (expectedReplication > 0) {
int current = expectedReplication;
try {
current = ((DFSOutputStream) logFile.getWrappedStream()).getCurrentBlockReplication();
} catch (IOException e) {
fail(work, e, "getting replication level");
}
if (current < expectedReplication) {
fail(work,
new IOException(
"replication of " + current + " is less than " + expectedReplication),
"replication check");
}
}
}
if (expectedReplication == 0 && logFile.getWrappedStream() instanceof DFSOutputStream) {
try {
expectedReplication =
((DFSOutputStream) logFile.getWrappedStream()).getCurrentBlockReplication();
} catch (IOException e) {
fail(work, e, "getting replication level");
}
}
for (DfsLogger.LogWork logWork : work)
if (logWork == CLOSED_MARKER)
sawClosedMarker = true;
else
logWork.latch.countDown();
}
}
private void fail(ArrayList<DfsLogger.LogWork> work, Exception ex, String why) {
log.warn("Exception {} {}", why, ex, ex);
for (DfsLogger.LogWork logWork : work) {
logWork.exception = ex;
}
}
}
private static class LogWork {
final CountDownLatch latch;
final Durability durability;
volatile Exception exception;
public LogWork(CountDownLatch latch, Durability durability) {
this.latch = latch;
this.durability = durability;
}
}
static class LoggerOperation {
private final LogWork work;
public LoggerOperation(LogWork work) {
this.work = work;
}
public void await() throws IOException {
try {
work.latch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
if (work.exception != null) {
if (work.exception instanceof IOException)
throw (IOException) work.exception;
else if (work.exception instanceof RuntimeException)
throw (RuntimeException) work.exception;
else
throw new RuntimeException(work.exception);
}
}
}
private static class NoWaitLoggerOperation extends LoggerOperation {
public NoWaitLoggerOperation() {
super(null);
}
@Override
public void await() {
return;
}
}
static final LoggerOperation NO_WAIT_LOGGER_OP = new NoWaitLoggerOperation();
@Override
public boolean equals(Object obj) {
// filename is unique
if (obj == null)
return false;
if (obj instanceof DfsLogger)
return getFileName().equals(((DfsLogger) obj).getFileName());
return false;
}
@Override
public int hashCode() {
// filename is unique
return getFileName().hashCode();
}
private final ServerContext context;
private final ServerResources conf;
private FSDataOutputStream logFile;
private DataOutputStream encryptingLogFile = null;
private String logPath;
private Thread syncThread;
/* Track what's actually in +r/!0 for this logger ref */
private String metaReference;
private AtomicLong syncCounter;
private AtomicLong flushCounter;
private final long slowFlushMillis;
private long writes = 0;
private DfsLogger(ServerContext context, ServerResources conf) {
this.context = context;
this.conf = conf;
this.slowFlushMillis =
conf.getConfiguration().getTimeInMillis(Property.TSERV_SLOW_FLUSH_MILLIS);
}
public DfsLogger(ServerContext context, ServerResources conf, AtomicLong syncCounter,
AtomicLong flushCounter) {
this(context, conf);
this.syncCounter = syncCounter;
this.flushCounter = flushCounter;
}
/**
* Reference a pre-existing log file.
*
* @param meta
* the cq for the "log" entry in +r/!0
*/
public DfsLogger(ServerContext context, ServerResources conf, String filename, String meta) {
this(context, conf);
this.logPath = filename;
metaReference = meta;
}
/**
* Reads the WAL file header, and returns a decrypting stream which wraps the original stream. If
* the file is not encrypted, the original stream is returned.
*
* @throws LogHeaderIncompleteException
* if the header cannot be fully read (can happen if the tserver died before finishing)
*/
public static DataInputStream getDecryptingStream(FSDataInputStream input,
AccumuloConfiguration conf) throws LogHeaderIncompleteException, IOException {
DataInputStream decryptingInput;
byte[] magic4 = DfsLogger.LOG_FILE_HEADER_V4.getBytes(UTF_8);
byte[] magic3 = DfsLogger.LOG_FILE_HEADER_V3.getBytes(UTF_8);
if (magic4.length != magic3.length)
throw new AssertionError("Always expect log file headers to be same length : " + magic4.length
+ " != " + magic3.length);
byte[] magicBuffer = new byte[magic4.length];
try {
input.readFully(magicBuffer);
if (Arrays.equals(magicBuffer, magic4)) {
CryptoService cryptoService =
CryptoServiceFactory.newInstance(conf, ClassloaderType.ACCUMULO);
FileDecrypter decrypter = CryptoUtils.getFileDecrypter(cryptoService, Scope.WAL, input);
log.debug("Using {} for decrypting WAL", cryptoService.getClass().getSimpleName());
decryptingInput = cryptoService instanceof NoCryptoService ? input
: new DataInputStream(decrypter.decryptStream(input));
} else if (Arrays.equals(magicBuffer, magic3)) {
// Read logs files from Accumulo 1.9
String cryptoModuleClassname = input.readUTF();
if (!cryptoModuleClassname.equals("NullCryptoModule")) {
throw new IllegalArgumentException(
"Old encryption modules not supported at this time. Unsupported module : "
+ cryptoModuleClassname);
}
decryptingInput = input;
} else {
throw new IllegalArgumentException(
"Unsupported write ahead log version " + new String(magicBuffer));
}
} catch (EOFException e) {
// Explicitly catch any exceptions that should be converted to LogHeaderIncompleteException
// A TabletServer might have died before the (complete) header was written
throw new LogHeaderIncompleteException(e);
}
return decryptingInput;
}
/**
* Opens a Write-Ahead Log file and writes the necessary header information and OPEN entry to the
* file. The file is ready to be used for ingest if this method returns successfully. If an
* exception is thrown from this method, it is the callers responsibility to ensure that
* {@link #close()} is called to prevent leaking the file handle and/or syncing thread.
*
* @param address
* The address of the host using this WAL
*/
public synchronized void open(String address) throws IOException {
String filename = UUID.randomUUID().toString();
log.debug("Address is {}", address);
String logger = Joiner.on("+").join(address.split(":"));
log.debug("DfsLogger.open() begin");
VolumeManager fs = conf.getVolumeManager();
var chooserEnv = new VolumeChooserEnvironmentImpl(
org.apache.accumulo.core.spi.fs.VolumeChooserEnvironment.Scope.LOGGER, context);
logPath = fs.choose(chooserEnv, context.getBaseUris()) + Path.SEPARATOR + Constants.WAL_DIR
+ Path.SEPARATOR + logger + Path.SEPARATOR + filename;
metaReference = toString();
LoggerOperation op = null;
try {
Path logfilePath = new Path(logPath);
short replication = (short) conf.getConfiguration().getCount(Property.TSERV_WAL_REPLICATION);
if (replication == 0)
replication = fs.getDefaultReplication(logfilePath);
long blockSize = getWalBlockSize(conf.getConfiguration());
if (conf.getConfiguration().getBoolean(Property.TSERV_WAL_SYNC))
logFile = fs.createSyncable(logfilePath, 0, replication, blockSize);
else
logFile = fs.create(logfilePath, true, 0, replication, blockSize);
// check again that logfile can be sync'd
if (!fs.canSyncAndFlush(logfilePath)) {
log.warn("sync not supported for log file {}. Data loss may occur.", logPath);
}
// Initialize the log file with a header and its encryption
CryptoService cryptoService = context.getCryptoService();
logFile.write(LOG_FILE_HEADER_V4.getBytes(UTF_8));
log.debug("Using {} for encrypting WAL {}", cryptoService.getClass().getSimpleName(),
filename);
CryptoEnvironment env = new CryptoEnvironmentImpl(Scope.WAL, null);
FileEncrypter encrypter = cryptoService.getFileEncrypter(env);
byte[] cryptoParams = encrypter.getDecryptionParameters();
CryptoUtils.writeParams(cryptoParams, logFile);
/**
* Always wrap the WAL in a NoFlushOutputStream to prevent extra flushing to HDFS. The
* {@link #write(LogFileKey, LogFileValue)} method will flush crypto data or do nothing when
* crypto is not enabled.
**/
OutputStream encryptedStream = encrypter.encryptStream(new NoFlushOutputStream(logFile));
if (encryptedStream instanceof NoFlushOutputStream) {
encryptingLogFile = (NoFlushOutputStream) encryptedStream;
} else {
encryptingLogFile = new DataOutputStream(encryptedStream);
}
LogFileKey key = new LogFileKey();
key.event = OPEN;
key.tserverSession = filename;
key.filename = filename;
op = logKeyData(key, Durability.SYNC);
} catch (Exception ex) {
if (logFile != null)
logFile.close();
logFile = null;
encryptingLogFile = null;
throw new IOException(ex);
}
syncThread = Threads.createThread("Accumulo WALog thread " + this, new LogSyncingTask());
syncThread.start();
op.await();
log.debug("Got new write-ahead log: {}", this);
}
@SuppressWarnings("deprecation")
static long getWalBlockSize(AccumuloConfiguration conf) {
long blockSize = conf.getAsBytes(Property.TSERV_WAL_BLOCKSIZE);
if (blockSize == 0)
blockSize = (long) (conf.getAsBytes(
conf.resolve(Property.TSERV_WAL_MAX_SIZE, Property.TSERV_WALOG_MAX_SIZE)) * 1.1);
return blockSize;
}
@Override
public String toString() {
String fileName = getFileName();
if (fileName.contains(":"))
return getLogger() + "/" + getFileName();
return fileName;
}
/**
* get the cq needed to reference this logger's entry in +r/!0
*/
public String getMeta() {
if (metaReference == null) {
throw new IllegalStateException("logger doesn't have meta reference. " + this);
}
return metaReference;
}
public String getFileName() {
return logPath;
}
public Path getPath() {
return new Path(logPath);
}
public void close() throws IOException {
synchronized (closeLock) {
if (closed)
return;
// after closed is set to true, nothing else should be added to the queue
// CLOSED_MARKER should be the last thing on the queue, therefore when the
// background thread sees the marker and exits there should be nothing else
// to process... so nothing should be left waiting for the background
// thread to do work
closed = true;
workQueue.add(CLOSED_MARKER);
}
// wait for background thread to finish before closing log file
if (syncThread != null) {
try {
syncThread.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
// expect workq should be empty at this point
if (!workQueue.isEmpty()) {
log.error("WAL work queue not empty after sync thread exited");
throw new IllegalStateException("WAL work queue not empty after sync thread exited");
}
if (encryptingLogFile != null)
try {
logFile.close();
} catch (IOException ex) {
log.error("Failed to close log file", ex);
throw new LogClosedException();
}
}
public synchronized long getWrites() {
Preconditions.checkState(writes >= 0);
return writes;
}
public LoggerOperation defineTablet(CommitSession cs) throws IOException {
// write this log to the METADATA table
final LogFileKey key = new LogFileKey();
key.event = DEFINE_TABLET;
key.seq = cs.getWALogSeq();
key.tabletId = cs.getLogId();
key.tablet = cs.getExtent();
return logKeyData(key, Durability.LOG);
}
private synchronized void write(LogFileKey key, LogFileValue value) throws IOException {
key.write(encryptingLogFile);
value.write(encryptingLogFile);
encryptingLogFile.flush();
writes++;
}
private LoggerOperation logKeyData(LogFileKey key, Durability d) throws IOException {
return logFileData(singletonList(new Pair<>(key, EMPTY)), d);
}
private LoggerOperation logFileData(List<Pair<LogFileKey,LogFileValue>> keys,
Durability durability) throws IOException {
DfsLogger.LogWork work = new DfsLogger.LogWork(new CountDownLatch(1), durability);
try {
for (Pair<LogFileKey,LogFileValue> pair : keys) {
write(pair.getFirst(), pair.getSecond());
}
} catch (ClosedChannelException ex) {
throw new LogClosedException();
} catch (Exception e) {
log.error("Failed to write log entries", e);
work.exception = e;
}
synchronized (closeLock) {
// use a different lock for close check so that adding to work queue does not need
// to wait on walog I/O operations
if (closed)
throw new LogClosedException();
if (durability == Durability.LOG)
return NO_WAIT_LOGGER_OP;
workQueue.add(work);
}
return new LoggerOperation(work);
}
public LoggerOperation logManyTablets(Collection<TabletMutations> mutations) throws IOException {
Durability durability = Durability.NONE;
List<Pair<LogFileKey,LogFileValue>> data = new ArrayList<>();
for (TabletMutations tabletMutations : mutations) {
LogFileKey key = new LogFileKey();
key.event = MANY_MUTATIONS;
key.seq = tabletMutations.getSeq();
key.tabletId = tabletMutations.getTid();
LogFileValue value = new LogFileValue();
value.mutations = tabletMutations.getMutations();
data.add(new Pair<>(key, value));
durability = maxDurability(tabletMutations.getDurability(), durability);
}
return logFileData(data, durability);
}
public LoggerOperation log(CommitSession cs, Mutation m, Durability d) throws IOException {
LogFileKey key = new LogFileKey();
key.event = MUTATION;
key.seq = cs.getWALogSeq();
key.tabletId = cs.getLogId();
LogFileValue value = new LogFileValue();
value.mutations = singletonList(m);
return logFileData(singletonList(new Pair<>(key, value)), d);
}
/**
* Return the Durability with the highest precedence
*/
static Durability maxDurability(Durability dur1, Durability dur2) {
if (dur1.ordinal() > dur2.ordinal()) {
return dur1;
} else {
return dur2;
}
}
public LoggerOperation minorCompactionFinished(long seq, int tid, Durability durability)
throws IOException {
LogFileKey key = new LogFileKey();
key.event = COMPACTION_FINISH;
key.seq = seq;
key.tabletId = tid;
return logKeyData(key, durability);
}
public LoggerOperation minorCompactionStarted(long seq, int tid, String fqfn,
Durability durability) throws IOException {
LogFileKey key = new LogFileKey();
key.event = COMPACTION_START;
key.seq = seq;
key.tabletId = tid;
key.filename = fqfn;
return logKeyData(key, durability);
}
private String getLogger() {
String[] parts = logPath.split("/");
return Joiner.on(":").join(parts[parts.length - 2].split("[+]"));
}
@Override
public int compareTo(DfsLogger o) {
return getFileName().compareTo(o.getFileName());
}
/*
* The following method was shamelessly lifted from HBASE-11240 (sans reflection). Thanks HBase!
*/
/**
* This method gets the pipeline for the current walog.
*
* @return non-null array of DatanodeInfo
*/
DatanodeInfo[] getPipeLine() {
if (logFile != null) {
OutputStream os = logFile.getWrappedStream();
if (os instanceof DFSOutputStream) {
return ((DFSOutputStream) os).getPipeline();
}
}
// Don't have a pipeline or can't figure it out.
return EMPTY_PIPELINE;
}
}
| apache-2.0 |
3cky/karaf-cellar | core/src/main/java/org/apache/karaf/cellar/core/control/ConsumerSwitchResultHandler.java | 919 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.karaf.cellar.core.control;
import org.apache.karaf.cellar.core.command.ResultHandler;
/**
* Consumer switch result handler.
*/
public class ConsumerSwitchResultHandler extends ResultHandler<ConsumerSwitchResult> {
@Override
public Class<ConsumerSwitchResult> getType() {
return ConsumerSwitchResult.class;
}
}
| apache-2.0 |
bradparks/beaker-notebook | plugin/jvm/src/main/java/com/twosigma/beaker/chart/xychart/plotitem/Points.java | 4543 | /*
* Copyright 2014 TWO SIGMA OPEN SOURCE, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.twosigma.beaker.chart.xychart.plotitem;
import com.twosigma.beaker.chart.Color;
import com.twosigma.beaker.chart.Filter;
import java.util.EnumSet;
import java.util.List;
public class Points extends XYGraphics {
private final static EnumSet<Filter> POSSIBLE_LOD_FILTERS = EnumSet.of(Filter.POINT,
Filter.BOX);
private float baseSize = 6.0f;
private List<Number> sizes;
private ShapeType baseShape = ShapeType.DEFAULT;
private List<ShapeType> shapes;
private Boolean baseFill;
private List<Boolean> fills;
private Color baseColor;
private List<Color> colors;
private Color baseOutlineColor;
private List<Color> outlineColors;
public void setSize(Object size) {
if (size instanceof Number) {
this.baseSize = ((Number) size).floatValue();
} else if (size instanceof List) {
@SuppressWarnings("unchecked")
List<Number> ss = (List<Number>) size;
setSizes(ss);
} else {
throw new IllegalArgumentException(
"setSize takes Number or List of Number");
}
}
private void setSizes(List<Number> sizes) {
this.sizes = sizes;
}
public float getSize() {
return this.baseSize;
}
public List<Number> getSizes() {
return this.sizes;
}
public void setShape(Object shape) {
if (shape instanceof ShapeType) {
this.baseShape = (ShapeType) shape;
} else if (shape instanceof List) {
@SuppressWarnings("unchecked")
List<ShapeType> ss = (List<ShapeType>) shape;
setShapes(ss);
} else {
throw new IllegalArgumentException(
"setShape takes ShapeType or List of ShapeType");
}
}
private void setShapes(List<ShapeType> shapes) {
this.shapes = shapes;
}
public ShapeType getShape() {
return this.baseShape;
}
public List<ShapeType> getShapes() {
return this.shapes;
}
public void setFill(Object fill) {
if (fill instanceof Boolean) {
this.baseFill = (Boolean) fill;
} else if (fill instanceof List) {
@SuppressWarnings("unchecked")
List<Boolean> fs = (List<Boolean>) fill;
setFills(fs);
} else {
throw new IllegalArgumentException(
"setFill takes ShapeType or List of ShapeType");
}
}
private void setFills(List<Boolean> fills) {
this.fills = fills;
}
public Boolean getFill() {
return this.baseFill;
}
public List<Boolean> getFills() {
return this.fills;
}
public void setColor(Object color) {
if (color instanceof Color) {
this.baseColor = (Color) color;
} else if (color instanceof List) {
@SuppressWarnings("unchecked")
List<Color> cs = (List<Color>) color;
setColors(cs);
} else {
throw new IllegalArgumentException(
"setColor takes Color or List of Color");
}
}
@Override
public void setColori(Color color) {
this.baseColor = color;
}
private void setColors(List<Color> colors) {
this.colors = colors;
}
@Override
public Color getColor() {
return this.baseColor;
}
public List<Color> getColors() {
return this.colors;
}
public void setOutlineColor(Object color) {
if (color instanceof Color) {
this.baseOutlineColor = (Color) color;
} else if (color instanceof List) {
@SuppressWarnings("unchecked")
List<Color> cs = (List<Color>) color;
setOutlineColors(cs);
} else {
throw new IllegalArgumentException(
"setOutlineColor takes Color or List of Color");
}
}
private void setOutlineColors(List<Color> colors) {
this.outlineColors = colors;
}
public Color getOutlineColor() {
return this.baseOutlineColor;
}
public List<Color> getOutlineColors() {
return this.outlineColors;
}
@Override
protected EnumSet<Filter> getPossibleFilters() {
return POSSIBLE_LOD_FILTERS;
}
}
| apache-2.0 |
hequn8128/flink | flink-core/src/main/java/org/apache/flink/api/common/functions/util/RuntimeUDFContext.java | 4631 | /*
* 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.api.common.functions.util;
import org.apache.flink.annotation.Internal;
import org.apache.flink.api.common.ExecutionConfig;
import org.apache.flink.api.common.TaskInfo;
import org.apache.flink.api.common.accumulators.Accumulator;
import org.apache.flink.api.common.externalresource.ExternalResourceInfo;
import org.apache.flink.api.common.functions.BroadcastVariableInitializer;
import org.apache.flink.api.common.functions.RuntimeContext;
import org.apache.flink.core.fs.Path;
import org.apache.flink.metrics.MetricGroup;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Future;
/**
* A standalone implementation of the {@link RuntimeContext}, created by runtime UDF operators.
*/
@Internal
public class RuntimeUDFContext extends AbstractRuntimeUDFContext {
private final HashMap<String, Object> initializedBroadcastVars = new HashMap<>();
private final HashMap<String, List<?>> uninitializedBroadcastVars = new HashMap<>();
public RuntimeUDFContext(TaskInfo taskInfo, ClassLoader userCodeClassLoader, ExecutionConfig executionConfig,
Map<String, Future<Path>> cpTasks, Map<String, Accumulator<?, ?>> accumulators,
MetricGroup metrics) {
super(taskInfo, userCodeClassLoader, executionConfig, accumulators, cpTasks, metrics);
}
@Override
public boolean hasBroadcastVariable(String name) {
return this.initializedBroadcastVars.containsKey(name) || this.uninitializedBroadcastVars.containsKey(name);
}
@Override
@SuppressWarnings("unchecked")
public <RT> List<RT> getBroadcastVariable(String name) {
// check if we have an initialized version
Object o = this.initializedBroadcastVars.get(name);
if (o != null) {
if (o instanceof List) {
return (List<RT>) o;
}
else {
throw new IllegalStateException("The broadcast variable with name '" + name +
"' is not a List. A different call must have requested this variable with a BroadcastVariableInitializer.");
}
}
else {
List<?> uninitialized = this.uninitializedBroadcastVars.remove(name);
if (uninitialized != null) {
this.initializedBroadcastVars.put(name, uninitialized);
return (List<RT>) uninitialized;
}
else {
throw new IllegalArgumentException("The broadcast variable with name '" + name + "' has not been set.");
}
}
}
@SuppressWarnings("unchecked")
@Override
public <T, C> C getBroadcastVariableWithInitializer(String name, BroadcastVariableInitializer<T, C> initializer) {
// check if we have an initialized version
Object o = this.initializedBroadcastVars.get(name);
if (o != null) {
return (C) o;
}
else {
List<T> uninitialized = (List<T>) this.uninitializedBroadcastVars.remove(name);
if (uninitialized != null) {
C result = initializer.initializeBroadcastVariable(uninitialized);
this.initializedBroadcastVars.put(name, result);
return result;
}
else {
throw new IllegalArgumentException("The broadcast variable with name '" + name + "' has not been set.");
}
}
}
@Override
public Set<ExternalResourceInfo> getExternalResourceInfos(String resourceName) {
throw new UnsupportedOperationException("Do not support external resource in current environment");
}
// --------------------------------------------------------------------------------------------
public void setBroadcastVariable(String name, List<?> value) {
this.uninitializedBroadcastVars.put(name, value);
this.initializedBroadcastVars.remove(name);
}
public void clearBroadcastVariable(String name) {
this.uninitializedBroadcastVars.remove(name);
this.initializedBroadcastVars.remove(name);
}
public void clearAllBroadcastVariables() {
this.uninitializedBroadcastVars.clear();
this.initializedBroadcastVars.clear();
}
}
| apache-2.0 |
HashEngineering/darkcoinj | core/src/main/java/org/bitcoinj/net/discovery/HttpDiscovery.java | 5635 | /*
* Copyright 2014 Mike Hearn
* Copyright 2015 Andreas Schildbach
*
* 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.bitcoinj.net.discovery;
import com.google.common.annotations.*;
import com.google.protobuf.*;
import org.bitcoin.crawler.*;
import org.bitcoinj.core.*;
import org.slf4j.*;
import javax.annotation.*;
import java.io.*;
import java.net.*;
import java.security.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.zip.*;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import static com.google.common.base.Preconditions.*;
/**
* A class that knows how to read signed sets of seeds over HTTP, using a simple protobuf based protocol. See the
* peerseeds.proto file for the definition, with a gzipped delimited SignedPeerSeeds being the root of the data.
* This is not currently in use by the Bitcoin community, but rather, is here for experimentation.
*/
public class HttpDiscovery implements PeerDiscovery {
private static final Logger log = LoggerFactory.getLogger(HttpDiscovery.class);
public static class Details {
@Nullable public final ECKey pubkey;
public final URI uri;
public Details(@Nullable ECKey pubkey, URI uri) {
this.pubkey = pubkey;
this.uri = uri;
}
}
private final Details details;
private final NetworkParameters params;
private final OkHttpClient client;
/**
* Constructs a discovery object that will read data from the given HTTP[S] URI and, if a public key is provided,
* will check the signature using that key.
*/
public HttpDiscovery(NetworkParameters params, URI uri, @Nullable ECKey pubkey) {
this(params, new Details(pubkey, uri));
}
/**
* Constructs a discovery object that will read data from the given HTTP[S] URI and, if a public key is provided,
* will check the signature using that key.
*/
public HttpDiscovery(NetworkParameters params, Details details) {
this(params, details, new OkHttpClient());
}
public HttpDiscovery(NetworkParameters params, Details details, OkHttpClient client) {
checkArgument(details.uri.getScheme().startsWith("http"));
this.details = details;
this.params = params;
this.client = client;
}
@Override
public InetSocketAddress[] getPeers(long services, long timeoutValue, TimeUnit timeoutUnit) throws PeerDiscoveryException {
try {
HttpUrl.Builder url = HttpUrl.get(details.uri).newBuilder();
if (services != 0)
url.addQueryParameter("srvmask", Long.toString(services));
Request.Builder request = new Request.Builder();
request.url(url.build());
request.addHeader("User-Agent", VersionMessage.LIBRARY_SUBVER); // TODO Add main version.
log.info("Requesting seeds from {}", url);
Response response = client.newCall(request.build()).execute();
if (!response.isSuccessful())
throw new PeerDiscoveryException("HTTP request failed: " + response.code() + " " + response.message());
InputStream stream = response.body().byteStream();
GZIPInputStream zip = new GZIPInputStream(stream);
PeerSeedProtos.SignedPeerSeeds proto;
try {
proto = PeerSeedProtos.SignedPeerSeeds.parseDelimitedFrom(zip);
} finally {
zip.close(); // will close InputStream as well
}
return protoToAddrs(proto);
} catch (PeerDiscoveryException e1) {
throw e1;
} catch (Exception e) {
throw new PeerDiscoveryException(e);
}
}
@VisibleForTesting
public InetSocketAddress[] protoToAddrs(PeerSeedProtos.SignedPeerSeeds proto) throws PeerDiscoveryException,
InvalidProtocolBufferException, SignatureDecodeException, SignatureException {
if (details.pubkey != null) {
if (!Arrays.equals(proto.getPubkey().toByteArray(), details.pubkey.getPubKey()))
throw new PeerDiscoveryException("Public key mismatch");
byte[] hash = Sha256Hash.hash(proto.getPeerSeeds().toByteArray());
details.pubkey.verifyOrThrow(hash, proto.getSignature().toByteArray());
}
PeerSeedProtos.PeerSeeds seeds = PeerSeedProtos.PeerSeeds.parseFrom(proto.getPeerSeeds());
if (seeds.getTimestamp() < Utils.currentTimeSeconds() - (60 * 60 * 24))
throw new PeerDiscoveryException("Seed data is more than one day old: replay attack?");
if (!seeds.getNet().equals(params.getPaymentProtocolId()))
throw new PeerDiscoveryException("Network mismatch");
InetSocketAddress[] results = new InetSocketAddress[seeds.getSeedCount()];
int i = 0;
for (PeerSeedProtos.PeerSeedData data : seeds.getSeedList())
results[i++] = new InetSocketAddress(data.getIpAddress(), data.getPort());
return results;
}
@Override
public void shutdown() {
}
}
| apache-2.0 |
vega113/incubator-wave | wave/src/main/java/org/waveprotocol/wave/model/document/util/FocusedPointRange.java | 2740 | /**
* 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.waveprotocol.wave.model.document.util;
import org.waveprotocol.wave.model.util.Preconditions;
/**
* @author danilatos@google.com (Daniel Danilatos)
*
*/
public class FocusedPointRange<N> {
private final Point<N> anchor;
private final Point<N> focus;
private final boolean isCollapsed;
/**
* Constructs a collapsed range.
*
* @param collapsedAt The point at which the collapsed range is located.
*/
public FocusedPointRange(Point<N> collapsedAt) {
assert collapsedAt != null;
anchor = collapsedAt;
focus = collapsedAt;
isCollapsed = true;
}
/**
* @param anchor
* @param focus
*/
public FocusedPointRange(Point<N> anchor, Point<N> focus) {
this.anchor = Preconditions.checkNotNull(anchor, "anchor");
this.focus = Preconditions.checkNotNull(focus, "focus");
this.isCollapsed = anchor.equals(focus);
}
/**
* @return True if the range is collapsed
*/
public boolean isCollapsed() {
return isCollapsed;
}
/**
* @return the anchor
*/
public Point<N> getAnchor() {
return anchor;
}
/**
* @return the focus
*/
public Point<N> getFocus() {
return focus;
}
@Override
public String toString() {
return "FocusedPointRange(" + getAnchor() + " -> " + getFocus() + ")";
}
@Override
public final int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + anchor.hashCode();
result = prime * result + focus.hashCode();
return result;
}
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public final boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (!(obj instanceof FocusedPointRange)) return false;
FocusedPointRange other = (FocusedPointRange) obj;
if (!anchor.equals(other.anchor)) return false;
if (!focus.equals(other.focus)) return false;
return true;
}
}
| apache-2.0 |
lankavitharana/siddhi | modules/siddhi-core/src/test/java/org/wso2/siddhi/test/distributed/FilterDistributedTestCase.java | 11362 | /*
* 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.siddhi.test.distributed;
import junit.framework.Assert;
import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Test;
import org.wso2.siddhi.core.SiddhiManager;
import org.wso2.siddhi.core.config.SiddhiConfiguration;
import org.wso2.siddhi.core.event.Event;
import org.wso2.siddhi.core.query.output.callback.QueryCallback;
import org.wso2.siddhi.core.stream.input.InputHandler;
import org.wso2.siddhi.core.util.EventPrinter;
import org.wso2.siddhi.query.api.QueryFactory;
import org.wso2.siddhi.query.api.condition.Condition;
import org.wso2.siddhi.query.api.definition.Attribute;
import org.wso2.siddhi.query.api.expression.Expression;
import org.wso2.siddhi.query.api.query.Query;
public class FilterDistributedTestCase {
static final Logger log = Logger.getLogger(FilterDistributedTestCase.class);
private int count;
private boolean eventArrived;
@Before
public void init() {
count = 0;
eventArrived = false;
}
@Test
public void testFilterDistributedQuery1() throws InterruptedException {
log.info("FilterDistributed test1");
SiddhiConfiguration configuration = new SiddhiConfiguration();
configuration.setDistributedProcessing(true);
SiddhiManager siddhiManager = new SiddhiManager(configuration);
try {
InputHandler inputHandler = siddhiManager.defineStream(QueryFactory.createStreamDefinition().name("cseEventStream").attribute("symbol", Attribute.Type.STRING).attribute("price", Attribute.Type.FLOAT).attribute("volume", Attribute.Type.INT));
Query query = QueryFactory.createQuery();
query.from(QueryFactory.inputStream("cseEventStream"));
query.select(
QueryFactory.outputSelector().
select("symbol", Expression.variable("symbol")).
select("price", Expression.variable("price")).
select("volume", Expression.variable("volume"))
);
query.insertInto("StockQuote");
String queryReference = siddhiManager.addQuery(query);
siddhiManager.addCallback(queryReference, new QueryCallback() {
@Override
public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
EventPrinter.print(timeStamp, inEvents, removeEvents);
Assert.assertTrue("IBM".equals(inEvents[0].getData(0)) || "WSO2".equals(inEvents[0].getData(0)));
count+=inEvents.length;
}
});
// InputHandler inputHandler = siddhiManager.getInputHandler("cseEventStream");
inputHandler.send(new Object[]{"IBM", 75.6f, 100});
inputHandler.send(new Object[]{"WSO2", 75.6f, 100});
Thread.sleep(500);
Assert.assertEquals(2, count);
} finally {
siddhiManager.shutdown();
}
}
@Test
public void testFilterDistributedQuery2() throws InterruptedException {
log.info("FilterDistributed test2");
SiddhiConfiguration configuration = new SiddhiConfiguration();
configuration.setDistributedProcessing(true);
SiddhiManager siddhiManager = new SiddhiManager(configuration);
try {
siddhiManager.defineStream(QueryFactory.createStreamDefinition().name("cseEventStream").attribute("symbol", Attribute.Type.STRING).attribute("price", Attribute.Type.FLOAT).attribute("volume", Attribute.Type.INT));
Query query = QueryFactory.createQuery();
query.from(QueryFactory.inputStream("cseEventStream"));
query.insertInto("StockQuote");
String queryReference = siddhiManager.addQuery(query);
siddhiManager.addCallback(queryReference, new QueryCallback() {
@Override
public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
EventPrinter.print(timeStamp, inEvents, removeEvents);
Assert.assertTrue("IBM".equals(inEvents[0].getData(0)) || "WSO2".equals(inEvents[0].getData(0)));
count+=inEvents.length;
}
});
InputHandler inputHandler = siddhiManager.getInputHandler("cseEventStream");
inputHandler.send(new Object[]{"IBM", 75.6f, 100});
inputHandler.send(new Object[]{"WSO2", 75.6f, 100});
Thread.sleep(500);
Assert.assertEquals(2, count);
} finally {
siddhiManager.shutdown();
}
}
@Test
public void testFilterDistributedQuery3() throws InterruptedException {
log.info("FilterDistributed test3");
SiddhiConfiguration configuration = new SiddhiConfiguration();
configuration.setDistributedProcessing(true);
SiddhiManager siddhiManager = new SiddhiManager(configuration);
try {
siddhiManager.defineStream(QueryFactory.createStreamDefinition().name("cseEventStream").attribute("symbol", Attribute.Type.STRING).attribute("price", Attribute.Type.FLOAT).attribute("volume", Attribute.Type.INT));
Query query = QueryFactory.createQuery();
query.from(QueryFactory.inputStream("cseEventStream"));
query.select(
QueryFactory.outputSelector().
select("symbol", Expression.variable("symbol"))
);
query.insertInto("StockQuote");
String queryReference = siddhiManager.addQuery(query);
siddhiManager.addCallback(queryReference, new QueryCallback() {
@Override
public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
EventPrinter.print(timeStamp, inEvents, removeEvents);
Assert.assertTrue("IBM".equals(inEvents[0].getData(0)) || "WSO2".equals(inEvents[0].getData(0)));
count+=inEvents.length;
}
});
InputHandler inputHandler = siddhiManager.getInputHandler("cseEventStream");
inputHandler.send(new Object[]{"IBM", 75.6f, 100});
inputHandler.send(new Object[]{"WSO2", 75.6f, 100});
Thread.sleep(500);
Assert.assertEquals(2, count);
} finally {
siddhiManager.shutdown();
}
}
@Test
public void testFilterDistributedQuery4() throws InterruptedException {
log.info("FilterDistributed test4");
SiddhiConfiguration configuration = new SiddhiConfiguration();
configuration.setDistributedProcessing(true);
SiddhiManager siddhiManager = new SiddhiManager(configuration);
try {
siddhiManager.defineStream(QueryFactory.createStreamDefinition().name("cseEventStream").attribute("symbol", Attribute.Type.STRING).attribute("price", Attribute.Type.FLOAT).attribute("volume", Attribute.Type.INT));
Query query = QueryFactory.createQuery();
query.from(QueryFactory.inputStream("cseEventStream").
filter(Condition.compare(Expression.value(70),
Condition.Operator.GREATER_THAN,
Expression.variable("price"))
)
);
query.select(
QueryFactory.outputSelector().
select("symbol", Expression.variable("symbol")).
select("price", Expression.variable("price"))
);
query.insertInto("StockQuote");
String queryReference = siddhiManager.addQuery(query);
siddhiManager.addCallback(queryReference, new QueryCallback() {
@Override
public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
EventPrinter.print(timeStamp, inEvents, removeEvents);
Assert.assertTrue("WSO2".equals(inEvents[0].getData(0)));
count+=inEvents.length;
}
});
InputHandler inputHandler = siddhiManager.getInputHandler("cseEventStream");
inputHandler.send(new Object[]{"WSO2", 55.6f, 100});
inputHandler.send(new Object[]{"IBM", 75.6f, 100});
inputHandler.send(new Object[]{"WSO2", 57.6f, 100});
Thread.sleep(500);
Assert.assertEquals(2, count);
} finally {
siddhiManager.shutdown();
}
}
@Test
public void testFilterDistributedQuery5() throws InterruptedException {
log.info("FilterDistributed test5");
SiddhiConfiguration configuration = new SiddhiConfiguration();
configuration.setDistributedProcessing(true);
SiddhiManager siddhiManager = new SiddhiManager(configuration);
try {
siddhiManager.defineStream(QueryFactory.createStreamDefinition().name("cseEventStream").attribute("symbol", Attribute.Type.STRING).attribute("price", Attribute.Type.FLOAT).attribute("volume", Attribute.Type.INT));
Query query = QueryFactory.createQuery();
query.from(QueryFactory.inputStream("cseEventStream"));
query.select(
QueryFactory.outputSelector().
select("symbol", Expression.variable("symbol")).
select("price", Expression.variable("price")).
select("volume", Expression.variable("volume")).groupBy("symbol")
);
query.insertInto("StockQuote");
String queryReference = siddhiManager.addQuery(query);
siddhiManager.addCallback(queryReference, new QueryCallback() {
@Override
public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
EventPrinter.print(timeStamp, inEvents, removeEvents);
Assert.assertTrue("IBM".equals(inEvents[0].getData(0)) || "WSO2".equals(inEvents[0].getData(0)));
count+=inEvents.length;
eventArrived = true;
}
});
InputHandler inputHandler = siddhiManager.getInputHandler("cseEventStream");
inputHandler.send(new Object[]{"IBM", 75.6f, 100});
inputHandler.send(new Object[]{"WSO2", 75.6f, 100});
Thread.sleep(500);
Assert.assertEquals(2, count);
Assert.assertEquals("Event arrived", true, eventArrived);
} finally {
siddhiManager.shutdown();
}
}
}
| apache-2.0 |
liveqmock/platform-tools-idea | java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsJavaTokenImpl.java | 2083 | /*
* Copyright 2000-2012 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.psi.impl.compiled;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.tree.TreeElement;
import com.intellij.psi.tree.IElementType;
import org.jetbrains.annotations.NotNull;
public class ClsJavaTokenImpl extends ClsElementImpl implements PsiJavaToken {
private ClsElementImpl myParent;
private final IElementType myTokenType;
private final String myTokenText;
public ClsJavaTokenImpl(ClsElementImpl parent, IElementType tokenType, String tokenText) {
myParent = parent;
myTokenType = tokenType;
myTokenText = tokenText;
}
void setParent(ClsElementImpl parent) {
myParent = parent;
}
@Override
public IElementType getTokenType() {
return myTokenType;
}
@Override
public String getText() {
return myTokenText;
}
@NotNull
@Override
public PsiElement[] getChildren() {
return EMPTY_ARRAY;
}
@Override
public PsiElement getParent() {
return myParent;
}
@Override
public void appendMirrorText(int indentLevel, @NotNull StringBuilder buffer) {
buffer.append(getText());
}
@Override
public void setMirror(@NotNull TreeElement element) throws InvalidMirrorException {
setMirrorCheckingType(element, myTokenType);
}
@Override
public void accept(@NotNull PsiElementVisitor visitor) {
if (visitor instanceof JavaElementVisitor) {
((JavaElementVisitor)visitor).visitJavaToken(this);
}
else {
visitor.visitElement(this);
}
}
}
| apache-2.0 |
besom/bbossgroups-mvn | bboss_security/src/main/java/org/frameworkset/web/token/MemToken.java | 2454 | package org.frameworkset.web.token;
import com.frameworkset.orm.annotation.Column;
/**
* @author biaoping.yin
*
*
*/
public class MemToken implements java.io.Serializable{
/**
* 令牌信息
*/
private String id;
private String token;
private long createTime;
@Column(name="validate_")
private boolean validate = true;
private long lastVistTime;
private long livetime;
private String appid;
private String secret;
private String signtoken;
public String getToken() {
return token;
}
public long getCreateTime() {
return createTime;
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
return token.hashCode();
}
public MemToken()
{
}
public MemToken(String token, long createTime) {
super();
this.token = token;
this.createTime = createTime;
}
public MemToken(String token, long createTime, boolean validate,
long lastVistTime, long livetime) {
super();
this.token = token;
this.createTime = createTime;
this.validate = validate;
this.lastVistTime = lastVistTime;
this.livetime = livetime;
}
@Override
public boolean equals(Object obj) {
if(obj != null && obj instanceof MemToken)
{
return token.equals(((MemToken)obj).getToken());
}
return false;
// TODO Auto-generated method stub
}
public boolean isValidate() {
return validate;
}
public void setValidate(boolean validate) {
this.validate = validate;
}
public long getLastVistTime() {
return lastVistTime;
}
public void setLastVistTime(long lastVistTime) {
this.lastVistTime = lastVistTime;
}
public void setToken(String token) {
this.token = token;
}
public void setCreateTime(long createTime) {
this.createTime = createTime;
}
public long getLivetime() {
return livetime;
}
public void setLivetime(long livetime) {
this.livetime = livetime;
}
public String getAppid() {
return appid;
}
public void setAppid(String appid) {
this.appid = appid;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public String getSigntoken() {
return signtoken;
}
public void setSigntoken(String signtoken) {
this.signtoken = signtoken;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
| apache-2.0 |
jeorme/OG-Platform | projects/OG-Analytics/src/test/java/com/opengamma/analytics/financial/provider/sensitivity/ParameterSensitivityProviderCalculatorTest.java | 10447 | /**
* Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.analytics.financial.provider.sensitivity;
import static org.testng.AssertJUnit.assertTrue;
import static org.testng.internal.junit.ArrayAsserts.assertArrayEquals;
import java.util.Set;
import java.util.TreeSet;
import org.testng.annotations.Test;
import org.threeten.bp.Period;
import org.threeten.bp.ZonedDateTime;
import com.opengamma.analytics.financial.instrument.annuity.AnnuityCouponFixedDefinition;
import com.opengamma.analytics.financial.instrument.index.GeneratorSwapFixedIbor;
import com.opengamma.analytics.financial.instrument.index.GeneratorSwapFixedIborMaster;
import com.opengamma.analytics.financial.instrument.index.GeneratorSwapFixedON;
import com.opengamma.analytics.financial.instrument.index.GeneratorSwapFixedONMaster;
import com.opengamma.analytics.financial.instrument.index.IborIndex;
import com.opengamma.analytics.financial.instrument.index.IndexON;
import com.opengamma.analytics.financial.instrument.swap.SwapFixedIborDefinition;
import com.opengamma.analytics.financial.instrument.swap.SwapFixedONDefinition;
import com.opengamma.analytics.financial.interestrate.annuity.derivative.AnnuityCouponFixed;
import com.opengamma.analytics.financial.interestrate.payments.derivative.Coupon;
import com.opengamma.analytics.financial.interestrate.swap.derivative.SwapFixedCoupon;
import com.opengamma.analytics.financial.model.interestrate.curve.YieldAndDiscountCurve;
import com.opengamma.analytics.financial.model.interestrate.curve.YieldCurve;
import com.opengamma.analytics.financial.provider.calculator.discounting.PresentValueCurveSensitivityDiscountingCalculator;
import com.opengamma.analytics.financial.provider.calculator.discounting.PresentValueDiscountingCalculator;
import com.opengamma.analytics.financial.provider.description.interestrate.MulticurveProviderDiscount;
import com.opengamma.analytics.financial.provider.description.interestrate.MulticurveProviderForward;
import com.opengamma.analytics.financial.provider.description.interestrate.ParameterProviderInterface;
import com.opengamma.analytics.financial.provider.sensitivity.multicurve.MultipleCurrencyParameterSensitivity;
import com.opengamma.analytics.financial.provider.sensitivity.multicurve.ParameterSensitivityMulticurveDiscountInterpolatedFDCalculator;
import com.opengamma.analytics.financial.provider.sensitivity.multicurve.ParameterSensitivityMulticurveForwardInterpolatedFDCalculator;
import com.opengamma.analytics.financial.provider.sensitivity.parameter.ParameterSensitivityParameterCalculator;
import com.opengamma.analytics.financial.util.AssertSensitivityObjects;
import com.opengamma.analytics.math.curve.DoublesCurve;
import com.opengamma.analytics.math.curve.InterpolatedDoublesCurve;
import com.opengamma.analytics.math.interpolation.CombinedInterpolatorExtrapolatorFactory;
import com.opengamma.analytics.math.interpolation.Interpolator1D;
import com.opengamma.analytics.math.interpolation.Interpolator1DFactory;
import com.opengamma.financial.convention.calendar.Calendar;
import com.opengamma.financial.convention.calendar.MondayToFridayCalendar;
import com.opengamma.util.money.Currency;
import com.opengamma.util.test.TestGroup;
import com.opengamma.util.time.DateUtils;
/**
* Tests related to the computation of parameter sensitivity from point sensitivity.
*
*/
@Test(groups = TestGroup.UNIT)
public class ParameterSensitivityProviderCalculatorTest {
private static final Calendar NYC = new MondayToFridayCalendar("NYC");
private static final GeneratorSwapFixedIbor USD6MLIBOR3M = GeneratorSwapFixedIborMaster.getInstance().getGenerator("USD6MLIBOR3M", NYC);
private static final IborIndex USDLIBOR3M = USD6MLIBOR3M.getIborIndex();
private static final Currency USD = USD6MLIBOR3M.getCurrency();
private static final ZonedDateTime EFFECTIVE_DATE = DateUtils.getUTCDate(2012, 10, 29);
private static final double NOTIONAL = 100000000;
private static final SwapFixedIborDefinition SWAP_DEFINITION = SwapFixedIborDefinition.from(EFFECTIVE_DATE, Period.ofYears(2), USD6MLIBOR3M, NOTIONAL, 0.05, false);
private static final AnnuityCouponFixedDefinition ANNUITY_DEFINITION = SWAP_DEFINITION.getFixedLeg();
private static final ZonedDateTime REFERENCE_DATE = DateUtils.getUTCDate(2012, 9, 26);
private static final SwapFixedCoupon<Coupon> SWAP = SWAP_DEFINITION.toDerivative(REFERENCE_DATE);
private static final AnnuityCouponFixed ANNUITY = ANNUITY_DEFINITION.toDerivative(REFERENCE_DATE);
private static final GeneratorSwapFixedON USD1YFEDFUND = GeneratorSwapFixedONMaster.getInstance().getGenerator("USD1YFEDFUND", NYC);
private static final IndexON FEDFUND = USD1YFEDFUND.getIndex();
private static final SwapFixedONDefinition OIS_DEFINITION = SwapFixedONDefinition.from(EFFECTIVE_DATE, Period.ofMonths(6), NOTIONAL, USD1YFEDFUND, 0.02, false);
private static final SwapFixedCoupon<Coupon> OIS = OIS_DEFINITION.toDerivative(REFERENCE_DATE);
private static final double[] TIME = {0.25, 0.50, 1.0, 2.0, 5.0};
private static final double[] YIELD = {0.02, 0.025, 0.03, 0.03, 0.028};
private static final Interpolator1D INTERPOLATOR_LINEAR = CombinedInterpolatorExtrapolatorFactory.getInterpolator(Interpolator1DFactory.LINEAR, Interpolator1DFactory.LINEAR_EXTRAPOLATOR,
Interpolator1DFactory.FLAT_EXTRAPOLATOR);
private static final String DSC_NAME = "USD Discounting";
private static final String FWD3_NAME = "USD Forward 3M";
private static final YieldAndDiscountCurve DSC = new YieldCurve(DSC_NAME, new InterpolatedDoublesCurve(TIME, YIELD, INTERPOLATOR_LINEAR, true));
private static final YieldAndDiscountCurve FWD3_DSC = new YieldCurve(FWD3_NAME, new InterpolatedDoublesCurve(TIME, YIELD, INTERPOLATOR_LINEAR, true));
private static final MulticurveProviderDiscount MARKET_DSC = new MulticurveProviderDiscount();
static {
MARKET_DSC.setCurve(USD, DSC);
MARKET_DSC.setCurve(FEDFUND, DSC);
MARKET_DSC.setCurve(USDLIBOR3M, FWD3_DSC);
}
private static final DoublesCurve FWD3_FWD = new InterpolatedDoublesCurve(TIME, YIELD, INTERPOLATOR_LINEAR, true, FWD3_NAME);
private static final MulticurveProviderForward MARKET_FWD = new MulticurveProviderForward();
static {
MARKET_FWD.setCurve(USD, DSC);
MARKET_FWD.setCurve(FEDFUND, DSC);
MARKET_FWD.setCurve(USDLIBOR3M, FWD3_FWD);
}
private static final PresentValueCurveSensitivityDiscountingCalculator PVCSC = PresentValueCurveSensitivityDiscountingCalculator.getInstance();
private static final PresentValueDiscountingCalculator PVC = PresentValueDiscountingCalculator.getInstance();
private static final ParameterSensitivityParameterCalculator<ParameterProviderInterface> PSC = new ParameterSensitivityParameterCalculator<>(PVCSC);
// private static final ParameterSensitivityMatrixMarketCalculator PSC_MAT = new ParameterSensitivityMatrixMarketCalculator(PVCSC);
private static final double SHIFT = 5.0E-7;
private static final ParameterSensitivityMulticurveDiscountInterpolatedFDCalculator PSC_DSC_FD = new ParameterSensitivityMulticurveDiscountInterpolatedFDCalculator(PVC, SHIFT);
private static final ParameterSensitivityMulticurveForwardInterpolatedFDCalculator PSC_FWD_FD = new ParameterSensitivityMulticurveForwardInterpolatedFDCalculator(PVC, SHIFT);
private static final double TOLERANCE_DELTA = 1.0E+2; // 0.01 currency unit for 1bp on 100m
@Test
public void parameterSensitivityBlock() {
final MultipleCurrencyParameterSensitivity pvpsAnnuityExact = PSC.calculateSensitivity(ANNUITY, MARKET_DSC, MARKET_DSC.getAllNames());
final MultipleCurrencyParameterSensitivity pvpsAnnuityFD = PSC_DSC_FD.calculateSensitivity(ANNUITY, MARKET_DSC);
AssertSensitivityObjects.assertEquals("ParameterSensitivityMarketBlockCalculator: fixed annuity ", pvpsAnnuityExact, pvpsAnnuityFD, TOLERANCE_DELTA);
final MultipleCurrencyParameterSensitivity pvps2AnnuityExact = PSC.calculateSensitivity(ANNUITY, MARKET_FWD, MARKET_FWD.getAllNames());
final MultipleCurrencyParameterSensitivity pvps2AnnuityFD = PSC_FWD_FD.calculateSensitivity(ANNUITY, MARKET_FWD);
AssertSensitivityObjects.assertEquals("ParameterSensitivityMarketBlockCalculator: fixed annuity ", pvps2AnnuityExact, pvps2AnnuityFD, TOLERANCE_DELTA);
final MultipleCurrencyParameterSensitivity pvpsSwapExact = PSC.calculateSensitivity(SWAP, MARKET_DSC, MARKET_DSC.getAllNames());
final MultipleCurrencyParameterSensitivity pvpsSwapFD = PSC_DSC_FD.calculateSensitivity(SWAP, MARKET_DSC);
AssertSensitivityObjects.assertEquals("ParameterSensitivityMarketBlockCalculator: swap ", pvpsSwapExact, pvpsSwapFD, TOLERANCE_DELTA);
final MultipleCurrencyParameterSensitivity pvps2SwapExact = PSC.calculateSensitivity(SWAP, MARKET_FWD, MARKET_FWD.getAllNames());
final MultipleCurrencyParameterSensitivity pvps2SwapFD = PSC_FWD_FD.calculateSensitivity(SWAP, MARKET_FWD);
AssertSensitivityObjects.assertEquals("ParameterSensitivityMarketBlockCalculator: swap", pvps2SwapExact, pvps2SwapFD, TOLERANCE_DELTA);
final MultipleCurrencyParameterSensitivity pvpsOisExact = PSC.calculateSensitivity(OIS, MARKET_DSC, MARKET_DSC.getAllNames());
final MultipleCurrencyParameterSensitivity pvpsOisFD = PSC_DSC_FD.calculateSensitivity(OIS, MARKET_DSC);
AssertSensitivityObjects.assertEquals("ParameterSensitivityMarketBlockCalculator: Ois", pvpsOisExact, pvpsOisFD, TOLERANCE_DELTA);
final MultipleCurrencyParameterSensitivity pvps2OisExact = PSC.calculateSensitivity(OIS, MARKET_FWD, MARKET_FWD.getAllNames());
final MultipleCurrencyParameterSensitivity pvps2OisFD = PSC_FWD_FD.calculateSensitivity(OIS, MARKET_FWD);
AssertSensitivityObjects.assertEquals("ParameterSensitivityMarketBlockCalculator: Ois", pvps2OisExact, pvps2OisFD, TOLERANCE_DELTA);
final Set<String> required = new TreeSet<>();
required.add(DSC_NAME);
final MultipleCurrencyParameterSensitivity pvpsSwapNoFwd = PSC.calculateSensitivity(SWAP, MARKET_DSC, required);
assertTrue("ParameterSensitivityMarketBlockCalculator: fixed curve ", pvpsSwapNoFwd.getAllNamesCurrency().size() == 1);
assertArrayEquals("ParameterSensitivityMarketBlockCalculator: fixed curve ", pvpsSwapNoFwd.getSensitivity(DSC_NAME, USD).getData(), pvpsSwapExact.getSensitivity(DSC_NAME, USD).getData(),
TOLERANCE_DELTA);
}
}
| apache-2.0 |
jeorme/OG-Platform | projects/OG-Engine/src/test/java/com/opengamma/engine/fudgemsg/RequirementResolutionFudgeBuilderTest.java | 2932 | /**
* Copyright (C) 2013 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.engine.fudgemsg;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import org.testng.annotations.Test;
import com.opengamma.engine.ComputationTargetSpecification;
import com.opengamma.engine.depgraph.DependencyNodeFunction;
import com.opengamma.engine.depgraph.ambiguity.FullRequirementResolution;
import com.opengamma.engine.depgraph.ambiguity.RequirementResolution;
import com.opengamma.engine.depgraph.impl.DependencyNodeFunctionImpl;
import com.opengamma.engine.function.EmptyFunctionParameters;
import com.opengamma.engine.function.SimpleFunctionParameters;
import com.opengamma.engine.value.ValueProperties;
import com.opengamma.engine.value.ValuePropertyNames;
import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.engine.value.ValueSpecification;
import com.opengamma.util.test.AbstractFudgeBuilderTestCase;
import com.opengamma.util.test.TestGroup;
/**
* Tests the {@link RequirementResolutionFudgeBuilder} class.
*/
@Test(groups = TestGroup.UNIT)
public class RequirementResolutionFudgeBuilderTest extends AbstractFudgeBuilderTestCase {
private ValueSpecification valueSpecification() {
return new ValueSpecification("Foo", ComputationTargetSpecification.NULL, ValueProperties.with(ValuePropertyNames.FUNCTION, "Test").get());
}
private DependencyNodeFunction functionNoParameters() {
return DependencyNodeFunctionImpl.of("Test", EmptyFunctionParameters.INSTANCE);
}
private DependencyNodeFunction functionWithParameters() {
return DependencyNodeFunctionImpl.of("Test", new SimpleFunctionParameters());
}
private ValueRequirement requirement(final String name) {
return new ValueRequirement(name, ComputationTargetSpecification.NULL);
}
public void testNoInputs() {
final RequirementResolution resolution = new RequirementResolution(valueSpecification(), functionNoParameters(), Collections.<FullRequirementResolution>emptySet());
assertEncodeDecodeCycle(RequirementResolution.class, resolution);
}
public void testInputs() {
final Collection<FullRequirementResolution> inputs = new ArrayList<FullRequirementResolution>();
inputs.add(new FullRequirementResolution(requirement("A")));
inputs.add(new FullRequirementResolution(requirement("B")));
final RequirementResolution resolution = new RequirementResolution(valueSpecification(), functionNoParameters(), inputs);
assertEncodeDecodeCycle(RequirementResolution.class, resolution);
}
public void testFunctionParameters() {
final RequirementResolution resolution = new RequirementResolution(valueSpecification(), functionWithParameters(), Collections.<FullRequirementResolution>emptySet());
assertEncodeDecodeCycle(RequirementResolution.class, resolution);
}
}
| apache-2.0 |
haikuowuya/android_system_code | src/org/apache/http/conn/EofSensorWatcher.java | 4276 | /*
* $HeadURL: http://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk/module-client/src/main/java/org/apache/http/conn/EofSensorWatcher.java $
* $Revision: 552264 $
* $Date: 2007-07-01 02:37:47 -0700 (Sun, 01 Jul 2007) $
*
* ====================================================================
*
* 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.conn;
import java.io.InputStream;
import java.io.IOException;
/**
* A watcher for {@link EofSensorInputStream EofSensorInputStream}.
* Each stream will notify it's watcher at most once.
*
* @author <a href="mailto:rolandw at apache.org">Roland Weber</a>
*
*
* <!-- empty lines to avoid svn diff problems -->
* @version $Revision: 552264 $
*
* @since 4.0
*/
public interface EofSensorWatcher {
/**
* Indicates that EOF is detected.
*
* @param wrapped the underlying stream which has reached EOF
*
* @return <code>true</code> if <code>wrapped</code> should be closed,
* <code>false</code> if it should be left alone
*
* @throws IOException
* in case of an IO problem, for example if the watcher itself
* closes the underlying stream. The caller will leave the
* wrapped stream alone, as if <code>false</code> was returned.
*/
boolean eofDetected(InputStream wrapped)
throws IOException
;
/**
* Indicates that the {@link EofSensorInputStream stream} is closed.
* This method will be called only if EOF was <i>not</i> detected
* before closing. Otherwise, {@link #eofDetected eofDetected} is called.
*
* @param wrapped the underlying stream which has not reached EOF
*
* @return <code>true</code> if <code>wrapped</code> should be closed,
* <code>false</code> if it should be left alone
*
* @throws IOException
* in case of an IO problem, for example if the watcher itself
* closes the underlying stream. The caller will leave the
* wrapped stream alone, as if <code>false</code> was returned.
*/
boolean streamClosed(InputStream wrapped)
throws IOException
;
/**
* Indicates that the {@link EofSensorInputStream stream} is aborted.
* This method will be called only if EOF was <i>not</i> detected
* before aborting. Otherwise, {@link #eofDetected eofDetected} is called.
* <p/>
* This method will also be invoked when an input operation causes an
* IOException to be thrown to make sure the input stream gets shut down.
*
* @param wrapped the underlying stream which has not reached EOF
*
* @return <code>true</code> if <code>wrapped</code> should be closed,
* <code>false</code> if it should be left alone
*
* @throws IOException
* in case of an IO problem, for example if the watcher itself
* closes the underlying stream. The caller will leave the
* wrapped stream alone, as if <code>false</code> was returned.
*/
boolean streamAbort(InputStream wrapped)
throws IOException
;
} // interface EofSensorWatcher
| apache-2.0 |
uaraven/nano | sample/webservice/eBayDemoApp/src/com/ebay/trading/api/AddressStatusCodeType.java | 873 | // Generated by xsd compiler for android/java
// DO NOT CHANGE!
package com.ebay.trading.api;
/**
*
* PayPal address status.
*
*/
public enum AddressStatusCodeType {
NONE("None"),
CONFIRMED("Confirmed"),
UNCONFIRMED("Unconfirmed"),
/**
*
* (out) Reserved for internal or future use.
*
*/
CUSTOM_CODE("CustomCode");
private final String value;
AddressStatusCodeType(String v) {
value = v;
}
public String value() {
return value;
}
public static AddressStatusCodeType fromValue(String v) {
if (v != null) {
for (AddressStatusCodeType c: AddressStatusCodeType.values()) {
if (c.value.equals(v)) {
return c;
}
}
}
throw new IllegalArgumentException(v);
}
} | apache-2.0 |
apache/olingo-odata2 | odata2-lib/odata-api/src/main/java/org/apache/olingo/odata2/api/uri/info/GetComplexPropertyUriInfo.java | 4535 | /*******************************************************************************
* 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.olingo.odata2.api.uri.info;
import java.util.List;
import java.util.Map;
import org.apache.olingo.odata2.api.edm.EdmEntityContainer;
import org.apache.olingo.odata2.api.edm.EdmEntitySet;
import org.apache.olingo.odata2.api.edm.EdmFunctionImport;
import org.apache.olingo.odata2.api.edm.EdmLiteral;
import org.apache.olingo.odata2.api.edm.EdmProperty;
import org.apache.olingo.odata2.api.edm.EdmType;
import org.apache.olingo.odata2.api.uri.KeyPredicate;
import org.apache.olingo.odata2.api.uri.NavigationSegment;
/**
* Access to the parts of the request URI that are relevant for GET requests
* of complex properties.
* @org.apache.olingo.odata2.DoNotImplement
*
*/
public interface GetComplexPropertyUriInfo {
/**
* Gets the target entity container.
* @return {@link EdmEntityContainer} the target entity container
*/
public EdmEntityContainer getEntityContainer();
/**
* Gets the start entity set - identical to the target entity set if no navigation
* has been used.
* @return {@link EdmEntitySet}
*/
public EdmEntitySet getStartEntitySet();
/**
* Gets the target entity set after navigation.
* @return {@link EdmEntitySet} target entity set
*/
public EdmEntitySet getTargetEntitySet();
/**
* Gets the function import.
* @return {@link EdmFunctionImport} the function import
*/
public EdmFunctionImport getFunctionImport();
/**
* Gets the target complex type of the request.
* @return {@link EdmType} the target type
*/
public EdmType getTargetType();
/**
* Gets the key predicates used to select a single entity out of the start entity set,
* or an empty list if not used.
* @return List of {@link KeyPredicate}
* @see #getStartEntitySet()
*/
public List<KeyPredicate> getKeyPredicates();
/**
* Gets the key predicates used to select a single entity out of the target entity set,
* or an empty list if not used - identical to the key predicates from the last entry
* retrieved from {@link #getNavigationSegments()} or, if no navigation has been used,
* to the result of {@link #getKeyPredicates()}.
* @return List of {@link KeyPredicate}
* @see #getTargetEntitySet()
*/
public List<KeyPredicate> getTargetKeyPredicates();
/**
* Gets the navigation segments, or an empty list if no navigation has been used.
* @return List of {@link NavigationSegment}
*/
public List<NavigationSegment> getNavigationSegments();
/**
* Gets the path used to select a (simple or complex) property of an entity,
* or an empty list if no property is accessed.
* @return List of {@link EdmProperty}
*/
public List<EdmProperty> getPropertyPath();
/**
* Gets the value of the $format system query option.
* @return the format (as set as <code>$format</code> query parameter) or null
*/
public String getFormat();
/**
* Gets the parameters of a function import as Map from parameter names to
* their corresponding typed values, or an empty list if no function import
* is used or no parameters are given in the URI.
* @return Map of {@literal <String,} {@link EdmLiteral}{@literal >} function import parameters
*/
public Map<String, EdmLiteral> getFunctionImportParameters();
/**
* Gets the custom query options as Map from option names to their
* corresponding String values, or an empty list if no custom query options
* are given in the URI.
* @return Map of {@literal <String, String>} custom query options
*/
public Map<String, String> getCustomQueryOptions();
}
| apache-2.0 |
hastef88/andes | modules/andes-core/client/src/main/java/org/wso2/andes/client/BasicMessageConsumer_0_10.java | 19190 | /* 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.wso2.andes.client;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wso2.andes.AMQException;
import org.wso2.andes.AMQInternalException;
import org.wso2.andes.client.AMQDestination.AddressOption;
import org.wso2.andes.client.AMQDestination.DestSyntax;
import org.wso2.andes.client.failover.FailoverException;
import org.wso2.andes.client.message.AMQMessageDelegateFactory;
import org.wso2.andes.client.message.AMQMessageDelegate_0_10;
import org.wso2.andes.client.message.AbstractJMSMessage;
import org.wso2.andes.client.message.MessageFactoryRegistry;
import org.wso2.andes.client.message.UnprocessedMessage_0_10;
import org.wso2.andes.client.protocol.AMQProtocolHandler;
import org.wso2.andes.filter.JMSSelectorFilter;
import org.wso2.andes.filter.MessageFilter;
import org.wso2.andes.framing.FieldTable;
import org.wso2.andes.protocol.AMQConstant;
import org.wso2.andes.transport.Acquired;
import org.wso2.andes.transport.MessageCreditUnit;
import org.wso2.andes.transport.Option;
import org.wso2.andes.transport.RangeSet;
import org.wso2.andes.transport.SessionException;
import java.util.Iterator;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.jms.InvalidSelectorException;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
/**
* This is a 0.10 message consumer.
*/
public class BasicMessageConsumer_0_10 extends BasicMessageConsumer<UnprocessedMessage_0_10>
{
/**
* This class logger
*/
protected final Logger _logger = LoggerFactory.getLogger(getClass());
/**
* The message selector filter associated with this consumer message selector
*/
private MessageFilter _filter = null;
/**
* The underlying QpidSession
*/
private AMQSession_0_10 _0_10session;
/**
* Indicates whether this consumer receives pre-acquired messages
*/
private boolean _preAcquire = true;
/**
* Indicate whether this consumer is started.
*/
private boolean _isStarted = false;
/**
* Specify whether this consumer is performing a sync receive
*/
private final AtomicBoolean _syncReceive = new AtomicBoolean(false);
private String _consumerTagString;
private long capacity = 0;
//--- constructor
protected BasicMessageConsumer_0_10(int channelId, AMQConnection connection, AMQDestination destination,
String messageSelector, boolean noLocal, MessageFactoryRegistry messageFactory,
AMQSession session, AMQProtocolHandler protocolHandler,
FieldTable arguments, int prefetchHigh, int prefetchLow,
boolean exclusive, int acknowledgeMode, boolean noConsume, boolean autoClose)
throws JMSException
{
super(channelId, connection, destination, messageSelector, noLocal, messageFactory, session, protocolHandler,
arguments, prefetchHigh, prefetchLow, exclusive, acknowledgeMode, noConsume, autoClose);
_0_10session = (AMQSession_0_10) session;
if (messageSelector != null && !messageSelector.equals(""))
{
try
{
_filter = new JMSSelectorFilter(messageSelector);
}
catch (AMQInternalException e)
{
throw new InvalidSelectorException("cannot create consumer because of selector issue");
}
if (destination instanceof AMQQueue)
{
_preAcquire = false;
}
}
_isStarted = connection.started();
// Destination setting overrides connection defaults
if (destination.getDestSyntax() == DestSyntax.ADDR &&
destination.getLink().getConsumerCapacity() > 0)
{
capacity = destination.getLink().getConsumerCapacity();
}
else if (getSession().prefetch())
{
capacity = _0_10session.getAMQConnection().getMaxPrefetch();
}
if (destination.isAddressResolved() && AMQDestination.TOPIC_TYPE == destination.getAddressType())
{
boolean namedQueue = destination.getLink() != null && destination.getLink().getName() != null ;
if (!namedQueue)
{
_destination = destination.copyDestination();
_destination.setQueueName(null);
}
}
}
@Override public void setConsumerTag(int consumerTag)
{
super.setConsumerTag(consumerTag);
_consumerTagString = String.valueOf(consumerTag);
}
public String getConsumerTagString()
{
return _consumerTagString;
}
/**
*
* This is invoked by the session thread when emptying the session message queue.
* We first check if the message is valid (match the selector) and then deliver it to the
* message listener or to the sync consumer queue.
*
* @param jmsMessage this message has already been processed so can't redo preDeliver
*/
@Override public void notifyMessage(AbstractJMSMessage jmsMessage)
{
try
{
if (checkPreConditions(jmsMessage))
{
if (isMessageListenerSet() && capacity == 0)
{
_0_10session.getQpidSession().messageFlow(getConsumerTagString(),
MessageCreditUnit.MESSAGE, 1,
Option.UNRELIABLE);
}
_logger.debug("messageOk, trying to notify");
super.notifyMessage(jmsMessage);
}
}
catch (AMQException e)
{
_logger.error("Receivecd an Exception when receiving message",e);
getSession().getAMQConnection().exceptionReceived(e);
}
}
//----- overwritten methods
/**
* This method is invoked when this consumer is stopped.
* It tells the broker to stop delivering messages to this consumer.
*/
@Override void sendCancel() throws AMQException
{
_0_10session.getQpidSession().messageCancel(getConsumerTagString());
try
{
_0_10session.getQpidSession().sync();
getSession().confirmConsumerCancelled(getConsumerTag()); // confirm cancel
}
catch (SessionException se)
{
_0_10session.setCurrentException(se);
}
AMQException amqe = _0_10session.getCurrentException();
if (amqe != null)
{
throw amqe;
}
}
@Override void notifyMessage(UnprocessedMessage_0_10 messageFrame)
{
super.notifyMessage(messageFrame);
}
@Override protected void preApplicationProcessing(AbstractJMSMessage jmsMsg) throws JMSException
{
super.preApplicationProcessing(jmsMsg);
if (!_session.getTransacted()
&& ((_session.getAcknowledgeMode() != org.wso2.andes.jms.Session.PER_MESSAGE_ACKNOWLEDGE)
|| (_session.getAcknowledgeMode() != org.wso2.andes.jms.Session.CLIENT_ACKNOWLEDGE)))
{
_session.addUnacknowledgedMessage(jmsMsg.getDeliveryTag());
}
}
@Override public AbstractJMSMessage createJMSMessageFromUnprocessedMessage(
AMQMessageDelegateFactory delegateFactory, UnprocessedMessage_0_10 msg) throws Exception
{
AMQMessageDelegate_0_10.updateExchangeTypeMapping(msg.getMessageTransfer().getHeader(), ((AMQSession_0_10)getSession()).getQpidSession());
return _messageFactory.createMessage(msg.getMessageTransfer());
}
// private methods
/**
* Check whether a message can be delivered to this consumer.
*
* @param message The message to be checked.
* @return true if the message matches the selector and can be acquired, false otherwise.
* @throws AMQException If the message preConditions cannot be checked due to some internal error.
*/
private boolean checkPreConditions(AbstractJMSMessage message) throws AMQException
{
boolean messageOk = true;
// TODO Use a tag for fiding out if message filtering is done here or by the broker.
try
{
if (_messageSelector != null && !_messageSelector.equals(""))
{
messageOk = _filter.matches(message);
}
}
catch (Exception e)
{
throw new AMQException(AMQConstant.INTERNAL_ERROR, "Error when evaluating message selector", e);
}
if (_logger.isDebugEnabled())
{
_logger.debug("messageOk " + messageOk);
_logger.debug("_preAcquire " + _preAcquire);
}
if (!messageOk)
{
if (_preAcquire)
{
// this is the case for topics
// We need to ack this message
if (_logger.isDebugEnabled())
{
_logger.debug("filterMessage - trying to ack message");
}
acknowledgeMessage(message);
}
else
{
if (_logger.isDebugEnabled())
{
_logger.debug("Message not OK, releasing");
}
releaseMessage(message);
}
// if we are syncrhonously waiting for a message
// and messages are not prefetched we then need to request another one
if(capacity == 0)
{
_0_10session.getQpidSession().messageFlow(getConsumerTagString(),
MessageCreditUnit.MESSAGE, 1,
Option.UNRELIABLE);
}
}
// now we need to acquire this message if needed
// this is the case of queue with a message selector set
if (!_preAcquire && messageOk && !isNoConsume())
{
if (_logger.isDebugEnabled())
{
_logger.debug("filterMessage - trying to acquire message");
}
messageOk = acquireMessage(message);
_logger.debug("filterMessage - message acquire status : " + messageOk);
}
return messageOk;
}
/**
* Acknowledge a message
*
* @param message The message to be acknowledged
* @throws AMQException If the message cannot be acquired due to some internal error.
*/
private void acknowledgeMessage(AbstractJMSMessage message) throws AMQException
{
if (!_preAcquire)
{
RangeSet ranges = new RangeSet();
ranges.add((int) message.getDeliveryTag());
_0_10session.messageAcknowledge
(ranges,
_acknowledgeMode != org.wso2.andes.jms.Session.NO_ACKNOWLEDGE);
AMQException amqe = _0_10session.getCurrentException();
if (amqe != null)
{
throw amqe;
}
}
}
/**
* Release a message
*
* @param message The message to be released
* @throws AMQException If the message cannot be released due to some internal error.
*/
private void releaseMessage(AbstractJMSMessage message) throws AMQException
{
if (_preAcquire)
{
RangeSet ranges = new RangeSet();
ranges.add((int) message.getDeliveryTag());
_0_10session.getQpidSession().messageRelease(ranges);
_0_10session.sync();
}
}
/**
* Acquire a message
*
* @param message The message to be acquired
* @return true if the message has been acquired, false otherwise.
* @throws AMQException If the message cannot be acquired due to some internal error.
*/
private boolean acquireMessage(AbstractJMSMessage message) throws AMQException
{
boolean result = false;
if (!_preAcquire)
{
RangeSet ranges = new RangeSet();
ranges.add((int) message.getDeliveryTag());
Acquired acq = _0_10session.getQpidSession().messageAcquire(ranges).get();
RangeSet acquired = acq.getTransfers();
if (acquired != null && acquired.size() > 0)
{
result = true;
}
}
return result;
}
public void setMessageListener(final MessageListener messageListener) throws JMSException
{
super.setMessageListener(messageListener);
if (messageListener != null && capacity == 0)
{
_0_10session.getQpidSession().messageFlow(getConsumerTagString(),
MessageCreditUnit.MESSAGE, 1,
Option.UNRELIABLE);
}
if (messageListener != null && !_synchronousQueue.isEmpty())
{
Iterator<DelayedObject> messages = _synchronousQueue.iterator();
while (messages.hasNext())
{
AbstractJMSMessage message = (AbstractJMSMessage) messages.next().getObject();
messages.remove();
_session.rejectMessage(message, true);
}
}
}
public void failedOverPost()
{
if (_0_10session.isStarted() && _syncReceive.get())
{
_0_10session.getQpidSession().messageFlow
(getConsumerTagString(), MessageCreditUnit.MESSAGE, 1,
Option.UNRELIABLE);
}
}
/**
* When messages are not prefetched we need to request a message from the
* broker.
* Note that if the timeout is too short a message may be queued in _synchronousQueue until
* this consumer closes or request it.
* @param l
* @return
* @throws InterruptedException
*/
public Object getMessageFromQueue(long l) throws InterruptedException
{
if (capacity == 0)
{
_syncReceive.set(true);
}
if (_0_10session.isStarted() && capacity == 0 && _synchronousQueue.isEmpty())
{
_0_10session.getQpidSession().messageFlow(getConsumerTagString(),
MessageCreditUnit.MESSAGE, 1,
Option.UNRELIABLE);
}
Object o = super.getMessageFromQueue(l);
if (o == null && _0_10session.isStarted())
{
_0_10session.getQpidSession().messageFlush
(getConsumerTagString(), Option.UNRELIABLE, Option.SYNC);
_0_10session.getQpidSession().sync();
_0_10session.getQpidSession().messageFlow
(getConsumerTagString(), MessageCreditUnit.BYTE,
0xFFFFFFFF, Option.UNRELIABLE);
if (capacity > 0)
{
_0_10session.getQpidSession().messageFlow
(getConsumerTagString(),
MessageCreditUnit.MESSAGE,
capacity,
Option.UNRELIABLE);
}
_0_10session.syncDispatchQueue();
o = super.getMessageFromQueue(-1);
}
if (capacity == 0)
{
_syncReceive.set(false);
}
return o;
}
void postDeliver(AbstractJMSMessage msg) throws JMSException
{
super.postDeliver(msg);
if (_acknowledgeMode == org.wso2.andes.jms.Session.NO_ACKNOWLEDGE && !_session.isInRecovery())
{
_session.acknowledgeMessage(msg.getDeliveryTag(), false);
}
if (_acknowledgeMode == org.wso2.andes.jms.Session.AUTO_ACKNOWLEDGE &&
!_session.isInRecovery() &&
_session.getAMQConnection().getSyncAck())
{
((AMQSession_0_10) getSession()).flushAcknowledgments();
((AMQSession_0_10) getSession()).getQpidSession().sync();
}
}
Message receiveBrowse() throws JMSException
{
return receiveNoWait();
}
@Override public void rollbackPendingMessages()
{
if (_synchronousQueue.size() > 0)
{
RangeSet ranges = new RangeSet();
Iterator<DelayedObject> iterator = _synchronousQueue.iterator();
while (iterator.hasNext()) {
Object o = iterator.next().getObject();
if (o instanceof AbstractJMSMessage)
{
ranges.add((int) ((AbstractJMSMessage) o).getDeliveryTag());
iterator.remove();
}
else
{
_logger.error("Queue contained a :" + o.getClass()
+ " unable to reject as it is not an AbstractJMSMessage. Will be cleared");
iterator.remove();
}
}
_0_10session.getQpidSession().messageRelease(ranges, Option.SET_REDELIVERED);
clearReceiveQueue();
}
}
public boolean isExclusive()
{
AMQDestination dest = this.getDestination();
if (dest.getDestSyntax() == AMQDestination.DestSyntax.ADDR)
{
if (dest.getAddressType() == AMQDestination.TOPIC_TYPE)
{
return true;
}
else
{
return dest.getLink().getSubscription().isExclusive();
}
}
else
{
return _exclusive;
}
}
void cleanupQueue() throws AMQException, FailoverException
{
AMQDestination dest = this.getDestination();
if (dest != null && dest.getDestSyntax() == AMQDestination.DestSyntax.ADDR)
{
if (dest.getDelete() == AddressOption.ALWAYS ||
dest.getDelete() == AddressOption.RECEIVER )
{
((AMQSession_0_10) getSession()).getQpidSession().queueDelete(
this.getDestination().getQueueName());
}
}
}
}
| apache-2.0 |
medicayun/medicayundicom | dcm4jboss-all/tags/DCM4JBOSS_2_2_1/dcm4jboss-wado/src/java/org/dcm4chex/wado/common/WADORequestObject.java | 2417 | /*
* Created on 10.12.2004
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package org.dcm4chex.wado.common;
import java.util.List;
import java.util.Map;
/**
* @author franz.willer
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public interface WADORequestObject {
public static final int OK = 0;
public static final int INVALID_WADO_URL = 1;
public static final int INVALID_ROWS = 2;
public static final int INVALID_COLUMNS = 3;
public static final int INVALID_FRAME_NUMBER = 4;
/**
* Returns the requestType parameter of the http request.
*
* @return requestType
*/
String getRequestType();
/**
* Returns the studyUID parameter of the http request.
*
* @return studyUID
*/
String getStudyUID();
/**
* Returns the seriesUID parameter of the http request.
*
* @return seriesUID
*/
String getSeriesUID();
/**
* Returns the objectUID parameter of the http request.
*
* @return objectUID
*/
String getObjectUID();
/**
* Returns the rows parameter of the http request.
*
* @return rows
*/
String getRows();
/**
* Returns the columns parameter of the http request.
*
* @return columns
*/
String getColumns();
/**
* Returns the frameNumber parameter of the http request.
*
* @return frame number as String
*/
String getFrameNumber();
/**
* Returns a list of content types as defined via the contentType http param.
*
* @return requestType
*/
List getContentTypes();
/**
* Returns a list of content types that the client supports.
* <p>
* This information comes from the http header.
*
*
* @return list of allowed content types or null if no restrictions.
*/
List getAllowedContentTypes();
/**
* Checks this request object and returns an error code.
*
* @return OK if it is a valid WADO request or an error code.
*/
int checkRequest();
/**
* Returns all parameter of the http request in a map.
*
* @return All http parameter
*/
Map getRequestParams();
/**
* Returns a Map of all request header fields of the http request.
*
* @see org.dcm4chex.wado.common.WADORequestObject#getRequestHeaders()
*
* @return All request header fields in a map.
*/
Map getRequestHeaders();
}
| apache-2.0 |
pkuwm/incubator-eagle | eagle-core/eagle-embed/eagle-embed-hbase/src/main/java/org/apache/eagle/service/hbase/EmbeddedHbase.java | 4212 | /*
* 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.eagle.service.hbase;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.MiniHBaseCluster;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*/
public class EmbeddedHbase {
private HBaseTestingUtility util;
private MiniHBaseCluster hBaseCluster;
private static EmbeddedHbase hbase;
private int port;
private String znode;
private static int DEFAULT_PORT = 2181;
private static String DEFAULT_ZNODE = "/hbase-unsecure";
private static final Logger LOG = LoggerFactory.getLogger(EmbeddedHbase.class);
private EmbeddedHbase(int port, String znode) {
this.port = port;
this.znode = znode;
}
private EmbeddedHbase(int port) {
this(port, DEFAULT_ZNODE);
}
public static EmbeddedHbase getInstance() {
if (hbase == null) {
synchronized(EmbeddedHbase.class) {
if (hbase == null) {
hbase = new EmbeddedHbase();
hbase.start();
}
}
}
return hbase;
}
private EmbeddedHbase() {
this(DEFAULT_PORT, DEFAULT_ZNODE);
}
public void start() {
try {
util = new HBaseTestingUtility();
Configuration conf= util.getConfiguration();
conf.setInt("test.hbase.zookeeper.property.clientPort", port);
conf.set("zookeeper.znode.parent", znode);
conf.setInt("hbase.zookeeper.property.maxClientCnxns", 200);
conf.setInt("hbase.master.info.port", -1);//avoid port clobbering
// start mini hbase cluster
hBaseCluster = util.startMiniCluster();
Configuration config = hBaseCluster.getConf();
config.set("zookeeper.session.timeout", "120000");
config.set("hbase.zookeeper.property.tickTime", "6000");
config.set(HConstants.HBASE_CLIENT_PAUSE, "3000");
config.set(HConstants.HBASE_CLIENT_RETRIES_NUMBER, "1");
config.set(HConstants.HBASE_CLIENT_OPERATION_TIMEOUT, "60000");
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
shutdown();
}
});
}
catch (Throwable t) {
LOG.error("Got an exception: ",t);
}
}
public void shutdown() {
try {
util.shutdownMiniCluster();
}
catch (Throwable t) {
LOG.info("Got an exception, " + t , t.getCause());
try {
util.shutdownMiniCluster();
}
catch (Throwable t1) {
}
}
}
public void createTable(String tableName, String cf) {
try {
util.createTable(tableName, cf);
}
catch (Exception ex) {
LOG.warn("Create table failed, probably table already existed, table name: " + tableName);
}
}
public void deleteTable(String tableName){
try {
util.deleteTable(tableName);
}
catch (Exception ex) {
LOG.warn("Delete table failed, probably table not existed, table name: " + tableName);
}
}
public static void main(String[] args){
EmbeddedHbase hbase = new EmbeddedHbase(12181);
hbase.start();
for(String table : new Tables().getTables()){
hbase.createTable(table, "f");
}
}
}
| apache-2.0 |
johtani/elasticsearch | src/main/java/org/elasticsearch/search/aggregations/bucket/terms/TermsAggregatorFactory.java | 14261 | /*
* 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.bucket.terms;
import org.apache.lucene.search.IndexSearcher;
import org.elasticsearch.ElasticsearchIllegalArgumentException;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.search.aggregations.*;
import org.elasticsearch.search.aggregations.Aggregator.SubAggCollectionMode;
import org.elasticsearch.search.aggregations.bucket.terms.support.IncludeExclude;
import org.elasticsearch.search.aggregations.support.AggregationContext;
import org.elasticsearch.search.aggregations.support.ValuesSource;
import org.elasticsearch.search.aggregations.support.ValuesSourceAggregatorFactory;
import org.elasticsearch.search.aggregations.support.ValuesSourceConfig;
/**
*
*/
public class TermsAggregatorFactory extends ValuesSourceAggregatorFactory {
public enum ExecutionMode {
MAP(new ParseField("map")) {
@Override
Aggregator create(String name, AggregatorFactories factories, ValuesSource valuesSource, long estimatedBucketCount,
long maxOrd, Terms.Order order, TermsAggregator.BucketCountThresholds bucketCountThresholds, IncludeExclude includeExclude,
AggregationContext aggregationContext, Aggregator parent, SubAggCollectionMode subAggCollectMode, boolean showTermDocCountError) {
return new StringTermsAggregator(name, factories, valuesSource, estimatedBucketCount, order, bucketCountThresholds, includeExclude, aggregationContext, parent, subAggCollectMode, showTermDocCountError);
}
@Override
boolean needsGlobalOrdinals() {
return false;
}
},
GLOBAL_ORDINALS(new ParseField("global_ordinals")) {
@Override
Aggregator create(String name, AggregatorFactories factories, ValuesSource valuesSource, long estimatedBucketCount,
long maxOrd, Terms.Order order, TermsAggregator.BucketCountThresholds bucketCountThresholds, IncludeExclude includeExclude,
AggregationContext aggregationContext, Aggregator parent, SubAggCollectionMode subAggCollectMode, boolean showTermDocCountError) {
return new GlobalOrdinalsStringTermsAggregator(name, factories, (ValuesSource.Bytes.WithOrdinals.FieldData) valuesSource, estimatedBucketCount, maxOrd, order, bucketCountThresholds, includeExclude, aggregationContext, parent, subAggCollectMode, showTermDocCountError);
}
@Override
boolean needsGlobalOrdinals() {
return true;
}
},
GLOBAL_ORDINALS_HASH(new ParseField("global_ordinals_hash")) {
@Override
Aggregator create(String name, AggregatorFactories factories, ValuesSource valuesSource, long estimatedBucketCount,
long maxOrd, Terms.Order order, TermsAggregator.BucketCountThresholds bucketCountThresholds, IncludeExclude includeExclude,
AggregationContext aggregationContext, Aggregator parent, SubAggCollectionMode subAggCollectMode, boolean showTermDocCountError) {
return new GlobalOrdinalsStringTermsAggregator.WithHash(name, factories, (ValuesSource.Bytes.WithOrdinals.FieldData) valuesSource, estimatedBucketCount, maxOrd, order, bucketCountThresholds, includeExclude, aggregationContext, parent, subAggCollectMode, showTermDocCountError);
}
@Override
boolean needsGlobalOrdinals() {
return true;
}
},
GLOBAL_ORDINALS_LOW_CARDINALITY(new ParseField("global_ordinals_low_cardinality")) {
@Override
Aggregator create(String name, AggregatorFactories factories, ValuesSource valuesSource, long estimatedBucketCount,
long maxOrd, Terms.Order order, TermsAggregator.BucketCountThresholds bucketCountThresholds, IncludeExclude includeExclude,
AggregationContext aggregationContext, Aggregator parent, SubAggCollectionMode subAggCollectMode, boolean showTermDocCountError) {
if (includeExclude != null || factories.count() > 0) {
return GLOBAL_ORDINALS.create(name, factories, valuesSource, estimatedBucketCount, maxOrd, order, bucketCountThresholds, includeExclude, aggregationContext, parent, subAggCollectMode, showTermDocCountError);
}
return new GlobalOrdinalsStringTermsAggregator.LowCardinality(name, factories, (ValuesSource.Bytes.WithOrdinals.FieldData) valuesSource, estimatedBucketCount, maxOrd, order, bucketCountThresholds, aggregationContext, parent, subAggCollectMode, showTermDocCountError);
}
@Override
boolean needsGlobalOrdinals() {
return true;
}
};
public static ExecutionMode fromString(String value) {
for (ExecutionMode mode : values()) {
if (mode.parseField.match(value)) {
return mode;
}
}
throw new ElasticsearchIllegalArgumentException("Unknown `execution_hint`: [" + value + "], expected any of " + values());
}
private final ParseField parseField;
ExecutionMode(ParseField parseField) {
this.parseField = parseField;
}
abstract Aggregator create(String name, AggregatorFactories factories, ValuesSource valuesSource, long estimatedBucketCount,
long maxOrd, Terms.Order order, TermsAggregator.BucketCountThresholds bucketCountThresholds,
IncludeExclude includeExclude, AggregationContext aggregationContext, Aggregator parent, SubAggCollectionMode subAggCollectMode, boolean showTermDocCountError);
abstract boolean needsGlobalOrdinals();
@Override
public String toString() {
return parseField.getPreferredName();
}
}
private final Terms.Order order;
private final IncludeExclude includeExclude;
private final String executionHint;
private SubAggCollectionMode subAggCollectMode;
private final TermsAggregator.BucketCountThresholds bucketCountThresholds;
private boolean showTermDocCountError;
public TermsAggregatorFactory(String name, ValuesSourceConfig config, Terms.Order order, TermsAggregator.BucketCountThresholds bucketCountThresholds, IncludeExclude includeExclude, String executionHint,SubAggCollectionMode executionMode, boolean showTermDocCountError) {
super(name, StringTerms.TYPE.name(), config);
this.order = order;
this.includeExclude = includeExclude;
this.executionHint = executionHint;
this.bucketCountThresholds = bucketCountThresholds;
this.subAggCollectMode = executionMode;
this.showTermDocCountError = showTermDocCountError;
}
@Override
protected Aggregator createUnmapped(AggregationContext aggregationContext, Aggregator parent) {
final InternalAggregation aggregation = new UnmappedTerms(name, order, bucketCountThresholds.getRequiredSize(), bucketCountThresholds.getShardSize(), bucketCountThresholds.getMinDocCount());
return new NonCollectingAggregator(name, aggregationContext, parent) {
@Override
public InternalAggregation buildEmptyAggregation() {
return aggregation;
}
};
}
public static long estimatedBucketCount(ValuesSource valuesSource, Aggregator parent) {
long estimatedBucketCount = valuesSource.metaData().maxAtomicUniqueValuesCount();
if (estimatedBucketCount < 0) {
// there isn't an estimation available.. 50 should be a good start
estimatedBucketCount = 50;
}
// adding an upper bound on the estimation as some atomic field data in the future (binary doc values) and not
// going to know their exact cardinality and will return upper bounds in AtomicFieldData.getNumberUniqueValues()
// that may be largely over-estimated.. the value chosen here is arbitrary just to play nice with typical CPU cache
//
// Another reason is that it may be faster to resize upon growth than to start directly with the appropriate size.
// And that all values are not necessarily visited by the matches.
estimatedBucketCount = Math.min(estimatedBucketCount, 512);
if (Aggregator.hasParentBucketAggregator(parent)) {
// There is a parent that creates buckets, potentially with a very long tail of buckets with few documents
// Let's be conservative with memory in that case
estimatedBucketCount = Math.min(estimatedBucketCount, 8);
}
return estimatedBucketCount;
}
@Override
protected Aggregator create(ValuesSource valuesSource, long expectedBucketsCount, AggregationContext aggregationContext, Aggregator parent) {
long estimatedBucketCount = estimatedBucketCount(valuesSource, parent);
if (valuesSource instanceof ValuesSource.Bytes) {
ExecutionMode execution = null;
if (executionHint != null) {
execution = ExecutionMode.fromString(executionHint);
}
// In some cases, using ordinals is just not supported: override it
if (!(valuesSource instanceof ValuesSource.Bytes.WithOrdinals)) {
execution = ExecutionMode.MAP;
}
final long maxOrd;
final double ratio;
if (execution == null || execution.needsGlobalOrdinals()) {
ValuesSource.Bytes.WithOrdinals valueSourceWithOrdinals = (ValuesSource.Bytes.WithOrdinals) valuesSource;
IndexSearcher indexSearcher = aggregationContext.searchContext().searcher();
maxOrd = valueSourceWithOrdinals.globalMaxOrd(indexSearcher);
ratio = maxOrd / ((double) indexSearcher.getIndexReader().numDocs());
} else {
maxOrd = -1;
ratio = -1;
}
// Let's try to use a good default
if (execution == null) {
// if there is a parent bucket aggregator the number of instances of this aggregator is going
// to be unbounded and most instances may only aggregate few documents, so use hashed based
// global ordinals to keep the bucket ords dense.
if (Aggregator.hasParentBucketAggregator(parent)) {
execution = ExecutionMode.GLOBAL_ORDINALS_HASH;
} else {
if (factories == AggregatorFactories.EMPTY) {
if (ratio <= 0.5 && maxOrd <= 2048) {
// 0.5: At least we need reduce the number of global ordinals look-ups by half
// 2048: GLOBAL_ORDINALS_LOW_CARDINALITY has additional memory usage, which directly linked to maxOrd, so we need to limit.
execution = ExecutionMode.GLOBAL_ORDINALS_LOW_CARDINALITY;
} else {
execution = ExecutionMode.GLOBAL_ORDINALS;
}
} else {
execution = ExecutionMode.GLOBAL_ORDINALS;
}
}
}
assert execution != null;
valuesSource.setNeedsGlobalOrdinals(execution.needsGlobalOrdinals());
return execution.create(name, factories, valuesSource, estimatedBucketCount, maxOrd, order, bucketCountThresholds, includeExclude, aggregationContext, parent, subAggCollectMode, showTermDocCountError);
}
if ((includeExclude != null) && (includeExclude.isRegexBased())) {
throw new AggregationExecutionException("Aggregation [" + name + "] cannot support regular expression style include/exclude " +
"settings as they can only be applied to string fields. Use an array of numeric values for include/exclude clauses used to filter numeric fields");
}
if (valuesSource instanceof ValuesSource.Numeric) {
IncludeExclude.LongFilter longFilter = null;
if (((ValuesSource.Numeric) valuesSource).isFloatingPoint()) {
if (includeExclude != null) {
longFilter = includeExclude.convertToDoubleFilter();
}
return new DoubleTermsAggregator(name, factories, (ValuesSource.Numeric) valuesSource, config.format(),
estimatedBucketCount, order, bucketCountThresholds, aggregationContext, parent, subAggCollectMode,
showTermDocCountError, longFilter);
}
if (includeExclude != null) {
longFilter = includeExclude.convertToLongFilter();
}
return new LongTermsAggregator(name, factories, (ValuesSource.Numeric) valuesSource, config.format(), estimatedBucketCount,
order, bucketCountThresholds, aggregationContext, parent, subAggCollectMode, showTermDocCountError, longFilter);
}
throw new AggregationExecutionException("terms aggregation cannot be applied to field [" + config.fieldContext().field() +
"]. It can only be applied to numeric or string fields.");
}
}
| apache-2.0 |
magicDGS/gatk | src/main/java/org/broadinstitute/hellbender/metrics/InsertSizeMetricsArgumentCollection.java | 3026 | package org.broadinstitute.hellbender.metrics;
import org.broadinstitute.barclay.argparser.Argument;
import org.broadinstitute.barclay.argparser.ArgumentCollection;
import org.broadinstitute.hellbender.cmdline.argumentcollections.MetricAccumulationLevelArgumentCollection;
import java.io.Serializable;
// TODO: filter reads based on only isReverseStrand/mateIsReverseStrand (strand bias)
// TODO: filter reads based on {MATE_ON_SAME_CONTIG, MATE_DIFFERENT_STRAND, GOOD_CIGAR, NON_ZERO_REFERENCE_LENGTH_ALIGNMENT}
// TODO: filter reads based on length value (if too large), and/or minimum_pct like in Picard.
// TODO: case EITHER for enum EndToUser. For truncated genomic regions of putative SV breakpoints, not all reads have
// both ends land in the region, so third case is possible: will use either end when only one end is available in
// the region specified, and only first end if both are available.
// TODO: user argument validation (eg. maxMADTolerance)
/**
* ArgumentCollection for InsertSizeMetrics collectors.
*/
public class InsertSizeMetricsArgumentCollection extends MetricsArgumentCollection implements Serializable {
private static final long serialVersionUID = 1L;
@Argument(
doc = "File to write insert size histogram chart to.",
fullName = "histogram-plot-file",
shortName = "H"
)
public String histogramPlotFile;
@Argument(
doc = "Generate mean, sd and plots by trimming the data down to MEDIAN + maxMADTolerance*MEDIAN_ABSOLUTE_DEVIATION. " +
"This is done because insert size data typically includes enough anomalous values from chimeras and other " +
"artifacts to make the mean and sd grossly misleading regarding the real distribution.",
fullName = "histogram-plot-deviations-tolerance",
shortName = "TOL",
optional = true
)
public double maxMADTolerance = 10.0;
@Argument(
doc = "Explicitly sets the histogram width, overriding automatic truncation of Histogram tail. " +
"Also, when calculating mean and standard deviation, only bins <= HISTOGRAM_WIDTH will be included.",
fullName = "width",
shortName = "W",
optional = true
)
public Integer histogramWidth = null;
@Argument(
doc = "When generating the histogram, discard any data categories (out of FR, TANDEM, RF) that have " +
"fewer than this percentage of overall reads (Range: 0 to 1).",
fullName = "min-category-reads-percentage",
shortName="M"
)
public float minimumPct = 0.05f;
@Argument(
doc = "If enabled, an output .pdf plot will be created.",
fullName = "produce-plot"
)
public boolean producePlot = false;
@ArgumentCollection
public MetricAccumulationLevelArgumentCollection metricAccumulationLevel
= new MetricAccumulationLevelArgumentCollection();
}
| bsd-3-clause |
sebbrudzinski/motech | platform/mds/mds/src/main/java/org/motechproject/mds/event/CrudEventBuilder.java | 4496 | package org.motechproject.mds.event;
import org.apache.commons.lang.StringUtils;
import org.motechproject.mds.entityinfo.EntityInfo;
import java.util.HashMap;
import java.util.Map;
import static org.motechproject.mds.util.ClassName.simplifiedModuleName;
import static org.motechproject.mds.util.Constants.MDSEvents.BASE_SUBJECT;
import static org.motechproject.mds.util.Constants.MDSEvents.ENTITY_CLASS;
import static org.motechproject.mds.util.Constants.MDSEvents.ENTITY_NAME;
import static org.motechproject.mds.util.Constants.MDSEvents.MODULE_NAME;
import static org.motechproject.mds.util.Constants.MDSEvents.NAMESPACE;
import static org.motechproject.mds.util.Constants.MDSEvents.OBJECT_ID;
/**
* The <code>MDSCrudEvents</code> class is responsible for creating MDS CRUD events.
*/
public final class CrudEventBuilder {
private CrudEventBuilder() {
}
/**
* Builds parameters for a Motech CRUD event.
*
* @param module module name of an entity
* @param namespace namespace of an entity
* @param entity entity name
* @param entityClassName entity class name
* @param id id of the affected instance
* @return constructed parameters for the events
*/
public static Map<String, Object> buildEventParams(String module, String namespace, String entity, String entityClassName, Long id) {
Map<String, Object> params = new HashMap<>();
params.put(OBJECT_ID, id);
setEntityData(params, module, namespace, entity, entityClassName);
return params;
}
/**
* Creates subject for a Motech event, sent upon encounter
* of a CRUD event in MDS.
*
* @param entity entity information
* @param action String representation of a CRUD event type
* @return Constructed subject for the event
*/
public static String createSubject(EntityInfo entity, String action) {
return createSubject(entity.getModule(), entity.getNamespace(), entity.getEntityName(), action);
}
/**
* Creates subject for a Motech Event, sent upon encounter
* of a CRUD event in MDS.
*
* @param module module name of an entity
* @param namespace namespace of an entity
* @param entity entity name
* @param action CRUD event type
* @return Constructed subject for the Motech Event
*/
public static String createSubject(String module, String namespace, String entity, CrudEventType action) {
return createSubject(module, namespace, entity, action.toString());
}
/**
* Creates subject for a Motech Event, sent upon encounter
* of a CRUD event in MDS.
*
* @param module module name of an entity
* @param namespace namespace of an entity
* @param entity entity name
* @param action String representation of a CRUD event type
* @return Constructed subject for the Motech Event
*/
public static String createSubject(String module, String namespace, String entity, String action) {
String subject;
String simplifiedModuleName = simplifiedModuleName(module);
if (StringUtils.isBlank(module)) {
subject = BASE_SUBJECT + entity + "." + action;
} else if (StringUtils.isBlank(namespace)) {
subject = BASE_SUBJECT + simplifiedModuleName + "." + entity + "." + action;
} else {
subject = BASE_SUBJECT + simplifiedModuleName + "." + namespace + "." + entity + "." + action;
}
return subject;
}
/**
* Sets properties in the given {@link java.util.Map}.
*
* @param params a {@link java.util.Map} to write properties in
* @param module module name of an entity
* @param namespace namespace of an entity
* @param entityName entity name
* @param entityClassName entity class name
*/
public static void setEntityData(Map<String, Object> params, String module, String namespace, String entityName,
String entityClassName) {
params.put(ENTITY_NAME, entityName);
params.put(ENTITY_CLASS, entityClassName);
setIfNotBlank(params, MODULE_NAME, simplifiedModuleName(module));
setIfNotBlank(params, NAMESPACE, namespace);
}
private static void setIfNotBlank(Map<String, Object> params, String property, String value) {
if (StringUtils.isBlank(property) || StringUtils.isBlank(value)) {
return;
}
params.put(property, value);
}
}
| bsd-3-clause |
hoastoolshop/react-native | ReactAndroid/src/main/java/com/facebook/react/modules/deviceinfo/DeviceInfoModule.java | 2589 | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.react.modules.deviceinfo;
import javax.annotation.Nullable;
import java.util.HashMap;
import java.util.Map;
import android.content.Context;
import android.util.DisplayMetrics;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.BaseJavaModule;
import com.facebook.react.bridge.LifecycleEventListener;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.module.annotations.ReactModule;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.facebook.react.uimanager.DisplayMetricsHolder;
/**
* Module that exposes Android Constants to JS.
*/
@ReactModule(name = "DeviceInfo")
public class DeviceInfoModule extends BaseJavaModule implements
LifecycleEventListener {
private @Nullable ReactApplicationContext mReactApplicationContext;
private float mFontScale;
public DeviceInfoModule(ReactApplicationContext reactContext) {
this((Context) reactContext);
mReactApplicationContext = reactContext;
mReactApplicationContext.addLifecycleEventListener(this);
}
public DeviceInfoModule(Context context) {
mReactApplicationContext = null;
DisplayMetricsHolder.initDisplayMetricsIfNotInitialized(context);
mFontScale = context.getResources().getConfiguration().fontScale;
}
@Override
public String getName() {
return "DeviceInfo";
}
@Override
public @Nullable Map<String, Object> getConstants() {
HashMap<String, Object> constants = new HashMap<>();
constants.put(
"Dimensions",
DisplayMetricsHolder.getDisplayMetricsMap(mFontScale));
return constants;
}
@Override
public void onHostResume() {
if (mReactApplicationContext == null) {
return;
}
float fontScale = mReactApplicationContext.getResources().getConfiguration().fontScale;
if (mFontScale != fontScale) {
mFontScale = fontScale;
emitUpdateDimensionsEvent();
}
}
@Override
public void onHostPause() {
}
@Override
public void onHostDestroy() {
}
public void emitUpdateDimensionsEvent() {
if (mReactApplicationContext == null) {
return;
}
mReactApplicationContext
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("didUpdateDimensions", DisplayMetricsHolder.getDisplayMetricsMap(mFontScale));
}
}
| bsd-3-clause |
andrewmkrug/Selenium-Grid-Extras | SeleniumGridExtras/src/test/java/com/groupon/seleniumgridextras/utilities/json/JsonParserWrapperTest.java | 3228 | package com.groupon.seleniumgridextras.utilities.json;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import org.junit.Before;
import org.junit.Test;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
public class JsonParserWrapperTest {
private static final String JSON_BUILDER_PRETTY_STRING =
"{\n" +
" \"exit_code\": 0,\n" +
" \"out\": [],\n" +
" \"error\": [],\n" +
" \"foo\": [\n" +
" \"hello\"\n" +
" ]\n" +
"}";
private static final String JSON_LIST_WITH_MAPS =
"[\n" +
" {\n" +
" \"id\": \"123456\",\n" +
" \"time\": \"time\"\n" +
" }\n" +
"]";
private JsonResponseBuilder responseBuilder;
private Map expectedParsedHash;
@Before
public void setUp() throws Exception {
responseBuilder = new JsonResponseBuilder();
responseBuilder.addKeyDescriptions("foo", "bar");
responseBuilder.addKeyValues("foo", "hello");
expectedParsedHash = new HashMap();
expectedParsedHash.put("exit_code", 0.0);
expectedParsedHash.put("error", new LinkedList());
expectedParsedHash.put("out", new LinkedList());
List foo = new LinkedList();
foo.add("hello");
expectedParsedHash.put("foo", foo);
}
@Test
public void testToListFromString() throws Exception {
Map expected = new HashMap();
expected.put("id", "123456");
expected.put("time", "time");
List actual =JsonParserWrapper.toList(JSON_LIST_WITH_MAPS);
assertEquals(1, actual.size());
assertEquals(expected, actual.get(0));
}
@Test
public void testToHashMapFromString() throws Exception {
assertEquals(expectedParsedHash, JsonParserWrapper.toHashMap(JSON_BUILDER_PRETTY_STRING));
}
@Test
public void testToHashMapFromJsonObject() throws Exception {
assertEquals(expectedParsedHash, JsonParserWrapper.toHashMap(responseBuilder.getJson()));
}
@Test
public void testPrettyPrintStringNormalObject() throws Exception {
String expected =
"{\n" +
" \"a\": \"b\",\n" +
" \"z\": \"a\"\n" +
"}";
Map map = new HashMap();
map.put("a", "b");
map.put("z", "a");
assertEquals(expected, JsonParserWrapper.prettyPrintString(map));
}
@Test
public void testPrettyPrintStringJsonObject() throws Exception {
assertEquals(JSON_BUILDER_PRETTY_STRING, JsonParserWrapper.prettyPrintString(responseBuilder.getJson()));
}
@Test
public void testToJsonObject() throws Exception {
Map foo = new HashMap();
foo.put("a", "b");
foo.put("b", 2);
JsonObject actual = JsonParserWrapper.toJsonObject(foo);
JsonObject expected = new JsonObject();
expected.add("a", new JsonPrimitive("b"));
expected.add("b", new JsonPrimitive(2));
assertEquals(expected, actual);
}
}
| bsd-3-clause |
mag/robolectric | robolectric/src/main/java/org/robolectric/internal/InstrumentingClassLoaderFactory.java | 2387 | package org.robolectric.internal;
import org.robolectric.internal.bytecode.InstrumentationConfiguration;
import org.robolectric.internal.bytecode.InstrumentingClassLoader;
import org.robolectric.internal.dependency.DependencyJar;
import org.robolectric.internal.dependency.DependencyResolver;
import org.robolectric.util.Pair;
import java.net.URL;
import java.util.LinkedHashMap;
import java.util.Map;
public class InstrumentingClassLoaderFactory {
/** The factor for cache size. See {@link #CACHE_SIZE} for details. */
private static final int CACHE_SIZE_FACTOR = 3;
/** We need to set the cache size of class loaders more than the number of supported APIs as different tests may have different configurations. */
private static final int CACHE_SIZE = SdkConfig.getSupportedApis().size() * CACHE_SIZE_FACTOR;
// Simple LRU Cache. SdkEnvironments are unique across InstrumentingClassloaderConfig and SdkConfig
private static final LinkedHashMap<Pair<InstrumentationConfiguration, SdkConfig>, SdkEnvironment> sdkToEnvironment = new LinkedHashMap<Pair<InstrumentationConfiguration, SdkConfig>, SdkEnvironment>() {
@Override
protected boolean removeEldestEntry(Map.Entry<Pair<InstrumentationConfiguration, SdkConfig>, SdkEnvironment> eldest) {
return size() > CACHE_SIZE;
}
};
private final InstrumentationConfiguration instrumentationConfig;
private final DependencyResolver dependencyResolver;
public InstrumentingClassLoaderFactory(InstrumentationConfiguration instrumentationConfig, DependencyResolver dependencyResolver) {
this.instrumentationConfig = instrumentationConfig;
this.dependencyResolver = dependencyResolver;
}
public synchronized SdkEnvironment getSdkEnvironment(SdkConfig sdkConfig) {
Pair<InstrumentationConfiguration, SdkConfig> key = Pair.create(instrumentationConfig, sdkConfig);
SdkEnvironment sdkEnvironment = sdkToEnvironment.get(key);
if (sdkEnvironment == null) {
URL[] urls = dependencyResolver.getLocalArtifactUrls(
sdkConfig.getAndroidSdkDependency(),
sdkConfig.getCoreShadowsDependency());
ClassLoader robolectricClassLoader = new InstrumentingClassLoader(instrumentationConfig, urls);
sdkEnvironment = new SdkEnvironment(sdkConfig, robolectricClassLoader);
sdkToEnvironment.put(key, sdkEnvironment);
}
return sdkEnvironment;
}
}
| mit |
aptana/Pydev | tests/org.python.pydev.refactoring.tests/src/org/python/pydev/refactoring/tests/core/TestData.java | 3377 | /******************************************************************************
* Copyright (C) 2007-2012 IFS Institute for Software 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
*
* Original authors:
* Reto Schuettel
* Robin Stocker
* Contributors:
* Fabio Zadrozny <fabiofz@gmail.com> - initial implementation
******************************************************************************/
/*
* Copyright (C) 2007 Reto Schuettel, Robin Stocker
*
* IFS Institute for Software, HSR Rapperswil, Switzerland
*
*/
package org.python.pydev.refactoring.tests.core;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.regex.Pattern;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.TextSelection;
import org.python.pydev.refactoring.utils.FileUtils;
import org.python.pydev.refactoring.utils.TestUtils;
import org.python.pydev.refactoring.utils.TestUtils.Cursors;
public class TestData {
/* allows ##c ##r, with or without comments on the same line */
private static final Pattern MAGIC_LEXER_CONFIG = Pattern.compile("^##[cr][^\\n]*$", Pattern.MULTILINE);
public String source;
public String config;
public String result;
public ITextSelection sourceSelection;
public ITextSelection resultSelection;
public File file;
public TestData(File file) {
String content;
this.file = file;
try {
content = FileUtils.read(file);
} catch (IOException e) {
throw new RuntimeException();
}
String[] parts = MAGIC_LEXER_CONFIG.split(content, 3);
source = parts[0];
if (parts.length == 3) {
config = parts[1];
result = parts[2];
} else if (parts.length == 2) {
config = "";
result = parts[1];
} else if (parts.length == 1) {
config = "";
result = source;
} else {
throw new RuntimeException("Invalid source file, only " + parts.length + " parts found in " + file);
}
source = source.trim();
result = result.trim();
config = config.trim();
Cursors sourceCursors = TestUtils.findCursors(source);
Cursors resultCursors = TestUtils.findCursors(result);
source = sourceCursors.text;
result = resultCursors.text;
sourceSelection = parseSelection(sourceCursors.positions);
resultSelection = parseSelection(resultCursors.positions);
}
private ITextSelection parseSelection(List<Integer> list) {
if (list.size() == 1) {
return new TextSelection(list.get(0), 0);
} else if (list.size() == 2) {
int start = list.get(0);
int end = list.get(1);
return new TextSelection(start, end - start);
} else {
return null;
}
}
public String getConfigContents() {
String c = config.trim();
if (c.startsWith("'''")) {
c = c.substring(3);
}
if (c.endsWith("'''")) {
c = c.substring(0, c.length() - 3);
}
return c;
}
}
| epl-1.0 |
gazarenkov/che-sketch | plugins/plugin-svn/che-plugin-svn-ext-shared/src/main/java/org/eclipse/che/plugin/svn/shared/LockRequest.java | 2168 | /*******************************************************************************
* Copyright (c) 2012-2017 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.plugin.svn.shared;
import org.eclipse.che.commons.annotation.Nullable;
import org.eclipse.che.dto.shared.DTO;
import java.util.List;
/**
* Request DTO for both lock and unlock requests.
*/
@DTO
public interface LockRequest {
/**
* Returns the path of the project.
*
* @return the project path
*/
String getProjectPath();
void setProjectPath(String path);
LockRequest withProjectPath(String path);
/**
* Returns the targets to lock.
*
* @return the targets
*/
List<String> getTargets();
void setTargets(List<String> targets);
LockRequest withTargets(List<String> targets);
/**
* The force option allows svn to steal locks from other users.<br>
* without force, svn leaves the files to the previous lock owner and warns.
*
* @return the 'force' value
*/
boolean isForce();
LockRequest withForce(boolean force);
void setForce(boolean force);
/** @return user name for authentication */
String getUsername();
/** Set user name for authentication. */
void setUsername(@Nullable final String username);
/** @return {@link CheckoutRequest} with specified user name for authentication */
LockRequest withUsername(@Nullable final String username);
/** @return password for authentication */
String getPassword();
/** Set password for authentication. */
void setPassword(@Nullable final String password);
/** @return {@link CheckoutRequest} with specified password for authentication */
LockRequest withPassword(@Nullable final String password);
}
| epl-1.0 |
gazarenkov/che-sketch | wsagent/che-core-api-debug-shared/src/main/java/org/eclipse/che/api/debug/shared/dto/event/BreakpointActivatedEventDto.java | 1114 | /*******************************************************************************
* Copyright (c) 2012-2017 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.api.debug.shared.dto.event;
import org.eclipse.che.api.debug.shared.dto.BreakpointDto;
import org.eclipse.che.dto.shared.DTO;
/**
* Event will be generated when breakpoint become active.
*
* @author Anatoliy Bazko
*/
@DTO
public interface BreakpointActivatedEventDto extends DebuggerEventDto {
TYPE getType();
void setType(TYPE type);
BreakpointActivatedEventDto withType(TYPE type);
BreakpointDto getBreakpoint();
void setBreakpoint(BreakpointDto breakpoint);
BreakpointActivatedEventDto withBreakpoint(BreakpointDto breakpoint);
}
| epl-1.0 |
md-5/jdk10 | src/java.desktop/share/classes/javax/sound/sampled/CompoundControl.java | 3276 | /*
* Copyright (c) 1999, 2018, 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.sound.sampled;
/**
* A {@code CompoundControl}, such as a graphic equalizer, provides control over
* two or more related properties, each of which is itself represented as a
* {@code Control}.
*
* @author Kara Kytle
* @since 1.3
*/
public abstract class CompoundControl extends Control {
/**
* The set of member controls.
*/
private final Control[] controls;
/**
* Constructs a new compound control object with the given parameters.
*
* @param type the type of control represented this compound control object
* @param memberControls the set of member controls
*/
protected CompoundControl(Type type, Control[] memberControls) {
super(type);
this.controls = memberControls;
}
/**
* Returns the set of member controls that comprise the compound control.
*
* @return the set of member controls
*/
public Control[] getMemberControls() {
return controls.clone();
}
/**
* Provides a string representation of the control.
*
* @return a string description
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < controls.length; i++) {
if (i != 0) {
sb.append(", ");
if ((i + 1) == controls.length) {
sb.append("and ");
}
}
sb.append(controls[i].getType());
}
return new String(getType() + " Control containing " + sb + " Controls.");
}
/**
* An instance of the {@code CompoundControl.Type} inner class identifies
* one kind of compound control.
*
* @author Kara Kytle
* @since 1.3
*/
public static class Type extends Control.Type {
/**
* Constructs a new compound control type.
*
* @param name the name of the new compound control type
*/
protected Type(final String name) {
super(name);
}
}
}
| gpl-2.0 |
md-5/jdk10 | test/hotspot/jtreg/vmTestbase/gc/ArrayJuggle/Juggle24/TestDescription.java | 1419 | /*
* Copyright (c) 2017, 2018, 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
* @key stress gc
*
* @summary converted from VM Testbase gc/ArrayJuggle/Juggle24.
* VM Testbase keywords: [gc, stress, stressopt, nonconcurrent]
*
* @library /vmTestbase
* /test/lib
* @run driver jdk.test.lib.FileInstaller . .
* @run main/othervm -Xlog:gc=debug:gc.log gc.ArrayJuggle.Juggle01.Juggle01 -gp doubleArr -ms high
*/
| gpl-2.0 |
rfdrake/opennms | opennms-provision/opennms-provision-persistence/src/main/java/org/opennms/netmgt/provision/persist/foreignsource/ParameterList.java | 2700 | /*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2009-2012 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) 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.
*
* OpenNMS(R) 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 OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.netmgt.provision.persist.foreignsource;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlRootElement
/**
* <p>ParameterList class.</p>
*
* @author ranger
* @version $Id: $
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name="pluginConfigParameter")
public class ParameterList {
public List<PluginParameter> parameter;
/**
* <p>Constructor for ParameterList.</p>
*/
public ParameterList() {
parameter = new LinkedList<PluginParameter>();
}
/**
* <p>Constructor for ParameterList.</p>
*
* @param m a {@link java.util.Map} object.
*/
public ParameterList(Map<String,String> m) {
parameter = new LinkedList<PluginParameter>();
for (Map.Entry<String,String> e : m.entrySet()) {
parameter.add(new PluginParameter(e));
}
}
/**
* <p>Setter for the field <code>parameter</code>.</p>
*
* @param list a {@link java.util.List} object.
*/
public void setParameter(List<PluginParameter> list) {
parameter = list;
}
/**
* <p>Getter for the field <code>parameter</code>.</p>
*
* @return a {@link java.util.List} object.
*/
public List<PluginParameter> getParameter() {
return parameter;
}
}
| gpl-2.0 |
shakalaca/ASUS_ZenFone_A450CG | external/proguard/src/proguard/classfile/instruction/Instruction.java | 22470 | /*
* ProGuard -- shrinking, optimization, obfuscation, and preverification
* of Java bytecode.
*
* Copyright (c) 2002-2009 Eric Lafortune (eric@graphics.cornell.edu)
*
* 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 2 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, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package proguard.classfile.instruction;
import proguard.classfile.*;
import proguard.classfile.attribute.CodeAttribute;
import proguard.classfile.instruction.visitor.InstructionVisitor;
/**
* Base class for representing instructions.
*
* @author Eric Lafortune
*/
public abstract class Instruction
{
// An array for marking Category 2 instructions.
private static final boolean[] IS_CATEGORY2 = new boolean[]
{
false, // nop
false, // aconst_null
false, // iconst_m1
false, // iconst_0
false, // iconst_1
false, // iconst_2
false, // iconst_3
false, // iconst_4
false, // iconst_5
true, // lconst_0
true, // lconst_1
false, // fconst_0
false, // fconst_1
false, // fconst_2
true, // dconst_0
true, // dconst_1
false, // bipush
false, // sipush
false, // ldc
false, // ldc_w
true, // ldc2_w
false, // iload
true, // lload
false, // fload
true, // dload
false, // aload
false, // iload_0
false, // iload_1
false, // iload_2
false, // iload_3
true, // lload_0
true, // lload_1
true, // lload_2
true, // lload_3
false, // fload_0
false, // fload_1
false, // fload_2
false, // fload_3
true, // dload_0
true, // dload_1
true, // dload_2
true, // dload_3
false, // aload_0
false, // aload_1
false, // aload_2
false, // aload_3
false, // iaload
true, // laload
false, // faload
true, // daload
false, // aaload
false, // baload
false, // caload
false, // saload
false, // istore
true, // lstore
false, // fstore
true, // dstore
false, // astore
false, // istore_0
false, // istore_1
false, // istore_2
false, // istore_3
true, // lstore_0
true, // lstore_1
true, // lstore_2
true, // lstore_3
false, // fstore_0
false, // fstore_1
false, // fstore_2
false, // fstore_3
true, // dstore_0
true, // dstore_1
true, // dstore_2
true, // dstore_3
false, // astore_0
false, // astore_1
false, // astore_2
false, // astore_3
false, // iastore
true, // lastore
false, // fastore
true, // dastore
false, // aastore
false, // bastore
false, // castore
false, // sastore
false, // pop
true, // pop2
false, // dup
false, // dup_x1
false, // dup_x2
true, // dup2
true, // dup2_x1
true, // dup2_x2
false, // swap
false, // iadd
true, // ladd
false, // fadd
true, // dadd
false, // isub
true, // lsub
false, // fsub
true, // dsub
false, // imul
true, // lmul
false, // fmul
true, // dmul
false, // idiv
true, // ldiv
false, // fdiv
true, // ddiv
false, // irem
true, // lrem
false, // frem
true, // drem
false, // ineg
true, // lneg
false, // fneg
true, // dneg
false, // ishl
true, // lshl
false, // ishr
true, // lshr
false, // iushr
true, // lushr
false, // iand
true, // land
false, // ior
true, // lor
false, // ixor
true, // lxor
false, // iinc
false, // i2l
false, // i2f
false, // i2d
true, // l2i
true, // l2f
true, // l2d
false, // f2i
false, // f2l
false, // f2d
true, // d2i
true, // d2l
true, // d2f
false, // i2b
false, // i2c
false, // i2s
true, // lcmp
false, // fcmpl
false, // fcmpg
true, // dcmpl
true, // dcmpg
false, // ifeq
false, // ifne
false, // iflt
false, // ifge
false, // ifgt
false, // ifle
false, // ificmpeq
false, // ificmpne
false, // ificmplt
false, // ificmpge
false, // ificmpgt
false, // ificmple
false, // ifacmpeq
false, // ifacmpne
false, // goto
false, // jsr
false, // ret
false, // tableswitch
false, // lookupswitch
false, // ireturn
true, // lreturn
false, // freturn
true, // dreturn
false, // areturn
false, // return
false, // getstatic
false, // putstatic
false, // getfield
false, // putfield
false, // invokevirtual
false, // invokespecial
false, // invokestatic
false, // invokeinterface
false, // unused
false, // new
false, // newarray
false, // anewarray
false, // arraylength
false, // athrow
false, // checkcast
false, // instanceof
false, // monitorenter
false, // monitorexit
false, // wide
false, // multianewarray
false, // ifnull
false, // ifnonnull
false, // goto_w
false, // jsr_w
};
// An array containing the fixed number of entries popped from the stack,
// for all instructions.
private static final int[] STACK_POP_COUNTS = new int[]
{
0, // nop
0, // aconst_null
0, // iconst_m1
0, // iconst_0
0, // iconst_1
0, // iconst_2
0, // iconst_3
0, // iconst_4
0, // iconst_5
0, // lconst_0
0, // lconst_1
0, // fconst_0
0, // fconst_1
0, // fconst_2
0, // dconst_0
0, // dconst_1
0, // bipush
0, // sipush
0, // ldc
0, // ldc_w
0, // ldc2_w
0, // iload
0, // lload
0, // fload
0, // dload
0, // aload
0, // iload_0
0, // iload_1
0, // iload_2
0, // iload_3
0, // lload_0
0, // lload_1
0, // lload_2
0, // lload_3
0, // fload_0
0, // fload_1
0, // fload_2
0, // fload_3
0, // dload_0
0, // dload_1
0, // dload_2
0, // dload_3
0, // aload_0
0, // aload_1
0, // aload_2
0, // aload_3
2, // iaload
2, // laload
2, // faload
2, // daload
2, // aaload
2, // baload
2, // caload
2, // saload
1, // istore
2, // lstore
1, // fstore
2, // dstore
1, // astore
1, // istore_0
1, // istore_1
1, // istore_2
1, // istore_3
2, // lstore_0
2, // lstore_1
2, // lstore_2
2, // lstore_3
1, // fstore_0
1, // fstore_1
1, // fstore_2
1, // fstore_3
2, // dstore_0
2, // dstore_1
2, // dstore_2
2, // dstore_3
1, // astore_0
1, // astore_1
1, // astore_2
1, // astore_3
3, // iastore
4, // lastore
3, // fastore
4, // dastore
3, // aastore
3, // bastore
3, // castore
3, // sastore
1, // pop
2, // pop2
1, // dup
2, // dup_x1
3, // dup_x2
2, // dup2
3, // dup2_x1
4, // dup2_x2
2, // swap
2, // iadd
4, // ladd
2, // fadd
4, // dadd
2, // isub
4, // lsub
2, // fsub
4, // dsub
2, // imul
4, // lmul
2, // fmul
4, // dmul
2, // idiv
4, // ldiv
2, // fdiv
4, // ddiv
2, // irem
4, // lrem
2, // frem
4, // drem
1, // ineg
2, // lneg
1, // fneg
2, // dneg
2, // ishl
3, // lshl
2, // ishr
3, // lshr
2, // iushr
3, // lushr
2, // iand
4, // land
2, // ior
4, // lor
2, // ixor
4, // lxor
0, // iinc
1, // i2l
1, // i2f
1, // i2d
2, // l2i
2, // l2f
2, // l2d
1, // f2i
1, // f2l
1, // f2d
2, // d2i
2, // d2l
2, // d2f
1, // i2b
1, // i2c
1, // i2s
4, // lcmp
2, // fcmpl
2, // fcmpg
4, // dcmpl
4, // dcmpg
1, // ifeq
1, // ifne
1, // iflt
1, // ifge
1, // ifgt
1, // ifle
2, // ificmpeq
2, // ificmpne
2, // ificmplt
2, // ificmpge
2, // ificmpgt
2, // ificmple
2, // ifacmpeq
2, // ifacmpne
0, // goto
0, // jsr
0, // ret
1, // tableswitch
1, // lookupswitch
1, // ireturn
2, // lreturn
1, // freturn
2, // dreturn
1, // areturn
0, // return
0, // getstatic
0, // putstatic
1, // getfield
1, // putfield
1, // invokevirtual
1, // invokespecial
0, // invokestatic
1, // invokeinterface
0, // unused
0, // new
1, // newarray
1, // anewarray
1, // arraylength
1, // athrow
1, // checkcast
1, // instanceof
1, // monitorenter
1, // monitorexit
0, // wide
0, // multianewarray
1, // ifnull
1, // ifnonnull
0, // goto_w
0, // jsr_w
};
// An array containing the fixed number of entries pushed onto the stack,
// for all instructions.
private static final int[] STACK_PUSH_COUNTS = new int[]
{
0, // nop
1, // aconst_null
1, // iconst_m1
1, // iconst_0
1, // iconst_1
1, // iconst_2
1, // iconst_3
1, // iconst_4
1, // iconst_5
2, // lconst_0
2, // lconst_1
1, // fconst_0
1, // fconst_1
1, // fconst_2
2, // dconst_0
2, // dconst_1
1, // bipush
1, // sipush
1, // ldc
1, // ldc_w
2, // ldc2_w
1, // iload
2, // lload
1, // fload
2, // dload
1, // aload
1, // iload_0
1, // iload_1
1, // iload_2
1, // iload_3
2, // lload_0
2, // lload_1
2, // lload_2
2, // lload_3
1, // fload_0
1, // fload_1
1, // fload_2
1, // fload_3
2, // dload_0
2, // dload_1
2, // dload_2
2, // dload_3
1, // aload_0
1, // aload_1
1, // aload_2
1, // aload_3
1, // iaload
2, // laload
1, // faload
2, // daload
1, // aaload
1, // baload
1, // caload
1, // saload
0, // istore
0, // lstore
0, // fstore
0, // dstore
0, // astore
0, // istore_0
0, // istore_1
0, // istore_2
0, // istore_3
0, // lstore_0
0, // lstore_1
0, // lstore_2
0, // lstore_3
0, // fstore_0
0, // fstore_1
0, // fstore_2
0, // fstore_3
0, // dstore_0
0, // dstore_1
0, // dstore_2
0, // dstore_3
0, // astore_0
0, // astore_1
0, // astore_2
0, // astore_3
0, // iastore
0, // lastore
0, // fastore
0, // dastore
0, // aastore
0, // bastore
0, // castore
0, // sastore
0, // pop
0, // pop2
2, // dup
3, // dup_x1
4, // dup_x2
4, // dup2
5, // dup2_x1
6, // dup2_x2
2, // swap
1, // iadd
2, // ladd
1, // fadd
2, // dadd
1, // isub
2, // lsub
1, // fsub
2, // dsub
1, // imul
2, // lmul
1, // fmul
2, // dmul
1, // idiv
2, // ldiv
1, // fdiv
2, // ddiv
1, // irem
2, // lrem
1, // frem
2, // drem
1, // ineg
2, // lneg
1, // fneg
2, // dneg
1, // ishl
2, // lshl
1, // ishr
2, // lshr
1, // iushr
2, // lushr
1, // iand
2, // land
1, // ior
2, // lor
1, // ixor
2, // lxor
0, // iinc
2, // i2l
1, // i2f
2, // i2d
1, // l2i
1, // l2f
2, // l2d
1, // f2i
2, // f2l
2, // f2d
1, // d2i
2, // d2l
1, // d2f
1, // i2b
1, // i2c
1, // i2s
1, // lcmp
1, // fcmpl
1, // fcmpg
1, // dcmpl
1, // dcmpg
0, // ifeq
0, // ifne
0, // iflt
0, // ifge
0, // ifgt
0, // ifle
0, // ificmpeq
0, // ificmpne
0, // ificmplt
0, // ificmpge
0, // ificmpgt
0, // ificmple
0, // ifacmpeq
0, // ifacmpne
0, // goto
1, // jsr
0, // ret
0, // tableswitch
0, // lookupswitch
0, // ireturn
0, // lreturn
0, // freturn
0, // dreturn
0, // areturn
0, // return
0, // getstatic
0, // putstatic
0, // getfield
0, // putfield
0, // invokevirtual
0, // invokespecial
0, // invokestatic
0, // invokeinterface
0, // unused
1, // new
1, // newarray
1, // anewarray
1, // arraylength
0, // athrow
1, // checkcast
1, // instanceof
0, // monitorenter
0, // monitorexit
0, // wide
1, // multianewarray
0, // ifnull
0, // ifnonnull
0, // goto_w
1, // jsr_w
};
public byte opcode;
/**
* Returns the canonical opcode of this instruction, i.e. typically the
* opcode whose extension has been removed.
*/
public byte canonicalOpcode()
{
return opcode;
}
/**
* Shrinks this instruction to its shortest possible form.
* @return this instruction.
*/
public abstract Instruction shrink();
/**
* Writes the Instruction at the given offset in the given code attribute.
*/
public final void write(CodeAttribute codeAttribute, int offset)
{
write(codeAttribute.code, offset);
}
/**
* Writes the Instruction at the given offset in the given code array.
*/
public void write(byte[] code, int offset)
{
// Write the wide opcode, if necessary.
if (isWide())
{
code[offset++] = InstructionConstants.OP_WIDE;
}
// Write the opcode.
code[offset++] = opcode;
// Write any additional arguments.
writeInfo(code, offset);
}
/**
* Returns whether the instruction is wide, i.e. preceded by a wide opcode.
* With the current specifications, only variable instructions can be wide.
*/
protected boolean isWide()
{
return false;
}
/**
* Reads the data following the instruction opcode.
*/
protected abstract void readInfo(byte[] code, int offset);
/**
* Writes data following the instruction opcode.
*/
protected abstract void writeInfo(byte[] code, int offset);
/**
* Returns the length in bytes of the instruction.
*/
public abstract int length(int offset);
/**
* Accepts the given visitor.
*/
public abstract void accept(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, InstructionVisitor instructionVisitor);
/**
* Returns a description of the instruction, at the given offset.
*/
public String toString(int offset)
{
return "["+offset+"] "+ this.toString();
}
/**
* Returns the name of the instruction.
*/
public String getName()
{
return InstructionConstants.NAMES[opcode & 0xff];
}
/**
* Returns whether the instruction is a Category 2 instruction. This means
* that it operates on long or double arguments.
*/
public boolean isCategory2()
{
return IS_CATEGORY2[opcode & 0xff];
}
/**
* Returns the number of entries popped from the stack during the execution
* of the instruction.
*/
public int stackPopCount(Clazz clazz)
{
return STACK_POP_COUNTS[opcode & 0xff];
}
/**
* Returns the number of entries pushed onto the stack during the execution
* of the instruction.
*/
public int stackPushCount(Clazz clazz)
{
return STACK_PUSH_COUNTS[opcode & 0xff];
}
// Small utility methods.
protected static int readByte(byte[] code, int offset)
{
return code[offset] & 0xff;
}
protected static int readShort(byte[] code, int offset)
{
return ((code[offset++] & 0xff) << 8) |
( code[offset ] & 0xff );
}
protected static int readInt(byte[] code, int offset)
{
return ( code[offset++] << 24) |
((code[offset++] & 0xff) << 16) |
((code[offset++] & 0xff) << 8) |
( code[offset ] & 0xff );
}
protected static int readValue(byte[] code, int offset, int valueSize)
{
switch (valueSize)
{
case 0: return 0;
case 1: return readByte( code, offset);
case 2: return readShort(code, offset);
case 4: return readInt( code, offset);
default: throw new IllegalArgumentException("Unsupported value size ["+valueSize+"]");
}
}
protected static int readSignedByte(byte[] code, int offset)
{
return code[offset];
}
protected static int readSignedShort(byte[] code, int offset)
{
return (code[offset++] << 8) |
(code[offset ] & 0xff);
}
protected static int readSignedValue(byte[] code, int offset, int valueSize)
{
switch (valueSize)
{
case 0: return 0;
case 1: return readSignedByte( code, offset);
case 2: return readSignedShort(code, offset);
case 4: return readInt( code, offset);
default: throw new IllegalArgumentException("Unsupported value size ["+valueSize+"]");
}
}
protected static void writeByte(byte[] code, int offset, int value)
{
if (value > 0xff)
{
throw new IllegalArgumentException("Unsigned byte value larger than 0xff ["+value+"]");
}
code[offset] = (byte)value;
}
protected static void writeShort(byte[] code, int offset, int value)
{
if (value > 0xffff)
{
throw new IllegalArgumentException("Unsigned short value larger than 0xffff ["+value+"]");
}
code[offset++] = (byte)(value >> 8);
code[offset ] = (byte)(value );
}
protected static void writeInt(byte[] code, int offset, int value)
{
code[offset++] = (byte)(value >> 24);
code[offset++] = (byte)(value >> 16);
code[offset++] = (byte)(value >> 8);
code[offset ] = (byte)(value );
}
protected static void writeValue(byte[] code, int offset, int value, int valueSize)
{
switch (valueSize)
{
case 0: break;
case 1: writeByte( code, offset, value); break;
case 2: writeShort(code, offset, value); break;
case 4: writeInt( code, offset, value); break;
default: throw new IllegalArgumentException("Unsupported value size ["+valueSize+"]");
}
}
protected static void writeSignedByte(byte[] code, int offset, int value)
{
if (value << 24 >> 24 != value)
{
throw new IllegalArgumentException("Signed byte value out of range ["+value+"]");
}
code[offset] = (byte)value;
}
protected static void writeSignedShort(byte[] code, int offset, int value)
{
if (value << 16 >> 16 != value)
{
throw new IllegalArgumentException("Signed short value out of range ["+value+"]");
}
code[offset++] = (byte)(value >> 8);
code[offset ] = (byte)(value );
}
protected static void writeSignedValue(byte[] code, int offset, int value, int valueSize)
{
switch (valueSize)
{
case 0: break;
case 1: writeSignedByte( code, offset, value); break;
case 2: writeSignedShort(code, offset, value); break;
case 4: writeInt( code, offset, value); break;
default: throw new IllegalArgumentException("Unsupported value size ["+valueSize+"]");
}
}
}
| gpl-2.0 |
eethomas/eucalyptus | clc/modules/msgs/src/main/java/com/eucalyptus/util/concurrent/CheckedFuture.java | 6118 | /*************************************************************************
* Copyright 2009-2012 Eucalyptus Systems, Inc.
*
* 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; version 3 of the License.
*
* 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/.
*
* Please contact Eucalyptus Systems, Inc., 6755 Hollister Ave., Goleta
* CA 93117, USA or visit http://www.eucalyptus.com/licenses/ if you need
* additional information or have any questions.
*
* This file may incorporate work covered under the following copyright
* and permission notice:
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Regents of the University of California
* All rights reserved.
*
* Redistribution and use of this software 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.
*
* 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. USERS OF THIS SOFTWARE ACKNOWLEDGE
* THE POSSIBLE PRESENCE OF OTHER OPEN SOURCE LICENSED MATERIAL,
* COPYRIGHTED MATERIAL OR PATENTED MATERIAL IN THIS SOFTWARE,
* AND IF ANY SUCH MATERIAL IS DISCOVERED THE PARTY DISCOVERING
* IT MAY INFORM DR. RICH WOLSKI AT THE UNIVERSITY OF CALIFORNIA,
* SANTA BARBARA WHO WILL THEN ASCERTAIN THE MOST APPROPRIATE REMEDY,
* WHICH IN THE REGENTS' DISCRETION MAY INCLUDE, WITHOUT LIMITATION,
* REPLACEMENT OF THE CODE SO IDENTIFIED, LICENSING OF THE CODE SO
* IDENTIFIED, OR WITHDRAWAL OF THE CODE CAPABILITY TO THE EXTENT
* NEEDED TO COMPLY WITH ANY SUCH LICENSES OR RIGHTS.
*
* This file may incorporate work covered under the following copyright
* and permission notice:
*
* Copyright (C) 2009 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.eucalyptus.util.concurrent;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* A {@code CheckedFuture} is an extension of {@link Future} that includes
* versions of the {@code get} methods that can throw a checked exception and
* allows listeners to be attached to the future. This makes it easier to
* create a future that executes logic which can throw an exception.
*
* <p>Implementations of this interface must adapt the exceptions thrown by
* {@code Future#get()}: {@link CancellationException},
* {@link ExecutionException} and {@link InterruptedException} into the type
* specified by the {@code E} type parameter.
*
* <p>This interface also extends the ListenableFuture interface to allow
* listeners to be added. This allows the future to be used as a normal
* {@link Future} or as an asynchronous callback mechanism as needed. This
* allows multiple callbacks to be registered for a particular task, and the
* future will guarantee execution of all listeners when the task completes.
*
* @author Sven Mawson
* @since 1
*/
public interface CheckedFuture<V, E extends Exception>
extends ListenableFuture<V> {
/**
* Exception checking version of {@link Future#get()} that will translate
* {@link InterruptedException}, {@link CancellationException} and
* {@link ExecutionException} into application-specific exceptions.
*
* @return the result of executing the future.
* @throws E on interruption, cancellation or execution exceptions.
*/
V checkedGet() throws E;
/**
* Exception checking version of {@link Future#get(long, TimeUnit)} that will
* translate {@link InterruptedException}, {@link CancellationException} and
* {@link ExecutionException} into application-specific exceptions. On
* timeout this method throws a normal {@link TimeoutException}.
*
* @return the result of executing the future.
* @throws TimeoutException if retrieving the result timed out.
* @throws E on interruption, cancellation or execution exceptions.
*/
V checkedGet(long timeout, TimeUnit unit) throws TimeoutException, E;
}
| gpl-3.0 |
goodwinnk/intellij-community | platform/lang-impl/src/com/intellij/util/indexing/IndexAccessValidator.java | 2062 | /*
* 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.util.indexing;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.ThrowableComputable;
import org.jetbrains.annotations.NotNull;
import java.text.MessageFormat;
public class IndexAccessValidator {
private final ThreadLocal<ID<?, ?>> ourAlreadyProcessingIndices = new ThreadLocal<>();
private void checkAccessingIndexDuringOtherIndexProcessing(@NotNull ID<?, ?> indexKey) {
final ID<?, ?> alreadyProcessingIndex = ourAlreadyProcessingIndices.get();
if (alreadyProcessingIndex != null && alreadyProcessingIndex != indexKey) {
final String message = MessageFormat.format("Accessing ''{0}'' during processing ''{1}''. Nested different indices processing may cause deadlock",
indexKey.getName(),
alreadyProcessingIndex.getName());
if (ApplicationManager.getApplication().isUnitTestMode()) throw new RuntimeException(message);
Logger.getInstance(FileBasedIndexImpl.class).error(message); // RuntimeException to skip rebuild
}
}
public <T,E extends Throwable> T validate(@NotNull ID<?, ?> indexKey, @NotNull ThrowableComputable<T, E> runnable) throws E {
checkAccessingIndexDuringOtherIndexProcessing(indexKey);
ourAlreadyProcessingIndices.set(indexKey);
try {
return runnable.compute();
}
finally {
ourAlreadyProcessingIndices.set(null);
}
}
}
| apache-2.0 |
doom369/netty | codec-http/src/main/java/io/netty/handler/codec/http/HttpObjectAggregator.java | 20227 | /*
* 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:
*
* 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 io.netty.handler.codec.http;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.DecoderResult;
import io.netty.handler.codec.MessageAggregator;
import io.netty.handler.codec.TooLongFrameException;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION;
import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH;
import static io.netty.handler.codec.http.HttpHeaderNames.EXPECT;
import static io.netty.handler.codec.http.HttpUtil.getContentLength;
/**
* A {@link ChannelHandler} that aggregates an {@link HttpMessage}
* and its following {@link HttpContent}s into a single {@link FullHttpRequest}
* or {@link FullHttpResponse} (depending on if it used to handle requests or responses)
* with no following {@link HttpContent}s. It is useful when you don't want to take
* care of HTTP messages whose transfer encoding is 'chunked'. Insert this
* handler after {@link HttpResponseDecoder} in the {@link ChannelPipeline} if being used to handle
* responses, or after {@link HttpRequestDecoder} and {@link HttpResponseEncoder} in the
* {@link ChannelPipeline} if being used to handle requests.
* <blockquote>
* <pre>
* {@link ChannelPipeline} p = ...;
* ...
* p.addLast("decoder", <b>new {@link HttpRequestDecoder}()</b>);
* p.addLast("encoder", <b>new {@link HttpResponseEncoder}()</b>);
* p.addLast("aggregator", <b>new {@link HttpObjectAggregator}(1048576)</b>);
* ...
* p.addLast("handler", new HttpRequestHandler());
* </pre>
* </blockquote>
* <p>
* For convenience, consider putting a {@link HttpServerCodec} before the {@link HttpObjectAggregator}
* as it functions as both a {@link HttpRequestDecoder} and a {@link HttpResponseEncoder}.
* </p>
* Be aware that {@link HttpObjectAggregator} may end up sending a {@link HttpResponse}:
* <table border summary="Possible Responses">
* <tbody>
* <tr>
* <th>Response Status</th>
* <th>Condition When Sent</th>
* </tr>
* <tr>
* <td>100 Continue</td>
* <td>A '100-continue' expectation is received and the 'content-length' doesn't exceed maxContentLength</td>
* </tr>
* <tr>
* <td>417 Expectation Failed</td>
* <td>A '100-continue' expectation is received and the 'content-length' exceeds maxContentLength</td>
* </tr>
* <tr>
* <td>413 Request Entity Too Large</td>
* <td>Either the 'content-length' or the bytes received so far exceed maxContentLength</td>
* </tr>
* </tbody>
* </table>
*
* @see FullHttpRequest
* @see FullHttpResponse
* @see HttpResponseDecoder
* @see HttpServerCodec
*/
public class HttpObjectAggregator
extends MessageAggregator<HttpObject, HttpMessage, HttpContent, FullHttpMessage> {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(HttpObjectAggregator.class);
private static final FullHttpResponse CONTINUE =
new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE, Unpooled.EMPTY_BUFFER);
private static final FullHttpResponse EXPECTATION_FAILED = new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1, HttpResponseStatus.EXPECTATION_FAILED, Unpooled.EMPTY_BUFFER);
private static final FullHttpResponse TOO_LARGE_CLOSE = new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1, HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE, Unpooled.EMPTY_BUFFER);
private static final FullHttpResponse TOO_LARGE = new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1, HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE, Unpooled.EMPTY_BUFFER);
static {
EXPECTATION_FAILED.headers().set(CONTENT_LENGTH, 0);
TOO_LARGE.headers().set(CONTENT_LENGTH, 0);
TOO_LARGE_CLOSE.headers().set(CONTENT_LENGTH, 0);
TOO_LARGE_CLOSE.headers().set(CONNECTION, HttpHeaderValues.CLOSE);
}
private final boolean closeOnExpectationFailed;
/**
* Creates a new instance.
* @param maxContentLength the maximum length of the aggregated content in bytes.
* If the length of the aggregated content exceeds this value,
* {@link #handleOversizedMessage(ChannelHandlerContext, HttpMessage)} will be called.
*/
public HttpObjectAggregator(int maxContentLength) {
this(maxContentLength, false);
}
/**
* Creates a new instance.
* @param maxContentLength the maximum length of the aggregated content in bytes.
* If the length of the aggregated content exceeds this value,
* {@link #handleOversizedMessage(ChannelHandlerContext, HttpMessage)} will be called.
* @param closeOnExpectationFailed If a 100-continue response is detected but the content length is too large
* then {@code true} means close the connection. otherwise the connection will remain open and data will be
* consumed and discarded until the next request is received.
*/
public HttpObjectAggregator(int maxContentLength, boolean closeOnExpectationFailed) {
super(maxContentLength);
this.closeOnExpectationFailed = closeOnExpectationFailed;
}
@Override
protected boolean isStartMessage(HttpObject msg) throws Exception {
return msg instanceof HttpMessage;
}
@Override
protected boolean isContentMessage(HttpObject msg) throws Exception {
return msg instanceof HttpContent;
}
@Override
protected boolean isLastContentMessage(HttpContent msg) throws Exception {
return msg instanceof LastHttpContent;
}
@Override
protected boolean isAggregated(HttpObject msg) throws Exception {
return msg instanceof FullHttpMessage;
}
@Override
protected boolean isContentLengthInvalid(HttpMessage start, int maxContentLength) {
try {
return getContentLength(start, -1L) > maxContentLength;
} catch (final NumberFormatException e) {
return false;
}
}
private static Object continueResponse(HttpMessage start, int maxContentLength, ChannelPipeline pipeline) {
if (HttpUtil.isUnsupportedExpectation(start)) {
// if the request contains an unsupported expectation, we return 417
pipeline.fireUserEventTriggered(HttpExpectationFailedEvent.INSTANCE);
return EXPECTATION_FAILED.retainedDuplicate();
} else if (HttpUtil.is100ContinueExpected(start)) {
// if the request contains 100-continue but the content-length is too large, we return 413
if (getContentLength(start, -1L) <= maxContentLength) {
return CONTINUE.retainedDuplicate();
}
pipeline.fireUserEventTriggered(HttpExpectationFailedEvent.INSTANCE);
return TOO_LARGE.retainedDuplicate();
}
return null;
}
@Override
protected Object newContinueResponse(HttpMessage start, int maxContentLength, ChannelPipeline pipeline) {
Object response = continueResponse(start, maxContentLength, pipeline);
// we're going to respond based on the request expectation so there's no
// need to propagate the expectation further.
if (response != null) {
start.headers().remove(EXPECT);
}
return response;
}
@Override
protected boolean closeAfterContinueResponse(Object msg) {
return closeOnExpectationFailed && ignoreContentAfterContinueResponse(msg);
}
@Override
protected boolean ignoreContentAfterContinueResponse(Object msg) {
if (msg instanceof HttpResponse) {
final HttpResponse httpResponse = (HttpResponse) msg;
return httpResponse.status().codeClass().equals(HttpStatusClass.CLIENT_ERROR);
}
return false;
}
@Override
protected FullHttpMessage beginAggregation(HttpMessage start, ByteBuf content) throws Exception {
assert !(start instanceof FullHttpMessage);
HttpUtil.setTransferEncodingChunked(start, false);
AggregatedFullHttpMessage ret;
if (start instanceof HttpRequest) {
ret = new AggregatedFullHttpRequest((HttpRequest) start, content, null);
} else if (start instanceof HttpResponse) {
ret = new AggregatedFullHttpResponse((HttpResponse) start, content, null);
} else {
throw new Error();
}
return ret;
}
@Override
protected void aggregate(FullHttpMessage aggregated, HttpContent content) throws Exception {
if (content instanceof LastHttpContent) {
// Merge trailing headers into the message.
((AggregatedFullHttpMessage) aggregated).setTrailingHeaders(((LastHttpContent) content).trailingHeaders());
}
}
@Override
protected void finishAggregation(FullHttpMessage aggregated) throws Exception {
// Set the 'Content-Length' header. If one isn't already set.
// This is important as HEAD responses will use a 'Content-Length' header which
// does not match the actual body, but the number of bytes that would be
// transmitted if a GET would have been used.
//
// See rfc2616 14.13 Content-Length
if (!HttpUtil.isContentLengthSet(aggregated)) {
aggregated.headers().set(
CONTENT_LENGTH,
String.valueOf(aggregated.content().readableBytes()));
}
}
@Override
protected void handleOversizedMessage(final ChannelHandlerContext ctx, HttpMessage oversized) throws Exception {
if (oversized instanceof HttpRequest) {
// send back a 413 and close the connection
// If the client started to send data already, close because it's impossible to recover.
// If keep-alive is off and 'Expect: 100-continue' is missing, no need to leave the connection open.
if (oversized instanceof FullHttpMessage ||
!HttpUtil.is100ContinueExpected(oversized) && !HttpUtil.isKeepAlive(oversized)) {
ChannelFuture future = ctx.writeAndFlush(TOO_LARGE_CLOSE.retainedDuplicate());
future.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (!future.isSuccess()) {
logger.debug("Failed to send a 413 Request Entity Too Large.", future.cause());
}
ctx.close();
}
});
} else {
ctx.writeAndFlush(TOO_LARGE.retainedDuplicate()).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (!future.isSuccess()) {
logger.debug("Failed to send a 413 Request Entity Too Large.", future.cause());
ctx.close();
}
}
});
}
} else if (oversized instanceof HttpResponse) {
ctx.close();
throw new TooLongFrameException("Response entity too large: " + oversized);
} else {
throw new IllegalStateException();
}
}
private abstract static class AggregatedFullHttpMessage implements FullHttpMessage {
protected final HttpMessage message;
private final ByteBuf content;
private HttpHeaders trailingHeaders;
AggregatedFullHttpMessage(HttpMessage message, ByteBuf content, HttpHeaders trailingHeaders) {
this.message = message;
this.content = content;
this.trailingHeaders = trailingHeaders;
}
@Override
public HttpHeaders trailingHeaders() {
HttpHeaders trailingHeaders = this.trailingHeaders;
if (trailingHeaders == null) {
return EmptyHttpHeaders.INSTANCE;
} else {
return trailingHeaders;
}
}
void setTrailingHeaders(HttpHeaders trailingHeaders) {
this.trailingHeaders = trailingHeaders;
}
@Override
public HttpVersion getProtocolVersion() {
return message.protocolVersion();
}
@Override
public HttpVersion protocolVersion() {
return message.protocolVersion();
}
@Override
public FullHttpMessage setProtocolVersion(HttpVersion version) {
message.setProtocolVersion(version);
return this;
}
@Override
public HttpHeaders headers() {
return message.headers();
}
@Override
public DecoderResult decoderResult() {
return message.decoderResult();
}
@Override
public DecoderResult getDecoderResult() {
return message.decoderResult();
}
@Override
public void setDecoderResult(DecoderResult result) {
message.setDecoderResult(result);
}
@Override
public ByteBuf content() {
return content;
}
@Override
public int refCnt() {
return content.refCnt();
}
@Override
public FullHttpMessage retain() {
content.retain();
return this;
}
@Override
public FullHttpMessage retain(int increment) {
content.retain(increment);
return this;
}
@Override
public FullHttpMessage touch(Object hint) {
content.touch(hint);
return this;
}
@Override
public FullHttpMessage touch() {
content.touch();
return this;
}
@Override
public boolean release() {
return content.release();
}
@Override
public boolean release(int decrement) {
return content.release(decrement);
}
@Override
public abstract FullHttpMessage copy();
@Override
public abstract FullHttpMessage duplicate();
@Override
public abstract FullHttpMessage retainedDuplicate();
}
private static final class AggregatedFullHttpRequest extends AggregatedFullHttpMessage implements FullHttpRequest {
AggregatedFullHttpRequest(HttpRequest request, ByteBuf content, HttpHeaders trailingHeaders) {
super(request, content, trailingHeaders);
}
@Override
public FullHttpRequest copy() {
return replace(content().copy());
}
@Override
public FullHttpRequest duplicate() {
return replace(content().duplicate());
}
@Override
public FullHttpRequest retainedDuplicate() {
return replace(content().retainedDuplicate());
}
@Override
public FullHttpRequest replace(ByteBuf content) {
DefaultFullHttpRequest dup = new DefaultFullHttpRequest(protocolVersion(), method(), uri(), content,
headers().copy(), trailingHeaders().copy());
dup.setDecoderResult(decoderResult());
return dup;
}
@Override
public FullHttpRequest retain(int increment) {
super.retain(increment);
return this;
}
@Override
public FullHttpRequest retain() {
super.retain();
return this;
}
@Override
public FullHttpRequest touch() {
super.touch();
return this;
}
@Override
public FullHttpRequest touch(Object hint) {
super.touch(hint);
return this;
}
@Override
public FullHttpRequest setMethod(HttpMethod method) {
((HttpRequest) message).setMethod(method);
return this;
}
@Override
public FullHttpRequest setUri(String uri) {
((HttpRequest) message).setUri(uri);
return this;
}
@Override
public HttpMethod getMethod() {
return ((HttpRequest) message).method();
}
@Override
public String getUri() {
return ((HttpRequest) message).uri();
}
@Override
public HttpMethod method() {
return getMethod();
}
@Override
public String uri() {
return getUri();
}
@Override
public FullHttpRequest setProtocolVersion(HttpVersion version) {
super.setProtocolVersion(version);
return this;
}
@Override
public String toString() {
return HttpMessageUtil.appendFullRequest(new StringBuilder(256), this).toString();
}
}
private static final class AggregatedFullHttpResponse extends AggregatedFullHttpMessage
implements FullHttpResponse {
AggregatedFullHttpResponse(HttpResponse message, ByteBuf content, HttpHeaders trailingHeaders) {
super(message, content, trailingHeaders);
}
@Override
public FullHttpResponse copy() {
return replace(content().copy());
}
@Override
public FullHttpResponse duplicate() {
return replace(content().duplicate());
}
@Override
public FullHttpResponse retainedDuplicate() {
return replace(content().retainedDuplicate());
}
@Override
public FullHttpResponse replace(ByteBuf content) {
DefaultFullHttpResponse dup = new DefaultFullHttpResponse(getProtocolVersion(), getStatus(), content,
headers().copy(), trailingHeaders().copy());
dup.setDecoderResult(decoderResult());
return dup;
}
@Override
public FullHttpResponse setStatus(HttpResponseStatus status) {
((HttpResponse) message).setStatus(status);
return this;
}
@Override
public HttpResponseStatus getStatus() {
return ((HttpResponse) message).status();
}
@Override
public HttpResponseStatus status() {
return getStatus();
}
@Override
public FullHttpResponse setProtocolVersion(HttpVersion version) {
super.setProtocolVersion(version);
return this;
}
@Override
public FullHttpResponse retain(int increment) {
super.retain(increment);
return this;
}
@Override
public FullHttpResponse retain() {
super.retain();
return this;
}
@Override
public FullHttpResponse touch(Object hint) {
super.touch(hint);
return this;
}
@Override
public FullHttpResponse touch() {
super.touch();
return this;
}
@Override
public String toString() {
return HttpMessageUtil.appendFullResponse(new StringBuilder(256), this).toString();
}
}
}
| apache-2.0 |
eclipsky/HowTomcatWorks | src/org/apache/catalina/session/ManagerBase.java | 22695 | /*
* $Header: /home/cvs/jakarta-tomcat-4.0/catalina/src/share/org/apache/catalina/session/ManagerBase.java,v 1.12 2002/09/19 22:55:48 amyroh Exp $
* $Revision: 1.12 $
* $Date: 2002/09/19 22:55:48 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
package org.apache.catalina.session;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
import org.apache.catalina.Container;
import org.apache.catalina.DefaultContext;
import org.apache.catalina.Engine;
import org.apache.catalina.Logger;
import org.apache.catalina.Manager;
import org.apache.catalina.Session;
import org.apache.catalina.util.StringManager;
/**
* Minimal implementation of the <b>Manager</b> interface that supports
* no session persistence or distributable capabilities. This class may
* be subclassed to create more sophisticated Manager implementations.
*
* @author Craig R. McClanahan
* @version $Revision: 1.12 $ $Date: 2002/09/19 22:55:48 $
*/
public abstract class ManagerBase implements Manager {
// ----------------------------------------------------- Instance Variables
/**
* The default message digest algorithm to use if we cannot use
* the requested one.
*/
protected static final String DEFAULT_ALGORITHM = "MD5";
/**
* The number of random bytes to include when generating a
* session identifier.
*/
protected static final int SESSION_ID_BYTES = 16;
/**
* The message digest algorithm to be used when generating session
* identifiers. This must be an algorithm supported by the
* <code>java.security.MessageDigest</code> class on your platform.
*/
protected String algorithm = DEFAULT_ALGORITHM;
/**
* The Container with which this Manager is associated.
*/
protected Container container;
/**
* The debugging detail level for this component.
*/
protected int debug = 0;
/**
* The DefaultContext with which this Manager is associated.
*/
protected DefaultContext defaultContext = null;
/**
* Return the MessageDigest implementation to be used when
* creating session identifiers.
*/
protected MessageDigest digest = null;
/**
* The distributable flag for Sessions created by this Manager. If this
* flag is set to <code>true</code>, any user attributes added to a
* session controlled by this Manager must be Serializable.
*/
protected boolean distributable;
/**
* A String initialization parameter used to increase the entropy of
* the initialization of our random number generator.
*/
protected String entropy = null;
/**
* The descriptive information string for this implementation.
*/
private static final String info = "ManagerBase/1.0";
/**
* The default maximum inactive interval for Sessions created by
* this Manager.
*/
protected int maxInactiveInterval = 60;
/**
* The descriptive name of this Manager implementation (for logging).
*/
protected static String name = "ManagerBase";
/**
* A random number generator to use when generating session identifiers.
*/
protected Random random = null;
/**
* The Java class name of the random number generator class to be used
* when generating session identifiers.
*/
protected String randomClass = "java.security.SecureRandom";
/**
* The set of previously recycled Sessions for this Manager.
*/
protected ArrayList recycled = new ArrayList();
/**
* The set of currently active Sessions for this Manager, keyed by
* session identifier.
*/
protected HashMap sessions = new HashMap();
/**
* The string manager for this package.
*/
protected static StringManager sm =
StringManager.getManager(Constants.Package);
/**
* The property change support for this component.
*/
protected PropertyChangeSupport support = new PropertyChangeSupport(this);
// ------------------------------------------------------------- Properties
/**
* Return the message digest algorithm for this Manager.
*/
public String getAlgorithm() {
return (this.algorithm);
}
/**
* Set the message digest algorithm for this Manager.
*
* @param algorithm The new message digest algorithm
*/
public void setAlgorithm(String algorithm) {
String oldAlgorithm = this.algorithm;
this.algorithm = algorithm;
support.firePropertyChange("algorithm", oldAlgorithm, this.algorithm);
}
/**
* Return the Container with which this Manager is associated.
*/
public Container getContainer() {
return (this.container);
}
/**
* Set the Container with which this Manager is associated.
*
* @param container The newly associated Container
*/
public void setContainer(Container container) {
Container oldContainer = this.container;
this.container = container;
support.firePropertyChange("container", oldContainer, this.container);
}
/**
* Return the DefaultContext with which this Manager is associated.
*/
public DefaultContext getDefaultContext() {
return (this.defaultContext);
}
/**
* Set the DefaultContext with which this Manager is associated.
*
* @param defaultContext The newly associated DefaultContext
*/
public void setDefaultContext(DefaultContext defaultContext) {
DefaultContext oldDefaultContext = this.defaultContext;
this.defaultContext = defaultContext;
support.firePropertyChange("defaultContext", oldDefaultContext, this.defaultContext);
}
/**
* Return the debugging detail level for this component.
*/
public int getDebug() {
return (this.debug);
}
/**
* Set the debugging detail level for this component.
*
* @param debug The new debugging detail level
*/
public void setDebug(int debug) {
this.debug = debug;
}
/**
* Return the MessageDigest object to be used for calculating
* session identifiers. If none has been created yet, initialize
* one the first time this method is called.
*/
public synchronized MessageDigest getDigest() {
if (this.digest == null) {
if (debug >= 1)
log(sm.getString("managerBase.getting", algorithm));
try {
this.digest = MessageDigest.getInstance(algorithm);
} catch (NoSuchAlgorithmException e) {
log(sm.getString("managerBase.digest", algorithm), e);
try {
this.digest = MessageDigest.getInstance(DEFAULT_ALGORITHM);
} catch (NoSuchAlgorithmException f) {
log(sm.getString("managerBase.digest",
DEFAULT_ALGORITHM), e);
this.digest = null;
}
}
if (debug >= 1)
log(sm.getString("managerBase.gotten"));
}
return (this.digest);
}
/**
* Return the distributable flag for the sessions supported by
* this Manager.
*/
public boolean getDistributable() {
return (this.distributable);
}
/**
* Set the distributable flag for the sessions supported by this
* Manager. If this flag is set, all user data objects added to
* sessions associated with this manager must implement Serializable.
*
* @param distributable The new distributable flag
*/
public void setDistributable(boolean distributable) {
boolean oldDistributable = this.distributable;
this.distributable = distributable;
support.firePropertyChange("distributable",
new Boolean(oldDistributable),
new Boolean(this.distributable));
}
/**
* Return the entropy increaser value, or compute a semi-useful value
* if this String has not yet been set.
*/
public String getEntropy() {
// Calculate a semi-useful value if this has not been set
if (this.entropy == null)
setEntropy(this.toString());
return (this.entropy);
}
/**
* Set the entropy increaser value.
*
* @param entropy The new entropy increaser value
*/
public void setEntropy(String entropy) {
String oldEntropy = entropy;
this.entropy = entropy;
support.firePropertyChange("entropy", oldEntropy, this.entropy);
}
/**
* Return descriptive information about this Manager implementation and
* the corresponding version number, in the format
* <code><description>/<version></code>.
*/
public String getInfo() {
return (this.info);
}
/**
* Return the default maximum inactive interval (in seconds)
* for Sessions created by this Manager.
*/
public int getMaxInactiveInterval() {
return (this.maxInactiveInterval);
}
/**
* Set the default maximum inactive interval (in seconds)
* for Sessions created by this Manager.
*
* @param interval The new default value
*/
public void setMaxInactiveInterval(int interval) {
int oldMaxInactiveInterval = this.maxInactiveInterval;
this.maxInactiveInterval = interval;
support.firePropertyChange("maxInactiveInterval",
new Integer(oldMaxInactiveInterval),
new Integer(this.maxInactiveInterval));
}
/**
* Return the descriptive short name of this Manager implementation.
*/
public String getName() {
return (name);
}
/**
* Return the random number generator instance we should use for
* generating session identifiers. If there is no such generator
* currently defined, construct and seed a new one.
*/
public synchronized Random getRandom() {
if (this.random == null) {
synchronized (this) {
if (this.random == null) {
// Calculate the new random number generator seed
log(sm.getString("managerBase.seeding", randomClass));
long seed = System.currentTimeMillis();
char entropy[] = getEntropy().toCharArray();
for (int i = 0; i < entropy.length; i++) {
long update = ((byte) entropy[i]) << ((i % 8) * 8);
seed ^= update;
}
try {
// Construct and seed a new random number generator
Class clazz = Class.forName(randomClass);
this.random = (Random) clazz.newInstance();
this.random.setSeed(seed);
} catch (Exception e) {
// Fall back to the simple case
log(sm.getString("managerBase.random", randomClass),
e);
this.random = new java.util.Random();
this.random.setSeed(seed);
}
log(sm.getString("managerBase.complete", randomClass));
}
}
}
return (this.random);
}
/**
* Return the random number generator class name.
*/
public String getRandomClass() {
return (this.randomClass);
}
/**
* Set the random number generator class name.
*
* @param randomClass The new random number generator class name
*/
public void setRandomClass(String randomClass) {
String oldRandomClass = this.randomClass;
this.randomClass = randomClass;
support.firePropertyChange("randomClass", oldRandomClass,
this.randomClass);
}
// --------------------------------------------------------- Public Methods
/**
* Add this Session to the set of active Sessions for this Manager.
*
* @param session Session to be added
*/
public void add(Session session) {
synchronized (sessions) {
sessions.put(session.getId(), session);
}
}
/**
* Add a property change listener to this component.
*
* @param listener The listener to add
*/
public void addPropertyChangeListener(PropertyChangeListener listener) {
support.addPropertyChangeListener(listener);
}
/**
* Construct and return a new session object, based on the default
* settings specified by this Manager's properties. The session
* id will be assigned by this method, and available via the getId()
* method of the returned session. If a new session cannot be created
* for any reason, return <code>null</code>.
*
* @exception IllegalStateException if a new session cannot be
* instantiated for any reason
*/
public Session createSession() {
// Recycle or create a Session instance
Session session = null;
synchronized (recycled) {
int size = recycled.size();
if (size > 0) {
session = (Session) recycled.get(size - 1);
recycled.remove(size - 1);
}
}
if (session != null)
session.setManager(this);
else
session = new StandardSession(this);
// Initialize the properties of the new session and return it
session.setNew(true);
session.setValid(true);
session.setCreationTime(System.currentTimeMillis());
session.setMaxInactiveInterval(this.maxInactiveInterval);
String sessionId = generateSessionId();
String jvmRoute = getJvmRoute();
// @todo Move appending of jvmRoute generateSessionId()???
if (jvmRoute != null) {
sessionId += '.' + jvmRoute;
session.setId(sessionId);
}
/*
synchronized (sessions) {
while (sessions.get(sessionId) != null) // Guarantee uniqueness
sessionId = generateSessionId();
}
*/
session.setId(sessionId);
return (session);
}
/**
* Return the active Session, associated with this Manager, with the
* specified session id (if any); otherwise return <code>null</code>.
*
* @param id The session id for the session to be returned
*
* @exception IllegalStateException if a new session cannot be
* instantiated for any reason
* @exception IOException if an input/output error occurs while
* processing this request
*/
public Session findSession(String id) throws IOException {
if (id == null)
return (null);
synchronized (sessions) {
Session session = (Session) sessions.get(id);
return (session);
}
}
/**
* Return the set of active Sessions associated with this Manager.
* If this Manager has no active Sessions, a zero-length array is returned.
*/
public Session[] findSessions() {
Session results[] = null;
synchronized (sessions) {
results = new Session[sessions.size()];
results = (Session[]) sessions.values().toArray(results);
}
return (results);
}
/**
* Remove this Session from the active Sessions for this Manager.
*
* @param session Session to be removed
*/
public void remove(Session session) {
synchronized (sessions) {
sessions.remove(session.getId());
}
}
/**
* Remove a property change listener from this component.
*
* @param listener The listener to remove
*/
public void removePropertyChangeListener(PropertyChangeListener listener) {
support.removePropertyChangeListener(listener);
}
// ------------------------------------------------------ Protected Methods
/**
* Generate and return a new session identifier.
*/
protected synchronized String generateSessionId() {
// Generate a byte array containing a session identifier
Random random = getRandom();
byte bytes[] = new byte[SESSION_ID_BYTES];
getRandom().nextBytes(bytes);
bytes = getDigest().digest(bytes);
// Render the result as a String of hexadecimal digits
StringBuffer result = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
byte b1 = (byte) ((bytes[i] & 0xf0) >> 4);
byte b2 = (byte) (bytes[i] & 0x0f);
if (b1 < 10)
result.append((char) ('0' + b1));
else
result.append((char) ('A' + (b1 - 10)));
if (b2 < 10)
result.append((char) ('0' + b2));
else
result.append((char) ('A' + (b2 - 10)));
}
return (result.toString());
}
// ------------------------------------------------------ Protected Methods
/**
* Retrieve the enclosing Engine for this Manager.
*
* @return an Engine object (or null).
*/
public Engine getEngine() {
Engine e = null;
for (Container c = getContainer(); e == null && c != null ; c = c.getParent()) {
if (c != null && c instanceof Engine) {
e = (Engine)c;
}
}
return e;
}
/**
* Retrieve the JvmRoute for the enclosing Engine.
* @return the JvmRoute or null.
*/
public String getJvmRoute() {
Engine e = getEngine();
return e == null ? null : e.getJvmRoute();
}
// -------------------------------------------------------- Package Methods
/**
* Log a message on the Logger associated with our Container (if any).
*
* @param message Message to be logged
*/
void log(String message) {
Logger logger = null;
if (container != null)
logger = container.getLogger();
if (logger != null)
logger.log(getName() + "[" + container.getName() + "]: "
+ message);
else {
String containerName = null;
if (container != null)
containerName = container.getName();
System.out.println(getName() + "[" + containerName
+ "]: " + message);
}
}
/**
* Log a message on the Logger associated with our Container (if any).
*
* @param message Message to be logged
* @param throwable Associated exception
*/
void log(String message, Throwable throwable) {
Logger logger = null;
if (container != null)
logger = container.getLogger();
if (logger != null)
logger.log(getName() + "[" + container.getName() + "] "
+ message, throwable);
else {
String containerName = null;
if (container != null)
containerName = container.getName();
System.out.println(getName() + "[" + containerName
+ "]: " + message);
throwable.printStackTrace(System.out);
}
}
/**
* Add this Session to the recycle collection for this Manager.
*
* @param session Session to be recycled
*/
void recycle(Session session) {
synchronized (recycled) {
recycled.add(session);
}
}
}
| apache-2.0 |
aeq/killbill | util/src/main/java/org/killbill/billing/util/cache/EhCacheCacheManagerProvider.java | 4903 | /*
* Copyright 2010-2012 Ning, Inc.
* Copyright 2014-2015 Groupon, Inc
* Copyright 2014-2015 The Billing Project, LLC
*
* The Billing 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.killbill.billing.util.cache;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.Collection;
import java.util.LinkedList;
import javax.inject.Inject;
import javax.inject.Provider;
import org.killbill.billing.util.config.CacheConfig;
import org.killbill.xmlloader.UriAccessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.ehcache.InstrumentedEhcache;
import net.sf.ehcache.CacheException;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.loader.CacheLoader;
// EhCache specific provider
public class EhCacheCacheManagerProvider implements Provider<CacheManager> {
private static final Logger logger = LoggerFactory.getLogger(EhCacheCacheManagerProvider.class);
private final MetricRegistry metricRegistry;
private final CacheConfig cacheConfig;
private final Collection<BaseCacheLoader> cacheLoaders = new LinkedList<BaseCacheLoader>();
@Inject
public EhCacheCacheManagerProvider(final MetricRegistry metricRegistry,
final CacheConfig cacheConfig,
final RecordIdCacheLoader recordIdCacheLoader,
final AccountRecordIdCacheLoader accountRecordIdCacheLoader,
final TenantRecordIdCacheLoader tenantRecordIdCacheLoader,
final ObjectIdCacheLoader objectIdCacheLoader,
final AuditLogCacheLoader auditLogCacheLoader,
final AuditLogViaHistoryCacheLoader auditLogViaHistoryCacheLoader,
final TenantCatalogCacheLoader tenantCatalogCacheLoader,
final TenantOverdueConfigCacheLoader tenantOverdueConfigCacheLoader,
final TenantKVCacheLoader tenantKVCacheLoader,
final OverriddenPlanCacheLoader overriddenPlanCacheLoader) {
this.metricRegistry = metricRegistry;
this.cacheConfig = cacheConfig;
cacheLoaders.add(recordIdCacheLoader);
cacheLoaders.add(accountRecordIdCacheLoader);
cacheLoaders.add(tenantRecordIdCacheLoader);
cacheLoaders.add(objectIdCacheLoader);
cacheLoaders.add(auditLogCacheLoader);
cacheLoaders.add(auditLogViaHistoryCacheLoader);
cacheLoaders.add(tenantCatalogCacheLoader);
cacheLoaders.add(tenantOverdueConfigCacheLoader);
cacheLoaders.add(tenantKVCacheLoader);
cacheLoaders.add(overriddenPlanCacheLoader);
}
@Override
public CacheManager get() {
final CacheManager cacheManager;
try {
final InputStream inputStream = UriAccessor.accessUri(cacheConfig.getCacheConfigLocation());
cacheManager = CacheManager.create(inputStream);
} catch (final IOException e) {
throw new RuntimeException(e);
} catch (final URISyntaxException e) {
throw new RuntimeException(e);
}
for (final BaseCacheLoader cacheLoader : cacheLoaders) {
cacheLoader.init();
final Ehcache cache = cacheManager.getEhcache(cacheLoader.getCacheType().getCacheName());
// Make sure we start from a clean state - this is mainly useful for tests
for (final CacheLoader existingCacheLoader : cache.getRegisteredCacheLoaders()) {
cache.unregisterCacheLoader(existingCacheLoader);
}
cache.registerCacheLoader(cacheLoader);
// Instrument the cache
final Ehcache decoratedCache = InstrumentedEhcache.instrument(metricRegistry, cache);
try {
cacheManager.replaceCacheWithDecoratedCache(cache, decoratedCache);
} catch (final CacheException e) {
logger.warn("Unable to instrument cache {}: {}", cache.getName(), e.getMessage());
}
}
return cacheManager;
}
}
| apache-2.0 |
rophy/rundeck | core/src/main/java/com/dtolabs/rundeck/core/logging/ExecutionMultiFileStorage.java | 1236 | /*
* Copyright 2016 SimplifyOps, Inc. (http://simplifyops.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 com.dtolabs.rundeck.core.logging;
import java.io.IOException;
/**
* Allows storing multiple files with a single method call
*/
public interface ExecutionMultiFileStorage {
/**
* Store some or all of the available files
*
* @param files available file set
*
* @throws java.io.IOException if an IO error occurs
* @throws com.dtolabs.rundeck.core.logging.ExecutionFileStorageException if other errors occur
*/
void storeMultiple(MultiFileStorageRequest files) throws IOException, ExecutionFileStorageException;
}
| apache-2.0 |
liveqmock/platform-tools-idea | plugins/git4idea/src/git4idea/settings/GitPushSettings.java | 1886 | /*
* Copyright 2000-2012 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 git4idea.settings;
import com.intellij.openapi.components.*;
import com.intellij.openapi.components.StoragePathMacros;
import com.intellij.openapi.project.Project;
import git4idea.config.UpdateMethod;
/**
* @author Kirill Likhodedov
*/
@State(name = "Git.Push.Settings", storages = {@Storage(file = StoragePathMacros.WORKSPACE_FILE)})
public class GitPushSettings implements PersistentStateComponent<GitPushSettings.State> {
private State myState = new State();
public static class State {
public boolean myUpdateAllRoots = true;
public UpdateMethod myUpdateMethod = UpdateMethod.MERGE;
}
public static GitPushSettings getInstance(Project project) {
return ServiceManager.getService(project, GitPushSettings.class);
}
@Override
public State getState() {
return myState;
}
@Override
public void loadState(State state) {
myState = state;
}
public boolean shouldUpdateAllRoots() {
return myState.myUpdateAllRoots;
}
public void setUpdateAllRoots(boolean updateAllRoots) {
myState.myUpdateAllRoots = updateAllRoots;
}
public UpdateMethod getUpdateMethod() {
return myState.myUpdateMethod;
}
public void setUpdateMethod(UpdateMethod updateMethod) {
myState.myUpdateMethod = updateMethod;
}
}
| apache-2.0 |
Fabryprog/camel | components/camel-spring/src/test/java/org/apache/camel/spring/produce/FluentProduceTemplateTest.java | 1679 | /*
* 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.produce;
import org.apache.camel.EndpointInject;
import org.apache.camel.FluentProducerTemplate;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.spring.SpringRunWithTestSupport;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
@ContextConfiguration
public class FluentProduceTemplateTest extends SpringRunWithTestSupport {
@Autowired
protected FluentProducerTemplate producer;
@EndpointInject("mock:result")
protected MockEndpoint result;
@Test
public void testProducerTemplate() throws Exception {
result.expectedBodiesReceived("hello");
// lets send a message
producer.withBody("hello").to("direct:start").send();
result.assertIsSatisfied();
}
}
| apache-2.0 |