repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
google/error-prone-javac | test/tools/javac/generics/inference/CaptureLowerBound.java | 463 | /*
* @test /nodynamiccopyright/
* @bug 8039214
* @summary Capture variable as an inference variable's lower bound
* @compile CaptureLowerBound.java
* @compile/fail/ref=CaptureLowerBound7.out -Xlint:-options -source 7 -XDrawDiagnostics CaptureLowerBound.java
*/
public class CaptureLowerBound {
interface I<X1,X2> {}
static class C<T> implements I<T,T> {}
<X> void m(I<? extends X, X> arg) {}
void test(C<?> arg) {
m(arg);
}
}
| gpl-2.0 |
prazanna/kite | kite-morphlines/kite-morphlines-solr-cell/src/test/java/org/kitesdk/morphline/solrcell/EnvironmentTest.java | 1189 | /*
* 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.kitesdk.morphline.solrcell;
import java.net.UnknownHostException;
import org.junit.Test;
/** Print and verify some info about the environment in which the unit tests are running */
public class EnvironmentTest extends org.kitesdk.morphline.solr.EnvironmentTest {
@Test
public void testEnvironment() throws UnknownHostException {
super.testEnvironment();
}
}
| apache-2.0 |
benralexander/efficient-java-matrix-library | test/org/ejml/alg/dense/misc/TestPermuteArray.java | 2515 | /*
* Copyright (c) 2009-2013, Peter Abeles. All Rights Reserved.
*
* This file is part of Efficient Java Matrix Library (EJML).
*
* 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.ejml.alg.dense.misc;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
/**
* @author Peter Abeles
*/
public class TestPermuteArray {
int fact( int N ) {
int ret = 1;
while( N > 0 ) {
ret *= N--;
}
return ret;
}
/**
* Sees if the expected number of permutations are created and that they are all
* unique
*/
@Test
public void permuteList() {
int N = 4;
List<int[]> perms = PermuteArray.createList(N);
checkPermutationList(N, perms);
}
private void checkPermutationList(int n, List<int[]> perms) {
assertEquals(PermuteArray.fact(n),perms.size());
// make sure each permutation in the list is unique
for( int i = 0; i < perms.size(); i++ ) {
int a[] = perms.get(i);
assertEquals(4,a.length);
for( int j = i+1; j < perms.size(); j++ ) {
int b[] = perms.get(j);
boolean identical = true;
for( int k = 0; k < n; k++ ) {
if( a[k] != b[k] ) {
identical = false;
break;
}
}
assertFalse(identical);
}
}
}
@Test
public void next() {
// create a list of all the permutations
PermuteArray alg = new PermuteArray(4);
List<int[]> perms = new ArrayList<int[]>();
for(;;) {
int d[] = alg.next();
if( d == null )
break;
perms.add(d.clone());
}
// see if the list is correct
checkPermutationList(4, perms);
}
}
| apache-2.0 |
opentelecoms-org/jsmpp-svn-mirror | src/java/main/org/jsmpp/extra/NegativeResponseException.java | 849 | package org.jsmpp.extra;
import org.jsmpp.util.IntUtil;
/**
* This exception is thrown if we receive an negative response.
*
* @author uudashr
* @version 1.0
* @since 1.0
*
*/
public class NegativeResponseException extends Exception {
private static final long serialVersionUID = 7198456791204091251L;
private int commandStatus;
/**
* Construct with specified command_status.
*
* @param commandStatus is the command_status.
*/
public NegativeResponseException(int commandStatus) {
super("Negative response " + IntUtil.toHexString(commandStatus)
+ " found");
this.commandStatus = commandStatus;
}
/**
* Get the command_status.
*
* @return is the command_status.
*/
public int getCommandStatus() {
return commandStatus;
}
}
| apache-2.0 |
sonamuthu/rice-1 | rice-middleware/it/core/src/test/java/org/kuali/rice/core/impl/component/DerivedComponentTest.java | 6052 | /*
* Copyright 2006-2014 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.rice.core.impl.component;
import org.junit.Before;
import org.junit.Test;
import org.kuali.rice.core.test.CORETestCase;
import org.kuali.rice.coreservice.api.CoreServiceApiServiceLocator;
import org.kuali.rice.coreservice.api.component.Component;
import org.kuali.rice.coreservice.api.component.ComponentService;
import org.kuali.rice.test.BaselineTestCase;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static org.junit.Assert.*;
/**
* An integration test which tests the reference implementation of the ComponentService
*
* TODO - For now this test is part of KRAD even though it should be part of the core (pending
* further modularity work)
*
* @author Kuali Rice Team (rice.collab@kuali.org)
*/
@BaselineTestCase.BaselineMode(BaselineTestCase.Mode.CLEAR_DB)
public class DerivedComponentTest extends CORETestCase {
private ComponentService componentService;
@Before
public void establishComponentService() {
componentService = CoreServiceApiServiceLocator.getComponentService();
assertNotNull("Failed to locate ComponentService", componentService);
}
@Test
/**
* tests {@link org.kuali.rice.coreservice.api.component.ComponentService#getDerivedComponentSet(String)} and {@link org.kuali.rice.coreservice.api.component.ComponentService#publishDerivedComponents(String, java.util.List)}
*/
public void testPublishComponents_and_getPublishedComponentSet() {
String testComponentSetId = "testComponentSet";
String workflowNamespace = "KR-WKFLW";
String testNamespace1 = "TestNamespace1";
String testNamespace2 = "TestNamespace2";
List<Component> testComponentSet = componentService.getDerivedComponentSet(testComponentSetId);
assertTrue("Initial testComponentSet should be empty", testComponentSet.isEmpty());
List<Component> workflowComponents = componentService.getAllComponentsByNamespaceCode(workflowNamespace);
assertTrue(componentService.getAllComponentsByNamespaceCode(testNamespace1).isEmpty());
assertTrue(componentService.getAllComponentsByNamespaceCode(testNamespace2).isEmpty());
String customTestWorkflowComponent = "CustomTestWorkflowComponent";
Component component1 = Component.Builder.create(workflowNamespace, customTestWorkflowComponent, customTestWorkflowComponent).build();
String testNamespace1Component = "TestNamespace1Component";
Component component2 = Component.Builder.create(testNamespace1, testNamespace1Component, testNamespace1Component).build();
String testNamespace2Component1 = "TestNamespace2Component1";
Component component3 = Component.Builder.create(testNamespace2, testNamespace2Component1, testNamespace2Component1).build();
String testNamespace2Component2 = "TestNamespace2Component2";
Component component4 = Component.Builder.create(testNamespace2, testNamespace2Component2, testNamespace2Component2).build();
List<Component> setToPublish = new ArrayList<Component>();
setToPublish.add(component1);
setToPublish.add(component2);
setToPublish.add(component3);
setToPublish.add(component4);
componentService.publishDerivedComponents(testComponentSetId, setToPublish);
// now if we fetch the component set it should be non-empty and should contain our 4 items
testComponentSet = componentService.getDerivedComponentSet(testComponentSetId);
assertEquals(4, testComponentSet.size());
for (Component component : testComponentSet) {
// ensure they all have the appropriate component set id
assertEquals(testComponentSetId, component.getComponentSetId());
}
List<Component> shuffledComponentSet = new ArrayList<Component>(testComponentSet);
// now, do a slight shuffle of the list and republish...
Collections.shuffle(shuffledComponentSet);
componentService.publishDerivedComponents(testComponentSetId, shuffledComponentSet);
// we should still have the same set
testComponentSet = componentService.getDerivedComponentSet(testComponentSetId);
assertEquals(4, testComponentSet.size());
// refetch by workflow namespace, we should have an additional component now
List<Component> workflowComponentsNew = componentService.getAllComponentsByNamespaceCode(workflowNamespace);
assertEquals(workflowComponents.size() + 1, workflowComponentsNew.size());
// now republish our component set without the workflow namespace component
setToPublish = new ArrayList<Component>();
setToPublish.add(component2);
setToPublish.add(component3);
setToPublish.add(component4);
componentService.publishDerivedComponents(testComponentSetId, setToPublish);
// we should have 3 components now
testComponentSet = componentService.getDerivedComponentSet(testComponentSetId);
assertEquals(3, testComponentSet.size());
// and the workflow component should be gone
workflowComponentsNew = componentService.getAllComponentsByNamespaceCode(workflowNamespace);
assertEquals(workflowComponents.size(), workflowComponentsNew.size());
}
}
| apache-2.0 |
arunasujith/wso2-axis2 | modules/jaxws/test/org/apache/axis2/jaxws/client/dispatch/DispatchOperationResolutionJAXBTest.java | 4385 | /*
* 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.axis2.jaxws.client.dispatch;
import org.apache.axis2.jaxws.client.InterceptableClientTestCase;
import org.apache.axis2.jaxws.client.TestClientInvocationController;
import org.apache.axis2.jaxws.core.InvocationContext;
import org.apache.axis2.jaxws.core.MessageContext;
import org.apache.axis2.jaxws.description.EndpointDescription;
import org.apache.axis2.jaxws.description.EndpointInterfaceDescription;
import org.apache.axis2.jaxws.description.OperationDescription;
import javax.xml.bind.JAXBContext;
import javax.xml.namespace.QName;
import javax.xml.ws.Dispatch;
import javax.xml.ws.Service;
import java.net.URL;
import test.EchoString;
import test.ObjectFactory;
/**
* Validate that Dispatch operation resolution occurs correctly for JAXB elements.
*
* Note that this test uses the JAXB-generated artifacts from test-resources/xsd/echo.xsd and that the WSDL
* used in this test, test-resources/wsdl/DispatchOperationResolutionJAXB.wsdl, was crafted to match the
* generated JAXB artifacts. That is why the WSDL and operations are different between this test and the other
* DispatchOperationResolution*.java tests
*/
public class DispatchOperationResolutionJAXBTest extends InterceptableClientTestCase {
URL wsdlDocumentLocation = getClass().getResource("/wsdl/DispatchOperationResolutionJAXB.wsdl");
QName serviceQName = new QName("http://test/", "EchoService");
QName portQName = new QName("http://test/", "EchoServicePort");
public void testJAXBResolution() {
try {
ObjectFactory factory = new ObjectFactory();
EchoString request = factory.createEchoString();
request.setInput("Operation resolution JAXB test");
JAXBContext jbc = JAXBContext.newInstance(EchoString.class);
Service service = Service.create(wsdlDocumentLocation, serviceQName);
Dispatch<Object> dispatch = service.createDispatch(portQName, jbc, Service.Mode.PAYLOAD);
// The InterceptableClientTestCase invoke will return the "request" as the response.
EchoString response = (EchoString) dispatch.invoke(request);
} catch (Exception e) {
fail("Caught exception: " + e);
}
TestClientInvocationController testController = getInvocationController();
InvocationContext ic = testController.getInvocationContext();
MessageContext requestMC = ic.getRequestMessageContext();
OperationDescription opDesc = requestMC.getOperationDescription();
assertNotNull("OpDesc from request MC should not be null", opDesc);
// Make sure we get the correct Operation Description
OperationDescription expectedOperationDescription = expectedOperationDescription(requestMC, "echoString");
assertSame("Wrong operation description returned", expectedOperationDescription, opDesc);
}
private OperationDescription expectedOperationDescription(MessageContext requestMC, String operationName) {
EndpointDescription endpointDescription = requestMC.getEndpointDescription();
EndpointInterfaceDescription endpointInterfaceDescription = endpointDescription.getEndpointInterfaceDescription();
QName operationQName = new QName("http://test/", operationName);
OperationDescription expectedOperationDescription = endpointInterfaceDescription.getOperation(operationQName)[0];
return expectedOperationDescription;
}
}
| apache-2.0 |
wskplho/jadx | jadx-core/src/test/java/jadx/tests/integration/trycatch/TestTryCatch2.java | 1018 | package jadx.tests.integration.trycatch;
import jadx.core.dex.nodes.ClassNode;
import jadx.tests.api.IntegrationTest;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertThat;
public class TestTryCatch2 extends IntegrationTest {
public static class TestCls {
private final static Object obj = new Object();
private static boolean test() {
try {
synchronized (obj) {
obj.wait(5);
}
return true;
} catch (InterruptedException e) {
return false;
}
}
}
@Test
public void test() {
ClassNode cls = getClassNode(TestCls.class);
String code = cls.getCode().toString();
assertThat(code, containsString("try {"));
assertThat(code, containsString("synchronized (obj) {"));
assertThat(code, containsString("obj.wait(5);"));
assertThat(code, containsString("return true;"));
assertThat(code, containsString("} catch (InterruptedException e) {"));
assertThat(code, containsString("return false;"));
}
}
| apache-2.0 |
xxjishi/stetho | stetho-urlconnection/src/main/java/com/facebook/stetho/urlconnection/URLConnectionInspectorRequest.java | 2274 | /*
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.stetho.urlconnection;
import com.facebook.stetho.inspector.network.NetworkEventReporter;
import com.facebook.stetho.inspector.network.RequestBodyHelper;
import javax.annotation.Nullable;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
class URLConnectionInspectorRequest
extends URLConnectionInspectorHeaders
implements NetworkEventReporter.InspectorRequest {
private final String mRequestId;
private final String mFriendlyName;
@Nullable private final SimpleRequestEntity mRequestEntity;
private final RequestBodyHelper mRequestBodyHelper;
private final String mUrl;
private final String mMethod;
public URLConnectionInspectorRequest(
String requestId,
String friendlyName,
HttpURLConnection configuredRequest,
@Nullable SimpleRequestEntity requestEntity,
RequestBodyHelper requestBodyHelper) {
super(Util.convertHeaders(configuredRequest.getRequestProperties()));
mRequestId = requestId;
mFriendlyName = friendlyName;
mRequestEntity = requestEntity;
mRequestBodyHelper = requestBodyHelper;
mUrl = configuredRequest.getURL().toString();
mMethod = configuredRequest.getRequestMethod();
}
@Override
public String id() {
return mRequestId;
}
@Override
public String friendlyName() {
return mFriendlyName;
}
@Override
public Integer friendlyNameExtra() {
return null;
}
@Override
public String url() {
return mUrl;
}
@Override
public String method() {
return mMethod;
}
@Nullable
@Override
public byte[] body() throws IOException {
if (mRequestEntity != null) {
OutputStream out = mRequestBodyHelper.createBodySink(firstHeaderValue("Content-Encoding"));
try {
mRequestEntity.writeTo(out);
} finally {
out.close();
}
return mRequestBodyHelper.getDisplayBody();
} else {
return null;
}
}
}
| bsd-3-clause |
Beabel2/lombok | test/transform/resource/before/GetterOnMethodErrors2.java | 551 | class GetterOnMethodErrors2 {
@lombok.Getter(onMethod=@_A_(@Deprecated)) private int bad1;
@lombok.Getter(onMethod=@__(5)) private int bad2;
@lombok.Getter(onMethod=@__({@Deprecated, 5})) private int bad3;
@lombok.Getter(onMethod=@$(bar=@Deprecated)) private int bad4;
@lombok.Getter(onMethod=@__) private int good1;
@lombok.Getter(onMethod=@X()) private int good2;
@lombok.Getter(onMethod=@__(value=@Deprecated)) private int good3;
@lombok.Getter(onMethod=@xXx$$(value={@Deprecated, @Test})) private int good4;
public @interface Test {
}
}
| mit |
shakuzen/spring-boot | spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-jpa/src/main/java/smoketest/jpa/SampleJpaApplication.java | 935 | /*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package smoketest.jpa;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SampleJpaApplication {
public static void main(String[] args) {
SpringApplication.run(SampleJpaApplication.class, args);
}
}
| apache-2.0 |
keshvari/cas | cas-server-core/src/main/java/org/jasig/cas/authentication/handler/BlockedCredentialsAuthenticationException.java | 2940 | /*
* Licensed to Apereo under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Apereo 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 the following location:
*
* 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.cas.authentication.handler;
/**
* Exception to represent credentials that have been blocked for a reason such
* as Locked account.
*
* @author Scott Battaglia
* @since 3.0.0
*/
public class BlockedCredentialsAuthenticationException extends
AuthenticationException {
/** Static instance of BlockedCredentialsAuthenticationException. */
public static final BlockedCredentialsAuthenticationException ERROR =
new BlockedCredentialsAuthenticationException();
/** Unique ID for serialization. */
private static final long serialVersionUID = 3544669598642420017L;
/** The default code for this exception used for message resolving. */
private static final String CODE = "error.authentication.credentials.blocked";
/**
* Default constructor that does not allow the chaining of exceptions and
* uses the default code as the error code for this exception.
*/
public BlockedCredentialsAuthenticationException() {
super(CODE);
}
/**
* Constructor that allows for the chaining of exceptions. Defaults to the
* default code provided for this exception.
*
* @param throwable the chained exception.
*/
public BlockedCredentialsAuthenticationException(final Throwable throwable) {
super(CODE, throwable);
}
/**
* Constructor that allows for providing a custom error code for this class.
* Error codes are often used to resolve exceptions into messages. Providing
* a custom error code allows the use of a different message.
*
* @param code the custom code to use with this exception.
*/
public BlockedCredentialsAuthenticationException(final String code) {
super(code);
}
/**
* Constructor that allows for chaining of exceptions and a custom error
* code.
*
* @param code the custom error code to use in message resolving.
* @param throwable the chained exception.
*/
public BlockedCredentialsAuthenticationException(final String code,
final Throwable throwable) {
super(code, throwable);
}
}
| apache-2.0 |
graben1437/titan0.5.4-hbase1.1.1-custom | titan-core/src/main/java/com/thinkaurelius/titan/core/attribute/Geo.java | 2964 | package com.thinkaurelius.titan.core.attribute;
import com.google.common.base.Preconditions;
import com.thinkaurelius.titan.graphdb.query.TitanPredicate;
/**
* Comparison relations for geographic shapes.
*
* @author Matthias Broecheler (me@matthiasb.com)
*/
public enum Geo implements TitanPredicate {
/**
* Whether the intersection between two geographic regions is non-empty
*/
INTERSECT {
@Override
public boolean evaluate(Object value, Object condition) {
Preconditions.checkArgument(condition instanceof Geoshape);
if (value == null) return false;
Preconditions.checkArgument(value instanceof Geoshape);
return ((Geoshape) value).intersect((Geoshape) condition);
}
@Override
public String toString() {
return "intersect";
}
@Override
public boolean hasNegation() {
return true;
}
@Override
public TitanPredicate negate() {
return DISJOINT;
}
},
/**
* Whether the intersection between two geographic regions is empty
*/
DISJOINT {
@Override
public boolean evaluate(Object value, Object condition) {
Preconditions.checkArgument(condition instanceof Geoshape);
if (value == null) return false;
Preconditions.checkArgument(value instanceof Geoshape);
return ((Geoshape) value).disjoint((Geoshape) condition);
}
@Override
public String toString() {
return "disjoint";
}
@Override
public boolean hasNegation() {
return true;
}
@Override
public TitanPredicate negate() {
return INTERSECT;
}
},
/**
* Whether one geographic region is completely contains within another
*/
WITHIN {
@Override
public boolean evaluate(Object value, Object condition) {
Preconditions.checkArgument(condition instanceof Geoshape);
if (value == null) return false;
Preconditions.checkArgument(value instanceof Geoshape);
return ((Geoshape) value).within((Geoshape) condition);
}
@Override
public String toString() {
return "within";
}
@Override
public boolean hasNegation() {
return false;
}
@Override
public TitanPredicate negate() {
throw new UnsupportedOperationException();
}
};
@Override
public boolean isValidCondition(Object condition) {
return condition != null && condition instanceof Geoshape;
}
@Override
public boolean isValidValueType(Class<?> clazz) {
Preconditions.checkNotNull(clazz);
return clazz.equals(Geoshape.class);
}
@Override
public boolean isQNF() {
return true;
}
}
| apache-2.0 |
kaen/Terasology | engine/src/main/java/org/terasology/world/time/WorldTimeImpl.java | 2941 | /*
* Copyright 2013 MovingBlocks
*
* 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.terasology.world.time;
import java.util.concurrent.atomic.AtomicLong;
import org.terasology.engine.Time;
import org.terasology.entitySystem.entity.EntityManager;
import org.terasology.entitySystem.entity.EntityRef;
import org.terasology.entitySystem.systems.BaseComponentSystem;
import org.terasology.entitySystem.systems.UpdateSubscriberSystem;
import org.terasology.registry.In;
import org.terasology.world.WorldComponent;
/**
*/
public class WorldTimeImpl extends BaseComponentSystem implements WorldTime, UpdateSubscriberSystem {
private static final float WORLD_TIME_MULTIPLIER = 48f;
private AtomicLong worldTime = new AtomicLong(0);
@In
private Time time;
@In
private EntityManager entityManager;
@Override
public long getMilliseconds() {
return worldTime.get();
}
@Override
public float getSeconds() {
return worldTime.get() / 1000f;
}
@Override
public float getDays() {
return worldTime.get() / (float) DAY_LENGTH;
}
@Override
public float getTimeRate() {
return WORLD_TIME_MULTIPLIER;
}
@Override
public void setMilliseconds(long newWorldTime) {
// TODO: Send network event to update
this.worldTime.getAndSet(newWorldTime);
}
@Override
public void setDays(float timeInDays) {
setMilliseconds((long) ((double) timeInDays * DAY_LENGTH));
}
@Override
public void update(float delta) {
long deltaMs = time.getGameDeltaInMs();
if (deltaMs > 0) {
deltaMs = (long) (deltaMs * WORLD_TIME_MULTIPLIER);
long startTime = worldTime.getAndAdd(deltaMs);
long endTime = startTime + deltaMs;
long startTick = startTime / TICK_EVENT_RATE;
long endTick = endTime / TICK_EVENT_RATE;
if (startTick != endTick) {
long tick = endTime - endTime % TICK_EVENT_RATE;
getWorldEntity().send(new WorldTimeEvent(tick));
}
// TODO: consider sending a DailyTick (independent from solar events such as midnight)
}
}
private EntityRef getWorldEntity() {
for (EntityRef entity : entityManager.getEntitiesWith(WorldComponent.class)) {
return entity;
}
return EntityRef.NULL;
}
}
| apache-2.0 |
Arvoreen/lombok | src/core/lombok/core/configuration/ConfigurationKey.java | 3507 | /*
* Copyright (C) 2013-2014 The Project Lombok Authors.
*
* 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 lombok.core.configuration;
import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Pattern;
/**
* Describes a configuration key and its type.
* <p>
* The recommended usage is to create a type token:
* <pre>
* private static ConfigurationKey<String> KEY = new ConfigurationKey<String>("keyName", "description") {};
* </pre>
*/
public abstract class ConfigurationKey<T> {
private static final Pattern VALID_NAMES = Pattern.compile("[-_a-zA-Z][-.\\w]*(?<![-.])");
private static final TreeMap<String, ConfigurationKey<?>> registeredKeys = new TreeMap<String, ConfigurationKey<?>>(String.CASE_INSENSITIVE_ORDER);
private static Map<String, ConfigurationKey<?>> copy;
private final String keyName;
private final String description;
private final ConfigurationDataType type;
public ConfigurationKey(String keyName, String description) {
this.keyName = checkName(keyName);
@SuppressWarnings("unchecked")
ConfigurationDataType type = ConfigurationDataType.toDataType((Class<? extends ConfigurationKey<?>>)getClass());
this.type = type;
this.description = description;
registerKey(keyName, this);
}
public final String getKeyName() {
return keyName;
}
public final String getDescription() {
return description;
}
public final ConfigurationDataType getType() {
return type;
}
@Override public String toString() {
return keyName + " (" + type + "): " + description;
}
private static String checkName(String keyName) {
if (keyName == null) throw new NullPointerException("keyName");
if (!VALID_NAMES.matcher(keyName).matches()) throw new IllegalArgumentException("Invalid keyName: " + keyName);
return keyName;
}
/**
* Returns a copy of the currently registered keys.
*/
@SuppressWarnings("unchecked")
public static Map<String, ConfigurationKey<?>> registeredKeys() {
synchronized (registeredKeys) {
if (copy == null) copy = Collections.unmodifiableMap((Map<String, ConfigurationKey<?>>) registeredKeys.clone());
return copy;
}
}
private static void registerKey(String keyName, ConfigurationKey<?> key) {
synchronized (registeredKeys) {
if (registeredKeys.containsKey(keyName)) throw new IllegalArgumentException("Key '" + keyName + "' already registered");
registeredKeys.put(keyName, key);
copy = null;
}
}
} | mit |
raincs13/phd | tests/org/jfree/data/xy/DefaultXYDatasetTest.java | 7159 | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2013, 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.]
*
* --------------------------
* DefaultXYDatasetTests.java
* --------------------------
* (C) Copyright 2006-2008, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 06-Jul-2006 : Version 1 (DG);
* 02-Nov-2006 : Added testAddSeries() method (DG);
* 22-Apr-2008 : Added testPublicCloneable (DG);
*
*/
package org.jfree.data.xy;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertEquals;
import org.jfree.chart.TestUtilities;
import org.jfree.util.PublicCloneable;
import org.junit.Test;
/**
* Tests for {@link DefaultXYDataset}.
*/
public class DefaultXYDatasetTest {
/**
* Confirm that the equals method can distinguish all the required fields.
*/
@Test
public void testEquals() {
DefaultXYDataset d1 = new DefaultXYDataset();
DefaultXYDataset d2 = new DefaultXYDataset();
assertTrue(d1.equals(d2));
assertTrue(d2.equals(d1));
double[] x1 = new double[] {1.0, 2.0, 3.0};
double[] y1 = new double[] {4.0, 5.0, 6.0};
double[][] data1 = new double[][] {x1, y1};
double[] x2 = new double[] {1.0, 2.0, 3.0};
double[] y2 = new double[] {4.0, 5.0, 6.0};
double[][] data2 = new double[][] {x2, y2};
d1.addSeries("S1", data1);
assertFalse(d1.equals(d2));
d2.addSeries("S1", data2);
assertTrue(d1.equals(d2));
}
/**
* Confirm that cloning works.
*/
@Test
public void testCloning() throws CloneNotSupportedException {
DefaultXYDataset d1 = new DefaultXYDataset();
DefaultXYDataset d2 = (DefaultXYDataset) d1.clone();
assertTrue(d1 != d2);
assertTrue(d1.getClass() == d2.getClass());
assertTrue(d1.equals(d2));
// try a dataset with some content...
double[] x1 = new double[] {1.0, 2.0, 3.0};
double[] y1 = new double[] {4.0, 5.0, 6.0};
double[][] data1 = new double[][] {x1, y1};
d1.addSeries("S1", data1);
d2 = (DefaultXYDataset) d1.clone();
assertTrue(d1 != d2);
assertTrue(d1.getClass() == d2.getClass());
assertTrue(d1.equals(d2));
// check that the clone doesn't share the same underlying arrays.
x1[1] = 2.2;
assertFalse(d1.equals(d2));
x1[1] = 2.0;
assertTrue(d1.equals(d2));
}
/**
* Verify that this class implements {@link PublicCloneable}.
*/
@Test
public void testPublicCloneable() {
DefaultXYDataset d1 = new DefaultXYDataset();
assertTrue(d1 instanceof PublicCloneable);
}
/**
* Serialize an instance, restore it, and check for equality.
*/
@Test
public void testSerialization() {
DefaultXYDataset d1 = new DefaultXYDataset();
DefaultXYDataset d2 = (DefaultXYDataset) TestUtilities.serialised(d1);
assertEquals(d1, d2);
// try a dataset with some content...
double[] x1 = new double[] {1.0, 2.0, 3.0};
double[] y1 = new double[] {4.0, 5.0, 6.0};
double[][] data1 = new double[][] {x1, y1};
d1.addSeries("S1", data1);
d2 = (DefaultXYDataset) TestUtilities.serialised(d1);
assertEquals(d1, d2);
}
/**
* Some checks for the getSeriesKey(int) method.
*/
@Test
public void testGetSeriesKey() {
DefaultXYDataset d = createSampleDataset1();
assertEquals("S1", d.getSeriesKey(0));
assertEquals("S2", d.getSeriesKey(1));
// check for series key out of bounds
boolean pass = false;
try {
/*Comparable k =*/ d.getSeriesKey(-1);
}
catch (IllegalArgumentException e) {
pass = true;
}
assertTrue(pass);
pass = false;
try {
/*Comparable k =*/ d.getSeriesKey(2);
}
catch (IllegalArgumentException e) {
pass = true;
}
assertTrue(pass);
}
/**
* Some checks for the indexOf(Comparable) method.
*/
@Test
public void testIndexOf() {
DefaultXYDataset d = createSampleDataset1();
assertEquals(0, d.indexOf("S1"));
assertEquals(1, d.indexOf("S2"));
assertEquals(-1, d.indexOf("Green Eggs and Ham"));
assertEquals(-1, d.indexOf(null));
}
static final double EPSILON = 0.0000000001;
/**
* Some tests for the addSeries() method.
*/
@Test
public void testAddSeries() {
DefaultXYDataset d = new DefaultXYDataset();
d.addSeries("S1", new double[][] {{1.0}, {2.0}});
assertEquals(1, d.getSeriesCount());
assertEquals("S1", d.getSeriesKey(0));
// check that adding a series will overwrite the old series
d.addSeries("S1", new double[][] {{11.0}, {12.0}});
assertEquals(1, d.getSeriesCount());
assertEquals(12.0, d.getYValue(0, 0), EPSILON);
// check null key
boolean pass = false;
try
{
d.addSeries(null, new double[][] {{1.0}, {2.0}});
}
catch (IllegalArgumentException e)
{
pass = true;
}
assertTrue(pass);
}
/**
* Creates a sample dataset for testing.
*
* @return A sample dataset.
*/
public DefaultXYDataset createSampleDataset1() {
DefaultXYDataset d = new DefaultXYDataset();
double[] x1 = new double[] {1.0, 2.0, 3.0};
double[] y1 = new double[] {4.0, 5.0, 6.0};
double[][] data1 = new double[][] {x1, y1};
d.addSeries("S1", data1);
double[] x2 = new double[] {1.0, 2.0, 3.0};
double[] y2 = new double[] {4.0, 5.0, 6.0};
double[][] data2 = new double[][] {x2, y2};
d.addSeries("S2", data2);
return d;
}
}
| lgpl-2.1 |
johtani/elasticsearch | src/main/java/org/elasticsearch/index/snapshots/IndexShardRepository.java | 3068 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.index.snapshots;
import org.elasticsearch.cluster.metadata.SnapshotId;
import org.elasticsearch.index.deletionpolicy.SnapshotIndexCommit;
import org.elasticsearch.indices.recovery.RecoveryState;
import org.elasticsearch.index.shard.ShardId;
/**
* Shard-level snapshot repository
* <p/>
* IndexShardRepository is used on data node to create snapshots of individual shards. See {@link org.elasticsearch.repositories.Repository}
* for more information.
*/
public interface IndexShardRepository {
/**
* Creates a snapshot of the shard based on the index commit point.
* <p/>
* The index commit point can be obtained by using {@link org.elasticsearch.index.engine.internal.InternalEngine#snapshotIndex()} method.
* IndexShardRepository implementations shouldn't release the snapshot index commit point. It is done by the method caller.
* <p/>
* As snapshot process progresses, implementation of this method should update {@link IndexShardSnapshotStatus} object and check
* {@link IndexShardSnapshotStatus#aborted()} to see if the snapshot process should be aborted.
*
* @param snapshotId snapshot id
* @param shardId shard to be snapshotted
* @param snapshotIndexCommit commit point
* @param snapshotStatus snapshot status
*/
void snapshot(SnapshotId snapshotId, ShardId shardId, SnapshotIndexCommit snapshotIndexCommit, IndexShardSnapshotStatus snapshotStatus);
/**
* Restores snapshot of the shard.
* <p/>
* The index can be renamed on restore, hence different {@code shardId} and {@code snapshotShardId} are supplied.
*
* @param snapshotId snapshot id
* @param shardId shard id (in the current index)
* @param snapshotShardId shard id (in the snapshot)
* @param recoveryState recovery state
*/
void restore(SnapshotId snapshotId, ShardId shardId, ShardId snapshotShardId, RecoveryState recoveryState);
/**
* Retrieve shard snapshot status for the stored snapshot
*
* @param snapshotId snapshot id
* @param shardId shard id
* @return snapshot status
*/
IndexShardSnapshotStatus snapshotStatus(SnapshotId snapshotId, ShardId shardId);
}
| apache-2.0 |
aakashysharma/opengse | testing/server-side/webapps-src/servlet-tests/web/WEB-INF/java/tests/javax_servlet/FilterConfig/GetFilterNameTestServlet.java | 3354 | /*
* $Header: /home/cvs/jakarta-watchdog-4.0/src/server/servlet-tests/WEB-INF/classes/tests/javax_servlet/FilterConfig/GetFilterNameTestServlet.java,v 1.1 2002/01/11 22:20:54 rlubke Exp $
* $Revision: 1.1 $
* $Date: 2002/01/11 22:20:54 $
*
* ====================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2002 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/>.
*
*/
package tests.javax_servlet.FilterConfig;
import javax.servlet.*;
import java.io.IOException;
import java.io.PrintWriter;
public class GetFilterNameTestServlet extends GenericServlet {
public void service ( ServletRequest request, ServletResponse response ) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println( "This text should not be displayed from the GetFilterNameTest servlet<BR>" );
}
}
| apache-2.0 |
whipermr5/teammates | src/main/java/teammates/common/util/StatusMessage.java | 639 | package teammates.common.util;
import java.io.Serializable;
/**
* The {@code StatusMessage} class encapsulates the text of status message
* and its level of seriousness of the status message (the color of the message).
*/
@SuppressWarnings("serial")
public class StatusMessage implements Serializable {
private String text;
private StatusMessageColor color;
public StatusMessage(String text, StatusMessageColor color) {
this.text = text;
this.color = color;
}
public String getText() {
return text;
}
public String getColor() {
return color.name().toLowerCase();
}
}
| gpl-2.0 |
pselle/openmrs-core | web/src/main/java/org/openmrs/web/taglib/ConceptTag.java | 5247 | /**
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can
* obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under
* the terms of the Healthcare Disclaimer located at http://openmrs.org/license.
*
* Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS
* graphic logo is a trademark of OpenMRS Inc.
*/
package org.openmrs.web.taglib;
import java.util.Locale;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.Concept;
import org.openmrs.ConceptName;
import org.openmrs.api.ConceptService;
import org.openmrs.api.context.Context;
public class ConceptTag extends BodyTagSupport {
public static final long serialVersionUID = 1234324234333L;
private final Log log = LogFactory.getLog(getClass());
private Concept c = null;
// Properties accessible through tag attributes
private Integer conceptId;
private String conceptName;
private String var;
private String nameVar;
private String shortestNameVar;
private String numericVar;
private String setMemberVar;
private String locale;
public int doStartTag() throws JspException {
ConceptService cs = Context.getConceptService();
// Search for a concept by id
if (conceptId != null) {
c = cs.getConcept(conceptId);
} else if (conceptName != null) {
c = cs.getConceptByName(conceptName);
}
if (c == null) {
if (conceptId != null && conceptId > 0) {
log.warn("ConceptTag is unable to find a concept with conceptId '" + conceptId + "'");
}
if (conceptName != null) {
log.warn("ConceptTag is unable to find a concept with conceptName '" + conceptName + "'");
}
return SKIP_BODY;
}
pageContext.setAttribute(var, c);
log.debug("Found concept with id " + conceptId + ", set to variable: " + var);
// If user specifies a locale in the tag, try to find a matching locale. Otherwise, use the user's default locale
Locale loc = Context.getLocale();
if (StringUtils.isNotEmpty(locale)) {
Locale[] locales = Locale.getAvailableLocales();
for (int i = 0; i < locales.length; i++) {
if (locale.equals(locales[i].toString())) {
loc = locales[i];
break;
}
}
}
if (nameVar != null) {
ConceptName cName = c.getName(loc);
pageContext.setAttribute(nameVar, cName);
log.debug("Retrieved name " + cName.getName() + ", set to variable: " + nameVar);
}
if (shortestNameVar != null) {
pageContext.setAttribute(shortestNameVar, c.getShortestName(loc, false));
}
if (numericVar != null) {
pageContext.setAttribute(numericVar, cs.getConceptNumeric(conceptId));
}
// If the Concept is a Set, get members of that Set
if (c.isSet() && setMemberVar != null) {
pageContext.setAttribute(setMemberVar, Context.getConceptService().getConceptsByConceptSet(c));
}
// If the Concept is a Set, get members of that Set
if (c.isSet() && setMemberVar != null) {
pageContext.setAttribute(setMemberVar, Context.getConceptService().getConceptsByConceptSet(c));
}
return EVAL_BODY_BUFFERED;
}
/**
* @see javax.servlet.jsp.tagext.Tag#doEndTag()
*/
public int doEndTag() throws JspException {
try {
if (bodyContent != null) {
bodyContent.writeOut(bodyContent.getEnclosingWriter());
}
}
catch (java.io.IOException e) {
throw new JspTagException("IO Error: " + e.getMessage());
}
return EVAL_PAGE;
}
/**
* @return the conceptId
*/
public Integer getConceptId() {
return conceptId;
}
/**
* @param conceptId the conceptId to set
*/
public void setConceptId(Integer conceptId) {
this.conceptId = conceptId;
}
/**
* @return the conceptName
*/
public String getConceptName() {
return conceptName;
}
/**
* @param conceptName the conceptName to set
*/
public void setConceptName(String conceptName) {
this.conceptName = conceptName;
}
/**
* @param var the var to set
*/
public void setVar(String var) {
this.var = var;
}
/**
* @param nameVar the nameVar to set
*/
public void setNameVar(String nameVar) {
this.nameVar = nameVar;
}
/**
* @return the locale
*/
public String getLocale() {
return locale;
}
/**
* @param locale the locale to set
*/
public void setLocale(String locale) {
this.locale = locale;
}
/**
* @return the numericVar
*/
public String getNumericVar() {
return numericVar;
}
/**
* @param numericVar the numericVar to set
*/
public void setNumericVar(String numericVar) {
this.numericVar = numericVar;
}
/**
* @return the SetMemberVar
*/
public String getSetMemberVar() {
return setMemberVar;
}
public String getShortestNameVar() {
return shortestNameVar;
}
public void setShortestNameVar(String shortestNameVar) {
this.shortestNameVar = shortestNameVar;
}
/**
* @param setMemberVar the SetMemberVar to set
*/
public void setSetMemberVar(String setMemberVar) {
this.setMemberVar = setMemberVar;
}
}
| mpl-2.0 |
apratkin/pentaho-kettle | engine/src/org/pentaho/di/job/entries/http/JobEntryHTTP.java | 25595 | /*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2013 by Pentaho : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.job.entries.http;
import static org.pentaho.di.job.entry.validator.AndValidator.putValidators;
import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.andValidator;
import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.integerValidator;
import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.notBlankValidator;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Authenticator;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.pentaho.di.cluster.SlaveServer;
import org.pentaho.di.core.CheckResultInterface;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.Result;
import org.pentaho.di.core.ResultFile;
import org.pentaho.di.core.RowMetaAndData;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.encryption.Encr;
import org.pentaho.di.core.exception.KettleDatabaseException;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.row.ValueMeta;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.job.entry.JobEntryBase;
import org.pentaho.di.job.entry.JobEntryInterface;
import org.pentaho.di.repository.ObjectId;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.resource.ResourceEntry;
import org.pentaho.di.resource.ResourceEntry.ResourceType;
import org.pentaho.di.resource.ResourceReference;
import org.pentaho.metastore.api.IMetaStore;
import org.w3c.dom.Node;
/**
* This defines an HTTP job entry.
*
* @author Matt
* @since 05-11-2003
*
*/
public class JobEntryHTTP extends JobEntryBase implements Cloneable, JobEntryInterface {
private static Class<?> PKG = JobEntryHTTP.class; // for i18n purposes, needed by Translator2!!
private static final String URL_FIELDNAME = "URL";
// Base info
private String url;
private String targetFilename;
private boolean fileAppended;
private boolean dateTimeAdded;
private String targetFilenameExtention;
// Send file content to server?
private String uploadFilename;
// The fieldname that contains the URL
// Get it from a previous transformation with Result.
private String urlFieldname;
private boolean runForEveryRow;
// Proxy settings
private String proxyHostname;
private String proxyPort;
private String nonProxyHosts;
private String username;
private String password;
private boolean addfilenameresult;
private String[] headerName;
private String[] headerValue;
public JobEntryHTTP( String n ) {
super( n, "" );
url = null;
addfilenameresult = true;
}
public JobEntryHTTP() {
this( "" );
}
public Object clone() {
JobEntryHTTP je = (JobEntryHTTP) super.clone();
return je;
}
public String getXML() {
StringBuffer retval = new StringBuffer( 300 );
retval.append( super.getXML() );
retval.append( " " ).append( XMLHandler.addTagValue( "url", url ) );
retval.append( " " ).append( XMLHandler.addTagValue( "targetfilename", targetFilename ) );
retval.append( " " ).append( XMLHandler.addTagValue( "file_appended", fileAppended ) );
retval.append( " " ).append( XMLHandler.addTagValue( "date_time_added", dateTimeAdded ) );
retval
.append( " " ).append( XMLHandler.addTagValue( "targetfilename_extention", targetFilenameExtention ) );
retval.append( " " ).append( XMLHandler.addTagValue( "uploadfilename", uploadFilename ) );
retval.append( " " ).append( XMLHandler.addTagValue( "url_fieldname", urlFieldname ) );
retval.append( " " ).append( XMLHandler.addTagValue( "run_every_row", runForEveryRow ) );
retval.append( " " ).append( XMLHandler.addTagValue( "username", username ) );
retval.append( " " ).append(
XMLHandler.addTagValue( "password", Encr.encryptPasswordIfNotUsingVariables( password ) ) );
retval.append( " " ).append( XMLHandler.addTagValue( "proxy_host", proxyHostname ) );
retval.append( " " ).append( XMLHandler.addTagValue( "proxy_port", proxyPort ) );
retval.append( " " ).append( XMLHandler.addTagValue( "non_proxy_hosts", nonProxyHosts ) );
retval.append( " " ).append( XMLHandler.addTagValue( "addfilenameresult", addfilenameresult ) );
retval.append( " <headers>" ).append( Const.CR );
if ( headerName != null ) {
for ( int i = 0; i < headerName.length; i++ ) {
retval.append( " <header>" ).append( Const.CR );
retval.append( " " ).append( XMLHandler.addTagValue( "header_name", headerName[i] ) );
retval.append( " " ).append( XMLHandler.addTagValue( "header_value", headerValue[i] ) );
retval.append( " </header>" ).append( Const.CR );
}
}
retval.append( " </headers>" ).append( Const.CR );
return retval.toString();
}
public void loadXML( Node entrynode, List<DatabaseMeta> databases, List<SlaveServer> slaveServers,
Repository rep, IMetaStore metaStore ) throws KettleXMLException {
try {
super.loadXML( entrynode, databases, slaveServers );
url = XMLHandler.getTagValue( entrynode, "url" );
targetFilename = XMLHandler.getTagValue( entrynode, "targetfilename" );
fileAppended = "Y".equalsIgnoreCase( XMLHandler.getTagValue( entrynode, "file_appended" ) );
dateTimeAdded = "Y".equalsIgnoreCase( XMLHandler.getTagValue( entrynode, "date_time_added" ) );
targetFilenameExtention = XMLHandler.getTagValue( entrynode, "targetfilename_extention" );
uploadFilename = XMLHandler.getTagValue( entrynode, "uploadfilename" );
urlFieldname = XMLHandler.getTagValue( entrynode, "url_fieldname" );
runForEveryRow = "Y".equalsIgnoreCase( XMLHandler.getTagValue( entrynode, "run_every_row" ) );
username = XMLHandler.getTagValue( entrynode, "username" );
password = Encr.decryptPasswordOptionallyEncrypted( XMLHandler.getTagValue( entrynode, "password" ) );
proxyHostname = XMLHandler.getTagValue( entrynode, "proxy_host" );
proxyPort = XMLHandler.getTagValue( entrynode, "proxy_port" );
nonProxyHosts = XMLHandler.getTagValue( entrynode, "non_proxy_hosts" );
addfilenameresult =
"Y".equalsIgnoreCase( Const.NVL( XMLHandler.getTagValue( entrynode, "addfilenameresult" ), "Y" ) );
Node headers = XMLHandler.getSubNode( entrynode, "headers" );
// How many field headerName?
int nrHeaders = XMLHandler.countNodes( headers, "header" );
headerName = new String[nrHeaders];
headerValue = new String[nrHeaders];
for ( int i = 0; i < nrHeaders; i++ ) {
Node fnode = XMLHandler.getSubNodeByNr( headers, "header", i );
headerName[i] = XMLHandler.getTagValue( fnode, "header_name" );
headerValue[i] = XMLHandler.getTagValue( fnode, "header_value" );
}
} catch ( KettleXMLException xe ) {
throw new KettleXMLException( "Unable to load job entry of type 'HTTP' from XML node", xe );
}
}
public void loadRep( Repository rep, IMetaStore metaStore, ObjectId id_jobentry, List<DatabaseMeta> databases,
List<SlaveServer> slaveServers ) throws KettleException {
try {
url = rep.getJobEntryAttributeString( id_jobentry, "url" );
targetFilename = rep.getJobEntryAttributeString( id_jobentry, "targetfilename" );
fileAppended = rep.getJobEntryAttributeBoolean( id_jobentry, "file_appended" );
dateTimeAdded = rep.getJobEntryAttributeBoolean( id_jobentry, "date_time_added" );
targetFilenameExtention = rep.getJobEntryAttributeString( id_jobentry, "targetfilename_extention" );
uploadFilename = rep.getJobEntryAttributeString( id_jobentry, "uploadfilename" );
urlFieldname = rep.getJobEntryAttributeString( id_jobentry, "url_fieldname" );
runForEveryRow = rep.getJobEntryAttributeBoolean( id_jobentry, "run_every_row" );
username = rep.getJobEntryAttributeString( id_jobentry, "username" );
password =
Encr.decryptPasswordOptionallyEncrypted( rep.getJobEntryAttributeString( id_jobentry, "password" ) );
proxyHostname = rep.getJobEntryAttributeString( id_jobentry, "proxy_host" );
proxyPort = rep.getJobEntryAttributeString( id_jobentry, "proxy_port" ); // backward compatible.
nonProxyHosts = rep.getJobEntryAttributeString( id_jobentry, "non_proxy_hosts" );
addfilenameresult =
"Y".equalsIgnoreCase( Const
.NVL( rep.getJobEntryAttributeString( id_jobentry, "addfilenameresult" ), "Y" ) );
// How many headerName?
int argnr = rep.countNrJobEntryAttributes( id_jobentry, "header_name" );
headerName = new String[argnr];
headerValue = new String[argnr];
for ( int a = 0; a < argnr; a++ ) {
headerName[a] = rep.getJobEntryAttributeString( id_jobentry, a, "header_name" );
headerValue[a] = rep.getJobEntryAttributeString( id_jobentry, a, "header_value" );
}
} catch ( KettleException dbe ) {
throw new KettleException( "Unable to load job entry of type 'HTTP' from the repository for id_jobentry="
+ id_jobentry, dbe );
}
}
public void saveRep( Repository rep, IMetaStore metaStore, ObjectId id_job ) throws KettleException {
try {
rep.saveJobEntryAttribute( id_job, getObjectId(), "url", url );
rep.saveJobEntryAttribute( id_job, getObjectId(), "targetfilename", targetFilename );
rep.saveJobEntryAttribute( id_job, getObjectId(), "file_appended", fileAppended );
rep.saveJobEntryAttribute( id_job, getObjectId(), "date_time_added", dateTimeAdded );
rep.saveJobEntryAttribute( id_job, getObjectId(), "targetfilename_extention", targetFilenameExtention );
rep.saveJobEntryAttribute( id_job, getObjectId(), "uploadfilename", uploadFilename );
rep.saveJobEntryAttribute( id_job, getObjectId(), "url_fieldname", urlFieldname );
rep.saveJobEntryAttribute( id_job, getObjectId(), "run_every_row", runForEveryRow );
rep.saveJobEntryAttribute( id_job, getObjectId(), "username", username );
rep.saveJobEntryAttribute( id_job, getObjectId(), "password", Encr
.encryptPasswordIfNotUsingVariables( password ) );
rep.saveJobEntryAttribute( id_job, getObjectId(), "proxy_host", proxyHostname );
rep.saveJobEntryAttribute( id_job, getObjectId(), "proxy_port", proxyPort );
rep.saveJobEntryAttribute( id_job, getObjectId(), "non_proxy_hosts", nonProxyHosts );
rep.saveJobEntryAttribute( id_job, getObjectId(), "addfilenameresult", addfilenameresult );
if ( headerName != null ) {
for ( int i = 0; i < headerName.length; i++ ) {
rep.saveJobEntryAttribute( id_job, getObjectId(), i, "header_name", headerName[i] );
rep.saveJobEntryAttribute( id_job, getObjectId(), i, "header_value", headerValue[i] );
}
}
} catch ( KettleDatabaseException dbe ) {
throw new KettleException(
"Unable to load job entry of type 'HTTP' to the repository for id_job=" + id_job, dbe );
}
}
/**
* @return Returns the URL.
*/
public String getUrl() {
return url;
}
/**
* @param url
* The URL to set.
*/
public void setUrl( String url ) {
this.url = url;
}
/**
* @return Returns the target filename.
*/
public String getTargetFilename() {
return targetFilename;
}
/**
* @param targetFilename
* The target filename to set.
*/
public void setTargetFilename( String targetFilename ) {
this.targetFilename = targetFilename;
}
public String getNonProxyHosts() {
return nonProxyHosts;
}
public void setNonProxyHosts( String nonProxyHosts ) {
this.nonProxyHosts = nonProxyHosts;
}
public boolean isAddFilenameToResult() {
return addfilenameresult;
}
public void setAddFilenameToResult( boolean addfilenameresult ) {
this.addfilenameresult = addfilenameresult;
}
public String getPassword() {
return password;
}
public void setPassword( String password ) {
this.password = password;
}
public String getProxyHostname() {
return proxyHostname;
}
public void setProxyHostname( String proxyHostname ) {
this.proxyHostname = proxyHostname;
}
public String getProxyPort() {
return proxyPort;
}
public void setProxyPort( String proxyPort ) {
this.proxyPort = proxyPort;
}
public String getUsername() {
return username;
}
public void setUsername( String username ) {
this.username = username;
}
public String[] getHeaderName() {
return headerName;
}
public void setHeaderName( String[] headerName ) {
this.headerName = headerName;
}
public String[] getHeaderValue() {
return headerValue;
}
public void setHeaderValue( String[] headerValue ) {
this.headerValue = headerValue;
}
/**
* We made this one synchronized in the JVM because otherwise, this is not thread safe. In that case if (on an
* application server for example) several HTTP's are running at the same time, you get into problems because the
* System.setProperty() calls are system wide!
*/
public synchronized Result execute( Result previousResult, int nr ) {
Result result = previousResult;
result.setResult( false );
logBasic( BaseMessages.getString( PKG, "JobHTTP.StartJobEntry" ) );
// Get previous result rows...
List<RowMetaAndData> resultRows;
String urlFieldnameToUse;
if ( Const.isEmpty( urlFieldname ) ) {
urlFieldnameToUse = URL_FIELDNAME;
} else {
urlFieldnameToUse = urlFieldname;
}
if ( runForEveryRow ) {
resultRows = previousResult.getRows();
if ( resultRows == null ) {
result.setNrErrors( 1 );
logError( BaseMessages.getString( PKG, "JobHTTP.Error.UnableGetResultPrevious" ) );
return result;
}
} else {
resultRows = new ArrayList<RowMetaAndData>();
RowMetaAndData row = new RowMetaAndData();
row.addValue(
new ValueMeta( urlFieldnameToUse, ValueMetaInterface.TYPE_STRING ), environmentSubstitute( url ) );
resultRows.add( row );
}
URL server = null;
String beforeProxyHost = System.getProperty( "http.proxyHost" );
String beforeProxyPort = System.getProperty( "http.proxyPort" );
String beforeNonProxyHosts = System.getProperty( "http.nonProxyHosts" );
for ( int i = 0; i < resultRows.size() && result.getNrErrors() == 0; i++ ) {
RowMetaAndData row = resultRows.get( i );
OutputStream outputFile = null;
OutputStream uploadStream = null;
BufferedInputStream fileStream = null;
InputStream input = null;
try {
String urlToUse = environmentSubstitute( row.getString( urlFieldnameToUse, "" ) );
logBasic( BaseMessages.getString( PKG, "JobHTTP.Log.ConnectingURL", urlToUse ) );
if ( !Const.isEmpty( proxyHostname ) ) {
System.setProperty( "http.proxyHost", environmentSubstitute( proxyHostname ) );
System.setProperty( "http.proxyPort", environmentSubstitute( proxyPort ) );
if ( nonProxyHosts != null ) {
System.setProperty( "http.nonProxyHosts", environmentSubstitute( nonProxyHosts ) );
}
}
if ( !Const.isEmpty( username ) ) {
Authenticator.setDefault( new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
String realPassword = Encr.decryptPasswordOptionallyEncrypted( environmentSubstitute( password ) );
return new PasswordAuthentication( environmentSubstitute( username ), realPassword != null
? realPassword.toCharArray() : new char[] {} );
}
} );
}
String realTargetFile = environmentSubstitute( targetFilename );
if ( dateTimeAdded ) {
SimpleDateFormat daf = new SimpleDateFormat();
Date now = new Date();
daf.applyPattern( "yyyMMdd" );
realTargetFile += "_" + daf.format( now );
daf.applyPattern( "HHmmss" );
realTargetFile += "_" + daf.format( now );
if ( !Const.isEmpty( targetFilenameExtention ) ) {
realTargetFile += "." + environmentSubstitute( targetFilenameExtention );
}
}
// Create the output File...
outputFile = KettleVFS.getOutputStream( realTargetFile, this, fileAppended );
// Get a stream for the specified URL
server = new URL( urlToUse );
URLConnection connection = server.openConnection();
// if we have HTTP headers, add them
if ( !Const.isEmpty( headerName ) ) {
if ( log.isDebug() ) {
log.logDebug( BaseMessages.getString( PKG, "JobHTTP.Log.HeadersProvided" ) );
}
for ( int j = 0; j < headerName.length; j++ ) {
if ( !Const.isEmpty( headerValue[j] ) ) {
connection.setRequestProperty(
environmentSubstitute( headerName[j] ), environmentSubstitute( headerValue[j] ) );
if ( log.isDebug() ) {
log.logDebug( BaseMessages.getString(
PKG, "JobHTTP.Log.HeaderSet", environmentSubstitute( headerName[j] ),
environmentSubstitute( headerValue[j] ) ) );
}
}
}
}
connection.setDoOutput( true );
// See if we need to send a file over?
String realUploadFilename = environmentSubstitute( uploadFilename );
if ( !Const.isEmpty( realUploadFilename ) ) {
if ( log.isDetailed() ) {
logDetailed( BaseMessages.getString( PKG, "JobHTTP.Log.SendingFile", realUploadFilename ) );
}
// Grab an output stream to upload data to web server
uploadStream = connection.getOutputStream();
fileStream = new BufferedInputStream( new FileInputStream( new File( realUploadFilename ) ) );
try {
int c;
while ( ( c = fileStream.read() ) >= 0 ) {
uploadStream.write( c );
}
} finally {
// Close upload and file
if ( uploadStream != null ) {
uploadStream.close();
uploadStream = null;
}
if ( fileStream != null ) {
fileStream.close();
fileStream = null;
}
}
if ( log.isDetailed() ) {
logDetailed( BaseMessages.getString( PKG, "JobHTTP.Log.FinishedSendingFile" ) );
}
}
if ( log.isDetailed() ) {
logDetailed( BaseMessages.getString( PKG, "JobHTTP.Log.StartReadingReply" ) );
}
// Read the result from the server...
input = connection.getInputStream();
Date date = new Date( connection.getLastModified() );
logBasic( BaseMessages.getString( PKG, "JobHTTP.Log.ReplayInfo", connection.getContentType(), date ) );
int oneChar;
long bytesRead = 0L;
while ( ( oneChar = input.read() ) != -1 ) {
outputFile.write( oneChar );
bytesRead++;
}
logBasic( BaseMessages.getString( PKG, "JobHTTP.Log.FinisedWritingReply", bytesRead, realTargetFile ) );
if ( addfilenameresult ) {
// Add to the result files...
ResultFile resultFile =
new ResultFile(
ResultFile.FILE_TYPE_GENERAL, KettleVFS.getFileObject( realTargetFile, this ), parentJob
.getJobname(), toString() );
result.getResultFiles().put( resultFile.getFile().toString(), resultFile );
}
result.setResult( true );
} catch ( MalformedURLException e ) {
result.setNrErrors( 1 );
logError( BaseMessages.getString( PKG, "JobHTTP.Error.NotValidURL", url, e.getMessage() ) );
logError( Const.getStackTracker( e ) );
} catch ( IOException e ) {
result.setNrErrors( 1 );
logError( BaseMessages.getString( PKG, "JobHTTP.Error.CanNotSaveHTTPResult", e.getMessage() ) );
logError( Const.getStackTracker( e ) );
} catch ( Exception e ) {
result.setNrErrors( 1 );
logError( BaseMessages.getString( PKG, "JobHTTP.Error.ErrorGettingFromHTTP", e.getMessage() ) );
logError( Const.getStackTracker( e ) );
} finally {
// Close it all
try {
if ( uploadStream != null ) {
uploadStream.close(); // just to make sure
}
if ( fileStream != null ) {
fileStream.close(); // just to make sure
}
if ( input != null ) {
input.close();
}
if ( outputFile != null ) {
outputFile.close();
}
} catch ( Exception e ) {
logError( BaseMessages.getString( PKG, "JobHTTP.Error.CanNotCloseStream", e.getMessage() ) );
result.setNrErrors( 1 );
}
// Set the proxy settings back as they were on the system!
System.setProperty( "http.proxyHost", Const.NVL( beforeProxyHost, "" ) );
System.setProperty( "http.proxyPort", Const.NVL( beforeProxyPort, "" ) );
System.setProperty( "http.nonProxyHosts", Const.NVL( beforeNonProxyHosts, "" ) );
}
}
return result;
}
public boolean evaluates() {
return true;
}
public String getUploadFilename() {
return uploadFilename;
}
public void setUploadFilename( String uploadFilename ) {
this.uploadFilename = uploadFilename;
}
/**
* @return Returns the getFieldname.
*/
public String getUrlFieldname() {
return urlFieldname;
}
/**
* @param getFieldname
* The getFieldname to set.
*/
public void setUrlFieldname( String getFieldname ) {
this.urlFieldname = getFieldname;
}
/**
* @return Returns the runForEveryRow.
*/
public boolean isRunForEveryRow() {
return runForEveryRow;
}
/**
* @param runForEveryRow
* The runForEveryRow to set.
*/
public void setRunForEveryRow( boolean runForEveryRow ) {
this.runForEveryRow = runForEveryRow;
}
/**
* @return Returns the fileAppended.
*/
public boolean isFileAppended() {
return fileAppended;
}
/**
* @param fileAppended
* The fileAppended to set.
*/
public void setFileAppended( boolean fileAppended ) {
this.fileAppended = fileAppended;
}
/**
* @return Returns the dateTimeAdded.
*/
public boolean isDateTimeAdded() {
return dateTimeAdded;
}
/**
* @param dateTimeAdded
* The dateTimeAdded to set.
*/
public void setDateTimeAdded( boolean dateTimeAdded ) {
this.dateTimeAdded = dateTimeAdded;
}
/**
* @return Returns the uploadFilenameExtention.
*/
public String getTargetFilenameExtention() {
return targetFilenameExtention;
}
/**
* @param uploadFilenameExtention
* The uploadFilenameExtention to set.
*/
public void setTargetFilenameExtention( String uploadFilenameExtention ) {
this.targetFilenameExtention = uploadFilenameExtention;
}
public List<ResourceReference> getResourceDependencies( JobMeta jobMeta ) {
List<ResourceReference> references = super.getResourceDependencies( jobMeta );
String realUrl = jobMeta.environmentSubstitute( url );
ResourceReference reference = new ResourceReference( this );
reference.getEntries().add( new ResourceEntry( realUrl, ResourceType.URL ) );
references.add( reference );
return references;
}
@Override
public void check( List<CheckResultInterface> remarks, JobMeta jobMeta, VariableSpace space,
Repository repository, IMetaStore metaStore ) {
andValidator().validate( this, "targetFilename", remarks, putValidators( notBlankValidator() ) );
andValidator().validate( this, "targetFilenameExtention", remarks, putValidators( notBlankValidator() ) );
andValidator().validate( this, "uploadFilename", remarks, putValidators( notBlankValidator() ) );
andValidator().validate( this, "proxyPort", remarks, putValidators( integerValidator() ) );
}
}
| apache-2.0 |
dyx/ansj_seg | src/test/java/org/ansj/demo/DefineDemo.java | 2088 | package org.ansj.demo;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.ansj.domain.Nature;
import org.ansj.domain.Term;
import org.ansj.domain.TermNatures;
import org.ansj.recognition.NatureRecognition;
import org.ansj.splitWord.analysis.BaseAnalysis;
/**
* @author ansj
*
*/
public class DefineDemo {
public static void main(String[] args) throws IOException {
String str = "java@ID:6321-000301@你好";
// 普通分词
List<Term> parse = BaseAnalysis.parse(str);
// 词性标注
new NatureRecognition(parse).recognition();
// 合并用户id
parse = mergerId(parse);
System.out.println(parse);
}
private static final Nature userIdNature = new Nature("userId");
public static List<Term> mergerId(List<Term> parse) {
List<Term> result = new ArrayList<Term>();
Term term = null;
Term newTerm = null;
for (int i = 0; i < parse.size(); i++) {
term = parse.get(i);
if ("@".equals(term.getName())) {
StringBuilder sb = new StringBuilder(term.getName());
int end = mergerId(parse, sb, i);
System.out.println(end);
if (end > 0) {
newTerm = new Term(sb.toString(), term.getOffe(), TermNatures.NULL);
newTerm.setNature(userIdNature);
result.add(newTerm);
i = end;
} else {
result.add(term);
}
} else {
result.add(parse.get(i));
}
}
return result;
}
private static int mergerId(List<Term> parse, StringBuilder sb, int i) {
// TODO Auto-generated method stub
Term term = null;
String natureStr = null;
int j = i + 1;
for (; j < parse.size(); j++) {
term = parse.get(j);
natureStr = term.natrue().natureStr;
if ("en".equals(natureStr) || "m".equals(natureStr) || "-".equals(term.getName()) || ":".equals(term.getName())) {
sb.append(term.getName());
} else if ("@".equals(term.getName())) {
sb.append(term.getName());
break;
} else {
return -1;
}
}
if (sb.length() > 2) {
return j;
} else {
return -1;
}
}
}
| apache-2.0 |
idea4bsd/idea4bsd | platform/platform-api/src/com/intellij/openapi/application/ApplicationActivationListener.java | 1944 | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.application;
import com.intellij.openapi.wm.IdeFrame;
import com.intellij.util.messages.Topic;
/**
* @author yole
*/
public interface ApplicationActivationListener {
Topic<ApplicationActivationListener> TOPIC = Topic.create("Application activation notifications", ApplicationActivationListener.class);
/**
* Called when app is activated by transferring focus to it.
*/
void applicationActivated(IdeFrame ideFrame);
/**
* Called when app is de-activated by transferring focus from it.
*/
void applicationDeactivated(IdeFrame ideFrame);
/**
* This is more precise notification than {code applicationDeactivated} callback.
* It is intended for focus subsystem and purposes where we do not want
* to be bothered by false application deactivation events.
*
* The shortcoming of the method is that a notification is delivered
* with a delay. See {code app.deactivation.timeout} key in the registry
*/
void delayedApplicationDeactivated(IdeFrame ideFrame);
abstract class Adapter implements ApplicationActivationListener {
@Override
public void applicationActivated(IdeFrame ideFrame) { }
@Override
public void applicationDeactivated(IdeFrame ideFrame) { }
@Override
public void delayedApplicationDeactivated(IdeFrame ideFrame) { }
}
}
| apache-2.0 |
mahaliachante/aws-sdk-java | aws-java-sdk-elasticache/src/main/java/com/amazonaws/services/elasticache/model/transform/EventStaxUnmarshaller.java | 2892 | /*
* Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.elasticache.model.transform;
import java.util.Map;
import java.util.Map.Entry;
import javax.xml.stream.events.XMLEvent;
import com.amazonaws.services.elasticache.model.*;
import com.amazonaws.transform.Unmarshaller;
import com.amazonaws.transform.MapEntry;
import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;
/**
* Event StAX Unmarshaller
*/
public class EventStaxUnmarshaller implements Unmarshaller<Event, StaxUnmarshallerContext> {
public Event unmarshall(StaxUnmarshallerContext context) throws Exception {
Event event = new Event();
int originalDepth = context.getCurrentDepth();
int targetDepth = originalDepth + 1;
if (context.isStartOfDocument()) targetDepth += 2;
while (true) {
XMLEvent xmlEvent = context.nextEvent();
if (xmlEvent.isEndDocument()) return event;
if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {
if (context.testExpression("SourceIdentifier", targetDepth)) {
event.setSourceIdentifier(StringStaxUnmarshaller.getInstance().unmarshall(context));
continue;
}
if (context.testExpression("SourceType", targetDepth)) {
event.setSourceType(StringStaxUnmarshaller.getInstance().unmarshall(context));
continue;
}
if (context.testExpression("Message", targetDepth)) {
event.setMessage(StringStaxUnmarshaller.getInstance().unmarshall(context));
continue;
}
if (context.testExpression("Date", targetDepth)) {
event.setDate(DateStaxUnmarshaller.getInstance().unmarshall(context));
continue;
}
} else if (xmlEvent.isEndElement()) {
if (context.getCurrentDepth() < originalDepth) {
return event;
}
}
}
}
private static EventStaxUnmarshaller instance;
public static EventStaxUnmarshaller getInstance() {
if (instance == null) instance = new EventStaxUnmarshaller();
return instance;
}
}
| apache-2.0 |
mahaliachante/aws-sdk-java | aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/marshallers/BooleanToNumberMarshaller.java | 1631 | /*
* Copyright 2014-2015 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.services.dynamodbv2.datamodeling.marshallers;
import com.amazonaws.services.dynamodbv2.datamodeling.ArgumentMarshaller.NumberAttributeMarshaller;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
/**
* A legacy marshaller that marshals Java {@code Booleans} into DynamoDB
* Numbers, representing {@code true} as '1' and {@code false} as '0'. Retained
* for backwards compatibility with older versions of the mapper which don't
* know about the DynamoDB BOOL type.
*/
public class BooleanToNumberMarshaller implements NumberAttributeMarshaller {
private static final BooleanToNumberMarshaller INSTANCE =
new BooleanToNumberMarshaller();
public static BooleanToNumberMarshaller instance() {
return INSTANCE;
}
private BooleanToNumberMarshaller() {
}
@Override
public AttributeValue marshall(Object obj) {
Boolean bool = (Boolean) obj;
if (bool == null || bool == false) {
return new AttributeValue().withN("0");
} else {
return new AttributeValue().withN("1");
}
}
}
| apache-2.0 |
zhakui/j2objc | translator/src/main/java/com/google/devtools/j2objc/ast/ArrayAccess.java | 2080 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.devtools.j2objc.ast;
import org.eclipse.jdt.core.dom.ITypeBinding;
/**
* Array access node type.
*/
public class ArrayAccess extends Expression {
private final ChildLink<Expression> array = ChildLink.create(Expression.class, this);
private final ChildLink<Expression> index = ChildLink.create(Expression.class, this);
public ArrayAccess(org.eclipse.jdt.core.dom.ArrayAccess jdtNode) {
super(jdtNode);
array.set((Expression) TreeConverter.convert(jdtNode.getArray()));
index.set((Expression) TreeConverter.convert(jdtNode.getIndex()));
}
public ArrayAccess(ArrayAccess other) {
super(other);
array.copyFrom(other.getArray());
index.copyFrom(other.getIndex());
}
@Override
public Kind getKind() {
return Kind.ARRAY_ACCESS;
}
@Override
public ITypeBinding getTypeBinding() {
Expression arrayNode = array.get();
ITypeBinding arrayType = arrayNode != null ? arrayNode.getTypeBinding() : null;
return arrayType != null ? arrayType.getComponentType() : null;
}
public Expression getArray() {
return array.get();
}
public Expression getIndex() {
return index.get();
}
public void setIndex(Expression newIndex) {
index.set(newIndex);
}
@Override
protected void acceptInner(TreeVisitor visitor) {
if (visitor.visit(this)) {
array.accept(visitor);
index.accept(visitor);
}
visitor.endVisit(this);
}
@Override
public ArrayAccess copy() {
return new ArrayAccess(this);
}
}
| apache-2.0 |
thariyarox/product-is | modules/samples/identity-mgt/info-recovery-sample/src/main/java/org/wso2/sample/inforecovery/client/ClientConstants.java | 1105 | /*
* Copyright (c) 2015, 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.sample.inforecovery.client;
public class ClientConstants {
public static final String ACCESS_USERNAME = "accessUsername";
public static final String CAPTCHA_DISABLE = "captchaDisable";
public static final String ACCESS_PASSWORD = "accessPassword";
public static final String TRUSTSTORE_PATH = "trustStorePath";
public static final String TRUSTSTORE_PROPERTY = "javax.net.ssl.trustStore";
}
| apache-2.0 |
mikibrv/sling | bundles/extensions/event/src/main/java/org/apache/sling/event/impl/jobs/notifications/NotificationUtility.java | 3068 | /*
* 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.sling.event.impl.jobs.notifications;
import java.util.Dictionary;
import java.util.Hashtable;
import org.apache.sling.event.impl.jobs.JobImpl;
import org.apache.sling.event.jobs.Job;
import org.apache.sling.event.jobs.NotificationConstants;
import org.apache.sling.event.jobs.consumer.JobConsumer;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventAdmin;
import org.osgi.service.event.EventConstants;
public abstract class NotificationUtility {
/** Event property containing the time for job start and job finished events. */
public static final String PROPERTY_TIME = ":time";
/**
* Helper method for sending the notification events.
*/
public static void sendNotification(final EventAdmin eventAdmin,
final String eventTopic,
final Job job,
final Long time) {
if ( eventAdmin != null ) {
// create new copy of job object
final Job jobCopy = new JobImpl(job.getTopic(), job.getId(), ((JobImpl)job).getProperties());
sendNotificationInternal(eventAdmin, eventTopic, jobCopy, time);
}
}
/**
* Helper method for sending the notification events.
*/
private static void sendNotificationInternal(final EventAdmin eventAdmin,
final String eventTopic,
final Job job,
final Long time) {
final Dictionary<String, Object> eventProps = new Hashtable<String, Object>();
// add basic job properties
eventProps.put(NotificationConstants.NOTIFICATION_PROPERTY_JOB_ID, job.getId());
eventProps.put(NotificationConstants.NOTIFICATION_PROPERTY_JOB_TOPIC, job.getTopic());
// copy payload
for(final String name : job.getPropertyNames()) {
eventProps.put(name, job.getProperty(name));
}
// remove async handler
eventProps.remove(JobConsumer.PROPERTY_JOB_ASYNC_HANDLER);
// add timestamp
eventProps.put(EventConstants.TIMESTAMP, System.currentTimeMillis());
// add internal time information
if ( time != null ) {
eventProps.put(PROPERTY_TIME, time);
}
eventAdmin.postEvent(new Event(eventTopic, eventProps));
}
}
| apache-2.0 |
shaotuanchen/sunflower_exp | tools/source/gcc-4.2.4/libjava/classpath/gnu/xml/xpath/TrueFunction.java | 2273 | /* TrueFunction.java --
Copyright (C) 2004 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnu.xml.xpath;
import javax.xml.namespace.QName;
import org.w3c.dom.Node;
/**
* The <code>true</code> function returns true.
*
* @author <a href='mailto:dog@gnu.org'>Chris Burdess</a>
*/
final class TrueFunction
extends Expr
{
public Object evaluate(Node context, int pos, int len)
{
return Boolean.TRUE;
}
public Expr clone(Object context)
{
return new TrueFunction();
}
public boolean references(QName var)
{
return false;
}
public String toString()
{
return "true()";
}
}
| bsd-3-clause |
ivan-fedorov/intellij-community | java/java-impl/src/com/intellij/slicer/SliceTooComplexDFAUsage.java | 2202 | /*
* Copyright 2000-2013 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.slicer;
import com.intellij.openapi.editor.markup.EffectType;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiSubstitutor;
import com.intellij.ui.JBColor;
import com.intellij.usages.TextChunk;
import com.intellij.usages.UsagePresentation;
import com.intellij.util.Processor;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.*;
/**
* User: cdr
*/
public class SliceTooComplexDFAUsage extends SliceUsage {
public SliceTooComplexDFAUsage(@NotNull PsiElement element, @NotNull SliceUsage parent, @NotNull PsiSubstitutor substitutor) {
super(element, parent, substitutor,0,"");
}
@Override
public void processChildren(@NotNull Processor<SliceUsage> processor) {
// no children
}
@NotNull
@Override
public UsagePresentation getPresentation() {
final UsagePresentation presentation = super.getPresentation();
return new UsagePresentation() {
@Override
@NotNull
public TextChunk[] getText() {
return new TextChunk[]{
new TextChunk(new TextAttributes(JBColor.RED, null, null, EffectType.WAVE_UNDERSCORE, Font.PLAIN), getTooltipText())
};
}
@Override
@NotNull
public String getPlainText() {
return presentation.getPlainText();
}
@Override
public Icon getIcon() {
return presentation.getIcon();
}
@Override
public String getTooltipText() {
return "Too complex to analyze, analysis stopped here";
}
};
}
}
| apache-2.0 |
marsorp/blog | presto166/presto-spi/src/main/java/com/facebook/presto/spi/Plugin.java | 2123 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.spi;
import com.facebook.presto.spi.block.BlockEncodingFactory;
import com.facebook.presto.spi.block.BlockEncodingSerde;
import com.facebook.presto.spi.connector.ConnectorFactory;
import com.facebook.presto.spi.eventlistener.EventListenerFactory;
import com.facebook.presto.spi.resourceGroups.ResourceGroupConfigurationManagerFactory;
import com.facebook.presto.spi.security.SystemAccessControlFactory;
import com.facebook.presto.spi.type.ParametricType;
import com.facebook.presto.spi.type.Type;
import java.util.Set;
import static java.util.Collections.emptyList;
import static java.util.Collections.emptySet;
public interface Plugin
{
default Iterable<ConnectorFactory> getConnectorFactories()
{
return emptyList();
}
default Iterable<BlockEncodingFactory<?>> getBlockEncodingFactories(BlockEncodingSerde serde)
{
return emptyList();
}
default Iterable<Type> getTypes()
{
return emptyList();
}
default Iterable<ParametricType> getParametricTypes()
{
return emptyList();
}
default Set<Class<?>> getFunctions()
{
return emptySet();
}
default Iterable<SystemAccessControlFactory> getSystemAccessControlFactories()
{
return emptyList();
}
default Iterable<EventListenerFactory> getEventListenerFactories()
{
return emptyList();
}
default Iterable<ResourceGroupConfigurationManagerFactory> getResourceGroupConfigurationManagerFactories()
{
return emptyList();
}
}
| apache-2.0 |
rokn/Count_Words_2015 | testing/openjdk/jdk/test/sun/security/provider/MessageDigest/TestSHAClone.java | 2384 | /*
* Copyright (c) 2002, 2003, 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 4775971
* @summary test the clone implementation of SHA, SHA-256,
* SHA-384, SHA-512 MessageDigest implementation.
*/
import java.security.*;
import java.util.*;
public class TestSHAClone {
private static final String[] ALGOS = {
"SHA", "SHA-256", "SHA-512", "SHA-384"
};
private static byte[] input1 = {
(byte)0x1, (byte)0x2, (byte)0x3
};
private static byte[] input2 = {
(byte)0x4, (byte)0x5, (byte)0x6
};
private MessageDigest md;
private TestSHAClone(String algo, Provider p) throws Exception {
md = MessageDigest.getInstance(algo, p);
}
private void run() throws Exception {
md.update(input1);
MessageDigest md2 = (MessageDigest) md.clone();
md.update(input2);
md2.update(input2);
if (!Arrays.equals(md.digest(), md2.digest())) {
throw new Exception(md.getAlgorithm() + ": comparison failed");
} else {
System.out.println(md.getAlgorithm() + ": passed");
}
}
public static void main(String[] argv) throws Exception {
Provider p = Security.getProvider("SUN");
for (int i=0; i<ALGOS.length; i++) {
TestSHAClone test = new TestSHAClone(ALGOS[i], p);
test.run();
}
}
}
| mit |
GlenRSmith/elasticsearch | server/src/main/java/org/elasticsearch/common/NamedRegistry.java | 1595 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.common;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import static java.util.Objects.requireNonNull;
/**
* A registry from String to some class implementation. Used to ensure implementations are registered only once.
*/
public class NamedRegistry<T> {
private final Map<String, T> registry = new HashMap<>();
private final String targetName;
public NamedRegistry(String targetName) {
this.targetName = targetName;
}
public Map<String, T> getRegistry() {
return registry;
}
public void register(String name, T t) {
requireNonNull(name, "name is required");
requireNonNull(t, targetName + " is required");
if (registry.putIfAbsent(name, t) != null) {
throw new IllegalArgumentException(targetName + " for name [" + name + "] already registered");
}
}
public <P> void extractAndRegister(List<P> plugins, Function<P, Map<String, T>> lookup) {
for (P plugin : plugins) {
for (Map.Entry<String, T> entry : lookup.apply(plugin).entrySet()) {
register(entry.getKey(), entry.getValue());
}
}
}
}
| apache-2.0 |
rokn/Count_Words_2015 | testing/openjdk2/jdk/src/windows/classes/sun/nio/ch/PendingIoCache.java | 5473 | /*
* Copyright (c) 2008, 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. 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 sun.nio.ch;
import java.nio.channels.*;
import java.util.*;
import sun.misc.Unsafe;
/**
* Maintains a mapping of pending I/O requests (identified by the address of
* an OVERLAPPED structure) to Futures.
*/
class PendingIoCache {
private static final Unsafe unsafe = Unsafe.getUnsafe();
private static final int addressSize = unsafe.addressSize();
private static int dependsArch(int value32, int value64) {
return (addressSize == 4) ? value32 : value64;
}
/*
* typedef struct _OVERLAPPED {
* DWORD Internal;
* DWORD InternalHigh;
* DWORD Offset;
* DWORD OffsetHigh;
* HANDLE hEvent;
* } OVERLAPPED;
*/
private static final int SIZEOF_OVERLAPPED = dependsArch(20, 32);
// set to true when closed
private boolean closed;
// set to true when thread is waiting for all I/O operations to complete
private boolean closePending;
// maps OVERLAPPED to PendingFuture
@SuppressWarnings("rawtypes")
private final Map<Long,PendingFuture> pendingIoMap =
new HashMap<Long,PendingFuture>();
// per-channel cache of OVERLAPPED structures
private long[] overlappedCache = new long[4];
private int overlappedCacheCount = 0;
PendingIoCache() {
}
long add(PendingFuture<?,?> result) {
synchronized (this) {
if (closed)
throw new AssertionError("Should not get here");
long ov;
if (overlappedCacheCount > 0) {
ov = overlappedCache[--overlappedCacheCount];
} else {
ov = unsafe.allocateMemory(SIZEOF_OVERLAPPED);
}
pendingIoMap.put(ov, result);
return ov;
}
}
@SuppressWarnings("unchecked")
<V,A> PendingFuture<V,A> remove(long overlapped) {
synchronized (this) {
PendingFuture<V,A> res = pendingIoMap.remove(overlapped);
if (res != null) {
if (overlappedCacheCount < overlappedCache.length) {
overlappedCache[overlappedCacheCount++] = overlapped;
} else {
// cache full or channel closing
unsafe.freeMemory(overlapped);
}
// notify closing thread.
if (closePending) {
this.notifyAll();
}
}
return res;
}
}
void close() {
synchronized (this) {
if (closed)
return;
// handle case where I/O operations that have not completed.
if (!pendingIoMap.isEmpty())
clearPendingIoMap();
// release memory for any cached OVERLAPPED structures
while (overlappedCacheCount > 0) {
unsafe.freeMemory( overlappedCache[--overlappedCacheCount] );
}
// done
closed = true;
}
}
private void clearPendingIoMap() {
assert Thread.holdsLock(this);
// wait up to 50ms for the I/O operations to complete
closePending = true;
try {
this.wait(50);
} catch (InterruptedException x) {
Thread.currentThread().interrupt();
}
closePending = false;
if (pendingIoMap.isEmpty())
return;
// cause all pending I/O operations to fail
// simulate the failure of all pending I/O operations.
for (Long ov: pendingIoMap.keySet()) {
PendingFuture<?,?> result = pendingIoMap.get(ov);
assert !result.isDone();
// make I/O port aware of the stale OVERLAPPED structure
Iocp iocp = (Iocp)((Groupable)result.channel()).group();
iocp.makeStale(ov);
// execute a task that invokes the result handler's failed method
final Iocp.ResultHandler rh = (Iocp.ResultHandler)result.getContext();
Runnable task = new Runnable() {
public void run() {
rh.failed(-1, new AsynchronousCloseException());
}
};
iocp.executeOnPooledThread(task);
}
pendingIoMap.clear();
}
}
| mit |
carlesls2/sitappandroidv1 | prova/facebook/src/com/facebook/internal/PermissionType.java | 1426 | /**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
* copy, modify, and distribute this software in source code or binary form for use
* in connection with the web services and APIs provided by Facebook.
*
* As with any software that integrates with the Facebook platform, your use of
* this software is subject to the Facebook Developer Principles and Policies
* [http://developers.facebook.com/policy/]. This copyright notice shall be
* included in all copies or substantial portions of the software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.facebook.internal;
/**
* com.facebook.internal is solely for the use of other packages within the Facebook SDK for
* Android. Use of any of the classes in this package is unsupported, and they may be modified or
* removed without warning at any time.
*/
public enum PermissionType {
READ,
PUBLISH
}
| lgpl-3.0 |
immortius/Terasology | engine/src/main/java/org/terasology/engine/module/ModuleExtension.java | 723 | /*
* Copyright 2015 MovingBlocks
*
* 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.terasology.engine.module;
public interface ModuleExtension {
String getKey();
Class<?> getValueType();
}
| apache-2.0 |
charlesmunger/robolectric | robolectric/src/test/java/org/robolectric/shadows/ShadowMediaPlayerTest.java | 49165 | package org.robolectric.shadows;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import org.assertj.core.api.Assertions;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.robolectric.Robolectric;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.TestRunners;
import org.robolectric.internal.Shadow;
import org.robolectric.shadows.ShadowMediaPlayer.InvalidStateBehavior;
import org.robolectric.shadows.ShadowMediaPlayer.MediaEvent;
import org.robolectric.shadows.ShadowMediaPlayer.MediaInfo;
import org.robolectric.shadows.ShadowMediaPlayer.State;
import org.robolectric.shadows.util.DataSource;
import org.robolectric.util.ReflectionHelpers;
import org.robolectric.util.Scheduler;
import static org.assertj.core.api.Assertions.assertThat;
import static org.robolectric.Shadows.shadowOf;
import static org.robolectric.shadows.ShadowMediaPlayer.addException;
import static org.robolectric.shadows.ShadowMediaPlayer.State.*;
import static org.robolectric.shadows.util.DataSource.toDataSource;
@RunWith(TestRunners.MultiApiWithDefaults.class)
public class ShadowMediaPlayerTest {
private static final String DUMMY_SOURCE = "dummy-source";
private MediaPlayer mediaPlayer;
private ShadowMediaPlayer shadowMediaPlayer;
private MediaPlayer.OnCompletionListener completionListener;
private MediaPlayer.OnErrorListener errorListener;
private MediaPlayer.OnInfoListener infoListener;
private MediaPlayer.OnPreparedListener preparedListener;
private MediaPlayer.OnSeekCompleteListener seekListener;
private Scheduler scheduler;
private MediaInfo info;
private DataSource defaultSource;
@Before
public void setUp() {
mediaPlayer = Shadow.newInstanceOf(MediaPlayer.class);
shadowMediaPlayer = shadowOf(mediaPlayer);
completionListener = Mockito.mock(MediaPlayer.OnCompletionListener.class);
mediaPlayer.setOnCompletionListener(completionListener);
preparedListener = Mockito.mock(MediaPlayer.OnPreparedListener.class);
mediaPlayer.setOnPreparedListener(preparedListener);
errorListener = Mockito.mock(MediaPlayer.OnErrorListener.class);
mediaPlayer.setOnErrorListener(errorListener);
infoListener = Mockito.mock(MediaPlayer.OnInfoListener.class);
mediaPlayer.setOnInfoListener(infoListener);
seekListener = Mockito.mock(MediaPlayer.OnSeekCompleteListener.class);
mediaPlayer.setOnSeekCompleteListener(seekListener);
// Scheduler is used in many of the tests to simulate
// moving forward in time.
scheduler = Robolectric.getForegroundThreadScheduler();
scheduler.pause();
defaultSource = toDataSource(DUMMY_SOURCE);
info = new MediaInfo();
ShadowMediaPlayer.addMediaInfo(defaultSource, info);
shadowMediaPlayer.doSetDataSource(defaultSource);
}
@Test
public void testInitialState() {
assertThat(shadowMediaPlayer.getState()).isEqualTo(IDLE);
}
@Test
public void testCreateListener() {
ShadowMediaPlayer.CreateListener createListener = Mockito
.mock(ShadowMediaPlayer.CreateListener.class);
ShadowMediaPlayer.setCreateListener(createListener);
MediaPlayer newPlayer = new MediaPlayer();
ShadowMediaPlayer shadow = shadowOf(newPlayer);
Mockito.verify(createListener).onCreate(newPlayer, shadow);
}
@Test
public void testResetResetsPosition() {
shadowMediaPlayer.setCurrentPosition(300);
mediaPlayer.reset();
assertThat(shadowMediaPlayer.getCurrentPositionRaw())
.isEqualTo(0);
}
@Test
public void testPrepare() throws IOException {
int[] testDelays = { 0, 10, 100, 1500 };
for (int delay : testDelays) {
final long startTime = scheduler.getCurrentTime();
info.setPreparationDelay(delay);
shadowMediaPlayer.setState(INITIALIZED);
mediaPlayer.prepare();
assertThat(shadowMediaPlayer.getState()).isEqualTo(PREPARED);
assertThat(scheduler.getCurrentTime()).isEqualTo(startTime + delay);
}
}
@Test
public void testSetDataSourceString() throws IOException {
DataSource ds = toDataSource("dummy");
ShadowMediaPlayer.addMediaInfo(ds, info);
mediaPlayer.setDataSource("dummy");
assertThat(shadowMediaPlayer.getDataSource()).as("dataSource").isEqualTo(ds);
}
@Test
public void testSetDataSourceUri() throws IOException {
Map<String, String> headers = new HashMap<>();
Uri uri = Uri.parse("file:/test");
DataSource ds = toDataSource(RuntimeEnvironment.application, uri, headers);
ShadowMediaPlayer.addMediaInfo(ds, info);
mediaPlayer.setDataSource(RuntimeEnvironment.application, uri, headers);
assertThat(shadowMediaPlayer.getSourceUri()).as("sourceUri").isSameAs(uri);
assertThat(shadowMediaPlayer.getDataSource()).as("dataSource").isEqualTo(ds);
}
@Test
public void testSetDataSourceFD() throws IOException {
File tmpFile = File.createTempFile("MediaPlayerTest", null);
try {
tmpFile.deleteOnExit();
FileInputStream is = new FileInputStream(tmpFile);
try {
FileDescriptor fd = is.getFD();
DataSource ds = toDataSource(fd, 23, 524);
ShadowMediaPlayer.addMediaInfo(ds, info);
mediaPlayer.setDataSource(fd, 23, 524);
assertThat(shadowMediaPlayer.getSourceUri()).as("sourceUri").isNull();
assertThat(shadowMediaPlayer.getDataSource()).as("dataSource")
.isEqualTo(ds);
} finally {
is.close();
}
} finally {
tmpFile.delete();
}
}
@Test
public void testPrepareAsyncAutoCallback() {
mediaPlayer.setOnPreparedListener(preparedListener);
int[] testDelays = { 0, 10, 100, 1500 };
for (int delay : testDelays) {
info.setPreparationDelay(delay);
shadowMediaPlayer.setState(INITIALIZED);
final long startTime = scheduler.getCurrentTime();
mediaPlayer.prepareAsync();
assertThat(shadowMediaPlayer.getState()).isEqualTo(PREPARING);
Mockito.verifyZeroInteractions(preparedListener);
scheduler.advanceToLastPostedRunnable();
assertThat(scheduler.getCurrentTime()).as("currentTime").isEqualTo(
startTime + delay);
assertThat(shadowMediaPlayer.getState()).isEqualTo(PREPARED);
Mockito.verify(preparedListener).onPrepared(mediaPlayer);
Mockito.verifyNoMoreInteractions(preparedListener);
Mockito.reset(preparedListener);
}
}
@Test
public void testPrepareAsyncManualCallback() {
mediaPlayer.setOnPreparedListener(preparedListener);
info.setPreparationDelay(-1);
shadowMediaPlayer.setState(INITIALIZED);
final long startTime = scheduler.getCurrentTime();
mediaPlayer.prepareAsync();
assertThat(scheduler.getCurrentTime()).as("currentTime").isEqualTo(
startTime);
assertThat(shadowMediaPlayer.getState()).isSameAs(PREPARING);
Mockito.verifyZeroInteractions(preparedListener);
shadowMediaPlayer.invokePreparedListener();
assertThat(shadowMediaPlayer.getState()).isSameAs(PREPARED);
Mockito.verify(preparedListener).onPrepared(mediaPlayer);
Mockito.verifyNoMoreInteractions(preparedListener);
}
@Test
public void testDefaultPreparationDelay() {
assertThat(info.getPreparationDelay())
.as("preparationDelay").isEqualTo(0);
}
@Test
public void testIsPlaying() {
EnumSet<State> nonPlayingStates = EnumSet.of(IDLE, INITIALIZED, PREPARED,
PAUSED, STOPPED, PLAYBACK_COMPLETED);
for (State state : nonPlayingStates) {
shadowMediaPlayer.setState(state);
assertThat(mediaPlayer.isPlaying()).overridingErrorMessage(
"In state <%s>, expected isPlaying() to be false", state).isFalse();
}
shadowMediaPlayer.setState(STARTED);
assertThat(mediaPlayer.isPlaying()).overridingErrorMessage(
"In state <STARTED>, expected isPlaying() to be true").isTrue();
}
@Test
public void testIsPrepared() {
EnumSet<State> prepStates = EnumSet.of(PREPARED, STARTED, PAUSED,
PLAYBACK_COMPLETED);
for (State state : State.values()) {
shadowMediaPlayer.setState(state);
if (prepStates.contains(state)) {
assertThat(shadowMediaPlayer.isPrepared()).overridingErrorMessage(
"In state <%s>, expected isPrepared() to be true", state).isTrue();
} else {
assertThat(shadowMediaPlayer.isPrepared()).overridingErrorMessage(
"In state <%s>, expected isPrepared() to be false", state)
.isFalse();
}
}
}
@Test
public void testPlaybackProgress() {
shadowMediaPlayer.setState(PREPARED);
// This time offset is just to make sure that it doesn't work by
// accident because the offsets are calculated relative to 0.
scheduler.advanceBy(100);
mediaPlayer.start();
assertThat(shadowMediaPlayer.getCurrentPosition()).isEqualTo(0);
assertThat(shadowMediaPlayer.getState()).isEqualTo(STARTED);
scheduler.advanceBy(500);
assertThat(shadowMediaPlayer.getCurrentPosition()).isEqualTo(500);
assertThat(shadowMediaPlayer.getState()).isEqualTo(STARTED);
scheduler.advanceBy(499);
assertThat(shadowMediaPlayer.getCurrentPosition()).isEqualTo(999);
assertThat(shadowMediaPlayer.getState()).isEqualTo(STARTED);
Mockito.verifyZeroInteractions(completionListener);
scheduler.advanceBy(1);
assertThat(shadowMediaPlayer.getCurrentPosition()).isEqualTo(1000);
assertThat(shadowMediaPlayer.getState()).isEqualTo(PLAYBACK_COMPLETED);
Mockito.verify(completionListener).onCompletion(mediaPlayer);
Mockito.verifyNoMoreInteractions(completionListener);
scheduler.advanceBy(1);
assertThat(shadowMediaPlayer.getCurrentPosition()).isEqualTo(1000);
assertThat(shadowMediaPlayer.getState()).isEqualTo(PLAYBACK_COMPLETED);
Mockito.verifyZeroInteractions(completionListener);
}
@Test
public void testStop() {
shadowMediaPlayer.setState(PREPARED);
mediaPlayer.start();
scheduler.advanceBy(300);
mediaPlayer.stop();
assertThat(mediaPlayer.getCurrentPosition()).isEqualTo(300);
scheduler.advanceBy(400);
assertThat(mediaPlayer.getCurrentPosition()).isEqualTo(300);
}
@Test
public void testPauseReschedulesCompletionCallback() {
shadowMediaPlayer.setState(PREPARED);
mediaPlayer.start();
scheduler.advanceBy(200);
mediaPlayer.pause();
scheduler.advanceBy(800);
Mockito.verifyZeroInteractions(completionListener);
mediaPlayer.start();
scheduler.advanceBy(799);
Mockito.verifyZeroInteractions(completionListener);
scheduler.advanceBy(1);
Mockito.verify(completionListener).onCompletion(mediaPlayer);
Mockito.verifyNoMoreInteractions(completionListener);
assertThat(scheduler.advanceToLastPostedRunnable()).isFalse();
Mockito.verifyZeroInteractions(completionListener);
}
@Test
public void testPauseUpdatesPosition() {
shadowMediaPlayer.setState(PREPARED);
mediaPlayer.start();
scheduler.advanceBy(200);
mediaPlayer.pause();
scheduler.advanceBy(200);
assertThat(shadowMediaPlayer.getState()).isEqualTo(PAUSED);
assertThat(shadowMediaPlayer.getCurrentPosition()).isEqualTo(200);
mediaPlayer.start();
scheduler.advanceBy(200);
assertThat(shadowMediaPlayer.getState()).isEqualTo(STARTED);
assertThat(shadowMediaPlayer.getCurrentPosition()).isEqualTo(400);
}
@Test
public void testSeekDuringPlaybackReschedulesCompletionCallback() {
shadowMediaPlayer.setState(PREPARED);
mediaPlayer.start();
scheduler.advanceBy(300);
mediaPlayer.seekTo(400);
scheduler.advanceBy(599);
Mockito.verifyZeroInteractions(completionListener);
scheduler.advanceBy(1);
Mockito.verify(completionListener).onCompletion(mediaPlayer);
Mockito.verifyNoMoreInteractions(completionListener);
assertThat(shadowMediaPlayer.getState()).isEqualTo(PLAYBACK_COMPLETED);
assertThat(scheduler.advanceToLastPostedRunnable()).isFalse();
Mockito.verifyZeroInteractions(completionListener);
}
@Test
public void testSeekDuringPlaybackUpdatesPosition() {
shadowMediaPlayer.setState(PREPARED);
// This time offset is just to make sure that it doesn't work by
// accident because the offsets are calculated relative to 0.
scheduler.advanceBy(100);
mediaPlayer.start();
scheduler.advanceBy(400);
assertThat(mediaPlayer.getCurrentPosition()).isEqualTo(400);
mediaPlayer.seekTo(600);
scheduler.advanceBy(0);
assertThat(mediaPlayer.getCurrentPosition()).isEqualTo(600);
scheduler.advanceBy(300);
assertThat(mediaPlayer.getCurrentPosition()).isEqualTo(900);
mediaPlayer.seekTo(100);
scheduler.advanceBy(0);
assertThat(mediaPlayer.getCurrentPosition()).isEqualTo(100);
scheduler.advanceBy(900);
assertThat(mediaPlayer.getCurrentPosition()).isEqualTo(1000);
assertThat(shadowMediaPlayer.getState()).isEqualTo(PLAYBACK_COMPLETED);
scheduler.advanceBy(100);
assertThat(mediaPlayer.getCurrentPosition()).isEqualTo(1000);
}
@Test
public void testPendingEventsRemovedOnError() {
Mockito.when(errorListener.onError(mediaPlayer, 2, 3)).thenReturn(true);
shadowMediaPlayer.setState(PREPARED);
mediaPlayer.start();
scheduler.advanceBy(200);
// We should have a pending completion callback.
assertThat(scheduler.size()).isEqualTo(1);
shadowMediaPlayer.invokeErrorListener(2, 3);
assertThat(scheduler.advanceToLastPostedRunnable()).isFalse();
Mockito.verifyZeroInteractions(completionListener);
}
@Test
public void testAttachAuxEffectStates() {
testStates(new MethodSpec("attachAuxEffect", 37), EnumSet.of(IDLE, ERROR),
onErrorTester, null);
}
private static final EnumSet<State> emptyStateSet = EnumSet
.noneOf(State.class);
@Test
public void testGetAudioSessionIdStates() {
testStates("getAudioSessionId", emptyStateSet, onErrorTester, null);
}
@Test
public void testGetCurrentPositionStates() {
testStates("getCurrentPosition", EnumSet.of(IDLE, ERROR), onErrorTester,
null);
}
@Test
public void testGetDurationStates() {
testStates("getDuration", EnumSet.of(IDLE, INITIALIZED, ERROR),
onErrorTester, null);
}
@Test
public void testGetVideoHeightAndWidthStates() {
testStates("getVideoHeight", EnumSet.of(IDLE, ERROR), logTester, null);
testStates("getVideoWidth", EnumSet.of(IDLE, ERROR), logTester, null);
}
@Test
public void testIsLoopingStates() {
// isLooping is quite unique as it throws ISE when in END state,
// even though every other state is legal.
testStates("isLooping", EnumSet.of(END), iseTester, null);
}
@Test
public void testIsPlayingStates() {
testStates("isPlaying", EnumSet.of(ERROR), onErrorTester, null);
}
@Test
public void testPauseStates() {
testStates("pause",
EnumSet.of(IDLE, INITIALIZED, PREPARED, STOPPED, ERROR), onErrorTester,
PAUSED);
}
@Test
public void testPrepareStates() {
testStates("prepare",
EnumSet.of(IDLE, PREPARED, STARTED, PAUSED, PLAYBACK_COMPLETED, ERROR),
PREPARED);
}
@Test
public void testPrepareAsyncStates() {
testStates("prepareAsync",
EnumSet.of(IDLE, PREPARED, STARTED, PAUSED, PLAYBACK_COMPLETED, ERROR),
PREPARING);
}
@Test
public void testReleaseStates() {
testStates("release", emptyStateSet, END);
}
@Test
public void testResetStates() {
testStates("reset", EnumSet.of(END), IDLE);
}
@Test
public void testSeekToStates() {
testStates(new MethodSpec("seekTo", 38),
EnumSet.of(IDLE, INITIALIZED, STOPPED, ERROR), onErrorTester, null);
}
@Test
public void testSetAudioSessionIdStates() {
testStates(new MethodSpec("setAudioSessionId", 40), EnumSet.of(INITIALIZED,
PREPARED, STARTED, PAUSED, STOPPED, PLAYBACK_COMPLETED, ERROR),
onErrorTester, null);
}
// NOTE: This test diverges from the spec in the MediaPlayer
// doc, which says that setAudioStreamType() is valid to call
// from any state other than ERROR. It mentions that
// unless you call it before prepare it won't be effective.
// However, by inspection I found that it actually calls onError
// and moves into the ERROR state unless invoked from IDLE state,
// so that is what I have emulated.
@Test
public void testSetAudioStreamTypeStates() {
testStates(new MethodSpec("setAudioStreamType", AudioManager.STREAM_MUSIC),
EnumSet.of(PREPARED, STARTED, PAUSED, PLAYBACK_COMPLETED, ERROR),
onErrorTester, null);
}
@Test
public void testSetLoopingStates() {
testStates(new MethodSpec("setLooping", true), EnumSet.of(ERROR),
onErrorTester, null);
}
@Test
public void testSetVolumeStates() {
testStates(new MethodSpec("setVolume", new Class<?>[] { float.class,
float.class }, new Object[] { 1.0f, 1.0f }), EnumSet.of(ERROR),
onErrorTester, null);
}
@Test
public void testSetDataSourceStates() {
final EnumSet<State> invalidStates = EnumSet.of(INITIALIZED, PREPARED,
STARTED, PAUSED, PLAYBACK_COMPLETED, STOPPED, ERROR);
testStates(new MethodSpec("setDataSource", DUMMY_SOURCE), invalidStates, iseTester, INITIALIZED);
}
@Test
public void testStartStates() {
testStates("start",
EnumSet.of(IDLE, INITIALIZED, PREPARING, STOPPED, ERROR),
onErrorTester, STARTED);
}
@Test
public void testStopStates() {
testStates("stop", EnumSet.of(IDLE, INITIALIZED, ERROR), onErrorTester,
STOPPED);
}
@Test
public void testCurrentPosition() {
int[] positions = { 0, 1, 2, 1024 };
for (int position : positions) {
shadowMediaPlayer.setCurrentPosition(position);
assertThat(mediaPlayer.getCurrentPosition()).isEqualTo(position);
}
}
@Test
public void testInitialAudioSessionIdIsNotZero() {
assertThat(mediaPlayer.getAudioSessionId()).as("initial audioSessionId")
.isNotEqualTo(0);
}
private Tester onErrorTester = new OnErrorTester(-38, 0);
private Tester iseTester = new ExceptionTester(IllegalStateException.class);
private Tester logTester = new LogTester(null);
private Tester assertTester = new ExceptionTester(AssertionError.class);
private void testStates(String methodName, EnumSet<State> invalidStates,
State nextState) {
testStates(new MethodSpec(methodName), invalidStates, iseTester, nextState);
}
public class MethodSpec {
public Method method;
// public String method;
public Class<?>[] argTypes;
public Object[] args;
public MethodSpec(String method) {
this(method, (Class<?>[]) null, (Object[]) null);
}
public MethodSpec(String method, Class<?>[] argTypes, Object[] args) {
try {
this.method = MediaPlayer.class.getDeclaredMethod(method, argTypes);
this.args = args;
} catch (NoSuchMethodException e) {
throw new AssertionError("Method lookup failed: " + method, e);
}
}
public MethodSpec(String method, int arg) {
this(method, new Class<?>[] { int.class }, new Object[] { arg });
}
public MethodSpec(String method, boolean arg) {
this(method, new Class<?>[] { boolean.class }, new Object[] { arg });
}
public MethodSpec(String method, Class<?> c) {
this(method, new Class<?>[] { c }, new Object[] { null });
}
public MethodSpec(String method, Object o) {
this(method, new Class<?>[] { o.getClass() }, new Object[] { o });
}
public <T> MethodSpec(String method, T o, Class<T> c) {
this(method, new Class<?>[] { c }, new Object[] { o });
}
public void invoke() throws InvocationTargetException {
try {
method.invoke(mediaPlayer, args);
} catch (IllegalAccessException e) {
throw new AssertionError(e);
}
}
public String toString() {
return method.toString();
}
}
private void testStates(String method, EnumSet<State> invalidStates,
Tester tester, State next) {
testStates(new MethodSpec(method), invalidStates, tester, next);
}
private void testStates(MethodSpec method, EnumSet<State> invalidStates,
Tester tester, State next) {
final EnumSet<State> invalid = EnumSet.copyOf(invalidStates);
// The documentation specifies that the behavior of calling any
// function while in the PREPARING state is undefined. I tried
// to play it safe but reasonable, by looking at whether the PREPARED or
// INITIALIZED are allowed (ie, the two states that PREPARING
// sites between). Only if both these states are allowed is
// PREPARING allowed too, if either PREPARED or INITALIZED is
// disallowed then so is PREPARING.
if (invalid.contains(PREPARED) || invalid.contains(INITIALIZED)) {
invalid.add(PREPARING);
}
shadowMediaPlayer.setInvalidStateBehavior(InvalidStateBehavior.SILENT);
for (State state : State.values()) {
shadowMediaPlayer.setState(state);
testMethodSuccess(method, next);
}
shadowMediaPlayer.setInvalidStateBehavior(InvalidStateBehavior.EMULATE);
for (State state : invalid) {
shadowMediaPlayer.setState(state);
tester.test(method);
}
for (State state : EnumSet.complementOf(invalid)) {
if (state == END) {
continue;
}
shadowMediaPlayer.setState(state);
testMethodSuccess(method, next);
}
// END state: by inspection we determined that if a method
// doesn't raise any kind of error in any other state then neither
// will it raise one in the END state; however if it raises errors
// in other states of any kind then it will throw
// IllegalArgumentException when in END.
shadowMediaPlayer.setState(END);
if (invalid.isEmpty()) {
testMethodSuccess(method, END);
} else {
iseTester.test(method);
}
shadowMediaPlayer.setInvalidStateBehavior(InvalidStateBehavior.ASSERT);
for (State state : invalid) {
shadowMediaPlayer.setState(state);
assertTester.test(method);
}
for (State state : EnumSet.complementOf(invalid)) {
if (state == END) {
continue;
}
shadowMediaPlayer.setState(state);
testMethodSuccess(method, next);
}
shadowMediaPlayer.setState(END);
if (invalid.isEmpty()) {
testMethodSuccess(method, END);
} else {
assertTester.test(method);
}
}
private interface Tester {
public void test(MethodSpec method);
}
private class OnErrorTester implements Tester {
private int what;
private int extra;
public OnErrorTester(int what, int extra) {
this.what = what;
this.extra = extra;
}
public void test(MethodSpec method) {
final State state = shadowMediaPlayer.getState();
final boolean wasPaused = scheduler.isPaused();
scheduler.pause();
try {
method.invoke();
} catch (InvocationTargetException e) {
Assertions.fail("Expected <" + method
+ "> to call onError rather than throw <" + e.getTargetException()
+ "> when called from <" + state + ">", e);
}
Mockito.verifyZeroInteractions(errorListener);
final State finalState = shadowMediaPlayer.getState();
assertThat(finalState)
.overridingErrorMessage(
"Expected state to change to ERROR when <%s> called from state <%s>, was <%s>",
method, state, finalState).isSameAs(ERROR);
scheduler.unPause();
Mockito.verify(errorListener).onError(mediaPlayer, what, extra);
Mockito.reset(errorListener);
if (wasPaused) {
scheduler.pause();
}
}
}
private class ExceptionTester implements Tester {
private Class<? extends Throwable> eClass;
public ExceptionTester(Class<? extends Throwable> eClass) {
this.eClass = eClass;
}
public void test(MethodSpec method) {
final State state = shadowMediaPlayer.getState();
boolean success = false;
try {
method.invoke();
success = true;
} catch (InvocationTargetException e) {
Throwable cause = e.getTargetException();
assertThat(cause)
.overridingErrorMessage(
"Unexpected exception <%s> thrown when <%s> called from state <%s>, expecting <%s>",
cause, method, state, eClass).isInstanceOf(eClass);
final State finalState = shadowMediaPlayer.getState();
assertThat(finalState)
.overridingErrorMessage(
"Expected player to remain in <%s> state when <%s> called, was <%s>",
state, method, finalState).isSameAs(state);
}
assertThat(success)
.overridingErrorMessage(
"No exception thrown, expected <%s> when <%s> called from state <%s>",
eClass, method, state).isFalse();
}
}
private class LogTester implements Tester {
private State next;
public LogTester(State next) {
this.next = next;
}
public void test(MethodSpec method) {
testMethodSuccess(method, next);
}
}
private void testMethodSuccess(MethodSpec method, State next) {
final State state = shadowMediaPlayer.getState();
try {
method.invoke();
final State finalState = shadowMediaPlayer.getState();
if (next == null) {
assertThat(finalState)
.overridingErrorMessage(
"Expected state <%s> to remain unchanged when <%s> called, was <%s>",
state, method, finalState).isEqualTo(state);
} else {
assertThat(finalState).overridingErrorMessage(
"Expected <%s> to change state from <%s> to <%s>, was <%s>",
method, state, next, finalState).isEqualTo(next);
}
} catch (InvocationTargetException e) {
Throwable cause = e.getTargetException();
Assertions
.fail("<" + method + "> should not throw exception when in state <"
+ state + ">", cause);
}
}
private static final State[] seekableStates = { PREPARED, PAUSED,
PLAYBACK_COMPLETED, STARTED };
// It is not 100% clear from the docs if seeking to < 0 should
// invoke an error. I have assumed from the documentation
// which says "Successful invoke of this method in a valid
// state does not change the state" that it doesn't invoke an
// error. Rounding the seek up to 0 seems to be the sensible
// alternative behavior.
@Test
public void testSeekBeforeStart() {
shadowMediaPlayer.setSeekDelay(-1);
for (State state : seekableStates) {
shadowMediaPlayer.setState(state);
shadowMediaPlayer.setCurrentPosition(500);
mediaPlayer.seekTo(-1);
shadowMediaPlayer.invokeSeekCompleteListener();
assertThat(mediaPlayer.getCurrentPosition()).as(
"Current postion while " + state).isEqualTo(0);
assertThat(shadowMediaPlayer.getState()).as("Final state " + state)
.isEqualTo(state);
}
}
// Similar comments apply to this test as to
// testSeekBeforeStart().
@Test
public void testSeekPastEnd() {
shadowMediaPlayer.setSeekDelay(-1);
for (State state : seekableStates) {
shadowMediaPlayer.setState(state);
shadowMediaPlayer.setCurrentPosition(500);
mediaPlayer.seekTo(1001);
shadowMediaPlayer.invokeSeekCompleteListener();
assertThat(mediaPlayer.getCurrentPosition()).as(
"Current postion while " + state).isEqualTo(1000);
assertThat(shadowMediaPlayer.getState()).as("Final state " + state)
.isEqualTo(state);
}
}
@Test
public void testCompletionListener() {
shadowMediaPlayer.invokeCompletionListener();
Mockito.verify(completionListener).onCompletion(mediaPlayer);
}
@Test
public void testCompletionWithoutListenerDoesNotThrowException() {
mediaPlayer.setOnCompletionListener(null);
shadowMediaPlayer.invokeCompletionListener();
assertThat(shadowMediaPlayer.getState()).isEqualTo(PLAYBACK_COMPLETED);
Mockito.verifyZeroInteractions(completionListener);
}
@Test
public void testSeekListener() {
shadowMediaPlayer.invokeSeekCompleteListener();
Mockito.verify(seekListener).onSeekComplete(mediaPlayer);
}
@Test
public void testSeekWithoutListenerDoesNotThrowException() {
mediaPlayer.setOnSeekCompleteListener(null);
shadowMediaPlayer.invokeSeekCompleteListener();
Mockito.verifyZeroInteractions(seekListener);
}
@Test
public void testSeekDuringPlaybackDelayedCallback() {
shadowMediaPlayer.setState(PREPARED);
shadowMediaPlayer.setSeekDelay(100);
assertThat(shadowMediaPlayer.getSeekDelay()).isEqualTo(100);
mediaPlayer.start();
scheduler.advanceBy(200);
assertThat(mediaPlayer.getCurrentPosition()).isEqualTo(200);
mediaPlayer.seekTo(450);
assertThat(mediaPlayer.getCurrentPosition()).isEqualTo(200);
scheduler.advanceBy(99);
assertThat(mediaPlayer.getCurrentPosition()).isEqualTo(200);
Mockito.verifyZeroInteractions(seekListener);
scheduler.advanceBy(1);
assertThat(mediaPlayer.getCurrentPosition()).isEqualTo(450);
Mockito.verify(seekListener).onSeekComplete(mediaPlayer);
assertThat(scheduler.advanceToLastPostedRunnable()).isTrue();
Mockito.verifyNoMoreInteractions(seekListener);
}
@Test
public void testSeekWhilePausedDelayedCallback() {
shadowMediaPlayer.setState(PAUSED);
shadowMediaPlayer.setSeekDelay(100);
scheduler.advanceBy(200);
mediaPlayer.seekTo(450);
scheduler.advanceBy(99);
assertThat(mediaPlayer.getCurrentPosition()).isEqualTo(0);
Mockito.verifyZeroInteractions(seekListener);
scheduler.advanceBy(1);
assertThat(mediaPlayer.getCurrentPosition()).isEqualTo(450);
Mockito.verify(seekListener).onSeekComplete(mediaPlayer);
// Check that no completion callback or alternative
// seek callbacks have been scheduled.
assertThat(scheduler.advanceToLastPostedRunnable()).isFalse();
}
@Test
public void testSeekWhileSeekingWhilePaused() {
shadowMediaPlayer.setState(PAUSED);
shadowMediaPlayer.setSeekDelay(100);
scheduler.advanceBy(200);
mediaPlayer.seekTo(450);
scheduler.advanceBy(50);
mediaPlayer.seekTo(600);
scheduler.advanceBy(99);
assertThat(mediaPlayer.getCurrentPosition()).isEqualTo(0);
Mockito.verifyZeroInteractions(seekListener);
scheduler.advanceBy(1);
assertThat(mediaPlayer.getCurrentPosition()).isEqualTo(600);
Mockito.verify(seekListener).onSeekComplete(mediaPlayer);
// Check that no completion callback or alternative
// seek callbacks have been scheduled.
assertThat(scheduler.advanceToLastPostedRunnable()).isFalse();
}
@Test
public void testSeekWhileSeekingWhilePlaying() {
shadowMediaPlayer.setState(PREPARED);
shadowMediaPlayer.setSeekDelay(100);
final long startTime = scheduler.getCurrentTime();
mediaPlayer.start();
scheduler.advanceBy(200);
mediaPlayer.seekTo(450);
scheduler.advanceBy(50);
mediaPlayer.seekTo(600);
scheduler.advanceBy(99);
// Not sure of the correct behavior to emulate here, as the MediaPlayer
// documentation is not detailed enough. There are three possibilities:
// 1. Playback is paused for the entire time that a seek is in progress.
// 2. Playback continues normally until the seek is complete.
// 3. Somewhere between these two extremes - playback continues for
// a while and then pauses until the seek is complete.
// I have decided to emulate the first. I don't think that
// implementations should depend on any of these particular behaviors
// and consider the behavior indeterminate.
assertThat(mediaPlayer.getCurrentPosition()).isEqualTo(200);
Mockito.verifyZeroInteractions(seekListener);
scheduler.advanceBy(1);
assertThat(mediaPlayer.getCurrentPosition()).isEqualTo(600);
Mockito.verify(seekListener).onSeekComplete(mediaPlayer);
// Check that the completion callback is scheduled properly
// but no alternative seek callbacks.
assertThat(scheduler.advanceToLastPostedRunnable()).isTrue();
Mockito.verify(completionListener).onCompletion(mediaPlayer);
Mockito.verifyNoMoreInteractions(seekListener);
assertThat(scheduler.getCurrentTime()).isEqualTo(startTime + 750);
assertThat(mediaPlayer.getCurrentPosition()).isEqualTo(1000);
assertThat(shadowMediaPlayer.getState()).isEqualTo(PLAYBACK_COMPLETED);
}
@Test
public void testSimulatenousEventsAllRun() {
// Simultaneous events should all run even if
// one of them stops playback.
MediaEvent e1 = new MediaEvent() {
@Override
public void run(MediaPlayer mp, ShadowMediaPlayer smp) {
smp.doStop();
}
};
MediaEvent e2 = Mockito.mock(MediaEvent.class);
info.scheduleEventAtOffset(100, e1);
info.scheduleEventAtOffset(100, e2);
shadowMediaPlayer.setState(INITIALIZED);
shadowMediaPlayer.doStart();
scheduler.advanceBy(100);
// Verify that the first event ran
assertThat(shadowMediaPlayer.isReallyPlaying()).isFalse();
Mockito.verify(e2).run(mediaPlayer, shadowMediaPlayer);
}
@Test
public void testResetCancelsCallbacks() {
shadowMediaPlayer.setState(STARTED);
mediaPlayer.seekTo(100);
MediaEvent e = Mockito.mock(MediaEvent.class);
shadowMediaPlayer.postEventDelayed(e, 200);
mediaPlayer.reset();
assertThat(scheduler.size()).isEqualTo(0);
}
@Test
public void testReleaseCancelsSeekCallback() {
shadowMediaPlayer.setState(STARTED);
mediaPlayer.seekTo(100);
MediaEvent e = Mockito.mock(MediaEvent.class);
shadowMediaPlayer.postEventDelayed(e, 200);
mediaPlayer.release();
assertThat(scheduler.size()).isEqualTo(0);
}
@Test
public void testSeekManualCallback() {
// Need to put the player into a state where seeking is allowed
shadowMediaPlayer.setState(STARTED);
// seekDelay of -1 signifies that OnSeekComplete won't be
// invoked automatically by the shadow player itself.
shadowMediaPlayer.setSeekDelay(-1);
assertThat(shadowMediaPlayer.getPendingSeek()).as("pendingSeek before")
.isEqualTo(-1);
int[] positions = { 0, 5, 2, 999 };
int prevPos = 0;
for (int position : positions) {
mediaPlayer.seekTo(position);
assertThat(shadowMediaPlayer.getPendingSeek()).as("pendingSeek")
.isEqualTo(position);
assertThat(mediaPlayer.getCurrentPosition()).as("pendingSeekCurrentPos")
.isEqualTo(prevPos);
shadowMediaPlayer.invokeSeekCompleteListener();
assertThat(shadowMediaPlayer.getPendingSeek()).isEqualTo(-1);
assertThat(mediaPlayer.getCurrentPosition()).isEqualTo(position);
prevPos = position;
}
}
@Test
public void testPreparedListenerCalled() {
shadowMediaPlayer.invokePreparedListener();
assertThat(shadowMediaPlayer.getState()).isEqualTo(PREPARED);
Mockito.verify(preparedListener).onPrepared(mediaPlayer);
}
@Test
public void testPreparedWithoutListenerDoesNotThrowException() {
mediaPlayer.setOnPreparedListener(null);
shadowMediaPlayer.invokePreparedListener();
assertThat(shadowMediaPlayer.getState()).isEqualTo(PREPARED);
Mockito.verifyZeroInteractions(preparedListener);
}
@Test
public void testInfoListenerCalled() {
shadowMediaPlayer.invokeInfoListener(21, 32);
Mockito.verify(infoListener).onInfo(mediaPlayer, 21, 32);
}
@Test
public void testInfoWithoutListenerDoesNotThrowException() {
mediaPlayer.setOnInfoListener(null);
shadowMediaPlayer.invokeInfoListener(3, 44);
Mockito.verifyZeroInteractions(infoListener);
}
@Test
public void testErrorListenerCalledNoOnCompleteCalledWhenReturnTrue() {
Mockito.when(errorListener.onError(mediaPlayer, 112, 221)).thenReturn(true);
shadowMediaPlayer.invokeErrorListener(112, 221);
assertThat(shadowMediaPlayer.getState()).isEqualTo(ERROR);
Mockito.verify(errorListener).onError(mediaPlayer, 112, 221);
Mockito.verifyZeroInteractions(completionListener);
}
@Test
public void testErrorListenerCalledOnCompleteCalledWhenReturnFalse() {
Mockito.when(errorListener.onError(mediaPlayer, 0, 0)).thenReturn(false);
shadowMediaPlayer.invokeErrorListener(321, 11);
Mockito.verify(errorListener).onError(mediaPlayer, 321, 11);
Mockito.verify(completionListener).onCompletion(mediaPlayer);
}
@Test
public void testErrorCausesOnCompleteCalledWhenNoErrorListener() {
mediaPlayer.setOnErrorListener(null);
shadowMediaPlayer.invokeErrorListener(321, 21);
Mockito.verifyZeroInteractions(errorListener);
Mockito.verify(completionListener).onCompletion(mediaPlayer);
}
@Test
public void testReleaseStopsScheduler() {
shadowMediaPlayer.doStart();
mediaPlayer.release();
assertThat(scheduler.size()).isEqualTo(0);
}
@Test
public void testResetStopsScheduler() {
shadowMediaPlayer.doStart();
mediaPlayer.reset();
assertThat(scheduler.size()).isEqualTo(0);
}
@Test
public void testDoStartStop() {
assertThat(shadowMediaPlayer.isReallyPlaying()).isFalse();
scheduler.advanceBy(100);
shadowMediaPlayer.doStart();
assertThat(shadowMediaPlayer.isReallyPlaying()).isTrue();
assertThat(shadowMediaPlayer.getCurrentPositionRaw()).isEqualTo(0);
assertThat(shadowMediaPlayer.getState()).isSameAs(IDLE);
scheduler.advanceBy(100);
assertThat(shadowMediaPlayer.getCurrentPositionRaw()).isEqualTo(100);
shadowMediaPlayer.doStop();
assertThat(shadowMediaPlayer.isReallyPlaying()).isFalse();
assertThat(shadowMediaPlayer.getCurrentPositionRaw()).isEqualTo(100);
assertThat(shadowMediaPlayer.getState()).isSameAs(IDLE);
scheduler.advanceBy(50);
assertThat(shadowMediaPlayer.getCurrentPositionRaw()).isEqualTo(100);
}
@Test
public void testScheduleErrorAtOffsetWhileNotPlaying() {
info.scheduleErrorAtOffset(500, 1, 3);
shadowMediaPlayer.setState(INITIALIZED);
shadowMediaPlayer.setState(PREPARED);
mediaPlayer.start();
scheduler.advanceBy(499);
Mockito.verifyZeroInteractions(errorListener);
scheduler.advanceBy(1);
Mockito.verify(errorListener).onError(mediaPlayer, 1, 3);
assertThat(shadowMediaPlayer.getState()).isSameAs(ERROR);
assertThat(scheduler.advanceToLastPostedRunnable()).isFalse();
assertThat(shadowMediaPlayer.getCurrentPositionRaw()).isEqualTo(500);
}
@Test
public void testScheduleErrorAtOffsetInPast() {
info.scheduleErrorAtOffset(200, 1, 2);
shadowMediaPlayer.setState(INITIALIZED);
shadowMediaPlayer.setCurrentPosition(400);
shadowMediaPlayer.setState(PAUSED);
mediaPlayer.start();
scheduler.unPause();
Mockito.verifyZeroInteractions(errorListener);
}
@Test
public void testScheduleBufferUnderrunAtOffset() {
info.scheduleBufferUnderrunAtOffset(100, 50);
shadowMediaPlayer.setState(INITIALIZED);
shadowMediaPlayer.setState(PREPARED);
mediaPlayer.start();
scheduler.advanceBy(99);
Mockito.verifyZeroInteractions(infoListener);
scheduler.advanceBy(1);
Mockito.verify(infoListener).onInfo(mediaPlayer,
MediaPlayer.MEDIA_INFO_BUFFERING_START, 0);
assertThat(shadowMediaPlayer.getCurrentPositionRaw()).isEqualTo(100);
assertThat(shadowMediaPlayer.isReallyPlaying()).isFalse();
scheduler.advanceBy(49);
Mockito.verifyZeroInteractions(infoListener);
scheduler.advanceBy(1);
assertThat(shadowMediaPlayer.getCurrentPositionRaw()).isEqualTo(100);
Mockito.verify(infoListener).onInfo(mediaPlayer,
MediaPlayer.MEDIA_INFO_BUFFERING_END, 0);
scheduler.advanceBy(100);
assertThat(shadowMediaPlayer.getCurrentPositionRaw()).isEqualTo(200);
}
@Test
public void testRemoveEventAtOffset() {
shadowMediaPlayer.setState(PREPARED);
mediaPlayer.start();
scheduler.advanceBy(200);
MediaEvent e = info.scheduleInfoAtOffset(
500, 1, 3);
scheduler.advanceBy(299);
info.removeEventAtOffset(500, e);
scheduler.advanceToLastPostedRunnable();
Mockito.verifyZeroInteractions(infoListener);
}
@Test
public void testRemoveEvent() {
shadowMediaPlayer.setState(PREPARED);
mediaPlayer.start();
scheduler.advanceBy(200);
MediaEvent e = info.scheduleInfoAtOffset(500, 1, 3);
scheduler.advanceBy(299);
shadowMediaPlayer.doStop();
info.removeEvent(e);
shadowMediaPlayer.doStart();
scheduler.advanceToLastPostedRunnable();
Mockito.verifyZeroInteractions(infoListener);
}
@Test
public void testScheduleMultipleRunnables() {
shadowMediaPlayer.setState(PREPARED);
scheduler.advanceBy(25);
mediaPlayer.start();
scheduler.advanceBy(200);
assertThat(scheduler.size()).isEqualTo(1);
shadowMediaPlayer.doStop();
info.scheduleInfoAtOffset(250, 2, 4);
shadowMediaPlayer.doStart();
assertThat(scheduler.size()).isEqualTo(1);
MediaEvent e1 = Mockito.mock(MediaEvent.class);
shadowMediaPlayer.doStop();
info.scheduleEventAtOffset(400, e1);
shadowMediaPlayer.doStart();
scheduler.advanceBy(49);
Mockito.verifyZeroInteractions(infoListener);
scheduler.advanceBy(1);
Mockito.verify(infoListener).onInfo(mediaPlayer, 2, 4);
scheduler.advanceBy(149);
shadowMediaPlayer.doStop();
info.scheduleErrorAtOffset(675, 32, 22);
shadowMediaPlayer.doStart();
Mockito.verifyZeroInteractions(e1);
scheduler.advanceBy(1);
Mockito.verify(e1).run(mediaPlayer, shadowMediaPlayer);
mediaPlayer.pause();
assertThat(scheduler.size()).isEqualTo(0);
scheduler.advanceBy(324);
MediaEvent e2 = Mockito.mock(MediaEvent.class);
info.scheduleEventAtOffset(680, e2);
mediaPlayer.start();
scheduler.advanceBy(274);
Mockito.verifyZeroInteractions(errorListener);
scheduler.advanceBy(1);
Mockito.verify(errorListener).onError(mediaPlayer, 32, 22);
assertThat(scheduler.size()).isEqualTo(0);
assertThat(shadowMediaPlayer.getCurrentPositionRaw()).isEqualTo(675);
assertThat(shadowMediaPlayer.getState()).isSameAs(ERROR);
Mockito.verifyZeroInteractions(e2);
}
@Test
public void testSetDataSourceExceptionWithWrongExceptionTypeAsserts() {
boolean fail = false;
Map<DataSource,Exception> exceptions = ReflectionHelpers.getStaticField(ShadowMediaPlayer.class, "exceptions");
DataSource ds = toDataSource("dummy");
Exception e = new CloneNotSupportedException(); // just a convenient, non-RuntimeException in java.lang
exceptions.put(ds, e);
try {
shadowMediaPlayer.setDataSource(ds);
fail = true;
} catch (AssertionError a) {
} catch (IOException ioe) {
Assertions.fail("Got exception <" + ioe + ">; expecting assertion");
}
if (fail) {
Assertions.fail("setDataSource() should assert with non-IOException,non-RuntimeException");
}
}
@Test
public void testSetDataSourceCustomExceptionOverridesIllegalState() {
shadowMediaPlayer.setState(PREPARED);
ShadowMediaPlayer.addException(toDataSource("dummy"), new IOException());
try {
mediaPlayer.setDataSource("dummy");
Assertions.fail("Expecting IOException to be thrown");
} catch (IOException eThrown) {
} catch (Exception eThrown) {
Assertions.fail(eThrown + " was thrown, expecting IOException");
}
}
@Test
public void testGetSetLooping() {
assertThat(mediaPlayer.isLooping()).isFalse();
mediaPlayer.setLooping(true);
assertThat(mediaPlayer.isLooping()).isTrue();
mediaPlayer.setLooping(false);
assertThat(mediaPlayer.isLooping()).isFalse();
}
/**
* If the looping mode was being set to <code>true</code>
* {@link MediaPlayer#setLooping(boolean)}, the MediaPlayer object shall
* remain in the Started state.
*/
@Test
public void testSetLoopingCalledWhilePlaying() {
shadowMediaPlayer.setState(PREPARED);
mediaPlayer.start();
scheduler.advanceBy(200);
mediaPlayer.setLooping(true);
scheduler.advanceBy(1100);
Mockito.verifyZeroInteractions(completionListener);
assertThat(mediaPlayer.getCurrentPosition()).isEqualTo(300);
mediaPlayer.setLooping(false);
scheduler.advanceBy(699);
Mockito.verifyZeroInteractions(completionListener);
scheduler.advanceBy(1);
Mockito.verify(completionListener).onCompletion(mediaPlayer);
}
@Test
public void testSetLoopingCalledWhileStartable() {
final State[] startableStates = { PREPARED, PAUSED };
for (State state : startableStates) {
shadowMediaPlayer.setCurrentPosition(500);
shadowMediaPlayer.setState(state);
mediaPlayer.setLooping(true);
mediaPlayer.start();
scheduler.advanceBy(700);
Mockito.verifyZeroInteractions(completionListener);
assertThat(mediaPlayer.getCurrentPosition()).as(state.toString())
.isEqualTo(200);
}
}
/**
* While in the PlaybackCompleted state, calling start() can restart the
* playback from the beginning of the audio/video source.
*/
@Test
public void testStartAfterPlaybackCompleted() {
shadowMediaPlayer.setState(PLAYBACK_COMPLETED);
shadowMediaPlayer.setCurrentPosition(1000);
mediaPlayer.start();
assertThat(mediaPlayer.getCurrentPosition()).isEqualTo(0);
}
@Test
public void testResetStaticState() {
ShadowMediaPlayer.CreateListener createListener = Mockito
.mock(ShadowMediaPlayer.CreateListener.class);
ShadowMediaPlayer.setCreateListener(createListener);
assertThat(ShadowMediaPlayer.createListener)
.as("createListener")
.isSameAs(createListener);
DataSource dummy = toDataSource("stuff");
IOException e = new IOException();
addException(dummy, e);
try {
shadowMediaPlayer.setState(IDLE);
shadowMediaPlayer.setDataSource(dummy);
Assertions.failBecauseExceptionWasNotThrown(e.getClass());
} catch (IOException e2) {
assertThat(e2).as("thrown exception").isSameAs(e);
}
// Check that the mediaInfo was cleared
shadowMediaPlayer.doSetDataSource(defaultSource);
assertThat(shadowMediaPlayer.getMediaInfo()).as("mediaInfo:before").isNotNull();
ShadowMediaPlayer.resetStaticState();
// Check that the listener was cleared.
assertThat(ShadowMediaPlayer.createListener)
.as("createListener")
.isNull();
// Check that the mediaInfo was cleared.
try {
shadowMediaPlayer.doSetDataSource(defaultSource);
Assertions.failBecauseExceptionWasNotThrown(IllegalArgumentException.class);
} catch (IllegalArgumentException ie) {
// We expect this if the static state has been cleared.
}
// Check that the exception was cleared.
try {
shadowMediaPlayer.setState(IDLE);
ShadowMediaPlayer.addMediaInfo(dummy, info);
shadowMediaPlayer.setDataSource(dummy);
} catch (IOException e2) {
Assertions.fail("Exception was not cleared by resetStaticState() for <" + dummy + ">", e2);
}
}
@Test
public void setDataSourceException_withRuntimeException() {
RuntimeException e = new RuntimeException("some dummy message");
addException(toDataSource("dummy"), e);
try {
mediaPlayer.setDataSource("dummy");
Assertions.failBecauseExceptionWasNotThrown(e.getClass());
} catch (Exception caught) {
assertThat(caught).isSameAs(e);
assertThat(e.getStackTrace()[0].getClassName())
.as("Stack trace should originate in Shadow")
.isEqualTo(ShadowMediaPlayer.class.getName());
}
}
@Test
public void setDataSourceException_withIOException() {
IOException e = new IOException("some dummy message");
addException(toDataSource("dummy"), e);
shadowMediaPlayer.setState(IDLE);
try {
mediaPlayer.setDataSource("dummy");
Assertions.failBecauseExceptionWasNotThrown(e.getClass());
} catch (Exception caught) {
assertThat(caught).isSameAs(e);
assertThat(e.getStackTrace()[0].getClassName())
.as("Stack trace should originate in Shadow")
.isEqualTo(ShadowMediaPlayer.class.getName());
assertThat(shadowMediaPlayer.getState()).as(
"State after " + e + " thrown should be unchanged").isSameAs(IDLE);
}
}
@Test
public void setDataSource_forNoDataSource_asserts() {
try {
mediaPlayer.setDataSource("some unspecified data source");
Assertions.failBecauseExceptionWasNotThrown(AssertionError.class);
} catch (IllegalArgumentException a) {
assertThat(a.getMessage()).as("assertionMessage")
.contains("addException")
.contains("addMediaInfo");
} catch (Exception e) {
Assertions.fail("Unexpected exception", e);
}
}
}
| mit |
Sravyaksr/selenium | java/client/test/org/openqa/selenium/SessionHandlingTest.java | 3066 | // Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.openqa.selenium;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.remote.SessionNotFoundException;
import org.openqa.selenium.testing.Ignore;
import org.openqa.selenium.testing.SeleniumTestRunner;
import org.openqa.selenium.testing.drivers.WebDriverBuilder;
import static org.openqa.selenium.testing.Ignore.Driver.FIREFOX;
import static org.openqa.selenium.testing.Ignore.Driver.MARIONETTE;
import static org.openqa.selenium.testing.Ignore.Driver.PHANTOMJS;
import static org.openqa.selenium.testing.Ignore.Driver.REMOTE;
import static org.openqa.selenium.testing.Ignore.Driver.SAFARI;
@RunWith(SeleniumTestRunner.class)
@Ignore(value = {REMOTE}, reason = "Not tested")
public class SessionHandlingTest {
@Test
public void callingQuitMoreThanOnceOnASessionIsANoOp() {
WebDriver driver = new WebDriverBuilder().get();
driver.quit();
try {
driver.quit();
} catch (RuntimeException e) {
throw new RuntimeException(
"It should be possible to quit a session more than once, got exception:", e);
}
}
@Test
@Ignore(value = {PHANTOMJS})
public void callingQuitAfterClosingTheLastWindowIsANoOp() {
WebDriver driver = new WebDriverBuilder().get();
driver.close();
try {
driver.quit();
} catch (RuntimeException e) {
throw new RuntimeException(
"It should be possible to quit a session more than once, got exception:", e);
}
}
@Test(expected = SessionNotFoundException.class)
@Ignore(value = {SAFARI}, reason = "Safari: throws UnreachableBrowserException")
public void callingAnyOperationAfterQuitShouldThrowAnException() {
WebDriver driver = new WebDriverBuilder().get();
driver.quit();
driver.getCurrentUrl();
}
@Test(expected = SessionNotFoundException.class)
@Ignore(value = {FIREFOX, PHANTOMJS, SAFARI, MARIONETTE}, reason =
"Firefox: can perform an operation after closing the last window,"
+ "PhantomJS: throws NoSuchWindowException,"
+ "Safari: throws NullPointerException")
public void callingAnyOperationAfterClosingTheLastWindowShouldThrowAnException() {
WebDriver driver = new WebDriverBuilder().get();
driver.close();
driver.getCurrentUrl();
}
}
| apache-2.0 |
bruthe/hadoop-2.6.0r | src/yarn/server/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FSParentQueue.java | 7794 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.classification.InterfaceAudience.Private;
import org.apache.hadoop.classification.InterfaceStability.Unstable;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.yarn.api.records.ApplicationAttemptId;
import org.apache.hadoop.yarn.api.records.QueueACL;
import org.apache.hadoop.yarn.api.records.QueueUserACLInfo;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer;
import org.apache.hadoop.yarn.util.resource.Resources;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ActiveUsersManager;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerApplicationAttempt;
@Private
@Unstable
public class FSParentQueue extends FSQueue {
private static final Log LOG = LogFactory.getLog(
FSParentQueue.class.getName());
private final List<FSQueue> childQueues =
new ArrayList<FSQueue>();
private Resource demand = Resources.createResource(0);
private int runnableApps;
public FSParentQueue(String name, FairScheduler scheduler,
FSParentQueue parent) {
super(name, scheduler, parent);
}
public void addChildQueue(FSQueue child) {
childQueues.add(child);
}
@Override
public void recomputeShares() {
policy.computeShares(childQueues, getFairShare());
for (FSQueue childQueue : childQueues) {
childQueue.getMetrics().setFairShare(childQueue.getFairShare());
childQueue.recomputeShares();
}
}
public void recomputeSteadyShares() {
policy.computeSteadyShares(childQueues, getSteadyFairShare());
for (FSQueue childQueue : childQueues) {
childQueue.getMetrics().setSteadyFairShare(childQueue.getSteadyFairShare());
if (childQueue instanceof FSParentQueue) {
((FSParentQueue) childQueue).recomputeSteadyShares();
}
}
}
@Override
public void updatePreemptionVariables() {
super.updatePreemptionVariables();
// For child queues
for (FSQueue childQueue : childQueues) {
childQueue.updatePreemptionVariables();
}
}
@Override
public Resource getDemand() {
return demand;
}
@Override
public Resource getResourceUsage() {
Resource usage = Resources.createResource(0);
for (FSQueue child : childQueues) {
Resources.addTo(usage, child.getResourceUsage());
}
return usage;
}
@Override
public void updateDemand() {
// Compute demand by iterating through apps in the queue
// Limit demand to maxResources
Resource maxRes = scheduler.getAllocationConfiguration()
.getMaxResources(getName());
demand = Resources.createResource(0);
for (FSQueue childQueue : childQueues) {
childQueue.updateDemand();
Resource toAdd = childQueue.getDemand();
if (LOG.isDebugEnabled()) {
LOG.debug("Counting resource from " + childQueue.getName() + " " +
toAdd + "; Total resource consumption for " + getName() +
" now " + demand);
}
demand = Resources.add(demand, toAdd);
demand = Resources.componentwiseMin(demand, maxRes);
if (Resources.equals(demand, maxRes)) {
break;
}
}
if (LOG.isDebugEnabled()) {
LOG.debug("The updated demand for " + getName() + " is " + demand +
"; the max is " + maxRes);
}
}
private synchronized QueueUserACLInfo getUserAclInfo(
UserGroupInformation user) {
QueueUserACLInfo userAclInfo =
recordFactory.newRecordInstance(QueueUserACLInfo.class);
List<QueueACL> operations = new ArrayList<QueueACL>();
for (QueueACL operation : QueueACL.values()) {
if (hasAccess(operation, user)) {
operations.add(operation);
}
}
userAclInfo.setQueueName(getQueueName());
userAclInfo.setUserAcls(operations);
return userAclInfo;
}
@Override
public synchronized List<QueueUserACLInfo> getQueueUserAclInfo(
UserGroupInformation user) {
List<QueueUserACLInfo> userAcls = new ArrayList<QueueUserACLInfo>();
// Add queue acls
userAcls.add(getUserAclInfo(user));
// Add children queue acls
for (FSQueue child : childQueues) {
userAcls.addAll(child.getQueueUserAclInfo(user));
}
return userAcls;
}
@Override
public Resource assignContainer(FSSchedulerNode node) {
Resource assigned = Resources.none();
// If this queue is over its limit, reject
if (!assignContainerPreCheck(node)) {
return assigned;
}
Collections.sort(childQueues, policy.getComparator());
for (FSQueue child : childQueues) {
assigned = child.assignContainer(node);
if (!Resources.equals(assigned, Resources.none())) {
break;
}
}
return assigned;
}
@Override
public RMContainer preemptContainer() {
RMContainer toBePreempted = null;
// Find the childQueue which is most over fair share
FSQueue candidateQueue = null;
Comparator<Schedulable> comparator = policy.getComparator();
for (FSQueue queue : childQueues) {
if (candidateQueue == null ||
comparator.compare(queue, candidateQueue) > 0) {
candidateQueue = queue;
}
}
// Let the selected queue choose which of its container to preempt
if (candidateQueue != null) {
toBePreempted = candidateQueue.preemptContainer();
}
return toBePreempted;
}
@Override
public List<FSQueue> getChildQueues() {
return childQueues;
}
@Override
public void setPolicy(SchedulingPolicy policy)
throws AllocationConfigurationException {
boolean allowed =
SchedulingPolicy.isApplicableTo(policy, (parent == null)
? SchedulingPolicy.DEPTH_ROOT
: SchedulingPolicy.DEPTH_INTERMEDIATE);
if (!allowed) {
throwPolicyDoesnotApplyException(policy);
}
super.policy = policy;
}
public void incrementRunnableApps() {
runnableApps++;
}
public void decrementRunnableApps() {
runnableApps--;
}
@Override
public int getNumRunnableApps() {
return runnableApps;
}
@Override
public void collectSchedulerApplications(
Collection<ApplicationAttemptId> apps) {
for (FSQueue childQueue : childQueues) {
childQueue.collectSchedulerApplications(apps);
}
}
@Override
public ActiveUsersManager getActiveUsersManager() {
// Should never be called since all applications are submitted to LeafQueues
return null;
}
@Override
public void recoverContainer(Resource clusterResource,
SchedulerApplicationAttempt schedulerAttempt, RMContainer rmContainer) {
// TODO Auto-generated method stub
}
}
| apache-2.0 |
curso007/camel | examples/camel-example-loan-broker-cxf/src/main/java/org/apache/camel/loanbroker/BankResponseAggregationStrategy.java | 1295 | /**
* 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.loanbroker;
import org.apache.camel.loanbroker.bank.BankQuote;
//START SNIPPET: aggregating
// This POJO aggregator is supported since Camel 2.12
public class BankResponseAggregationStrategy {
public BankQuote aggregate(BankQuote oldQuote, BankQuote newQuote) {
if (oldQuote != null && oldQuote.getRate() <= newQuote.getRate()) {
return oldQuote;
} else {
return newQuote;
}
}
}
//END SNIPPET: aggregating
| apache-2.0 |
OpenCollabZA/sakai | rwiki/rwiki-util/radeox/src/java/org/radeox/filter/balance/Balancer.java | 6781 | /**
*
*/
package org.radeox.filter.balance;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import lombok.extern.slf4j.Slf4j;
/**
* @author andrew
*/
@Slf4j
public class Balancer
{
StringBuffer sb;
TagStack tagStack;
TagStack rememberedStack;
Matcher m;
int head;
public String filter()
{
sb = new StringBuffer();
tagStack = new TagStack();
rememberedStack = new TagStack();
m.reset();
head = -1;
while (m.find())
{
if (m.group(1) != null)
{
tagStack.push(new Tag(m.group(2), m.group(1)));
// We have an open!!
if (rememberedStack.size() > 0 && head < m.start())
{
/*
* We have text between the head and the open tag emit the
* remembered tags:
*/
emitOpenWithRemembered();
}
else
{
emitOpen();
}
}
else
{
if (rememberedStack.size() > 0 && head < m.start())
{
emitCloseWithRemembered();
}
else
{
emitClose();
}
}
head = m.end();
}
m.appendTail(sb);
return sb.toString();
}
private void emitClose()
{
doClosing(new StringBuffer());
}
private void emitCloseWithRemembered()
{
// OPEN the remembered tags
for (Iterator it = rememberedStack.iterator(); it.hasNext();)
{
Tag tag = (Tag) it.next();
sb.append(tag.open);
}
// Create replacement string
StringBuffer replacementBuffer = new StringBuffer();
for (Iterator it = rememberedStack.backIterator(); it.hasNext();)
{
Tag tag = (Tag) it.next();
replacementBuffer.append("</").append(tag.name).append(">");
}
doClosing(replacementBuffer);
}
private void doClosing(StringBuffer replacementBuffer)
{
Tag currentTag = new Tag(m.group(4));
// Now check what we're closing...
if (tagStack.search(currentTag) > -1)
{
/*
* The tagStack contains this current tag we've got: 1. <A> </A> -->
* No work 2. <A> <B> </A> ... --> must remember <B>! 3. <A> <B> <C>
* </A> --> must remember <B> and <C>! 4. <A> <B attrs=""> </A> <A>
* <B other=""> <C> </B> ... --> remember <C> and keep remembering
* <B attrs=""> (Case not dealt by this check: <A> <B> </A> <A> </B>
* ... ) Action is: pop everything off the tagStack, and remember
* them till we hit the currentTag
*/
for (Tag tag = tagStack.pop(); (tagStack.size() > 0) && !currentTag.equals(tag); tag = tagStack.pop())
{
if ( tag != null ) {
replacementBuffer.append("</").append(tag.name).append(">");
rememberedStack.push(tag);
} else {
log.warn("Found Null tag in ballancer ");
}
}
replacementBuffer.append("</").append(currentTag.name).append(">");
}
else
{
/*
* The tag stack doesn't contain the current tag: We are closing a
* remembered tag! (well we hope!) 1. <A> <B> </A> <A> </B> ... -->
* just forget the B 2. <A> <B> <C> </A> <A> </B> ... --> just
* forget the B 3. <A> <B attr=""> </A> <B other=""> <C> </A> <A>
* </B> ... --> forget the <B other=""> not the <B>
*/
TagStack tempStack = new TagStack();
for (Tag tag = rememberedStack.pop(); (rememberedStack.size() > 0) && !currentTag.equals(tag); tag = rememberedStack
.pop())
{
if (tag != null)
{
tempStack.push(tag);
}
}
for (Tag tag = tempStack.pop(); tag != null; tag = tempStack.pop())
{
rememberedStack.push(tag);
}
}
m.appendReplacement(sb, replacementBuffer.toString());
}
public void setMatcher(Matcher matcher)
{
this.m = matcher;
}
private void emitOpenWithRemembered()
{
// Append the opens to sb
for (Iterator it = rememberedStack.iterator(); it.hasNext();)
{
Tag tag = (Tag) it.next();
sb.append(tag.open);
}
// Create replacement string
StringBuffer buffer = new StringBuffer();
for (Iterator it = rememberedStack.backIterator(); it.hasNext();)
{
Tag tag = (Tag) it.next();
buffer.append("</").append(tag.name).append(">");
}
buffer.append(m.group(1).replaceAll("\\\\", "\\\\\\\\").replaceAll("\\$",
"\\\\\\$"));
m.appendReplacement(sb, buffer.toString());
}
private void emitOpen()
{
m.appendReplacement(sb, "$1");
}
class Tag
{
public Tag(String name, String open)
{
this.name = name;
this.open = open;
}
public Tag(String name)
{
this.name = name;
this.open = null;
}
public String name;
public String open;
public boolean equals(Object o)
{
if (o == null) return false;
if (o instanceof Tag)
{
Tag that = (Tag) o;
if (that.name == null && this.name == null) return true;
if (this.name == null) return false;
return (this.name.equals(that.name));
}
return false;
}
}
class TagStack
{
List internalList;
int size = 0;
public TagStack()
{
internalList = new ArrayList();
}
public Tag push(Tag toPush)
{
internalList.add(size++, toPush);
if (size > 1)
{
return (Tag) internalList.get(size - 2);
}
else
{
return null;
}
}
public Tag peek()
{
if (size > 0)
{
return (Tag) internalList.get(size - 1);
}
else
{
return null;
}
}
public Tag pop()
{
if (size > 0)
{
return (Tag) internalList.get(--size);
}
else
{
return null;
}
}
public int size()
{
return size;
}
public boolean empty()
{
return (size == 0);
}
public int search(Tag o)
{
if (o == null)
{
return -1;
}
for (int i = size; i > 0; i--)
{
if (o.equals(internalList.get(i - 1)))
{
return (size - i + 1);
}
}
return -1;
}
public Tag get(int i)
{
if (i < size)
{
return (Tag) internalList.get(i);
}
else
{
throw new ArrayIndexOutOfBoundsException(i);
}
}
public Iterator iterator()
{
return new Iterator()
{
int ourHead = size;
public boolean hasNext()
{
return ourHead > 0;
}
public Object next()
{
return internalList.get(--ourHead);
}
public void remove()
{
throw new UnsupportedOperationException(
"remove is not implemented for this iterator");
}
};
}
public Iterator backIterator()
{
return new Iterator()
{
int ourHead = 0;
public boolean hasNext()
{
return (ourHead < size);
}
public Object next()
{
return internalList.get(ourHead++);
}
public void remove()
{
throw new UnsupportedOperationException(
"remove is not implemented for this iterator");
}
};
}
public String toString()
{
StringBuffer sb = new StringBuffer();
for (Iterator it = iterator(); it.hasNext();)
{
Tag t = (Tag) it.next();
sb.append("Tag: " + t.open + "\n");
}
return sb.toString();
}
}
}
| apache-2.0 |
xiaoleiPENG/my-project | spring-boot-test/src/test/java/org/springframework/boot/test/json/ExampleObject.java | 1465 | /*
* Copyright 2012-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.test.json;
import org.springframework.util.ObjectUtils;
/**
* Example object used for serialization.
*/
public class ExampleObject {
private String name;
private int age;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return this.age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public int hashCode() {
return 0;
}
@Override
public boolean equals(Object obj) {
if (obj == null || obj.getClass() != getClass()) {
return false;
}
ExampleObject other = (ExampleObject) obj;
return ObjectUtils.nullSafeEquals(this.name, other.name)
&& ObjectUtils.nullSafeEquals(this.age, other.age);
}
@Override
public String toString() {
return this.name + " " + this.age;
}
}
| apache-2.0 |
gingerwizard/elasticsearch | x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/StatsEnclosed.java | 346 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.sql.expression.function.aggregate;
public interface StatsEnclosed {
}
| apache-2.0 |
ZhangXFeng/hadoop | src/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapred/pipes/TestPipeApplication.java | 24228 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.mapred.pipes;
import java.io.ByteArrayOutputStream;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.RawLocalFileSystem;
import org.apache.hadoop.io.BooleanWritable;
import org.apache.hadoop.io.FloatWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.mapred.IFile.Writer;
import org.apache.hadoop.mapreduce.MRJobConfig;
import org.apache.hadoop.mapreduce.security.TokenCache;
import org.apache.hadoop.mapred.Counters;
import org.apache.hadoop.mapred.Counters.Counter;
import org.apache.hadoop.mapred.Counters.Group;
import org.apache.hadoop.mapred.InputSplit;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.RecordReader;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.mapred.TaskAttemptID;
import org.apache.hadoop.mapred.TaskLog;
import org.apache.hadoop.security.token.Token;
import org.apache.hadoop.util.ExitUtil;
import org.apache.hadoop.util.Progressable;
import org.apache.hadoop.yarn.security.AMRMTokenIdentifier;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.Assert.*;
public class TestPipeApplication {
private static File workSpace = new File("target",
TestPipeApplication.class.getName() + "-workSpace");
private static String taskName = "attempt_001_02_r03_04_05";
/**
* test PipesMapRunner test the transfer data from reader
*
* @throws Exception
*/
@Test
public void testRunner() throws Exception {
// clean old password files
File[] psw = cleanTokenPasswordFile();
try {
RecordReader<FloatWritable, NullWritable> rReader = new ReaderPipesMapRunner();
JobConf conf = new JobConf();
conf.set(Submitter.IS_JAVA_RR, "true");
// for stdour and stderror
conf.set(MRJobConfig.TASK_ATTEMPT_ID, taskName);
CombineOutputCollector<IntWritable, Text> output = new CombineOutputCollector<IntWritable, Text>(
new Counters.Counter(), new Progress());
FileSystem fs = new RawLocalFileSystem();
fs.setConf(conf);
Writer<IntWritable, Text> wr = new Writer<IntWritable, Text>(conf, fs.create(
new Path(workSpace + File.separator + "outfile")), IntWritable.class,
Text.class, null, null, true);
output.setWriter(wr);
// stub for client
File fCommand = getFileCommand("org.apache.hadoop.mapred.pipes.PipeApplicationRunnableStub");
conf.set(MRJobConfig.CACHE_LOCALFILES, fCommand.getAbsolutePath());
// token for authorization
Token<AMRMTokenIdentifier> token = new Token<AMRMTokenIdentifier>(
"user".getBytes(), "password".getBytes(), new Text("kind"), new Text(
"service"));
TokenCache.setJobToken(token, conf.getCredentials());
conf.setBoolean(MRJobConfig.SKIP_RECORDS, true);
TestTaskReporter reporter = new TestTaskReporter();
PipesMapRunner<FloatWritable, NullWritable, IntWritable, Text> runner = new PipesMapRunner<FloatWritable, NullWritable, IntWritable, Text>();
initStdOut(conf);
runner.configure(conf);
runner.run(rReader, output, reporter);
String stdOut = readStdOut(conf);
// test part of translated data. As common file for client and test -
// clients stdOut
// check version
assertTrue(stdOut.contains("CURRENT_PROTOCOL_VERSION:0"));
// check key and value classes
assertTrue(stdOut
.contains("Key class:org.apache.hadoop.io.FloatWritable"));
assertTrue(stdOut
.contains("Value class:org.apache.hadoop.io.NullWritable"));
// test have sent all data from reader
assertTrue(stdOut.contains("value:0.0"));
assertTrue(stdOut.contains("value:9.0"));
} finally {
if (psw != null) {
// remove password files
for (File file : psw) {
file.deleteOnExit();
}
}
}
}
/**
* test org.apache.hadoop.mapred.pipes.Application
* test a internal functions: MessageType.REGISTER_COUNTER, INCREMENT_COUNTER, STATUS, PROGRESS...
*
* @throws Throwable
*/
@Test
public void testApplication() throws Throwable {
JobConf conf = new JobConf();
RecordReader<FloatWritable, NullWritable> rReader = new Reader();
// client for test
File fCommand = getFileCommand("org.apache.hadoop.mapred.pipes.PipeApplicationStub");
TestTaskReporter reporter = new TestTaskReporter();
File[] psw = cleanTokenPasswordFile();
try {
conf.set(MRJobConfig.TASK_ATTEMPT_ID, taskName);
conf.set(MRJobConfig.CACHE_LOCALFILES, fCommand.getAbsolutePath());
// token for authorization
Token<AMRMTokenIdentifier> token = new Token<AMRMTokenIdentifier>(
"user".getBytes(), "password".getBytes(), new Text("kind"), new Text(
"service"));
TokenCache.setJobToken(token, conf.getCredentials());
FakeCollector output = new FakeCollector(new Counters.Counter(),
new Progress());
FileSystem fs = new RawLocalFileSystem();
fs.setConf(conf);
Writer<IntWritable, Text> wr = new Writer<IntWritable, Text>(conf, fs.create(
new Path(workSpace.getAbsolutePath() + File.separator + "outfile")),
IntWritable.class, Text.class, null, null, true);
output.setWriter(wr);
conf.set(Submitter.PRESERVE_COMMANDFILE, "true");
initStdOut(conf);
Application<WritableComparable<IntWritable>, Writable, IntWritable, Text> application = new Application<WritableComparable<IntWritable>, Writable, IntWritable, Text>(
conf, rReader, output, reporter, IntWritable.class, Text.class);
application.getDownlink().flush();
application.getDownlink().mapItem(new IntWritable(3), new Text("txt"));
application.getDownlink().flush();
application.waitForFinish();
wr.close();
// test getDownlink().mapItem();
String stdOut = readStdOut(conf);
assertTrue(stdOut.contains("key:3"));
assertTrue(stdOut.contains("value:txt"));
// reporter test counter, and status should be sended
// test MessageType.REGISTER_COUNTER and INCREMENT_COUNTER
assertEquals(1.0, reporter.getProgress(), 0.01);
assertNotNull(reporter.getCounter("group", "name"));
// test status MessageType.STATUS
assertEquals(reporter.getStatus(), "PROGRESS");
stdOut = readFile(new File(workSpace.getAbsolutePath() + File.separator
+ "outfile"));
// check MessageType.PROGRESS
assertEquals(0.55f, rReader.getProgress(), 0.001);
application.getDownlink().close();
// test MessageType.OUTPUT
Entry<IntWritable, Text> entry = output.getCollect().entrySet()
.iterator().next();
assertEquals(123, entry.getKey().get());
assertEquals("value", entry.getValue().toString());
try {
// try to abort
application.abort(new Throwable());
fail();
} catch (IOException e) {
// abort works ?
assertEquals("pipe child exception", e.getMessage());
}
} finally {
if (psw != null) {
// remove password files
for (File file : psw) {
file.deleteOnExit();
}
}
}
}
/**
* test org.apache.hadoop.mapred.pipes.Submitter
*
* @throws Exception
*/
@Test
public void testSubmitter() throws Exception {
JobConf conf = new JobConf();
File[] psw = cleanTokenPasswordFile();
System.setProperty("test.build.data",
"target/tmp/build/TEST_SUBMITTER_MAPPER/data");
conf.set("hadoop.log.dir", "target/tmp");
// prepare configuration
Submitter.setIsJavaMapper(conf, false);
Submitter.setIsJavaReducer(conf, false);
Submitter.setKeepCommandFile(conf, false);
Submitter.setIsJavaRecordReader(conf, false);
Submitter.setIsJavaRecordWriter(conf, false);
PipesPartitioner<IntWritable, Text> partitioner = new PipesPartitioner<IntWritable, Text>();
partitioner.configure(conf);
Submitter.setJavaPartitioner(conf, partitioner.getClass());
assertEquals(PipesPartitioner.class, (Submitter.getJavaPartitioner(conf)));
// test going to call main method with System.exit(). Change Security
SecurityManager securityManager = System.getSecurityManager();
// store System.out
PrintStream oldps = System.out;
ByteArrayOutputStream out = new ByteArrayOutputStream();
ExitUtil.disableSystemExit();
// test without parameters
try {
System.setOut(new PrintStream(out));
Submitter.main(new String[0]);
fail();
} catch (ExitUtil.ExitException e) {
// System.exit prohibited! output message test
assertTrue(out.toString().contains(""));
assertTrue(out.toString().contains("bin/hadoop pipes"));
assertTrue(out.toString().contains("[-input <path>] // Input directory"));
assertTrue(out.toString()
.contains("[-output <path>] // Output directory"));
assertTrue(out.toString().contains("[-jar <jar file> // jar filename"));
assertTrue(out.toString().contains(
"[-inputformat <class>] // InputFormat class"));
assertTrue(out.toString().contains("[-map <class>] // Java Map class"));
assertTrue(out.toString().contains(
"[-partitioner <class>] // Java Partitioner"));
assertTrue(out.toString().contains(
"[-reduce <class>] // Java Reduce class"));
assertTrue(out.toString().contains(
"[-writer <class>] // Java RecordWriter"));
assertTrue(out.toString().contains(
"[-program <executable>] // executable URI"));
assertTrue(out.toString().contains(
"[-reduces <num>] // number of reduces"));
assertTrue(out.toString().contains(
"[-lazyOutput <true/false>] // createOutputLazily"));
assertTrue(out
.toString()
.contains(
"-conf <configuration file> specify an application configuration file"));
assertTrue(out.toString().contains(
"-D <property=value> use value for given property"));
assertTrue(out.toString().contains(
"-fs <local|namenode:port> specify a namenode"));
assertTrue(out.toString().contains(
"-jt <local|resourcemanager:port> specify a ResourceManager"));
assertTrue(out
.toString()
.contains(
"-files <comma separated list of files> specify comma separated files to be copied to the map reduce cluster"));
assertTrue(out
.toString()
.contains(
"-libjars <comma separated list of jars> specify comma separated jar files to include in the classpath."));
assertTrue(out
.toString()
.contains(
"-archives <comma separated list of archives> specify comma separated archives to be unarchived on the compute machines."));
} finally {
System.setOut(oldps);
// restore
System.setSecurityManager(securityManager);
if (psw != null) {
// remove password files
for (File file : psw) {
file.deleteOnExit();
}
}
}
// test call Submitter form command line
try {
File fCommand = getFileCommand(null);
String[] args = new String[22];
File input = new File(workSpace + File.separator + "input");
if (!input.exists()) {
Assert.assertTrue(input.createNewFile());
}
File outPut = new File(workSpace + File.separator + "output");
FileUtil.fullyDelete(outPut);
args[0] = "-input";
args[1] = input.getAbsolutePath();// "input";
args[2] = "-output";
args[3] = outPut.getAbsolutePath();// "output";
args[4] = "-inputformat";
args[5] = "org.apache.hadoop.mapred.TextInputFormat";
args[6] = "-map";
args[7] = "org.apache.hadoop.mapred.lib.IdentityMapper";
args[8] = "-partitioner";
args[9] = "org.apache.hadoop.mapred.pipes.PipesPartitioner";
args[10] = "-reduce";
args[11] = "org.apache.hadoop.mapred.lib.IdentityReducer";
args[12] = "-writer";
args[13] = "org.apache.hadoop.mapred.TextOutputFormat";
args[14] = "-program";
args[15] = fCommand.getAbsolutePath();// "program";
args[16] = "-reduces";
args[17] = "2";
args[18] = "-lazyOutput";
args[19] = "lazyOutput";
args[20] = "-jobconf";
args[21] = "mapreduce.pipes.isjavarecordwriter=false,mapreduce.pipes.isjavarecordreader=false";
Submitter.main(args);
fail();
} catch (ExitUtil.ExitException e) {
// status should be 0
assertEquals(e.status, 0);
} finally {
System.setOut(oldps);
System.setSecurityManager(securityManager);
}
}
/**
* test org.apache.hadoop.mapred.pipes.PipesReducer
* test the transfer of data: key and value
*
* @throws Exception
*/
@Test
public void testPipesReduser() throws Exception {
File[] psw = cleanTokenPasswordFile();
JobConf conf = new JobConf();
try {
Token<AMRMTokenIdentifier> token = new Token<AMRMTokenIdentifier>(
"user".getBytes(), "password".getBytes(), new Text("kind"), new Text(
"service"));
TokenCache.setJobToken(token, conf.getCredentials());
File fCommand = getFileCommand("org.apache.hadoop.mapred.pipes.PipeReducerStub");
conf.set(MRJobConfig.CACHE_LOCALFILES, fCommand.getAbsolutePath());
PipesReducer<BooleanWritable, Text, IntWritable, Text> reducer = new PipesReducer<BooleanWritable, Text, IntWritable, Text>();
reducer.configure(conf);
BooleanWritable bw = new BooleanWritable(true);
conf.set(MRJobConfig.TASK_ATTEMPT_ID, taskName);
initStdOut(conf);
conf.setBoolean(MRJobConfig.SKIP_RECORDS, true);
CombineOutputCollector<IntWritable, Text> output = new CombineOutputCollector<IntWritable, Text>(
new Counters.Counter(), new Progress());
Reporter reporter = new TestTaskReporter();
List<Text> texts = new ArrayList<Text>();
texts.add(new Text("first"));
texts.add(new Text("second"));
texts.add(new Text("third"));
reducer.reduce(bw, texts.iterator(), output, reporter);
reducer.close();
String stdOut = readStdOut(conf);
// test data: key
assertTrue(stdOut.contains("reducer key :true"));
// and values
assertTrue(stdOut.contains("reduce value :first"));
assertTrue(stdOut.contains("reduce value :second"));
assertTrue(stdOut.contains("reduce value :third"));
} finally {
if (psw != null) {
// remove password files
for (File file : psw) {
file.deleteOnExit();
}
}
}
}
/**
* test PipesPartitioner
* test set and get data from PipesPartitioner
*/
@Test
public void testPipesPartitioner() {
PipesPartitioner<IntWritable, Text> partitioner = new PipesPartitioner<IntWritable, Text>();
JobConf configuration = new JobConf();
Submitter.getJavaPartitioner(configuration);
partitioner.configure(new JobConf());
IntWritable iw = new IntWritable(4);
// the cache empty
assertEquals(0, partitioner.getPartition(iw, new Text("test"), 2));
// set data into cache
PipesPartitioner.setNextPartition(3);
// get data from cache
assertEquals(3, partitioner.getPartition(iw, new Text("test"), 2));
}
/**
* clean previous std error and outs
*/
private void initStdOut(JobConf configuration) {
TaskAttemptID taskId = TaskAttemptID.forName(configuration
.get(MRJobConfig.TASK_ATTEMPT_ID));
File stdOut = TaskLog.getTaskLogFile(taskId, false, TaskLog.LogName.STDOUT);
File stdErr = TaskLog.getTaskLogFile(taskId, false, TaskLog.LogName.STDERR);
// prepare folder
if (!stdOut.getParentFile().exists()) {
stdOut.getParentFile().mkdirs();
} else { // clean logs
stdOut.deleteOnExit();
stdErr.deleteOnExit();
}
}
private String readStdOut(JobConf conf) throws Exception {
TaskAttemptID taskId = TaskAttemptID.forName(conf
.get(MRJobConfig.TASK_ATTEMPT_ID));
File stdOut = TaskLog.getTaskLogFile(taskId, false, TaskLog.LogName.STDOUT);
return readFile(stdOut);
}
private String readFile(File file) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream is = new FileInputStream(file);
byte[] buffer = new byte[1024];
int counter = 0;
while ((counter = is.read(buffer)) >= 0) {
out.write(buffer, 0, counter);
}
is.close();
return out.toString();
}
private class Progress implements Progressable {
@Override
public void progress() {
}
}
private File[] cleanTokenPasswordFile() throws Exception {
File[] result = new File[2];
result[0] = new File("./jobTokenPassword");
if (result[0].exists()) {
FileUtil.chmod(result[0].getAbsolutePath(), "700");
assertTrue(result[0].delete());
}
result[1] = new File("./.jobTokenPassword.crc");
if (result[1].exists()) {
FileUtil.chmod(result[1].getAbsolutePath(), "700");
result[1].delete();
}
return result;
}
private File getFileCommand(String clazz) throws Exception {
String classpath = System.getProperty("java.class.path");
File fCommand = new File(workSpace + File.separator + "cache.sh");
fCommand.deleteOnExit();
if (!fCommand.getParentFile().exists()) {
fCommand.getParentFile().mkdirs();
}
fCommand.createNewFile();
OutputStream os = new FileOutputStream(fCommand);
os.write("#!/bin/sh \n".getBytes());
if (clazz == null) {
os.write(("ls ").getBytes());
} else {
os.write(("java -cp " + classpath + " " + clazz).getBytes());
}
os.flush();
os.close();
FileUtil.chmod(fCommand.getAbsolutePath(), "700");
return fCommand;
}
private class CombineOutputCollector<K, V extends Object> implements
OutputCollector<K, V> {
private Writer<K, V> writer;
private Counters.Counter outCounter;
private Progressable progressable;
public CombineOutputCollector(Counters.Counter outCounter,
Progressable progressable) {
this.outCounter = outCounter;
this.progressable = progressable;
}
public synchronized void setWriter(Writer<K, V> writer) {
this.writer = writer;
}
public synchronized void collect(K key, V value) throws IOException {
outCounter.increment(1);
writer.append(key, value);
progressable.progress();
}
}
public static class FakeSplit implements InputSplit {
public void write(DataOutput out) throws IOException {
}
public void readFields(DataInput in) throws IOException {
}
public long getLength() {
return 0L;
}
public String[] getLocations() {
return new String[0];
}
}
private class TestTaskReporter implements Reporter {
private int recordNum = 0; // number of records processed
private String status = null;
private Counters counters = new Counters();
private InputSplit split = new FakeSplit();
@Override
public void progress() {
recordNum++;
}
@Override
public void setStatus(String status) {
this.status = status;
}
public String getStatus() {
return this.status;
}
public Counters.Counter getCounter(String group, String name) {
Counters.Counter counter = null;
if (counters != null) {
counter = counters.findCounter(group, name);
if (counter == null) {
Group grp = counters.addGroup(group, group);
counter = grp.addCounter(name, name, 10);
}
}
return counter;
}
public Counters.Counter getCounter(Enum<?> name) {
return counters == null ? null : counters.findCounter(name);
}
public void incrCounter(Enum<?> key, long amount) {
if (counters != null) {
counters.incrCounter(key, amount);
}
}
public void incrCounter(String group, String counter, long amount) {
if (counters != null) {
counters.incrCounter(group, counter, amount);
}
}
@Override
public InputSplit getInputSplit() throws UnsupportedOperationException {
return split;
}
@Override
public float getProgress() {
return recordNum;
}
}
private class Reader implements RecordReader<FloatWritable, NullWritable> {
private int index = 0;
private FloatWritable progress;
@Override
public boolean next(FloatWritable key, NullWritable value)
throws IOException {
progress = key;
index++;
return index <= 10;
}
@Override
public float getProgress() throws IOException {
return progress.get();
}
@Override
public long getPos() throws IOException {
return index;
}
@Override
public NullWritable createValue() {
return NullWritable.get();
}
@Override
public FloatWritable createKey() {
FloatWritable result = new FloatWritable(index);
return result;
}
@Override
public void close() throws IOException {
}
}
private class ReaderPipesMapRunner implements RecordReader<FloatWritable, NullWritable> {
private int index = 0;
@Override
public boolean next(FloatWritable key, NullWritable value)
throws IOException {
key.set(index++);
return index <= 10;
}
@Override
public float getProgress() throws IOException {
return index;
}
@Override
public long getPos() throws IOException {
return index;
}
@Override
public NullWritable createValue() {
return NullWritable.get();
}
@Override
public FloatWritable createKey() {
FloatWritable result = new FloatWritable(index);
return result;
}
@Override
public void close() throws IOException {
}
}
private class FakeCollector extends
CombineOutputCollector<IntWritable, Text> {
final private Map<IntWritable, Text> collect = new HashMap<IntWritable, Text>();
public FakeCollector(Counter outCounter, Progressable progressable) {
super(outCounter, progressable);
}
@Override
public synchronized void collect(IntWritable key, Text value)
throws IOException {
collect.put(key, value);
super.collect(key, value);
}
public Map<IntWritable, Text> getCollect() {
return collect;
}
}
}
| apache-2.0 |
DMCsys/smartalkaudio | storage/UniversalMusicPlayer_v01/mobile/src/main/java/com/example/android/uamp/utils/CarHelper.java | 4892 | /*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.uamp.utils;
import android.app.UiModeManager;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Bundle;
import com.example.android.uamp.MusicService;
public class CarHelper {
private static final String TAG = LogHelper.makeLogTag(CarHelper.class);
private static final String AUTO_APP_PACKAGE_NAME = "com.google.android.projection.gearhead";
// Use these extras to reserve space for the corresponding actions, even when they are disabled
// in the playbackstate, so the custom actions don't reflow.
private static final String SLOT_RESERVATION_SKIP_TO_NEXT =
"com.google.android.gms.car.media.ALWAYS_RESERVE_SPACE_FOR.ACTION_SKIP_TO_NEXT";
private static final String SLOT_RESERVATION_SKIP_TO_PREV =
"com.google.android.gms.car.media.ALWAYS_RESERVE_SPACE_FOR.ACTION_SKIP_TO_PREVIOUS";
private static final String SLOT_RESERVATION_QUEUE =
"com.google.android.gms.car.media.ALWAYS_RESERVE_SPACE_FOR.ACTION_QUEUE";
/**
* Action for an intent broadcast by Android Auto when a media app is connected or
* disconnected. A "connected" media app is the one currently attached to the "media" facet
* on Android Auto. So, this intent is sent by AA on:
*
* - connection: when the phone is projecting and at the moment the app is selected from the
* list of media apps
* - disconnection: when another media app is selected from the list of media apps or when
* the phone stops projecting (when the user unplugs it, for example)
*
* The actual event (connected or disconnected) will come as an Intent extra,
* with the key MEDIA_CONNECTION_STATUS (see below).
*/
public static final String ACTION_MEDIA_STATUS = "com.google.android.gms.car.media.STATUS";
/**
* Key in Intent extras that contains the media connection event type (connected or disconnected)
*/
public static final String MEDIA_CONNECTION_STATUS = "media_connection_status";
/**
* Value of the key MEDIA_CONNECTION_STATUS in Intent extras used when the current media app
* is connected.
*/
public static final String MEDIA_CONNECTED = "media_connected";
/**
* Value of the key MEDIA_CONNECTION_STATUS in Intent extras used when the current media app
* is disconnected.
*/
public static final String MEDIA_DISCONNECTED = "media_disconnected";
public static boolean isValidCarPackage(String packageName) {
return AUTO_APP_PACKAGE_NAME.equals(packageName);
}
public static void setSlotReservationFlags(Bundle extras, boolean reservePlayingQueueSlot,
boolean reserveSkipToNextSlot, boolean reserveSkipToPrevSlot) {
if (reservePlayingQueueSlot) {
extras.putBoolean(SLOT_RESERVATION_QUEUE, true);
} else {
extras.remove(SLOT_RESERVATION_QUEUE);
}
if (reserveSkipToPrevSlot) {
extras.putBoolean(SLOT_RESERVATION_SKIP_TO_PREV, true);
} else {
extras.remove(SLOT_RESERVATION_SKIP_TO_PREV);
}
if (reserveSkipToNextSlot) {
extras.putBoolean(SLOT_RESERVATION_SKIP_TO_NEXT, true);
} else {
extras.remove(SLOT_RESERVATION_SKIP_TO_NEXT);
}
}
/**
* Returns true when running Android Auto or a car dock.
*
* A preferable way of detecting if your app is running in the context of an Android Auto
* compatible car is by registering a BroadcastReceiver for the action
* {@link CarHelper#ACTION_MEDIA_STATUS}. See a sample implementation in
* {@link MusicService#onCreate()}.
*
* @param c Context to detect UI Mode.
* @return true when device is running in car mode, false otherwise.
*/
public static boolean isCarUiMode(Context c) {
UiModeManager uiModeManager = (UiModeManager) c.getSystemService(Context.UI_MODE_SERVICE);
if (uiModeManager.getCurrentModeType() == Configuration.UI_MODE_TYPE_CAR) {
LogHelper.d(TAG, "Running in Car mode");
return true;
} else {
LogHelper.d(TAG, "Running on a non-Car mode");
return false;
}
}
}
| gpl-3.0 |
elilevine/apache-phoenix | phoenix-core/src/main/java/org/apache/phoenix/schema/SequenceKey.java | 3420 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.phoenix.schema;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.phoenix.query.QueryConstants;
import org.apache.phoenix.util.ByteUtil;
public class SequenceKey implements Comparable<SequenceKey> {
private final String tenantId;
private final String schemaName;
private final String sequenceName;
private final byte[] key;
public SequenceKey(String tenantId, String schemaName, String sequenceName, int nBuckets) {
this.tenantId = tenantId;
this.schemaName = schemaName;
this.sequenceName = sequenceName;
this.key = ByteUtil.concat((nBuckets <= 0 ? ByteUtil.EMPTY_BYTE_ARRAY : QueryConstants.SEPARATOR_BYTE_ARRAY), tenantId == null ? ByteUtil.EMPTY_BYTE_ARRAY : Bytes.toBytes(tenantId), QueryConstants.SEPARATOR_BYTE_ARRAY, schemaName == null ? ByteUtil.EMPTY_BYTE_ARRAY : Bytes.toBytes(schemaName), QueryConstants.SEPARATOR_BYTE_ARRAY, Bytes.toBytes(sequenceName));
if (nBuckets > 0) {
key[0] = SaltingUtil.getSaltingByte(key, SaltingUtil.NUM_SALTING_BYTES, key.length - SaltingUtil.NUM_SALTING_BYTES, nBuckets);
}
}
public byte[] getKey() {
return key;
}
public String getTenantId() {
return tenantId;
}
public String getSchemaName() {
return schemaName;
}
public String getSequenceName() {
return sequenceName;
}
@Override
public int compareTo(SequenceKey that) {
int c = this.tenantId == that.getTenantId() ? 0 : this.tenantId == null ? -1 : that.getTenantId() == null ? 1 : this.tenantId.compareTo(that.getTenantId());
if (c == 0) {
c = this.schemaName == that.getSchemaName() ? 0 : this.schemaName == null ? -1 : that.getSchemaName() == null ? 1 : this.schemaName.compareTo(that.getSchemaName());
if (c == 0) {
return sequenceName.compareTo(that.getSequenceName());
}
}
return c;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((tenantId == null) ? 0 : tenantId.hashCode());
result = prime * result + ((schemaName == null) ? 0 : schemaName.hashCode());
result = prime * result + sequenceName.hashCode();
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
SequenceKey other = (SequenceKey)obj;
return this.compareTo(other) == 0;
}
} | apache-2.0 |
ivan-fedorov/intellij-community | java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/LayoutTreeComponent.java | 26621 | /*
* 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.openapi.roots.ui.configuration.artifacts;
import com.intellij.ide.dnd.DnDEvent;
import com.intellij.ide.dnd.DnDManager;
import com.intellij.ide.dnd.DnDTarget;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.roots.ui.configuration.artifacts.nodes.ArtifactRootNode;
import com.intellij.openapi.roots.ui.configuration.artifacts.nodes.PackagingElementNode;
import com.intellij.openapi.roots.ui.configuration.artifacts.nodes.PackagingNodeSource;
import com.intellij.openapi.roots.ui.configuration.artifacts.nodes.PackagingTreeNodeFactory;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.packaging.artifacts.Artifact;
import com.intellij.packaging.artifacts.ArtifactType;
import com.intellij.packaging.elements.CompositePackagingElement;
import com.intellij.packaging.elements.PackagingElement;
import com.intellij.packaging.elements.PackagingElementFactory;
import com.intellij.packaging.elements.PackagingElementType;
import com.intellij.packaging.impl.elements.DirectoryPackagingElement;
import com.intellij.packaging.ui.ArtifactEditorContext;
import com.intellij.packaging.ui.PackagingElementPropertiesPanel;
import com.intellij.packaging.ui.PackagingSourceItem;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.ui.awt.RelativeRectangle;
import com.intellij.ui.border.CustomLineBorder;
import com.intellij.ui.treeStructure.SimpleNode;
import com.intellij.ui.treeStructure.SimpleTreeBuilder;
import com.intellij.ui.treeStructure.SimpleTreeStructure;
import com.intellij.ui.treeStructure.WeightBasedComparator;
import com.intellij.util.ArrayUtil;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.io.URLUtil;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.tree.TreeUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.util.*;
import java.util.List;
public class LayoutTreeComponent implements DnDTarget, Disposable {
@NonNls private static final String EMPTY_CARD = "<empty>";
@NonNls private static final String PROPERTIES_CARD = "properties";
private final ArtifactEditorImpl myArtifactsEditor;
private final LayoutTree myTree;
private final JPanel myTreePanel;
private final ComplexElementSubstitutionParameters mySubstitutionParameters;
private final ArtifactEditorContext myContext;
private final Artifact myOriginalArtifact;
private SelectedElementInfo<?> mySelectedElementInfo = new SelectedElementInfo<PackagingElement<?>>(null);
private JPanel myPropertiesPanelWrapper;
private JPanel myPropertiesPanel;
private final LayoutTreeBuilder myBuilder;
private boolean mySortElements;
private final LayoutTreeStructure myTreeStructure;
public LayoutTreeComponent(ArtifactEditorImpl artifactsEditor, ComplexElementSubstitutionParameters substitutionParameters,
ArtifactEditorContext context, Artifact originalArtifact, boolean sortElements) {
myArtifactsEditor = artifactsEditor;
mySubstitutionParameters = substitutionParameters;
myContext = context;
myOriginalArtifact = originalArtifact;
mySortElements = sortElements;
myTree = new LayoutTree(myArtifactsEditor);
myTreeStructure = new LayoutTreeStructure();
myBuilder = new LayoutTreeBuilder();
Disposer.register(this, myTree);
Disposer.register(this, myBuilder);
myTree.addTreeSelectionListener(new TreeSelectionListener() {
@Override
public void valueChanged(TreeSelectionEvent e) {
updatePropertiesPanel(false);
}
});
createPropertiesPanel();
myTreePanel = new JPanel(new BorderLayout());
myTreePanel.add(ScrollPaneFactory.createScrollPane(myTree), BorderLayout.CENTER);
myTreePanel.add(myPropertiesPanelWrapper, BorderLayout.SOUTH);
if (!ApplicationManager.getApplication().isUnitTestMode()) {
DnDManager.getInstance().registerTarget(this, myTree);
}
}
@Nullable
private WeightBasedComparator getComparator() {
return mySortElements ? new WeightBasedComparator(true) : null;
}
public void setSortElements(boolean sortElements) {
mySortElements = sortElements;
myBuilder.setNodeDescriptorComparator(getComparator());
myArtifactsEditor.getContext().getParent().getDefaultSettings().setSortElements(sortElements);
}
@Nullable
private static PackagingElementNode getNode(Object value) {
if (!(value instanceof DefaultMutableTreeNode)) return null;
final Object userObject = ((DefaultMutableTreeNode)value).getUserObject();
return userObject instanceof PackagingElementNode ? (PackagingElementNode)userObject : null;
}
private void createPropertiesPanel() {
myPropertiesPanel = new JPanel(new BorderLayout());
final JPanel emptyPanel = new JPanel();
emptyPanel.setMinimumSize(JBUI.emptySize());
emptyPanel.setPreferredSize(JBUI.emptySize());
myPropertiesPanelWrapper = new JPanel(new CardLayout());
myPropertiesPanel.setBorder(new CustomLineBorder(1, 0, 0, 0));
myPropertiesPanelWrapper.add(EMPTY_CARD, emptyPanel);
myPropertiesPanelWrapper.add(PROPERTIES_CARD, myPropertiesPanel);
}
public Artifact getArtifact() {
return myArtifactsEditor.getArtifact();
}
public LayoutTree getLayoutTree() {
return myTree;
}
public void updatePropertiesPanel(final boolean force) {
final PackagingElement<?> selected = getSelection().getElementIfSingle();
if (!force && Comparing.equal(selected, mySelectedElementInfo.myElement)) {
return;
}
mySelectedElementInfo.save();
mySelectedElementInfo = new SelectedElementInfo<PackagingElement<?>>(selected);
mySelectedElementInfo.showPropertiesPanel();
}
public void saveElementProperties() {
mySelectedElementInfo.save();
}
public void rebuildTree() {
myBuilder.updateFromRoot(true);
updatePropertiesPanel(true);
myArtifactsEditor.queueValidation();
}
public LayoutTreeSelection getSelection() {
return myTree.getSelection();
}
public void addNewPackagingElement(@NotNull PackagingElementType<?> type) {
PackagingElementNode<?> parentNode = getParentNode(myTree.getSelection());
final PackagingElement<?> element = parentNode.getFirstElement();
final CompositePackagingElement<?> parent;
if (element instanceof CompositePackagingElement<?>) {
parent = (CompositePackagingElement<?>)element;
}
else {
parent = getArtifact().getRootElement();
parentNode = myTree.getRootPackagingNode();
}
if (!checkCanAdd(parent, parentNode)) return;
final List<? extends PackagingElement<?>> children = type.chooseAndCreate(myContext, getArtifact(), parent);
final PackagingElementNode<?> finalParentNode = parentNode;
editLayout(new Runnable() {
@Override
public void run() {
CompositePackagingElement<?> actualParent = getOrCreateModifiableParent(parent, finalParentNode);
for (PackagingElement<?> child : children) {
actualParent.addOrFindChild(child);
}
}
});
updateAndSelect(parentNode, children);
}
private static CompositePackagingElement<?> getOrCreateModifiableParent(CompositePackagingElement<?> parentElement, PackagingElementNode<?> node) {
PackagingElementNode<?> current = node;
List<String> dirNames = new ArrayList<String>();
while (current != null && !(current instanceof ArtifactRootNode)) {
final PackagingElement<?> packagingElement = current.getFirstElement();
if (!(packagingElement instanceof DirectoryPackagingElement)) {
return parentElement;
}
dirNames.add(((DirectoryPackagingElement)packagingElement).getDirectoryName());
current = current.getParentNode();
}
if (current == null) return parentElement;
final PackagingElement<?> rootElement = current.getElementIfSingle();
if (!(rootElement instanceof CompositePackagingElement<?>)) return parentElement;
Collections.reverse(dirNames);
String path = StringUtil.join(dirNames, "/");
return PackagingElementFactory.getInstance().getOrCreateDirectory((CompositePackagingElement<?>)rootElement, path);
}
public boolean checkCanModify(@NotNull PackagingElement<?> element, @NotNull PackagingElementNode<?> node) {
return checkCanModify(node.getNodeSource(element));
}
public boolean checkCanModifyChildren(@NotNull PackagingElement<?> parentElement,
@NotNull PackagingElementNode<?> parentNode,
@NotNull Collection<? extends PackagingElementNode<?>> children) {
final List<PackagingNodeSource> sources = new ArrayList<PackagingNodeSource>(parentNode.getNodeSource(parentElement));
for (PackagingElementNode<?> child : children) {
sources.addAll(child.getNodeSources());
}
return checkCanModify(sources);
}
public boolean checkCanModify(final Collection<PackagingNodeSource> nodeSources) {
if (nodeSources.isEmpty()) {
return true;
}
if (nodeSources.size() > 1) {
Messages.showErrorDialog(myArtifactsEditor.getMainComponent(),
"The selected node consist of several elements so it cannot be edited.\nSwitch off 'Show content of elements' checkbox to edit the output layout.");
}
else {
final PackagingNodeSource source = ContainerUtil.getFirstItem(nodeSources, null);
if (source != null) {
Messages.showErrorDialog(myArtifactsEditor.getMainComponent(),
"The selected node belongs to '" + source.getPresentableName() + "' element so it cannot be edited.\nSwitch off 'Show content of elements' checkbox to edit the output layout.");
}
}
return false;
}
public boolean checkCanAdd(CompositePackagingElement<?> parentElement, PackagingElementNode<?> parentNode) {
boolean allParentsAreDirectories = true;
PackagingElementNode<?> current = parentNode;
while (current != null && !(current instanceof ArtifactRootNode)) {
final PackagingElement<?> element = current.getFirstElement();
if (!(element instanceof DirectoryPackagingElement)) {
allParentsAreDirectories = false;
break;
}
current = current.getParentNode();
}
return allParentsAreDirectories || checkCanModify(parentElement, parentNode);
}
public boolean checkCanRemove(final List<? extends PackagingElementNode<?>> nodes) {
Set<PackagingNodeSource> rootSources = new HashSet<PackagingNodeSource>();
for (PackagingElementNode<?> node : nodes) {
rootSources.addAll(getRootNodeSources(node.getNodeSources()));
}
if (!rootSources.isEmpty()) {
final String message;
if (rootSources.size() == 1) {
final String name = rootSources.iterator().next().getPresentableName();
message = "The selected node belongs to '" + name + "' element. Do you want to remove the whole '" + name + "' element from the artifact?";
}
else {
message = "The selected node belongs to " + nodes.size() + " elements. Do you want to remove all these elements from the artifact?";
}
final int answer = Messages.showYesNoDialog(myArtifactsEditor.getMainComponent(), message, "Remove Elements", null);
if (answer != Messages.YES) return false;
}
return true;
}
public void updateAndSelect(PackagingElementNode<?> node, final List<? extends PackagingElement<?>> toSelect) {
myArtifactsEditor.queueValidation();
myTreeStructure.clearCaches();
myBuilder.queueUpdateFrom(node, true).doWhenDone(new Runnable() {
@Override
public void run() {
List<PackagingElementNode<?>> nodes = myTree.findNodes(toSelect);
myBuilder.select(ArrayUtil.toObjectArray(nodes), null);
}
});
}
public void selectNode(@NotNull String parentPath, @NotNull PackagingElement<?> element) {
final PackagingElementNode<?> parent = myTree.findCompositeNodeByPath(parentPath);
if (parent == null) return;
for (SimpleNode node : parent.getChildren()) {
if (node instanceof PackagingElementNode) {
final List<? extends PackagingElement<?>> elements = ((PackagingElementNode<?>)node).getPackagingElements();
for (PackagingElement<?> packagingElement : elements) {
if (packagingElement.isEqualTo(element)) {
myBuilder.select(node);
return;
}
}
}
}
}
@TestOnly
public void selectNode(@NotNull String parentPath, @NotNull String nodeName) {
final PackagingElementNode<?> parent = myTree.findCompositeNodeByPath(parentPath);
if (parent == null) return;
for (SimpleNode node : parent.getChildren()) {
if (node instanceof PackagingElementNode) {
if (nodeName.equals(((PackagingElementNode)node).getElementPresentation().getSearchName())) {
myBuilder.select(node);
return;
}
}
}
}
public void editLayout(Runnable action) {
myContext.editLayout(myOriginalArtifact, action);
}
public void removeSelectedElements() {
final LayoutTreeSelection selection = myTree.getSelection();
if (!checkCanRemove(selection.getNodes())) return;
editLayout(new Runnable() {
@Override
public void run() {
removeNodes(selection.getNodes());
}
});
myArtifactsEditor.rebuildTries();
}
public void removeNodes(final List<PackagingElementNode<?>> nodes) {
Set<PackagingElement<?>> parents = new HashSet<PackagingElement<?>>();
for (PackagingElementNode<?> node : nodes) {
final List<? extends PackagingElement<?>> toDelete = node.getPackagingElements();
for (PackagingElement<?> element : toDelete) {
final Collection<PackagingNodeSource> nodeSources = node.getNodeSource(element);
if (nodeSources.isEmpty()) {
final CompositePackagingElement<?> parent = node.getParentElement(element);
if (parent != null) {
parents.add(parent);
parent.removeChild(element);
}
}
else {
Collection<PackagingNodeSource> rootSources = getRootNodeSources(nodeSources);
for (PackagingNodeSource source : rootSources) {
parents.add(source.getSourceParentElement());
source.getSourceParentElement().removeChild(source.getSourceElement());
}
}
}
}
final List<PackagingElementNode<?>> parentNodes = myTree.findNodes(parents);
for (PackagingElementNode<?> parentNode : parentNodes) {
myTree.addSubtreeToUpdate(parentNode);
}
}
private static Collection<PackagingNodeSource> getRootNodeSources(Collection<PackagingNodeSource> nodeSources) {
Set<PackagingNodeSource> result = new HashSet<PackagingNodeSource>();
collectRootNodeSources(nodeSources, result);
return result;
}
private static void collectRootNodeSources(Collection<PackagingNodeSource> nodeSources, Set<PackagingNodeSource> result) {
for (PackagingNodeSource nodeSource : nodeSources) {
final Collection<PackagingNodeSource> parentSources = nodeSource.getParentSources();
if (parentSources.isEmpty()) {
result.add(nodeSource);
}
else {
collectRootNodeSources(parentSources, result);
}
}
}
private PackagingElementNode<?> getParentNode(final LayoutTreeSelection selection) {
final PackagingElementNode<?> node = selection.getNodeIfSingle();
if (node != null) {
if (node.getFirstElement() instanceof CompositePackagingElement) {
return node;
}
final PackagingElementNode<?> parent = node.getParentNode();
if (parent != null) {
return parent;
}
}
return myTree.getRootPackagingNode();
}
public JPanel getTreePanel() {
return myTreePanel;
}
@Override
public void dispose() {
if (!ApplicationManager.getApplication().isUnitTestMode()) {
DnDManager.getInstance().unregisterTarget(this, myTree);
}
}
@Override
public boolean update(DnDEvent aEvent) {
aEvent.setDropPossible(false);
aEvent.hideHighlighter();
final Object object = aEvent.getAttachedObject();
if (object instanceof PackagingElementDraggingObject) {
final DefaultMutableTreeNode parent = findParentCompositeElementNode(aEvent.getRelativePoint().getPoint(myTree));
if (parent != null) {
final PackagingElementDraggingObject draggingObject = (PackagingElementDraggingObject)object;
final PackagingElementNode node = getNode(parent);
if (node != null && draggingObject.canDropInto(node)) {
final PackagingElement element = node.getFirstElement();
if (element instanceof CompositePackagingElement) {
draggingObject.setTargetNode(node);
draggingObject.setTargetElement((CompositePackagingElement<?>)element);
final Rectangle bounds = myTree.getPathBounds(TreeUtil.getPathFromRoot(parent));
aEvent.setHighlighting(new RelativeRectangle(myTree, bounds), DnDEvent.DropTargetHighlightingType.RECTANGLE);
aEvent.setDropPossible(true);
}
}
}
}
return false;
}
@Override
public void drop(DnDEvent aEvent) {
final Object object = aEvent.getAttachedObject();
if (object instanceof PackagingElementDraggingObject) {
final PackagingElementDraggingObject draggingObject = (PackagingElementDraggingObject)object;
final PackagingElementNode<?> targetNode = draggingObject.getTargetNode();
final CompositePackagingElement<?> targetElement = draggingObject.getTargetElement();
if (targetElement == null || targetNode == null || !draggingObject.checkCanDrop()) return;
if (!checkCanAdd(targetElement, targetNode)) {
return;
}
final List<PackagingElement<?>> toSelect = new ArrayList<PackagingElement<?>>();
editLayout(new Runnable() {
@Override
public void run() {
draggingObject.beforeDrop();
final CompositePackagingElement<?> parent = getOrCreateModifiableParent(targetElement, targetNode);
for (PackagingElement<?> element : draggingObject.createPackagingElements(myContext)) {
toSelect.add(element);
parent.addOrFindChild(element);
}
}
});
updateAndSelect(targetNode, toSelect);
myArtifactsEditor.getSourceItemsTree().rebuildTree();
}
}
@Nullable
private DefaultMutableTreeNode findParentCompositeElementNode(Point point) {
TreePath path = myTree.getPathForLocation(point.x, point.y);
while (path != null) {
final PackagingElement<?> element = myTree.getElementByPath(path);
if (element instanceof CompositePackagingElement) {
return (DefaultMutableTreeNode)path.getLastPathComponent();
}
path = path.getParentPath();
}
return null;
}
@Override
public void cleanUpOnLeave() {
}
@Override
public void updateDraggedImage(Image image, Point dropPoint, Point imageOffset) {
}
public void startRenaming(TreePath path) {
myTree.startEditingAtPath(path);
}
public boolean isEditing() {
return myTree.isEditing();
}
public void setRootElement(CompositePackagingElement<?> rootElement) {
myContext.getOrCreateModifiableArtifactModel().getOrCreateModifiableArtifact(myOriginalArtifact).setRootElement(rootElement);
myTreeStructure.updateRootElement();
final DefaultMutableTreeNode node = myTree.getRootNode();
node.setUserObject(myTreeStructure.getRootElement());
myBuilder.updateNode(node);
rebuildTree();
myArtifactsEditor.getSourceItemsTree().rebuildTree();
}
public CompositePackagingElement<?> getRootElement() {
return myContext.getRootElement(myOriginalArtifact);
}
public void updateTreeNodesPresentation() {
myBuilder.updateFromRoot(false);
}
public void updateRootNode() {
myBuilder.updateNode(myTree.getRootNode());
}
public void initTree() {
myBuilder.initRootNode();
mySelectedElementInfo.showPropertiesPanel();
}
public void putIntoDefaultLocations(@NotNull final List<? extends PackagingSourceItem> items) {
final List<PackagingElement<?>> toSelect = new ArrayList<PackagingElement<?>>();
editLayout(new Runnable() {
@Override
public void run() {
final CompositePackagingElement<?> rootElement = getArtifact().getRootElement();
final ArtifactType artifactType = getArtifact().getArtifactType();
for (PackagingSourceItem item : items) {
final String path = artifactType.getDefaultPathFor(item);
if (path != null) {
final CompositePackagingElement<?> parent;
if (path.endsWith(URLUtil.JAR_SEPARATOR)) {
parent = PackagingElementFactory.getInstance().getOrCreateArchive(rootElement, StringUtil.trimEnd(path, URLUtil.JAR_SEPARATOR));
}
else {
parent = PackagingElementFactory.getInstance().getOrCreateDirectory(rootElement, path);
}
final List<? extends PackagingElement<?>> elements = item.createElements(myContext);
toSelect.addAll(parent.addOrFindChildren(elements));
}
}
}
});
myArtifactsEditor.getSourceItemsTree().rebuildTree();
updateAndSelect(myTree.getRootPackagingNode(), toSelect);
}
public void putElements(@NotNull final String path, @NotNull final List<? extends PackagingElement<?>> elements) {
final List<PackagingElement<?>> toSelect = new ArrayList<PackagingElement<?>>();
editLayout(new Runnable() {
@Override
public void run() {
final CompositePackagingElement<?> directory =
PackagingElementFactory.getInstance().getOrCreateDirectory(getArtifact().getRootElement(), path);
toSelect.addAll(directory.addOrFindChildren(elements));
}
});
myArtifactsEditor.getSourceItemsTree().rebuildTree();
updateAndSelect(myTree.getRootPackagingNode(), toSelect);
}
public void packInto(@NotNull final List<? extends PackagingSourceItem> items, final String pathToJar) {
final List<PackagingElement<?>> toSelect = new ArrayList<PackagingElement<?>>();
final CompositePackagingElement<?> rootElement = getArtifact().getRootElement();
editLayout(new Runnable() {
@Override
public void run() {
final CompositePackagingElement<?> archive = PackagingElementFactory.getInstance().getOrCreateArchive(rootElement, pathToJar);
for (PackagingSourceItem item : items) {
final List<? extends PackagingElement<?>> elements = item.createElements(myContext);
archive.addOrFindChildren(elements);
}
toSelect.add(archive);
}
});
myArtifactsEditor.getSourceItemsTree().rebuildTree();
updateAndSelect(myTree.getRootPackagingNode(), toSelect);
}
public boolean isPropertiesModified() {
final PackagingElementPropertiesPanel panel = mySelectedElementInfo.myCurrentPanel;
return panel != null && panel.isModified();
}
public void resetElementProperties() {
final PackagingElementPropertiesPanel panel = mySelectedElementInfo.myCurrentPanel;
if (panel != null) {
panel.reset();
}
}
public boolean isSortElements() {
return mySortElements;
}
private class SelectedElementInfo<E extends PackagingElement<?>> {
private final E myElement;
private PackagingElementPropertiesPanel myCurrentPanel;
private SelectedElementInfo(@Nullable E element) {
myElement = element;
if (myElement != null) {
//noinspection unchecked
myCurrentPanel = element.getType().createElementPropertiesPanel(myElement, myContext);
myPropertiesPanel.removeAll();
if (myCurrentPanel != null) {
myPropertiesPanel.add(BorderLayout.CENTER, ScrollPaneFactory.createScrollPane(myCurrentPanel.createComponent(), true));
myCurrentPanel.reset();
myPropertiesPanel.revalidate();
}
}
}
public void save() {
if (myCurrentPanel != null && myCurrentPanel.isModified()) {
editLayout(new Runnable() {
@Override
public void run() {
myCurrentPanel.apply();
}
});
}
}
public void showPropertiesPanel() {
final CardLayout cardLayout = (CardLayout)myPropertiesPanelWrapper.getLayout();
if (myCurrentPanel != null) {
cardLayout.show(myPropertiesPanelWrapper, PROPERTIES_CARD);
}
else {
cardLayout.show(myPropertiesPanelWrapper, EMPTY_CARD);
}
myPropertiesPanelWrapper.repaint();
}
}
private class LayoutTreeStructure extends SimpleTreeStructure {
private ArtifactRootNode myRootNode;
@Override
public Object getRootElement() {
if (myRootNode == null) {
myRootNode = PackagingTreeNodeFactory.createRootNode(myArtifactsEditor, myContext, mySubstitutionParameters, getArtifact().getArtifactType());
}
return myRootNode;
}
public void updateRootElement() {
myRootNode = null;
}
}
private class LayoutTreeBuilder extends SimpleTreeBuilder {
public LayoutTreeBuilder() {
super(LayoutTreeComponent.this.myTree, LayoutTreeComponent.this.myTree.getBuilderModel(), LayoutTreeComponent.this.myTreeStructure,
LayoutTreeComponent.this.getComparator());
}
@Override
public void updateNode(DefaultMutableTreeNode node) {
super.updateNode(node);
}
}
}
| apache-2.0 |
gabrielborgesmagalhaes/hadoop-hdfs | src/java/org/apache/hadoop/hdfs/tools/offlineImageViewer/FileDistributionVisitor.java | 6070 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs.tools.offlineImageViewer;
import java.io.IOException;
import java.util.LinkedList;
/**
* File size distribution visitor.
*
* <h3>Description.</h3>
* This is the tool for analyzing file sizes in the namespace image.
* In order to run the tool one should define a range of integers
* <tt>[0, maxSize]</tt> by specifying <tt>maxSize</tt> and a <tt>step</tt>.
* The range of integers is divided into segments of size <tt>step</tt>:
* <tt>[0, s<sub>1</sub>, ..., s<sub>n-1</sub>, maxSize]</tt>,
* and the visitor calculates how many files in the system fall into
* each segment <tt>[s<sub>i-1</sub>, s<sub>i</sub>)</tt>.
* Note that files larger than <tt>maxSize</tt> always fall into
* the very last segment.
*
* <h3>Input.</h3>
* <ul>
* <li><tt>filename</tt> specifies the location of the image file;</li>
* <li><tt>maxSize</tt> determines the range <tt>[0, maxSize]</tt> of files
* sizes considered by the visitor;</li>
* <li><tt>step</tt> the range is divided into segments of size step.</li>
* </ul>
*
* <h3>Output.</h3>
* The output file is formatted as a tab separated two column table:
* Size and NumFiles. Where Size represents the start of the segment,
* and numFiles is the number of files form the image which size falls in
* this segment.
*/
class FileDistributionVisitor extends TextWriterImageVisitor {
final private LinkedList<ImageElement> elemS = new LinkedList<ImageElement>();
private final static long MAX_SIZE_DEFAULT = 0x2000000000L; // 1/8 TB = 2^37
private final static int INTERVAL_DEFAULT = 0x200000; // 2 MB = 2^21
private int[] distribution;
private long maxSize;
private int step;
private int totalFiles;
private int totalDirectories;
private int totalBlocks;
private long totalSpace;
private long maxFileSize;
private FileContext current;
private boolean inInode = false;
/**
* File or directory information.
*/
private static class FileContext {
String path;
long fileSize;
int numBlocks;
int replication;
}
public FileDistributionVisitor(String filename,
long maxSize,
int step) throws IOException {
super(filename, false);
this.maxSize = (maxSize == 0 ? MAX_SIZE_DEFAULT : maxSize);
this.step = (step == 0 ? INTERVAL_DEFAULT : step);
long numIntervals = this.maxSize / this.step;
if(numIntervals >= Integer.MAX_VALUE)
throw new IOException("Too many distribution intervals " + numIntervals);
this.distribution = new int[1 + (int)(numIntervals)];
this.totalFiles = 0;
this.totalDirectories = 0;
this.totalBlocks = 0;
this.totalSpace = 0;
this.maxFileSize = 0;
}
@Override
void start() throws IOException {}
@Override
void finish() throws IOException {
// write the distribution into the output file
write("Size\tNumFiles\n");
for(int i = 0; i < distribution.length; i++)
write(((long)i * step) + "\t" + distribution[i] + "\n");
System.out.println("totalFiles = " + totalFiles);
System.out.println("totalDirectories = " + totalDirectories);
System.out.println("totalBlocks = " + totalBlocks);
System.out.println("totalSpace = " + totalSpace);
System.out.println("maxFileSize = " + maxFileSize);
super.finish();
}
@Override
void leaveEnclosingElement() throws IOException {
ImageElement elem = elemS.pop();
if(elem != ImageElement.INODE &&
elem != ImageElement.INODE_UNDER_CONSTRUCTION)
return;
inInode = false;
if(current.numBlocks < 0) {
totalDirectories ++;
return;
}
totalFiles++;
totalBlocks += current.numBlocks;
totalSpace += current.fileSize * current.replication;
if(maxFileSize < current.fileSize)
maxFileSize = current.fileSize;
int high;
if(current.fileSize > maxSize)
high = distribution.length-1;
else
high = (int)Math.ceil((double)current.fileSize / step);
distribution[high]++;
if(totalFiles % 1000000 == 1)
System.out.println("Files processed: " + totalFiles
+ " Current: " + current.path);
}
@Override
void visit(ImageElement element, String value) throws IOException {
if(inInode) {
switch(element) {
case INODE_PATH:
current.path = (value.equals("") ? "/" : value);
break;
case REPLICATION:
current.replication = Integer.valueOf(value);
break;
case NUM_BYTES:
current.fileSize += Long.valueOf(value);
break;
default:
break;
}
}
}
@Override
void visitEnclosingElement(ImageElement element) throws IOException {
elemS.push(element);
if(element == ImageElement.INODE ||
element == ImageElement.INODE_UNDER_CONSTRUCTION) {
current = new FileContext();
inInode = true;
}
}
@Override
void visitEnclosingElement(ImageElement element,
ImageElement key, String value) throws IOException {
elemS.push(element);
if(element == ImageElement.INODE ||
element == ImageElement.INODE_UNDER_CONSTRUCTION)
inInode = true;
else if(element == ImageElement.BLOCKS)
current.numBlocks = Integer.parseInt(value);
}
}
| apache-2.0 |
RyanTech/DexHunter | dalvik/dexgen/src/com/android/dexgen/dex/code/InsnFormat.java | 18563 | /*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.dexgen.dex.code;
import com.android.dexgen.rop.code.RegisterSpecList;
import com.android.dexgen.rop.cst.Constant;
import com.android.dexgen.rop.cst.CstInteger;
import com.android.dexgen.rop.cst.CstKnownNull;
import com.android.dexgen.rop.cst.CstLiteral64;
import com.android.dexgen.rop.cst.CstLiteralBits;
import com.android.dexgen.util.AnnotatedOutput;
import com.android.dexgen.util.Hex;
/**
* Base class for all instruction format handlers. Instruction format
* handlers know how to translate {@link DalvInsn} instances into
* streams of code words, as well as human-oriented listing strings
* representing such translations.
*/
public abstract class InsnFormat {
/**
* Returns the string form, suitable for inclusion in a listing
* dump, of the given instruction. The instruction must be of this
* instance's format for proper operation.
*
* @param insn {@code non-null;} the instruction
* @param noteIndices whether to include an explicit notation of
* constant pool indices
* @return {@code non-null;} the string form
*/
public final String listingString(DalvInsn insn, boolean noteIndices) {
String op = insn.getOpcode().getName();
String arg = insnArgString(insn);
String comment = insnCommentString(insn, noteIndices);
StringBuilder sb = new StringBuilder(100);
sb.append(op);
if (arg.length() != 0) {
sb.append(' ');
sb.append(arg);
}
if (comment.length() != 0) {
sb.append(" // ");
sb.append(comment);
}
return sb.toString();
}
/**
* Returns the string form of the arguments to the given instruction.
* The instruction must be of this instance's format. If the instruction
* has no arguments, then the result should be {@code ""}, not
* {@code null}.
*
* <p>Subclasses must override this method.</p>
*
* @param insn {@code non-null;} the instruction
* @return {@code non-null;} the string form
*/
public abstract String insnArgString(DalvInsn insn);
/**
* Returns the associated comment for the given instruction, if any.
* The instruction must be of this instance's format. If the instruction
* has no comment, then the result should be {@code ""}, not
* {@code null}.
*
* <p>Subclasses must override this method.</p>
*
* @param insn {@code non-null;} the instruction
* @param noteIndices whether to include an explicit notation of
* constant pool indices
* @return {@code non-null;} the string form
*/
public abstract String insnCommentString(DalvInsn insn,
boolean noteIndices);
/**
* Gets the code size of instructions that use this format. The
* size is a number of 16-bit code units, not bytes. This should
* throw an exception if this format is of variable size.
*
* @return {@code >= 0;} the instruction length in 16-bit code units
*/
public abstract int codeSize();
/**
* Returns whether or not the given instruction's arguments will
* fit in this instance's format. This includes such things as
* counting register arguments, checking register ranges, and
* making sure that additional arguments are of appropriate types
* and are in-range. If this format has a branch target but the
* instruction's branch offset is unknown, this method will simply
* not check the offset.
*
* <p>Subclasses must override this method.</p>
*
* @param insn {@code non-null;} the instruction to check
* @return {@code true} iff the instruction's arguments are
* appropriate for this instance, or {@code false} if not
*/
public abstract boolean isCompatible(DalvInsn insn);
/**
* Returns whether or not the given instruction's branch offset will
* fit in this instance's format. This always returns {@code false}
* for formats that don't include a branch offset.
*
* <p>The default implementation of this method always returns
* {@code false}. Subclasses must override this method if they
* include branch offsets.</p>
*
* @param insn {@code non-null;} the instruction to check
* @return {@code true} iff the instruction's branch offset is
* appropriate for this instance, or {@code false} if not
*/
public boolean branchFits(TargetInsn insn) {
return false;
}
/**
* Returns the next instruction format to try to match an instruction
* with, presuming that this instance isn't compatible, if any.
*
* <p>Subclasses must override this method.</p>
*
* @return {@code null-ok;} the next format to try, or {@code null} if
* there are no suitable alternatives
*/
public abstract InsnFormat nextUp();
/**
* Writes the code units for the given instruction to the given
* output destination. The instruction must be of this instance's format.
*
* <p>Subclasses must override this method.</p>
*
* @param out {@code non-null;} the output destination to write to
* @param insn {@code non-null;} the instruction to write
*/
public abstract void writeTo(AnnotatedOutput out, DalvInsn insn);
/**
* Helper method to return a register list string.
*
* @param list {@code non-null;} the list of registers
* @return {@code non-null;} the string form
*/
protected static String regListString(RegisterSpecList list) {
int sz = list.size();
StringBuffer sb = new StringBuffer(sz * 5 + 2);
sb.append('{');
for (int i = 0; i < sz; i++) {
if (i != 0) {
sb.append(", ");
}
sb.append(list.get(i).regString());
}
sb.append('}');
return sb.toString();
}
/**
* Helper method to return a literal bits argument string.
*
* @param value the value
* @return {@code non-null;} the string form
*/
protected static String literalBitsString(CstLiteralBits value) {
StringBuffer sb = new StringBuffer(100);
sb.append('#');
if (value instanceof CstKnownNull) {
sb.append("null");
} else {
sb.append(value.typeName());
sb.append(' ');
sb.append(value.toHuman());
}
return sb.toString();
}
/**
* Helper method to return a literal bits comment string.
*
* @param value the value
* @param width the width of the constant, in bits (used for displaying
* the uninterpreted bits; one of: {@code 4 8 16 32 64}
* @return {@code non-null;} the comment
*/
protected static String literalBitsComment(CstLiteralBits value,
int width) {
StringBuffer sb = new StringBuffer(20);
sb.append("#");
long bits;
if (value instanceof CstLiteral64) {
bits = ((CstLiteral64) value).getLongBits();
} else {
bits = value.getIntBits();
}
switch (width) {
case 4: sb.append(Hex.uNibble((int) bits)); break;
case 8: sb.append(Hex.u1((int) bits)); break;
case 16: sb.append(Hex.u2((int) bits)); break;
case 32: sb.append(Hex.u4((int) bits)); break;
case 64: sb.append(Hex.u8(bits)); break;
default: {
throw new RuntimeException("shouldn't happen");
}
}
return sb.toString();
}
/**
* Helper method to return a branch address string.
*
* @param insn {@code non-null;} the instruction in question
* @return {@code non-null;} the string form of the instruction's branch target
*/
protected static String branchString(DalvInsn insn) {
TargetInsn ti = (TargetInsn) insn;
int address = ti.getTargetAddress();
return (address == (char) address) ? Hex.u2(address) : Hex.u4(address);
}
/**
* Helper method to return the comment for a branch.
*
* @param insn {@code non-null;} the instruction in question
* @return {@code non-null;} the comment
*/
protected static String branchComment(DalvInsn insn) {
TargetInsn ti = (TargetInsn) insn;
int offset = ti.getTargetOffset();
return (offset == (short) offset) ? Hex.s2(offset) : Hex.s4(offset);
}
/**
* Helper method to return a constant string.
*
* @param insn {@code non-null;} a constant-bearing instruction
* @return {@code non-null;} the string form of the contained constant
*/
protected static String cstString(DalvInsn insn) {
CstInsn ci = (CstInsn) insn;
Constant cst = ci.getConstant();
return cst.toHuman();
}
/**
* Helper method to return an instruction comment for a constant.
*
* @param insn {@code non-null;} a constant-bearing instruction
* @return {@code non-null;} comment string representing the constant
*/
protected static String cstComment(DalvInsn insn) {
CstInsn ci = (CstInsn) insn;
if (! ci.hasIndex()) {
return "";
}
StringBuilder sb = new StringBuilder(20);
int index = ci.getIndex();
sb.append(ci.getConstant().typeName());
sb.append('@');
if (index < 65536) {
sb.append(Hex.u2(index));
} else {
sb.append(Hex.u4(index));
}
return sb.toString();
}
/**
* Helper method to determine if a signed int value fits in a nibble.
*
* @param value the value in question
* @return {@code true} iff it's in the range -8..+7
*/
protected static boolean signedFitsInNibble(int value) {
return (value >= -8) && (value <= 7);
}
/**
* Helper method to determine if an unsigned int value fits in a nibble.
*
* @param value the value in question
* @return {@code true} iff it's in the range 0..0xf
*/
protected static boolean unsignedFitsInNibble(int value) {
return value == (value & 0xf);
}
/**
* Helper method to determine if a signed int value fits in a byte.
*
* @param value the value in question
* @return {@code true} iff it's in the range -0x80..+0x7f
*/
protected static boolean signedFitsInByte(int value) {
return (byte) value == value;
}
/**
* Helper method to determine if an unsigned int value fits in a byte.
*
* @param value the value in question
* @return {@code true} iff it's in the range 0..0xff
*/
protected static boolean unsignedFitsInByte(int value) {
return value == (value & 0xff);
}
/**
* Helper method to determine if a signed int value fits in a short.
*
* @param value the value in question
* @return {@code true} iff it's in the range -0x8000..+0x7fff
*/
protected static boolean signedFitsInShort(int value) {
return (short) value == value;
}
/**
* Helper method to determine if an unsigned int value fits in a short.
*
* @param value the value in question
* @return {@code true} iff it's in the range 0..0xffff
*/
protected static boolean unsignedFitsInShort(int value) {
return value == (value & 0xffff);
}
/**
* Helper method to determine if a signed int value fits in three bytes.
*
* @param value the value in question
* @return {@code true} iff it's in the range -0x800000..+0x7fffff
*/
protected static boolean signedFitsIn3Bytes(int value) {
return value == ((value << 8) >> 8);
}
/**
* Helper method to extract the callout-argument index from an
* appropriate instruction.
*
* @param insn {@code non-null;} the instruction
* @return {@code >= 0;} the callout argument index
*/
protected static int argIndex(DalvInsn insn) {
int arg = ((CstInteger) ((CstInsn) insn).getConstant()).getValue();
if (arg < 0) {
throw new IllegalArgumentException("bogus insn");
}
return arg;
}
/**
* Helper method to combine an opcode and a second byte of data into
* the appropriate form for emitting into a code buffer.
*
* @param insn {@code non-null;} the instruction containing the opcode
* @param arg {@code 0..255;} arbitrary other byte value
* @return combined value
*/
protected static short opcodeUnit(DalvInsn insn, int arg) {
if ((arg & 0xff) != arg) {
throw new IllegalArgumentException("arg out of range 0..255");
}
int opcode = insn.getOpcode().getOpcode();
if ((opcode & 0xff) != opcode) {
throw new IllegalArgumentException("opcode out of range 0..255");
}
return (short) (opcode | (arg << 8));
}
/**
* Helper method to combine two bytes into a code unit.
*
* @param low {@code 0..255;} low byte
* @param high {@code 0..255;} high byte
* @return combined value
*/
protected static short codeUnit(int low, int high) {
if ((low & 0xff) != low) {
throw new IllegalArgumentException("low out of range 0..255");
}
if ((high & 0xff) != high) {
throw new IllegalArgumentException("high out of range 0..255");
}
return (short) (low | (high << 8));
}
/**
* Helper method to combine four nibbles into a code unit.
*
* @param n0 {@code 0..15;} low nibble
* @param n1 {@code 0..15;} medium-low nibble
* @param n2 {@code 0..15;} medium-high nibble
* @param n3 {@code 0..15;} high nibble
* @return combined value
*/
protected static short codeUnit(int n0, int n1, int n2, int n3) {
if ((n0 & 0xf) != n0) {
throw new IllegalArgumentException("n0 out of range 0..15");
}
if ((n1 & 0xf) != n1) {
throw new IllegalArgumentException("n1 out of range 0..15");
}
if ((n2 & 0xf) != n2) {
throw new IllegalArgumentException("n2 out of range 0..15");
}
if ((n3 & 0xf) != n3) {
throw new IllegalArgumentException("n3 out of range 0..15");
}
return (short) (n0 | (n1 << 4) | (n2 << 8) | (n3 << 12));
}
/**
* Helper method to combine two nibbles into a byte.
*
* @param low {@code 0..15;} low nibble
* @param high {@code 0..15;} high nibble
* @return {@code 0..255;} combined value
*/
protected static int makeByte(int low, int high) {
if ((low & 0xf) != low) {
throw new IllegalArgumentException("low out of range 0..15");
}
if ((high & 0xf) != high) {
throw new IllegalArgumentException("high out of range 0..15");
}
return low | (high << 4);
}
/**
* Writes one code unit to the given output destination.
*
* @param out {@code non-null;} where to write to
* @param c0 code unit to write
*/
protected static void write(AnnotatedOutput out, short c0) {
out.writeShort(c0);
}
/**
* Writes two code units to the given output destination.
*
* @param out {@code non-null;} where to write to
* @param c0 code unit to write
* @param c1 code unit to write
*/
protected static void write(AnnotatedOutput out, short c0, short c1) {
out.writeShort(c0);
out.writeShort(c1);
}
/**
* Writes three code units to the given output destination.
*
* @param out {@code non-null;} where to write to
* @param c0 code unit to write
* @param c1 code unit to write
* @param c2 code unit to write
*/
protected static void write(AnnotatedOutput out, short c0, short c1,
short c2) {
out.writeShort(c0);
out.writeShort(c1);
out.writeShort(c2);
}
/**
* Writes four code units to the given output destination.
*
* @param out {@code non-null;} where to write to
* @param c0 code unit to write
* @param c1 code unit to write
* @param c2 code unit to write
* @param c3 code unit to write
*/
protected static void write(AnnotatedOutput out, short c0, short c1,
short c2, short c3) {
out.writeShort(c0);
out.writeShort(c1);
out.writeShort(c2);
out.writeShort(c3);
}
/**
* Writes five code units to the given output destination.
*
* @param out {@code non-null;} where to write to
* @param c0 code unit to write
* @param c1 code unit to write
* @param c2 code unit to write
* @param c3 code unit to write
* @param c4 code unit to write
*/
protected static void write(AnnotatedOutput out, short c0, short c1,
short c2, short c3, short c4) {
out.writeShort(c0);
out.writeShort(c1);
out.writeShort(c2);
out.writeShort(c3);
out.writeShort(c4);
}
/**
* Writes six code units to the given output destination.
*
* @param out {@code non-null;} where to write to
* @param c0 code unit to write
* @param c1 code unit to write
* @param c2 code unit to write
* @param c3 code unit to write
* @param c4 code unit to write
* @param c5 code unit to write
*/
protected static void write(AnnotatedOutput out, short c0, short c1,
short c2, short c3, short c4, short c5) {
out.writeShort(c0);
out.writeShort(c1);
out.writeShort(c2);
out.writeShort(c3);
out.writeShort(c4);
out.writeShort(c5);
}
}
| apache-2.0 |
stevem999/gocd | server/src/main/java/com/thoughtworks/go/server/messaging/plugin/PluginNotificationQueue.java | 1274 | /*************************GO-LICENSE-START*********************************
* Copyright 2014 ThoughtWorks, 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.
*************************GO-LICENSE-END***********************************/
package com.thoughtworks.go.server.messaging.plugin;
import com.thoughtworks.go.server.messaging.GoMessageQueue;
import com.thoughtworks.go.server.messaging.MessagingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class PluginNotificationQueue extends GoMessageQueue<PluginNotificationMessage> {
@Autowired
public PluginNotificationQueue(MessagingService messaging) {
super(messaging, "plugin-notification");
}
}
| apache-2.0 |
Lekanich/intellij-community | platform/xdebugger-api/src/com/intellij/xdebugger/settings/XDebuggerSettings.java | 2529 | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.xdebugger.settings;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.options.Configurable;
import com.intellij.xdebugger.XDebuggerUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
import java.util.Collections;
/**
* Implement this class to provide settings page for debugger. Settings page will be placed under 'Debugger' node in the 'Settings' dialog.
* An implementation should be registered in plugin.xml:
* <p>
* <extensions defaultExtensionNs="com.intellij"><br>
* <xdebugger.settings implementation="qualified-class-name"/><br>
* </extensions>
*
* @author nik
*/
public abstract class XDebuggerSettings<T> implements PersistentStateComponent<T> {
public static final ExtensionPointName<XDebuggerSettings> EXTENSION_POINT = ExtensionPointName.create("com.intellij.xdebugger.settings");
private final String myId;
protected XDebuggerSettings(final @NotNull @NonNls String id) {
myId = id;
}
protected static <S extends XDebuggerSettings<?>> S getInstance(Class<S> aClass) {
return XDebuggerUtil.getInstance().getDebuggerSettings(aClass);
}
public final String getId() {
return myId;
}
@Nullable
@Deprecated
/**
* @deprecated Please use {@link #createConfigurables(DebuggerSettingsCategory)}
*/
public Configurable createConfigurable() {
return null;
}
@NotNull
public Collection<? extends Configurable> createConfigurables(@NotNull DebuggerSettingsCategory category) {
return Collections.emptyList();
}
public void generalApplied(@NotNull DebuggerSettingsCategory category) {
}
public boolean isTargetedToProduct(@NotNull Configurable configurable) {
return false;
}
}
| apache-2.0 |
agoncharuk/ignite | modules/core/src/test/java/org/apache/ignite/util/GridSnapshotLockSelfTest.java | 3677 | /*
* 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.ignite.util;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.ignite.IgniteException;
import org.apache.ignite.internal.IgniteInternalFuture;
import org.apache.ignite.internal.util.GridSnapshotLock;
import org.apache.ignite.internal.util.typedef.T3;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
/**
*
*/
public class GridSnapshotLockSelfTest extends GridCommonAbstractTest {
/**
* @throws Exception If failed.
*/
public void testSyncConsistent() throws Exception {
final AtomicBoolean stop = new AtomicBoolean();
final AtomicLong x = new AtomicLong();
final AtomicLong y = new AtomicLong();
final AtomicLong z = new AtomicLong();
final Random rnd = new Random();
final String oops = "Oops!";
final GridSnapshotLock<T3<Long, Long, Long>> lock = new GridSnapshotLock<T3<Long, Long, Long>>() {
@Override protected T3<Long, Long, Long> doSnapshot() {
if (rnd.nextBoolean())
throw new IgniteException(oops);
return new T3<>(x.get(), y.get(), z.get());
}
};
IgniteInternalFuture<?> fut1 = multithreadedAsync(new Callable<Object>() {
@Override public Object call() throws Exception {
Random rnd = new Random();
while(!stop.get()) {
if (rnd.nextBoolean()) {
if (!lock.tryBeginUpdate())
continue;
}
else
lock.beginUpdate();
int n = 1 + rnd.nextInt(1000);
if (rnd.nextBoolean())
x.addAndGet(n);
else
y.addAndGet(n);
z.addAndGet(n);
lock.endUpdate();
}
return null;
}
}, 15, "update");
IgniteInternalFuture<?> fut2 = multithreadedAsync(new Callable<Object>() {
@Override public Object call() throws Exception {
while(!stop.get()) {
T3<Long, Long, Long> t;
try {
t = lock.snapshot();
}
catch (IgniteException e) {
assertEquals(oops, e.getMessage());
continue;
}
assertEquals(t.get3().longValue(), t.get1() + t.get2());
}
return null;
}
}, 8, "snapshot");
Thread.sleep(20000);
stop.set(true);
fut1.get();
fut2.get();
}
} | apache-2.0 |
agoncharuk/ignite | modules/core/src/main/java/org/apache/ignite/internal/util/lang/IgnitePredicate2X.java | 2234 | /*
* 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.ignite.internal.util.lang;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.internal.util.typedef.PX2;
import org.apache.ignite.lang.IgniteBiPredicate;
/**
* Convenient predicate subclass that allows for thrown grid exception. This class
* implements {@link #apply(Object, Object)} method that calls {@link #applyx(Object, Object)}
* method and properly wraps {@link IgniteCheckedException} into {@link GridClosureException} instance.
* @see PX2
*/
public abstract class IgnitePredicate2X<E1, E2> implements IgniteBiPredicate<E1, E2> {
/** */
private static final long serialVersionUID = 0L;
/** {@inheritDoc} */
@Override public boolean apply(E1 e1, E2 e2) {
try {
return applyx(e1, e2);
}
catch (IgniteCheckedException ex) {
throw F.wrap(ex);
}
}
/**
* Predicate body that can throw {@link IgniteCheckedException}.
*
* @param e1 First bound free variable, i.e. the element the predicate is called or closed on.
* @param e2 Second bound free variable, i.e. the element the predicate is called or closed on.
* @return Return value.
* @throws IgniteCheckedException Thrown in case of any error condition inside of the predicate.
*/
public abstract boolean applyx(E1 e1, E2 e2) throws IgniteCheckedException;
} | apache-2.0 |
mplushnikov/lombok-intellij-plugin | testData/after/val/ValErrors.java | 164 | public class ValErrors {
public void unresolvableExpression() {
final java.lang.Object c = d;
}
public void arrayInitializer() {
val e = {"foo", "bar"};
}
} | bsd-3-clause |
sarwarbhuiyan/elasticsearch | core/src/main/java/org/elasticsearch/action/update/TransportUpdateAction.java | 14881 | /*
* 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.action.update;
import com.google.common.collect.ImmutableList;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.ActionRunnable;
import org.elasticsearch.action.RoutingMissingException;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.create.TransportCreateIndexAction;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.delete.TransportDeleteAction;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.index.TransportIndexAction;
import org.elasticsearch.action.support.ActionFilters;
import org.elasticsearch.action.support.AutoCreateIndex;
import org.elasticsearch.action.support.TransportActions;
import org.elasticsearch.action.support.single.instance.TransportInstanceSingleOperationAction;
import org.elasticsearch.cluster.ClusterService;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver;
import org.elasticsearch.cluster.routing.PlainShardIterator;
import org.elasticsearch.cluster.routing.ShardIterator;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.engine.DocumentAlreadyExistsException;
import org.elasticsearch.index.engine.VersionConflictEngineException;
import org.elasticsearch.index.IndexService;
import org.elasticsearch.index.shard.IndexShard;
import org.elasticsearch.indices.IndexAlreadyExistsException;
import org.elasticsearch.indices.IndicesService;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.TransportService;
import java.util.Map;
/**
*/
public class TransportUpdateAction extends TransportInstanceSingleOperationAction<UpdateRequest, UpdateResponse> {
private final TransportDeleteAction deleteAction;
private final TransportIndexAction indexAction;
private final AutoCreateIndex autoCreateIndex;
private final TransportCreateIndexAction createIndexAction;
private final UpdateHelper updateHelper;
private final IndicesService indicesService;
@Inject
public TransportUpdateAction(Settings settings, ThreadPool threadPool, ClusterService clusterService, TransportService transportService,
TransportIndexAction indexAction, TransportDeleteAction deleteAction, TransportCreateIndexAction createIndexAction,
UpdateHelper updateHelper, ActionFilters actionFilters, IndexNameExpressionResolver indexNameExpressionResolver,
IndicesService indicesService, AutoCreateIndex autoCreateIndex) {
super(settings, UpdateAction.NAME, threadPool, clusterService, transportService, actionFilters, indexNameExpressionResolver, UpdateRequest.class);
this.indexAction = indexAction;
this.deleteAction = deleteAction;
this.createIndexAction = createIndexAction;
this.updateHelper = updateHelper;
this.indicesService = indicesService;
this.autoCreateIndex = autoCreateIndex;
}
@Override
protected String executor() {
return ThreadPool.Names.INDEX;
}
@Override
protected UpdateResponse newResponse() {
return new UpdateResponse();
}
@Override
protected boolean retryOnFailure(Throwable e) {
return TransportActions.isShardNotAvailableException(e);
}
@Override
protected boolean resolveRequest(ClusterState state, UpdateRequest request, ActionListener<UpdateResponse> listener) {
request.routing((state.metaData().resolveIndexRouting(request.routing(), request.index())));
// Fail fast on the node that received the request, rather than failing when translating on the index or delete request.
if (request.routing() == null && state.getMetaData().routingRequired(request.concreteIndex(), request.type())) {
throw new RoutingMissingException(request.concreteIndex(), request.type(), request.id());
}
return true;
}
@Override
protected void doExecute(final UpdateRequest request, final ActionListener<UpdateResponse> listener) {
// if we don't have a master, we don't have metadata, that's fine, let it find a master using create index API
if (autoCreateIndex.shouldAutoCreate(request.index(), clusterService.state())) {
createIndexAction.execute(new CreateIndexRequest(request).index(request.index()).cause("auto(update api)").masterNodeTimeout(request.timeout()), new ActionListener<CreateIndexResponse>() {
@Override
public void onResponse(CreateIndexResponse result) {
innerExecute(request, listener);
}
@Override
public void onFailure(Throwable e) {
if (ExceptionsHelper.unwrapCause(e) instanceof IndexAlreadyExistsException) {
// we have the index, do it
try {
innerExecute(request, listener);
} catch (Throwable e1) {
listener.onFailure(e1);
}
} else {
listener.onFailure(e);
}
}
});
} else {
innerExecute(request, listener);
}
}
private void innerExecute(final UpdateRequest request, final ActionListener<UpdateResponse> listener) {
super.doExecute(request, listener);
}
@Override
protected ShardIterator shards(ClusterState clusterState, UpdateRequest request) {
if (request.shardId() != -1) {
return clusterState.routingTable().index(request.concreteIndex()).shard(request.shardId()).primaryShardIt();
}
ShardIterator shardIterator = clusterService.operationRouting()
.indexShards(clusterState, request.concreteIndex(), request.type(), request.id(), request.routing());
ShardRouting shard;
while ((shard = shardIterator.nextOrNull()) != null) {
if (shard.primary()) {
return new PlainShardIterator(shardIterator.shardId(), ImmutableList.of(shard));
}
}
return new PlainShardIterator(shardIterator.shardId(), ImmutableList.<ShardRouting>of());
}
@Override
protected void shardOperation(final UpdateRequest request, final ActionListener<UpdateResponse> listener) {
shardOperation(request, listener, 0);
}
protected void shardOperation(final UpdateRequest request, final ActionListener<UpdateResponse> listener, final int retryCount) {
IndexService indexService = indicesService.indexServiceSafe(request.concreteIndex());
IndexShard indexShard = indexService.shardSafe(request.shardId());
final UpdateHelper.Result result = updateHelper.prepare(request, indexShard);
switch (result.operation()) {
case UPSERT:
IndexRequest upsertRequest = new IndexRequest((IndexRequest)result.action(), request);
// we fetch it from the index request so we don't generate the bytes twice, its already done in the index request
final BytesReference upsertSourceBytes = upsertRequest.source();
indexAction.execute(upsertRequest, new ActionListener<IndexResponse>() {
@Override
public void onResponse(IndexResponse response) {
UpdateResponse update = new UpdateResponse(response.getShardInfo(), response.getIndex(), response.getType(), response.getId(), response.getVersion(), response.isCreated());
if (request.fields() != null && request.fields().length > 0) {
Tuple<XContentType, Map<String, Object>> sourceAndContent = XContentHelper.convertToMap(upsertSourceBytes, true);
update.setGetResult(updateHelper.extractGetResult(request, request.concreteIndex(), response.getVersion(), sourceAndContent.v2(), sourceAndContent.v1(), upsertSourceBytes));
} else {
update.setGetResult(null);
}
listener.onResponse(update);
}
@Override
public void onFailure(Throwable e) {
e = ExceptionsHelper.unwrapCause(e);
if (e instanceof VersionConflictEngineException || e instanceof DocumentAlreadyExistsException) {
if (retryCount < request.retryOnConflict()) {
threadPool.executor(executor()).execute(new ActionRunnable<UpdateResponse>(listener) {
@Override
protected void doRun() {
shardOperation(request, listener, retryCount + 1);
}
});
return;
}
}
listener.onFailure(e);
}
});
break;
case INDEX:
IndexRequest indexRequest = new IndexRequest((IndexRequest)result.action(), request);
// we fetch it from the index request so we don't generate the bytes twice, its already done in the index request
final BytesReference indexSourceBytes = indexRequest.source();
indexAction.execute(indexRequest, new ActionListener<IndexResponse>() {
@Override
public void onResponse(IndexResponse response) {
UpdateResponse update = new UpdateResponse(response.getShardInfo(), response.getIndex(), response.getType(), response.getId(), response.getVersion(), response.isCreated());
update.setGetResult(updateHelper.extractGetResult(request, request.concreteIndex(), response.getVersion(), result.updatedSourceAsMap(), result.updateSourceContentType(), indexSourceBytes));
listener.onResponse(update);
}
@Override
public void onFailure(Throwable e) {
e = ExceptionsHelper.unwrapCause(e);
if (e instanceof VersionConflictEngineException) {
if (retryCount < request.retryOnConflict()) {
threadPool.executor(executor()).execute(new ActionRunnable<UpdateResponse>(listener) {
@Override
protected void doRun() {
shardOperation(request, listener, retryCount + 1);
}
});
return;
}
}
listener.onFailure(e);
}
});
break;
case DELETE:
DeleteRequest deleteRequest = new DeleteRequest((DeleteRequest)result.action(), request);
deleteAction.execute(deleteRequest, new ActionListener<DeleteResponse>() {
@Override
public void onResponse(DeleteResponse response) {
UpdateResponse update = new UpdateResponse(response.getShardInfo(), response.getIndex(), response.getType(), response.getId(), response.getVersion(), false);
update.setGetResult(updateHelper.extractGetResult(request, request.concreteIndex(), response.getVersion(), result.updatedSourceAsMap(), result.updateSourceContentType(), null));
listener.onResponse(update);
}
@Override
public void onFailure(Throwable e) {
e = ExceptionsHelper.unwrapCause(e);
if (e instanceof VersionConflictEngineException) {
if (retryCount < request.retryOnConflict()) {
threadPool.executor(executor()).execute(new ActionRunnable<UpdateResponse>(listener) {
@Override
protected void doRun() {
shardOperation(request, listener, retryCount + 1);
}
});
return;
}
}
listener.onFailure(e);
}
});
break;
case NONE:
UpdateResponse update = result.action();
IndexService indexServiceOrNull = indicesService.indexService(request.concreteIndex());
if (indexServiceOrNull != null) {
IndexShard shard = indexService.shard(request.shardId());
if (shard != null) {
shard.indexingService().noopUpdate(request.type());
}
}
listener.onResponse(update);
break;
default:
throw new IllegalStateException("Illegal operation " + result.operation());
}
}
}
| apache-2.0 |
akosyakov/intellij-community | java/java-tests/testData/refactoring/extractMethod/IDEADEV33368_after.java | 379 | class Test {
void m(boolean b) {
int x = 42;
try {
x = newMethod(b, x);
} catch(Exception e) {
System.out.println(x);
}
}
private int newMethod(boolean b, int x) throws Exception {
if(b) {
x = 23;
throw new Exception();
}
return x;
}
} | apache-2.0 |
wangkang0627/actor-platform | actor-apps/core/src/main/java/im/actor/model/droidkit/actors/MailboxCreator.java | 460 | /*
* Copyright (C) 2015 Actor LLC. <https://actor.im>
*/
package im.actor.model.droidkit.actors;
import im.actor.model.droidkit.actors.mailbox.Mailbox;
import im.actor.model.droidkit.actors.mailbox.MailboxesQueue;
/**
* Creator of mailbox for Actor
*/
public interface MailboxCreator {
/**
* Creating of mailbox in queue
*
* @param queue mailbox queue
* @return mailbox
*/
Mailbox createMailbox(MailboxesQueue queue);
}
| mit |
hardikamal/actor-platform | actor-apps/core/src/main/java/im/actor/model/network/mtp/entity/Pong.java | 980 | /*
* Copyright (C) 2015 Actor LLC. <https://actor.im>
*/
package im.actor.model.network.mtp.entity;
import im.actor.model.droidkit.bser.DataInput;
import im.actor.model.droidkit.bser.DataOutput;
import java.io.IOException;
public class Pong extends ProtoStruct {
public static final byte HEADER = (byte) 0x02;
private long randomId;
public Pong(DataInput stream) throws IOException {
super(stream);
}
public Pong(long randomId) {
this.randomId = randomId;
}
public long getRandomId() {
return randomId;
}
@Override
protected byte getHeader() {
return HEADER;
}
@Override
protected void writeBody(DataOutput bs) throws IOException {
bs.writeLong(randomId);
}
@Override
protected void readBody(DataInput bs) throws IOException {
randomId = bs.readLong();
}
@Override
public String toString() {
return "Pong{" + randomId + "}";
}
}
| mit |
android-ia/platform_tools_idea | platform/platform-api/src/com/intellij/ui/EditableRowTable.java | 6402 | /*
* Copyright 2000-2011 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ui;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* @author Konstantin Bulenkov
*/
public class EditableRowTable{
private EditableRowTable() {
}
public static JPanel createButtonsTable(final JTable table, final RowEditableTableModel tableModel, boolean addMnemonics) {
JPanel buttonsPanel = new JPanel();
buttonsPanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
buttonsPanel.setLayout(new GridBagLayout());
GridBagConstraints gbConstraints = new GridBagConstraints();
gbConstraints.gridwidth = GridBagConstraints.REMAINDER;
gbConstraints.fill = GridBagConstraints.HORIZONTAL;
gbConstraints.insets = new Insets(2, 4, 2, 4);
final JButton addButton = new JButton();
addButton.setText(addMnemonics ?
UIBundle.message("row.add") :
UIBundle.message("row.add.without.mnemonic"));
addButton.setDefaultCapable(false);
buttonsPanel.add(addButton, gbConstraints);
final JButton removeButton = new JButton();
removeButton.setText(addMnemonics ?
UIBundle.message("row.remove") :
UIBundle.message("row.remove.without.mnemonic"));
removeButton.setDefaultCapable(false);
buttonsPanel.add(removeButton, gbConstraints);
final JButton upButton = new JButton();
upButton.setText(addMnemonics ?
UIBundle.message("row.move.up") :
UIBundle.message("row.move.up.without.mnemonic"));
upButton.setDefaultCapable(false);
buttonsPanel.add(upButton, gbConstraints);
final JButton downButton = new JButton();
downButton.setText(addMnemonics ?
UIBundle.message("row.move.down") :
UIBundle.message("row.move.down.without.mnemonic"));
downButton.setDefaultCapable(false);
buttonsPanel.add(downButton, gbConstraints);
gbConstraints.weighty = 1;
buttonsPanel.add(new JPanel(), gbConstraints);
addButton.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
TableUtil.stopEditing(table);
tableModel.addRow();
final int index = tableModel.getRowCount() - 1;
table.editCellAt(index, 0);
table.setRowSelectionInterval(index, index);
table.setColumnSelectionInterval(0, 0);
table.getParent().repaint();
final Component editorComponent = table.getEditorComponent();
if (editorComponent != null) {
final Rectangle bounds = editorComponent.getBounds();
table.scrollRectToVisible(bounds);
editorComponent.requestFocus();
}
}
}
);
removeButton.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
TableUtil.stopEditing(table);
int index = table.getSelectedRow();
if (0 <= index && index < tableModel.getRowCount()) {
tableModel.removeRow(index);
if (index < tableModel.getRowCount()) {
table.setRowSelectionInterval(index, index);
}
else {
if (index > 0) {
table.setRowSelectionInterval(index - 1, index - 1);
}
}
updateButtons(table, tableModel, addButton, removeButton, upButton, downButton);
}
table.getParent().repaint();
table.requestFocus();
}
}
);
upButton.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
TableUtil.stopEditing(table);
int index = table.getSelectedRow();
if (0 < index && index < tableModel.getRowCount()) {
tableModel.exchangeRows(index, index - 1);
table.setRowSelectionInterval(index - 1, index - 1);
}
table.requestFocus();
}
}
);
downButton.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
TableUtil.stopEditing(table);
int index = table.getSelectedRow();
if (0 <= index && index < tableModel.getRowCount() - 1) {
tableModel.exchangeRows(index, index + 1);
table.setRowSelectionInterval(index + 1, index + 1);
}
table.requestFocus();
}
}
);
table.getSelectionModel().addListSelectionListener(
new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
updateButtons(table, tableModel, addButton, removeButton, upButton, downButton);
}
}
);
updateButtons(table, tableModel, addButton, removeButton, upButton, downButton);
return buttonsPanel;
}
private static void updateButtons(JTable table, final RowEditableTableModel tableModel,
final JButton addButton,
final JButton removeButton,
final JButton upButton,
final JButton downButton) {
if (table.isEnabled()) {
int index = table.getSelectedRow();
if (0 <= index && index < tableModel.getRowCount()) {
removeButton.setEnabled(true);
upButton.setEnabled(index > 0);
downButton.setEnabled(index < tableModel.getRowCount() - 1);
}
else {
removeButton.setEnabled(false);
upButton.setEnabled(false);
downButton.setEnabled(false);
}
addButton.setEnabled(true);
}
}
}
| apache-2.0 |
akosyakov/intellij-community | xml/openapi/src/com/intellij/xml/breadcrumbs/BreadcrumbsInfoProvider.java | 1534 | /*
* 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.
*/
/*
* Created by IntelliJ IDEA.
* User: spleaner
* Date: Jun 19, 2007
* Time: 3:33:15 PM
*/
package com.intellij.xml.breadcrumbs;
import com.intellij.lang.Language;
import com.intellij.psi.PsiElement;
import com.intellij.openapi.extensions.ExtensionPointName;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public abstract class BreadcrumbsInfoProvider {
public static final ExtensionPointName<BreadcrumbsInfoProvider> EP_NAME = ExtensionPointName.create("com.intellij.breadcrumbsInfoProvider");
public abstract Language[] getLanguages();
public abstract boolean acceptElement(@NotNull final PsiElement e);
@Nullable
public PsiElement getParent(@NotNull final PsiElement e) {
return e.getParent();
}
@NotNull
public abstract String getElementInfo(@NotNull final PsiElement e);
@Nullable
public abstract String getElementTooltip(@NotNull final PsiElement e);
} | apache-2.0 |
pselle/jenkins | core/src/main/java/hudson/model/queue/QueueTaskDispatcher.java | 6457 | /*
* The MIT License
*
* Copyright (c) 2010, InfraDNA, 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.queue;
import hudson.Extension;
import hudson.ExtensionList;
import hudson.ExtensionPoint;
import hudson.model.Queue.Item;
import hudson.slaves.Cloud;
import jenkins.model.Jenkins;
import hudson.model.Node;
import hudson.model.Queue;
import hudson.model.Queue.BuildableItem;
import hudson.model.Queue.Task;
import javax.annotation.CheckForNull;
/**
* Vetos the execution of a task on a node
*
* <p>
* To register your dispatcher implementations, put @{@link Extension} on your subtypes.
*
* @author Kohsuke Kawaguchi
* @since 1.360
*/
public abstract class QueueTaskDispatcher implements ExtensionPoint {
/**
* Called whenever {@link Queue} is considering to execute the given task on a given node.
*
* <p>
* Implementations can return null to indicate that the assignment is fine, or it can return
* a non-null instance to block the execution of the task on the given node.
*
* <p>
* Queue doesn't remember/cache the response from dispatchers, and instead it'll keep asking.
* The upside of this is that it's very easy to block execution for a limited time period (
* as you just need to return null when it's ready to execute.) The downside of this is that
* the decision needs to be made quickly.
*
* <p>
* Vetos are additive. When multiple {@link QueueTaskDispatcher}s are in the system,
* the task won't run on the given node if any one of them returns a non-null value.
* (This relationship is also the same with built-in check logic.)
*
* @deprecated since 1.413
* Use {@link #canTake(Node, Queue.BuildableItem)}
*/
@Deprecated
public @CheckForNull CauseOfBlockage canTake(Node node, Task task) {
return null;
}
/**
* Called when {@link Queue} is deciding where to execute the given task.
*
* <p>
* Implementations can return null to indicate that the assignment is fine, or it can return
* a non-null instance to block the execution of the task on the given node.
*
* <p>
* Queue doesn't remember/cache the response from dispatchers, and instead it'll keep asking.
* The upside of this is that it's very easy to block execution for a limited time period (
* as you just need to return null when it's ready to execute.) The downside of this is that
* the decision needs to be made quickly.
*
* <p>
* This method is primarily designed to fine-tune where the execution should take place. If the execution
* shouldn't commence anywhere at all, implementation should use {@link #canRun(Queue.Item)} instead so
* that Jenkins understands the difference between "this node isn't the right place for this work"
* vs "the time isn't right for this work to execute." This affects the provisioning behaviour
* with elastic Jenkins deployments.
*
* <p>
* Vetos are additive. When multiple {@link QueueTaskDispatcher}s are in the system,
* the task won't run on the given node if any one of them returns a non-null value.
* (This relationship is also the same with built-in check logic.)
*
* @since 1.413
*/
public @CheckForNull CauseOfBlockage canTake(Node node, BuildableItem item) {
return canTake(node,item.task); // backward compatible behaviour
}
/**
* Called whenever {@link Queue} is considering if {@link hudson.model.Queue.Item} is ready to execute immediately
* (which doesn't necessarily mean that it gets executed right away — it's still subject to
* executor availability), or if it should be considered blocked.
*
* <p>
* Compared to {@link #canTake(Node, Queue.BuildableItem)}, this version tells Jenkins that the task is
* simply not ready to execute, even if there's available executor. This is more efficient
* than {@link #canTake(Node, Queue.BuildableItem)}, and it sends the right signal to Jenkins so that
* it won't use {@link Cloud} to try to provision new executors.
*
* <p>
* Vetos are additive. When multiple {@link QueueTaskDispatcher}s are in the system,
* the task is considered blocked if any one of them returns a non-null value.
* (This relationship is also the same with built-in check logic.)
*
* <p>
* If a {@link QueueTaskDispatcher} returns non-null from this method, the task is placed into
* the 'blocked' state, and generally speaking it stays in this state for a few seconds before
* its state gets re-evaluated. If a {@link QueueTaskDispatcher} wants the blockage condition
* to be re-evaluated earlier, call {@link Queue#scheduleMaintenance()} to initiate that process.
*
* @return
* null to indicate that the item is ready to proceed to the buildable state as far as this
* {@link QueueTaskDispatcher} is concerned. Otherwise return an object that indicates why
* the build is blocked.
* @since 1.427
*/
public @CheckForNull CauseOfBlockage canRun(Queue.Item item) {
return null;
}
/**
* All registered {@link QueueTaskDispatcher}s.
*/
public static ExtensionList<QueueTaskDispatcher> all() {
return ExtensionList.lookup(QueueTaskDispatcher.class);
}
}
| mit |
nsabharwal/presto | presto-spi/src/main/java/com/facebook/presto/spi/type/SqlTimestampWithTimeZone.java | 2655 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.spi.type;
import com.fasterxml.jackson.annotation.JsonValue;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;
import java.util.TimeZone;
import static com.facebook.presto.spi.type.DateTimeEncoding.unpackMillisUtc;
import static com.facebook.presto.spi.type.DateTimeEncoding.unpackZoneKey;
import static com.facebook.presto.spi.type.TimeZoneIndex.getTimeZoneForKey;
public final class SqlTimestampWithTimeZone
{
private final long millisUtc;
private final TimeZoneKey timeZoneKey;
public SqlTimestampWithTimeZone(long timestampWithTimeZone)
{
millisUtc = unpackMillisUtc(timestampWithTimeZone);
timeZoneKey = unpackZoneKey(timestampWithTimeZone);
}
public SqlTimestampWithTimeZone(long millisUtc, TimeZoneKey timeZoneKey)
{
this.millisUtc = millisUtc;
this.timeZoneKey = timeZoneKey;
}
public SqlTimestampWithTimeZone(long millisUtc, TimeZone timeZone)
{
this.millisUtc = millisUtc;
this.timeZoneKey = TimeZoneKey.getTimeZoneKey(timeZone.getID());
}
public long getMillisUtc()
{
return millisUtc;
}
public TimeZoneKey getTimeZoneKey()
{
return timeZoneKey;
}
@Override
public int hashCode()
{
return Objects.hash(millisUtc, timeZoneKey);
}
@Override
public boolean equals(Object obj)
{
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
SqlTimestampWithTimeZone other = (SqlTimestampWithTimeZone) obj;
return Objects.equals(this.millisUtc, other.millisUtc) &&
Objects.equals(this.timeZoneKey, other.timeZoneKey);
}
@JsonValue
@Override
public String toString()
{
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
format.setTimeZone(getTimeZoneForKey(timeZoneKey));
return format.format(new Date(millisUtc)) + " " + timeZoneKey.getId();
}
}
| apache-2.0 |
dmiszkiewicz/elasticsearch | src/main/java/org/elasticsearch/common/util/concurrent/EsAbortPolicy.java | 2693 | /*
* 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.common.util.concurrent;
import org.elasticsearch.ElasticsearchIllegalStateException;
import org.elasticsearch.common.metrics.CounterMetric;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
/**
*/
public class EsAbortPolicy implements XRejectedExecutionHandler {
private final CounterMetric rejected = new CounterMetric();
public static final String SHUTTING_DOWN_KEY = "(shutting down)";
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
if (r instanceof AbstractRunnable) {
if (((AbstractRunnable) r).isForceExecution()) {
BlockingQueue<Runnable> queue = executor.getQueue();
if (!(queue instanceof SizeBlockingQueue)) {
throw new ElasticsearchIllegalStateException("forced execution, but expected a size queue");
}
try {
((SizeBlockingQueue) queue).forcePut(r);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new ElasticsearchIllegalStateException("forced execution, but got interrupted", e);
}
return;
}
}
rejected.inc();
StringBuilder sb = new StringBuilder("rejected execution ");
if (executor.isShutdown()) {
sb.append(SHUTTING_DOWN_KEY + " ");
} else {
if (executor.getQueue() instanceof SizeBlockingQueue) {
sb.append("(queue capacity ").append(((SizeBlockingQueue) executor.getQueue()).capacity()).append(") ");
}
}
sb.append("on ").append(r.toString());
throw new EsRejectedExecutionException(sb.toString());
}
@Override
public long rejected() {
return rejected.count();
}
}
| apache-2.0 |
crowell/binnavi | src/main/java/com/google/security/zynamics/binnavi/Gui/Debug/MemoryPanel/Actions/CLittleEndiannessAction.java | 1631 | /*
Copyright 2015 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.google.security.zynamics.binnavi.Gui.Debug.MemoryPanel.Actions;
import com.google.common.base.Preconditions;
import com.google.security.zynamics.zylib.gui.JHexPanel.JHexView;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
/**
* Action class for toggling the display of a memory viewer to Little Endian.
*/
public final class CLittleEndiannessAction extends AbstractAction {
/**
* Used for serialization.
*/
private static final long serialVersionUID = -4528074491653335332L;
/**
* The memory viewer whose display is toggled.
*/
private final JHexView hexView;
/**
* Creates a new action object.
*
* @param hexView The memory viewer whose display is toggled.
*/
public CLittleEndiannessAction(final JHexView hexView) {
super("Little Endian");
this.hexView =
Preconditions.checkNotNull(hexView, "IE01420: Memory viewer argument can not be null");
}
@Override
public void actionPerformed(final ActionEvent event) {
hexView.setFlipBytes(true);
}
}
| apache-2.0 |
rokn/Count_Words_2015 | testing/openjdk2/langtools/test/tools/javac/file/zip/T6865530.java | 2368 | /*
* Copyright (c) 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 6865530
* @summary ensure JavacFileManager handles non-standard zipfiles.
* @compile -XDignore.symbol.file T6865530.java
* @run main T6865530
*/
import java.io.File;
public class T6865530 {
public static void main(String... args) throws Exception {
File badFile = new File("bad.exe");
File testJar = new File("test.jar");
File fooJava = new File("Foo.java");
File barJava = new File("Bar.java");
// create a jar by compiling a file, and append the jar to some
// arbitrary data to offset the start of the zip/jar archive
Utils.createJavaFile(fooJava);
Utils.compile("-doe", "-verbose", fooJava.getName());
String[] jarArgs = {
"cvf", testJar.getAbsolutePath(), "Foo.class"
};
Utils.jarTool.run(jarArgs);
Utils.cat(badFile, fooJava, testJar);
// create test file and use the above file as a classpath
Utils.createJavaFile(barJava);
try {
if (!Utils.compile("-doe", "-verbose", "-cp", badFile.getAbsolutePath(), "Bar.java")) {
throw new RuntimeException("test fails javac did not compile");
}
} finally {
Utils.deleteFile(badFile);
Utils.deleteFile(testJar);
}
}
}
| mit |
CandleCandle/camel | components/camel-spring-boot/src/test/java/org/apache/camel/spring/boot/CamelNonInvasiveCamelContextTest.java | 2804 | /**
* 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.boot;
import javax.annotation.Resource;
import org.apache.camel.CamelContext;
import org.apache.camel.ConsumerTemplate;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.spring.boot.CamelNonInvasiveCamelContextTest.TestApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@RunWith(SpringJUnit4ClassRunner.class)
@EnableAutoConfiguration
@SpringApplicationConfiguration(classes = { TestApplication.class, CamelNonInvasiveCamelContextTest.class })
public class CamelNonInvasiveCamelContextTest {
// Collaborators fixtures
@Autowired
CamelContext camelContext;
@Autowired
ProducerTemplate producerTemplate;
@Resource(name = "xmlProducerTemplate")
ProducerTemplate xmlProducerTemplate;
@Autowired
ConsumerTemplate consumerTemplate;
@Resource(name = "xmlConsumerTemplate")
ConsumerTemplate xmlConsumerTemplate;
// Tests
@Test
public void shouldUseCamelContextFromXml() {
assertNotNull(camelContext);
assertEquals("xmlCamelContext", camelContext.getName());
}
@Test
public void shouldUseProducerTemplateFromXml() {
assertNotNull(producerTemplate);
assertEquals(xmlProducerTemplate, producerTemplate);
}
@Test
public void shouldUseConsumerTemplateFromXml() {
assertNotNull(consumerTemplate);
assertEquals(xmlConsumerTemplate, consumerTemplate);
}
@ImportResource(value = { "classpath:externalCamelContext.xml" })
public static class TestApplication {
}
} | apache-2.0 |
tvomf/appinventor-mapps | appinventor/appengine/src/com/google/appinventor/client/explorer/commands/BuildCommand.java | 4269 | // -*- mode: java; c-basic-offset: 2; -*-
// Copyright 2009-2011 Google, All Rights reserved
// Copyright 2011-2012 MIT, All rights reserved
// Released under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
package com.google.appinventor.client.explorer.commands;
import com.google.appinventor.client.ErrorReporter;
import com.google.appinventor.client.Ode;
import static com.google.appinventor.client.Ode.MESSAGES;
import com.google.appinventor.client.OdeAsyncCallback;
import com.google.appinventor.client.output.MessagesOutput;
import com.google.appinventor.client.tracking.Tracking;
import com.google.appinventor.shared.rpc.RpcResult;
import com.google.appinventor.shared.rpc.project.ProjectNode;
import com.google.gwt.http.client.Response;
import com.google.gwt.i18n.client.DateTimeFormat;
import java.util.Date;
/**
* Command for building a target in a project.
*
*/
public class BuildCommand extends ChainableCommand {
// The build target
private String target;
/**
* Creates a new build command.
*
* @param target the build target
*/
public BuildCommand(String target) {
this(target, null);
}
/**
* Creates a new build command, with additional behavior provided by
* another ChainableCommand.
*
* @param target the build target
* @param nextCommand the command to execute after the build has finished
*/
public BuildCommand(String target, ChainableCommand nextCommand) {
super(nextCommand);
this.target = target;
}
@Override
public boolean willCallExecuteNextCommand() {
return true;
}
@Override
public void execute(final ProjectNode node) {
final Ode ode = Ode.getInstance();
final MessagesOutput messagesOutput = MessagesOutput.getMessagesOutput();
messagesOutput.clear();
messagesOutput.addMessages(MESSAGES.buildRequestedMessage(node.getName(),
DateTimeFormat.getMediumDateTimeFormat().format(new Date())));
OdeAsyncCallback<RpcResult> callback =
new OdeAsyncCallback<RpcResult>(
// failure message
MESSAGES.buildError()) {
@Override
public void onSuccess(RpcResult result) {
messagesOutput.addMessages(result.getOutput());
messagesOutput.addMessages(result.getError());
Tracking.trackEvent(Tracking.PROJECT_EVENT, Tracking.PROJECT_SUBACTION_BUILD_YA,
node.getName(), getElapsedMillis());
if (result.succeeded()) {
executeNextCommand(node);
} else {
// The result is the HTTP response code from the build server.
int responseCode = result.getResult();
switch (responseCode) {
case Response.SC_SERVICE_UNAVAILABLE:
// SC_SERVICE_UNAVAILABLE (response code 503), means that the build server is too busy
// at this time to accept this build request.
// We use ErrorReporter.reportInfo so that the message has yellow background instead of
// red background.
ErrorReporter.reportInfo(MESSAGES.buildServerBusyError());
break;
case Response.SC_CONFLICT:
// SC_CONFLICT (response code 409), means that the build server is running a
// different version of the App Inventor code.
// We use ErrorReporter.reportInfo so that the message has yellow background instead
// of red background.
ErrorReporter.reportInfo(MESSAGES.buildServerDifferentVersion());
break;
default:
String errorMsg = result.getError();
// This is not an internal App Inventor bug. The error is reported as info so that
// the red background is not shown.
ErrorReporter.reportInfo(MESSAGES.buildFailedError() +
(errorMsg.isEmpty() ? "" : " " + errorMsg));
break;
}
executionFailedOrCanceled();
}
}
@Override
public void onFailure(Throwable caught) {
super.onFailure(caught);
executionFailedOrCanceled();
}
};
String nonce = ode.generateNonce();
ode.getProjectService().build(node.getProjectId(), nonce, target, callback);
}
}
| apache-2.0 |
ChunPIG/spring-boot | spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/MustacheResourceTemplateLoader.java | 2392 | /*
* Copyright 2012-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.autoconfigure.mustache;
import java.io.InputStreamReader;
import java.io.Reader;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Mustache.TemplateLoader;
/**
* Mustache TemplateLoader implementation that uses a prefix, suffix and the Spring
* Resource abstraction to load a template from a file, classpath, URL etc. A
* TemplateLoader is needed in the Compiler when you want to render partials (i.e.
* tiles-like features).
*
* @author Dave Syer
* @since 1.2.2
* @see Mustache
* @see Resource
*/
public class MustacheResourceTemplateLoader implements TemplateLoader,
ResourceLoaderAware {
private String prefix = "";
private String suffix = "";
private String charSet = "UTF-8";
private ResourceLoader resourceLoader = new DefaultResourceLoader();
public MustacheResourceTemplateLoader() {
}
public MustacheResourceTemplateLoader(String prefix, String suffix) {
super();
this.prefix = prefix;
this.suffix = suffix;
}
/**
* Set the charset.
* @param charSet the charset
*/
public void setCharset(String charSet) {
this.charSet = charSet;
}
/**
* Set the resource loader.
* @param resourceLoader the resource loader
*/
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
@Override
public Reader getTemplate(String name) throws Exception {
return new InputStreamReader(this.resourceLoader.getResource(
this.prefix + name + this.suffix).getInputStream(), this.charSet);
}
}
| apache-2.0 |
asedunov/intellij-community | python/src/com/jetbrains/python/validation/ImportAnnotator.java | 1273 | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.validation;
import com.intellij.psi.util.PsiTreeUtil;
import com.jetbrains.python.PyBundle;
import com.jetbrains.python.psi.PyClass;
import com.jetbrains.python.psi.PyFromImportStatement;
import com.jetbrains.python.psi.PyFunction;
/**
* Checks for non-top-level star imports.
*/
public class ImportAnnotator extends PyAnnotator {
@Override
public void visitPyFromImportStatement(final PyFromImportStatement node) {
if (node.isStarImport() && PsiTreeUtil.getParentOfType(node, PyFunction.class, PyClass.class) != null) {
getHolder().createWarningAnnotation(node, PyBundle.message("ANN.star.import.at.top.only"));
}
}
}
| apache-2.0 |
tbadie/spring-boot | spring-boot/src/main/java/org/springframework/boot/context/ContextIdApplicationContextInitializer.java | 3342 | /*
* Copyright 2010-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.context;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.util.StringUtils;
/**
* {@link ApplicationContextInitializer} that set the Spring
* {@link ApplicationContext#getId() ApplicationContext ID}. The following environment
* properties will be consulted to create the ID:
* <ul>
* <li>spring.application.name</li>
* <li>vcap.application.name</li>
* <li>spring.config.name</li>
* </ul>
* If no property is set the ID 'application' will be used.
*
* <p>
* In addition the following environment properties will be consulted to append a relevant
* port or index:
*
* <ul>
* <li>spring.application.index</li>
* <li>vcap.application.instance_index</li>
* <li>PORT</li>
* </ul>
*
* @author Dave Syer
*/
public class ContextIdApplicationContextInitializer implements
ApplicationContextInitializer<ConfigurableApplicationContext>, Ordered {
/**
* Placeholder pattern to resolve for application name.
*/
private static final String NAME_PATTERN = "${vcap.application.name:${spring.application.name:${spring.config.name:application}}}";
/**
* Placeholder pattern to resolve for application index.
*/
private static final String INDEX_PATTERN = "${vcap.application.instance_index:${spring.application.index:${server.port:${PORT:null}}}}";
private final String name;
private int order = Integer.MAX_VALUE - 10;
public ContextIdApplicationContextInitializer() {
this(NAME_PATTERN);
}
/**
* Create a new {@link ContextIdApplicationContextInitializer} instance.
* @param name the name of the application (can include placeholders)
*/
public ContextIdApplicationContextInitializer(String name) {
this.name = name;
}
public void setOrder(int order) {
this.order = order;
}
@Override
public int getOrder() {
return this.order;
}
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
applicationContext.setId(getApplicationId(applicationContext.getEnvironment()));
}
private String getApplicationId(ConfigurableEnvironment environment) {
String name = environment.resolvePlaceholders(this.name);
String index = environment.resolvePlaceholders(INDEX_PATTERN);
String profiles = StringUtils.arrayToCommaDelimitedString(environment
.getActiveProfiles());
if (StringUtils.hasText(profiles)) {
name = name + ":" + profiles;
}
if (!"null".equals(index)) {
name = name + ":" + index;
}
return name;
}
}
| apache-2.0 |
ApiSecRay/spring-boot | spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/RunArguments.java | 1715 | /*
* Copyright 2012-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.maven;
import java.util.Arrays;
import java.util.LinkedList;
import org.codehaus.plexus.util.cli.CommandLineUtils;
/**
* Parse and expose arguments specified in a single string.
*
* @author Stephane Nicoll
* @since 1.1.0
*/
class RunArguments {
private static final String[] NO_ARGS = {};
private final LinkedList<String> args;
RunArguments(String arguments) {
this(parseArgs(arguments));
}
RunArguments(String[] args) {
this.args = new LinkedList<String>(Arrays.asList(args));
}
public LinkedList<String> getArgs() {
return this.args;
}
public String[] asArray() {
return this.args.toArray(new String[this.args.size()]);
}
private static String[] parseArgs(String arguments) {
if (arguments == null || arguments.trim().isEmpty()) {
return NO_ARGS;
}
try {
arguments = arguments.replace('\n', ' ').replace('\t', ' ');
return CommandLineUtils.translateCommandline(arguments);
}
catch (Exception ex) {
throw new IllegalArgumentException("Failed to parse arguments [" + arguments
+ "]", ex);
}
}
}
| apache-2.0 |
ernestp/consulo | platform/compiler-artifact-api/src/com/intellij/packaging/ui/ArtifactProblemQuickFix.java | 1041 | /*
* 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.packaging.ui;
/**
* @author nik
*/
public abstract class ArtifactProblemQuickFix {
private String myActionName;
protected ArtifactProblemQuickFix() {
this("Fix");
}
protected ArtifactProblemQuickFix(String actionName) {
myActionName = actionName;
}
public String getActionName() {
return myActionName;
}
public abstract void performFix(ArtifactEditorContext artifactEditorContext);
}
| apache-2.0 |
ThalaivaStars/OrgRepo1 | core/src/test/java/org/elasticsearch/index/mapper/core/IntegerFieldTypeTests.java | 1228 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.index.mapper.core;
import org.elasticsearch.index.mapper.FieldTypeTestCase;
import org.elasticsearch.index.mapper.MappedFieldType;
public class IntegerFieldTypeTests extends FieldTypeTestCase {
@Override
protected MappedFieldType createDefaultFieldType() {
return new IntegerFieldMapper.IntegerFieldType();
}
@Override
protected Object dummyNullValue() {
return 10;
}
}
| apache-2.0 |
akosyakov/intellij-community | java/java-tests/testData/inspection/dataFlow/ArrayAccessNPE/src/Test.java | 142 | public class Test {
public String foo(String[] path) {
if (path != null) return null;
String p = path[0];
return "";
}
}
| apache-2.0 |
raviagarwal7/buck | third-party/java/dx/src/com/android/dx/dex/code/InsnFormat.java | 22935 | /*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.dx.dex.code;
import com.android.dx.rop.code.RegisterSpec;
import com.android.dx.rop.code.RegisterSpecList;
import com.android.dx.rop.cst.Constant;
import com.android.dx.rop.cst.CstInteger;
import com.android.dx.rop.cst.CstKnownNull;
import com.android.dx.rop.cst.CstLiteral64;
import com.android.dx.rop.cst.CstLiteralBits;
import com.android.dx.rop.cst.CstString;
import com.android.dx.util.AnnotatedOutput;
import com.android.dx.util.Hex;
import java.util.BitSet;
/**
* Base class for all instruction format handlers. Instruction format
* handlers know how to translate {@link DalvInsn} instances into
* streams of code units, as well as human-oriented listing strings
* representing such translations.
*/
public abstract class InsnFormat {
/**
* flag to enable/disable the new extended opcode formats; meant as a
* temporary measure until VM support for the salient opcodes is
* added. TODO: Remove this declaration when the VM can deal.
*/
public static boolean ALLOW_EXTENDED_OPCODES = true;
/**
* Returns the string form, suitable for inclusion in a listing
* dump, of the given instruction. The instruction must be of this
* instance's format for proper operation.
*
* @param insn {@code non-null;} the instruction
* @param noteIndices whether to include an explicit notation of
* constant pool indices
* @return {@code non-null;} the string form
*/
public final String listingString(DalvInsn insn, boolean noteIndices) {
String op = insn.getOpcode().getName();
String arg = insnArgString(insn);
String comment = insnCommentString(insn, noteIndices);
StringBuilder sb = new StringBuilder(100);
sb.append(op);
if (arg.length() != 0) {
sb.append(' ');
sb.append(arg);
}
if (comment.length() != 0) {
sb.append(" // ");
sb.append(comment);
}
return sb.toString();
}
/**
* Returns the string form of the arguments to the given instruction.
* The instruction must be of this instance's format. If the instruction
* has no arguments, then the result should be {@code ""}, not
* {@code null}.
*
* <p>Subclasses must override this method.</p>
*
* @param insn {@code non-null;} the instruction
* @return {@code non-null;} the string form
*/
public abstract String insnArgString(DalvInsn insn);
/**
* Returns the associated comment for the given instruction, if any.
* The instruction must be of this instance's format. If the instruction
* has no comment, then the result should be {@code ""}, not
* {@code null}.
*
* <p>Subclasses must override this method.</p>
*
* @param insn {@code non-null;} the instruction
* @param noteIndices whether to include an explicit notation of
* constant pool indices
* @return {@code non-null;} the string form
*/
public abstract String insnCommentString(DalvInsn insn,
boolean noteIndices);
/**
* Gets the code size of instructions that use this format. The
* size is a number of 16-bit code units, not bytes. This should
* throw an exception if this format is of variable size.
*
* @return {@code >= 0;} the instruction length in 16-bit code units
*/
public abstract int codeSize();
/**
* Returns whether or not the given instruction's arguments will
* fit in this instance's format. This includes such things as
* counting register arguments, checking register ranges, and
* making sure that additional arguments are of appropriate types
* and are in-range. If this format has a branch target but the
* instruction's branch offset is unknown, this method will simply
* not check the offset.
*
* <p>Subclasses must override this method.</p>
*
* @param insn {@code non-null;} the instruction to check
* @return {@code true} iff the instruction's arguments are
* appropriate for this instance, or {@code false} if not
*/
public abstract boolean isCompatible(DalvInsn insn);
/**
* Returns which of a given instruction's registers will fit in
* this instance's format.
*
* <p>The default implementation of this method always returns
* an empty BitSet. Subclasses must override this method if they
* have registers.</p>
*
* @param insn {@code non-null;} the instruction to check
* @return {@code non-null;} a BitSet flagging registers in the
* register list that are compatible to this format
*/
public BitSet compatibleRegs(DalvInsn insn) {
return new BitSet();
}
/**
* Returns whether or not the given instruction's branch offset will
* fit in this instance's format. This always returns {@code false}
* for formats that don't include a branch offset.
*
* <p>The default implementation of this method always returns
* {@code false}. Subclasses must override this method if they
* include branch offsets.</p>
*
* @param insn {@code non-null;} the instruction to check
* @return {@code true} iff the instruction's branch offset is
* appropriate for this instance, or {@code false} if not
*/
public boolean branchFits(TargetInsn insn) {
return false;
}
/**
* Writes the code units for the given instruction to the given
* output destination. The instruction must be of this instance's format.
*
* <p>Subclasses must override this method.</p>
*
* @param out {@code non-null;} the output destination to write to
* @param insn {@code non-null;} the instruction to write
*/
public abstract void writeTo(AnnotatedOutput out, DalvInsn insn);
/**
* Helper method to return a register list string.
*
* @param list {@code non-null;} the list of registers
* @return {@code non-null;} the string form
*/
protected static String regListString(RegisterSpecList list) {
int sz = list.size();
StringBuffer sb = new StringBuffer(sz * 5 + 2);
sb.append('{');
for (int i = 0; i < sz; i++) {
if (i != 0) {
sb.append(", ");
}
sb.append(list.get(i).regString());
}
sb.append('}');
return sb.toString();
}
/**
* Helper method to return a register range string.
*
* @param list {@code non-null;} the list of registers (which must be
* sequential)
* @return {@code non-null;} the string form
*/
protected static String regRangeString(RegisterSpecList list) {
int size = list.size();
StringBuilder sb = new StringBuilder(30);
sb.append("{");
switch (size) {
case 0: {
// Nothing to do.
break;
}
case 1: {
sb.append(list.get(0).regString());
break;
}
default: {
RegisterSpec lastReg = list.get(size - 1);
if (lastReg.getCategory() == 2) {
/*
* Add one to properly represent a list-final
* category-2 register.
*/
lastReg = lastReg.withOffset(1);
}
sb.append(list.get(0).regString());
sb.append("..");
sb.append(lastReg.regString());
}
}
sb.append("}");
return sb.toString();
}
/**
* Helper method to return a literal bits argument string.
*
* @param value the value
* @return {@code non-null;} the string form
*/
protected static String literalBitsString(CstLiteralBits value) {
StringBuffer sb = new StringBuffer(100);
sb.append('#');
if (value instanceof CstKnownNull) {
sb.append("null");
} else {
sb.append(value.typeName());
sb.append(' ');
sb.append(value.toHuman());
}
return sb.toString();
}
/**
* Helper method to return a literal bits comment string.
*
* @param value the value
* @param width the width of the constant, in bits (used for displaying
* the uninterpreted bits; one of: {@code 4 8 16 32 64}
* @return {@code non-null;} the comment
*/
protected static String literalBitsComment(CstLiteralBits value,
int width) {
StringBuffer sb = new StringBuffer(20);
sb.append("#");
long bits;
if (value instanceof CstLiteral64) {
bits = ((CstLiteral64) value).getLongBits();
} else {
bits = value.getIntBits();
}
switch (width) {
case 4: sb.append(Hex.uNibble((int) bits)); break;
case 8: sb.append(Hex.u1((int) bits)); break;
case 16: sb.append(Hex.u2((int) bits)); break;
case 32: sb.append(Hex.u4((int) bits)); break;
case 64: sb.append(Hex.u8(bits)); break;
default: {
throw new RuntimeException("shouldn't happen");
}
}
return sb.toString();
}
/**
* Helper method to return a branch address string.
*
* @param insn {@code non-null;} the instruction in question
* @return {@code non-null;} the string form of the instruction's
* branch target
*/
protected static String branchString(DalvInsn insn) {
TargetInsn ti = (TargetInsn) insn;
int address = ti.getTargetAddress();
return (address == (char) address) ? Hex.u2(address) : Hex.u4(address);
}
/**
* Helper method to return the comment for a branch.
*
* @param insn {@code non-null;} the instruction in question
* @return {@code non-null;} the comment
*/
protected static String branchComment(DalvInsn insn) {
TargetInsn ti = (TargetInsn) insn;
int offset = ti.getTargetOffset();
return (offset == (short) offset) ? Hex.s2(offset) : Hex.s4(offset);
}
/**
* Helper method to return the constant string for a {@link CstInsn}
* in human form.
*
* @param insn {@code non-null;} a constant-bearing instruction
* @return {@code non-null;} the human string form of the contained
* constant
*/
protected static String cstString(DalvInsn insn) {
CstInsn ci = (CstInsn) insn;
Constant cst = ci.getConstant();
return cst instanceof CstString ? ((CstString) cst).toQuoted() : cst.toHuman();
}
/**
* Helper method to return an instruction comment for a constant.
*
* @param insn {@code non-null;} a constant-bearing instruction
* @return {@code non-null;} comment string representing the constant
*/
protected static String cstComment(DalvInsn insn) {
CstInsn ci = (CstInsn) insn;
if (! ci.hasIndex()) {
return "";
}
StringBuilder sb = new StringBuilder(20);
int index = ci.getIndex();
sb.append(ci.getConstant().typeName());
sb.append('@');
if (index < 65536) {
sb.append(Hex.u2(index));
} else {
sb.append(Hex.u4(index));
}
return sb.toString();
}
/**
* Helper method to determine if a signed int value fits in a nibble.
*
* @param value the value in question
* @return {@code true} iff it's in the range -8..+7
*/
protected static boolean signedFitsInNibble(int value) {
return (value >= -8) && (value <= 7);
}
/**
* Helper method to determine if an unsigned int value fits in a nibble.
*
* @param value the value in question
* @return {@code true} iff it's in the range 0..0xf
*/
protected static boolean unsignedFitsInNibble(int value) {
return value == (value & 0xf);
}
/**
* Helper method to determine if a signed int value fits in a byte.
*
* @param value the value in question
* @return {@code true} iff it's in the range -0x80..+0x7f
*/
protected static boolean signedFitsInByte(int value) {
return (byte) value == value;
}
/**
* Helper method to determine if an unsigned int value fits in a byte.
*
* @param value the value in question
* @return {@code true} iff it's in the range 0..0xff
*/
protected static boolean unsignedFitsInByte(int value) {
return value == (value & 0xff);
}
/**
* Helper method to determine if a signed int value fits in a short.
*
* @param value the value in question
* @return {@code true} iff it's in the range -0x8000..+0x7fff
*/
protected static boolean signedFitsInShort(int value) {
return (short) value == value;
}
/**
* Helper method to determine if an unsigned int value fits in a short.
*
* @param value the value in question
* @return {@code true} iff it's in the range 0..0xffff
*/
protected static boolean unsignedFitsInShort(int value) {
return value == (value & 0xffff);
}
/**
* Helper method to determine if a list of registers are sequential,
* including degenerate cases for empty or single-element lists.
*
* @param list {@code non-null;} the list of registers
* @return {@code true} iff the list is sequentially ordered
*/
protected static boolean isRegListSequential(RegisterSpecList list) {
int sz = list.size();
if (sz < 2) {
return true;
}
int first = list.get(0).getReg();
int next = first;
for (int i = 0; i < sz; i++) {
RegisterSpec one = list.get(i);
if (one.getReg() != next) {
return false;
}
next += one.getCategory();
}
return true;
}
/**
* Helper method to extract the callout-argument index from an
* appropriate instruction.
*
* @param insn {@code non-null;} the instruction
* @return {@code >= 0;} the callout argument index
*/
protected static int argIndex(DalvInsn insn) {
int arg = ((CstInteger) ((CstInsn) insn).getConstant()).getValue();
if (arg < 0) {
throw new IllegalArgumentException("bogus insn");
}
return arg;
}
/**
* Helper method to combine an opcode and a second byte of data into
* the appropriate form for emitting into a code buffer.
*
* @param insn {@code non-null;} the instruction containing the opcode
* @param arg {@code 0..255;} arbitrary other byte value
* @return combined value
*/
protected static short opcodeUnit(DalvInsn insn, int arg) {
if ((arg & 0xff) != arg) {
throw new IllegalArgumentException("arg out of range 0..255");
}
int opcode = insn.getOpcode().getOpcode();
if ((opcode & 0xff) != opcode) {
throw new IllegalArgumentException("opcode out of range 0..255");
}
return (short) (opcode | (arg << 8));
}
/**
* Helper method to get an extended (16-bit) opcode out of an
* instruction, returning it as a code unit. The opcode
* <i>must</i> be an extended opcode.
*
* @param insn {@code non-null;} the instruction containing the
* extended opcode
* @return the opcode as a code unit
*/
protected static short opcodeUnit(DalvInsn insn) {
int opcode = insn.getOpcode().getOpcode();
if ((opcode < 0x100) || (opcode > 0xffff)) {
throw new IllegalArgumentException("opcode out of range 0..65535");
}
return (short) opcode;
}
/**
* Helper method to combine two bytes into a code unit.
*
* @param low {@code 0..255;} low byte
* @param high {@code 0..255;} high byte
* @return combined value
*/
protected static short codeUnit(int low, int high) {
if ((low & 0xff) != low) {
throw new IllegalArgumentException("low out of range 0..255");
}
if ((high & 0xff) != high) {
throw new IllegalArgumentException("high out of range 0..255");
}
return (short) (low | (high << 8));
}
/**
* Helper method to combine four nibbles into a code unit.
*
* @param n0 {@code 0..15;} low nibble
* @param n1 {@code 0..15;} medium-low nibble
* @param n2 {@code 0..15;} medium-high nibble
* @param n3 {@code 0..15;} high nibble
* @return combined value
*/
protected static short codeUnit(int n0, int n1, int n2, int n3) {
if ((n0 & 0xf) != n0) {
throw new IllegalArgumentException("n0 out of range 0..15");
}
if ((n1 & 0xf) != n1) {
throw new IllegalArgumentException("n1 out of range 0..15");
}
if ((n2 & 0xf) != n2) {
throw new IllegalArgumentException("n2 out of range 0..15");
}
if ((n3 & 0xf) != n3) {
throw new IllegalArgumentException("n3 out of range 0..15");
}
return (short) (n0 | (n1 << 4) | (n2 << 8) | (n3 << 12));
}
/**
* Helper method to combine two nibbles into a byte.
*
* @param low {@code 0..15;} low nibble
* @param high {@code 0..15;} high nibble
* @return {@code 0..255;} combined value
*/
protected static int makeByte(int low, int high) {
if ((low & 0xf) != low) {
throw new IllegalArgumentException("low out of range 0..15");
}
if ((high & 0xf) != high) {
throw new IllegalArgumentException("high out of range 0..15");
}
return low | (high << 4);
}
/**
* Writes one code unit to the given output destination.
*
* @param out {@code non-null;} where to write to
* @param c0 code unit to write
*/
protected static void write(AnnotatedOutput out, short c0) {
out.writeShort(c0);
}
/**
* Writes two code units to the given output destination.
*
* @param out {@code non-null;} where to write to
* @param c0 code unit to write
* @param c1 code unit to write
*/
protected static void write(AnnotatedOutput out, short c0, short c1) {
out.writeShort(c0);
out.writeShort(c1);
}
/**
* Writes three code units to the given output destination.
*
* @param out {@code non-null;} where to write to
* @param c0 code unit to write
* @param c1 code unit to write
* @param c2 code unit to write
*/
protected static void write(AnnotatedOutput out, short c0, short c1,
short c2) {
out.writeShort(c0);
out.writeShort(c1);
out.writeShort(c2);
}
/**
* Writes four code units to the given output destination.
*
* @param out {@code non-null;} where to write to
* @param c0 code unit to write
* @param c1 code unit to write
* @param c2 code unit to write
* @param c3 code unit to write
*/
protected static void write(AnnotatedOutput out, short c0, short c1,
short c2, short c3) {
out.writeShort(c0);
out.writeShort(c1);
out.writeShort(c2);
out.writeShort(c3);
}
/**
* Writes five code units to the given output destination.
*
* @param out {@code non-null;} where to write to
* @param c0 code unit to write
* @param c1 code unit to write
* @param c2 code unit to write
* @param c3 code unit to write
* @param c4 code unit to write
*/
protected static void write(AnnotatedOutput out, short c0, short c1,
short c2, short c3, short c4) {
out.writeShort(c0);
out.writeShort(c1);
out.writeShort(c2);
out.writeShort(c3);
out.writeShort(c4);
}
/**
* Writes three code units to the given output destination, where the
* second and third are represented as single <code>int</code> and emitted
* in little-endian order.
*
* @param out {@code non-null;} where to write to
* @param c0 code unit to write
* @param c1c2 code unit pair to write
*/
protected static void write(AnnotatedOutput out, short c0, int c1c2) {
write(out, c0, (short) c1c2, (short) (c1c2 >> 16));
}
/**
* Writes four code units to the given output destination, where the
* second and third are represented as single <code>int</code> and emitted
* in little-endian order.
*
* @param out {@code non-null;} where to write to
* @param c0 code unit to write
* @param c1c2 code unit pair to write
* @param c3 code unit to write
*/
protected static void write(AnnotatedOutput out, short c0, int c1c2,
short c3) {
write(out, c0, (short) c1c2, (short) (c1c2 >> 16), c3);
}
/**
* Writes five code units to the given output destination, where the
* second and third are represented as single <code>int</code> and emitted
* in little-endian order.
*
* @param out {@code non-null;} where to write to
* @param c0 code unit to write
* @param c1c2 code unit pair to write
* @param c3 code unit to write
* @param c4 code unit to write
*/
protected static void write(AnnotatedOutput out, short c0, int c1c2,
short c3, short c4) {
write(out, c0, (short) c1c2, (short) (c1c2 >> 16), c3, c4);
}
/**
* Writes five code units to the given output destination, where the
* second through fifth are represented as single <code>long</code>
* and emitted in little-endian order.
*
* @param out {@code non-null;} where to write to
* @param c0 code unit to write
* @param c1c2c3c4 code unit quad to write
*/
protected static void write(AnnotatedOutput out, short c0, long c1c2c3c4) {
write(out, c0, (short) c1c2c3c4, (short) (c1c2c3c4 >> 16),
(short) (c1c2c3c4 >> 32), (short) (c1c2c3c4 >> 48));
}
}
| apache-2.0 |
jenskastensson/openhab | bundles/binding/org.openhab.binding.tinkerforge/src/main/java/org/openhab/binding/tinkerforge/internal/model/TFIOSensorConfiguration.java | 2066 | /**
* Copyright (c) 2010-2015, openHAB.org and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.tinkerforge.internal.model;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>TFIO Sensor Configuration</b></em>'.
*
* @author Theo Weiss
* @since 1.4.0
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link org.openhab.binding.tinkerforge.internal.model.TFIOSensorConfiguration#isPullUpResistorEnabled <em>Pull Up Resistor Enabled</em>}</li>
* </ul>
* </p>
*
* @see org.openhab.binding.tinkerforge.internal.model.ModelPackage#getTFIOSensorConfiguration()
* @model
* @generated
*/
public interface TFIOSensorConfiguration extends TFConfig
{
/**
* Returns the value of the '<em><b>Pull Up Resistor Enabled</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Pull Up Resistor Enabled</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Pull Up Resistor Enabled</em>' attribute.
* @see #setPullUpResistorEnabled(boolean)
* @see org.openhab.binding.tinkerforge.internal.model.ModelPackage#getTFIOSensorConfiguration_PullUpResistorEnabled()
* @model unique="false"
* @generated
*/
boolean isPullUpResistorEnabled();
/**
* Sets the value of the '{@link org.openhab.binding.tinkerforge.internal.model.TFIOSensorConfiguration#isPullUpResistorEnabled <em>Pull Up Resistor Enabled</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Pull Up Resistor Enabled</em>' attribute.
* @see #isPullUpResistorEnabled()
* @generated
*/
void setPullUpResistorEnabled(boolean value);
} // TFIOSensorConfiguration
| epl-1.0 |
asedunov/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/api/statements/branch/GrContinueStatement.java | 774 | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.lang.psi.api.statements.branch;
/**
* @author ilyas
*/
public interface GrContinueStatement extends GrFlowInterruptingStatement {
}
| apache-2.0 |
liupugong/spring-boot | spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/IncludeFilterTests.java | 4996 | /*
* Copyright 2014 the original author or authors.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.maven;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.shared.artifact.filter.collection.ArtifactFilterException;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link org.springframework.boot.maven.IncludeFilter}.
*
* @author David Turanski
*/
@SuppressWarnings("rawtypes")
public class IncludeFilterTests {
@Test
public void includeSimple() throws ArtifactFilterException {
IncludeFilter filter = new IncludeFilter(Arrays.asList(createInclude("com.foo",
"bar")));
Artifact artifact = createArtifact("com.foo", "bar");
Set result = filter.filter(Collections.singleton(artifact));
assertEquals("Should not have been filtered", 1, result.size());
assertSame(artifact, result.iterator().next());
}
@Test
public void includeGroupIdNoMatch() throws ArtifactFilterException {
IncludeFilter filter = new IncludeFilter(Arrays.asList(createInclude("com.foo",
"bar")));
Artifact artifact = createArtifact("com.baz", "bar");
Set result = filter.filter(Collections.singleton(artifact));
assertEquals("Should have been filtered", 0, result.size());
}
@Test
public void includeArtifactIdNoMatch() throws ArtifactFilterException {
IncludeFilter filter = new IncludeFilter(Arrays.asList(createInclude("com.foo",
"bar")));
Artifact artifact = createArtifact("com.foo", "biz");
Set result = filter.filter(Collections.singleton(artifact));
assertEquals("Should have been filtered", 0, result.size());
}
@Test
public void includeClassifier() throws ArtifactFilterException {
IncludeFilter filter = new IncludeFilter(Arrays.asList(createInclude("com.foo",
"bar", "jdk5")));
Artifact artifact = createArtifact("com.foo", "bar", "jdk5");
Set result = filter.filter(Collections.singleton(artifact));
assertEquals("Should not have been filtered", 1, result.size());
assertSame(artifact, result.iterator().next());
}
@Test
public void includeClassifierNoTargetClassifier() throws ArtifactFilterException {
IncludeFilter filter = new IncludeFilter(Arrays.asList(createInclude("com.foo",
"bar", "jdk5")));
Artifact artifact = createArtifact("com.foo", "bar");
Set result = filter.filter(Collections.singleton(artifact));
assertEquals("Should have been filtered", 0, result.size());
}
@Test
public void includeClassifierNoMatch() throws ArtifactFilterException {
IncludeFilter filter = new IncludeFilter(Arrays.asList(createInclude("com.foo",
"bar", "jdk5")));
Artifact artifact = createArtifact("com.foo", "bar", "jdk6");
Set result = filter.filter(Collections.singleton(artifact));
assertEquals("Should have been filtered", 0, result.size());
}
@Test
public void includeMulti() throws ArtifactFilterException {
IncludeFilter filter = new IncludeFilter(Arrays.asList(
createInclude("com.foo", "bar"), createInclude("com.foo", "bar2"),
createInclude("org.acme", "app")));
Set<Artifact> artifacts = new HashSet<Artifact>();
artifacts.add(createArtifact("com.foo", "bar"));
artifacts.add(createArtifact("com.foo", "bar"));
Artifact anotherAcme = createArtifact("org.acme", "another-app");
artifacts.add(anotherAcme);
Set result = filter.filter(artifacts);
assertEquals("One dependency should have been filtered", 2, result.size());
}
private Include createInclude(String groupId, String artifactId) {
return createInclude(groupId, artifactId, null);
}
private Include createInclude(String groupId, String artifactId, String classifier) {
Include include = new Include();
include.setGroupId(groupId);
include.setArtifactId(artifactId);
if (classifier != null) {
include.setClassifier(classifier);
}
return include;
}
private Artifact createArtifact(String groupId, String artifactId, String classifier) {
Artifact a = mock(Artifact.class);
given(a.getGroupId()).willReturn(groupId);
given(a.getArtifactId()).willReturn(artifactId);
given(a.getClassifier()).willReturn(classifier);
return a;
}
private Artifact createArtifact(String groupId, String artifactId) {
return createArtifact(groupId, artifactId, null);
}
}
| apache-2.0 |
rokn/Count_Words_2015 | testing/openjdk2/jdk/src/share/classes/com/sun/jndi/dns/Header.java | 4355 | /*
* Copyright (c) 2000, 2002, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.jndi.dns;
import javax.naming.*;
/**
* The Header class represents the header of a DNS message.
*
* @author Scott Seligman
*/
class Header {
static final int HEADER_SIZE = 12; // octets in a DNS header
// Masks and shift amounts for DNS header flag fields.
static final short QR_BIT = (short) 0x8000;
static final short OPCODE_MASK = (short) 0x7800;
static final int OPCODE_SHIFT = 11;
static final short AA_BIT = (short) 0x0400;
static final short TC_BIT = (short) 0x0200;
static final short RD_BIT = (short) 0x0100;
static final short RA_BIT = (short) 0x0080;
static final short RCODE_MASK = (short) 0x000F;
int xid; // ID: 16-bit query identifier
boolean query; // QR: true if query, false if response
int opcode; // OPCODE: 4-bit opcode
boolean authoritative; // AA
boolean truncated; // TC
boolean recursionDesired; // RD
boolean recursionAvail; // RA
int rcode; // RCODE: 4-bit response code
int numQuestions;
int numAnswers;
int numAuthorities;
int numAdditionals;
/*
* Returns a representation of a decoded DNS message header.
* Does not modify or store a reference to the msg array.
*/
Header(byte[] msg, int msgLen) throws NamingException {
decode(msg, msgLen);
}
/*
* Decodes a DNS message header. Does not modify or store a
* reference to the msg array.
*/
private void decode(byte[] msg, int msgLen) throws NamingException {
try {
int pos = 0; // current offset into msg
if (msgLen < HEADER_SIZE) {
throw new CommunicationException(
"DNS error: corrupted message header");
}
xid = getShort(msg, pos);
pos += 2;
// Flags
short flags = (short) getShort(msg, pos);
pos += 2;
query = (flags & QR_BIT) == 0;
opcode = (flags & OPCODE_MASK) >>> OPCODE_SHIFT;
authoritative = (flags & AA_BIT) != 0;
truncated = (flags & TC_BIT) != 0;
recursionDesired = (flags & RD_BIT) != 0;
recursionAvail = (flags & RA_BIT) != 0;
rcode = (flags & RCODE_MASK);
// RR counts
numQuestions = getShort(msg, pos);
pos += 2;
numAnswers = getShort(msg, pos);
pos += 2;
numAuthorities = getShort(msg, pos);
pos += 2;
numAdditionals = getShort(msg, pos);
pos += 2;
} catch (IndexOutOfBoundsException e) {
throw new CommunicationException(
"DNS error: corrupted message header");
}
}
/*
* Returns the 2-byte unsigned value at msg[pos]. The high
* order byte comes first.
*/
private static int getShort(byte[] msg, int pos) {
return (((msg[pos] & 0xFF) << 8) |
(msg[pos + 1] & 0xFF));
}
}
| mit |
ahb0327/intellij-community | java/java-tests/testData/inspection/deadCode/chainOfCalls/src/A.java | 38 | public class A {
public A() {
}
} | apache-2.0 |
Flipkart/elasticsearch | src/main/java/org/elasticsearch/action/admin/cluster/snapshots/get/GetSnapshotsRequestBuilder.java | 2908 | /*
* 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.action.admin.cluster.snapshots.get;
import com.google.common.collect.ObjectArrays;
import org.elasticsearch.action.support.master.MasterNodeOperationRequestBuilder;
import org.elasticsearch.client.ElasticsearchClient;
/**
* Get snapshots request builder
*/
public class GetSnapshotsRequestBuilder extends MasterNodeOperationRequestBuilder<GetSnapshotsRequest, GetSnapshotsResponse, GetSnapshotsRequestBuilder> {
/**
* Constructs the new get snapshot request
*/
public GetSnapshotsRequestBuilder(ElasticsearchClient client, GetSnapshotsAction action) {
super(client, action, new GetSnapshotsRequest());
}
/**
* Constructs the new get snapshot request with specified repository
*/
public GetSnapshotsRequestBuilder(ElasticsearchClient client, GetSnapshotsAction action, String repository) {
super(client, action, new GetSnapshotsRequest(repository));
}
/**
* Sets the repository name
*
* @param repository repository name
* @return this builder
*/
public GetSnapshotsRequestBuilder setRepository(String repository) {
request.repository(repository);
return this;
}
/**
* Sets list of snapshots to return
*
* @param snapshots list of snapshots
* @return this builder
*/
public GetSnapshotsRequestBuilder setSnapshots(String... snapshots) {
request.snapshots(snapshots);
return this;
}
/**
* Makes the request to return the current snapshot
*
* @return this builder
*/
public GetSnapshotsRequestBuilder setCurrentSnapshot() {
request.snapshots(new String[]{GetSnapshotsRequest.CURRENT_SNAPSHOT});
return this;
}
/**
* Adds additional snapshots to the list of snapshots to return
*
* @param snapshots additional snapshots
* @return this builder
*/
public GetSnapshotsRequestBuilder addSnapshots(String... snapshots) {
request.snapshots(ObjectArrays.concat(request.snapshots(), snapshots, String.class));
return this;
}
}
| apache-2.0 |
anoordover/camel | components/camel-spring-ldap/src/main/java/org/apache/camel/component/springldap/SpringLdapComponent.java | 2271 | /**
* 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.springldap;
import java.util.Map;
import org.apache.camel.CamelContext;
import org.apache.camel.Endpoint;
import org.apache.camel.impl.UriEndpointComponent;
import org.apache.camel.spi.Registry;
import org.springframework.ldap.core.LdapTemplate;
/**
* Creates endpoints for the Spring LDAP component.
*/
public class SpringLdapComponent extends UriEndpointComponent {
public SpringLdapComponent() {
super(SpringLdapEndpoint.class);
}
/**
* creates a Spring LDAP endpoint
* @param remaining name of the Spring LDAP template bean to be used for the LDAP operation
* @param parameters key-value pairs to be set on @see org.apache.camel.component.springldap.SpringLdapEndpoint.
* Currently supported keys are operation and scope.
* 'operation' is defined in org.apache.camel.component.springldap.LdapOperation.
* 'scope' must be one of "object", "onelevel", or "subtree".
*/
@Override
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
CamelContext camelContext = getCamelContext();
Registry registry = camelContext.getRegistry();
LdapTemplate ldapTemplate = registry.lookupByNameAndType(remaining, LdapTemplate.class);
Endpoint endpoint = new SpringLdapEndpoint(remaining, ldapTemplate);
setProperties(endpoint, parameters);
return endpoint;
}
}
| apache-2.0 |
robin13/elasticsearch | server/src/main/java/org/elasticsearch/common/inject/internal/ProviderMethodsModule.java | 5388 | /*
* Copyright (C) 2008 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 org.elasticsearch.common.inject.internal;
import org.elasticsearch.common.inject.Binder;
import org.elasticsearch.common.inject.Key;
import org.elasticsearch.common.inject.Module;
import org.elasticsearch.common.inject.Provider;
import org.elasticsearch.common.inject.Provides;
import org.elasticsearch.common.inject.TypeLiteral;
import org.elasticsearch.common.inject.spi.Dependency;
import org.elasticsearch.common.inject.spi.Message;
import org.elasticsearch.common.inject.util.Modules;
import java.lang.annotation.Annotation;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import static java.util.Collections.unmodifiableSet;
/**
* Creates bindings to methods annotated with {@literal @}{@link Provides}. Use the scope and
* binding annotations on the provider method to configure the binding.
*
* @author crazybob@google.com (Bob Lee)
* @author jessewilson@google.com (Jesse Wilson)
*/
public final class ProviderMethodsModule implements Module {
private final Object delegate;
private final TypeLiteral<?> typeLiteral;
private ProviderMethodsModule(Object delegate) {
this.delegate = Objects.requireNonNull(delegate, "delegate");
this.typeLiteral = TypeLiteral.get(this.delegate.getClass());
}
/**
* Returns a module which creates bindings for provider methods from the given module.
*/
public static Module forModule(Module module) {
return forObject(module);
}
/**
* Returns a module which creates bindings for provider methods from the given object.
* This is useful notably for <a href="http://code.google.com/p/google-gin/">GIN</a>
*/
public static Module forObject(Object object) {
// avoid infinite recursion, since installing a module always installs itself
if (object instanceof ProviderMethodsModule) {
return Modules.EMPTY_MODULE;
}
return new ProviderMethodsModule(object);
}
@Override
public synchronized void configure(Binder binder) {
for (ProviderMethod<?> providerMethod : getProviderMethods(binder)) {
providerMethod.configure(binder);
}
}
public List<ProviderMethod<?>> getProviderMethods(Binder binder) {
List<ProviderMethod<?>> result = new ArrayList<>();
for (Class<?> c = delegate.getClass(); c != Object.class; c = c.getSuperclass()) {
for (Method method : c.getMethods()) {
if (method.getAnnotation(Provides.class) != null) {
result.add(createProviderMethod(binder, method));
}
}
}
return result;
}
<T> ProviderMethod<T> createProviderMethod(Binder binder, final Method method) {
binder = binder.withSource(method);
Errors errors = new Errors(method);
// prepare the parameter providers
Set<Dependency<?>> dependencies = new HashSet<>();
List<Provider<?>> parameterProviders = new ArrayList<>();
List<TypeLiteral<?>> parameterTypes = typeLiteral.getParameterTypes(method);
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
for (int i = 0; i < parameterTypes.size(); i++) {
Key<?> key = getKey(errors, parameterTypes.get(i), method, parameterAnnotations[i]);
dependencies.add(Dependency.get(key));
parameterProviders.add(binder.getProvider(key));
}
@SuppressWarnings("unchecked") // Define T as the method's return type.
TypeLiteral<T> returnType = (TypeLiteral<T>) typeLiteral.getReturnType(method);
Key<T> key = getKey(errors, returnType, method, method.getAnnotations());
Class<? extends Annotation> scopeAnnotation
= Annotations.findScopeAnnotation(errors, method.getAnnotations());
for (Message message : errors.getMessages()) {
binder.addError(message);
}
return new ProviderMethod<>(key, method, delegate, unmodifiableSet(dependencies),
parameterProviders, scopeAnnotation);
}
<T> Key<T> getKey(Errors errors, TypeLiteral<T> type, Member member, Annotation[] annotations) {
Annotation bindingAnnotation = Annotations.findBindingAnnotation(errors, member, annotations);
return bindingAnnotation == null ? Key.get(type) : Key.get(type, bindingAnnotation);
}
@Override
public boolean equals(Object o) {
return o instanceof ProviderMethodsModule
&& ((ProviderMethodsModule) o).delegate == delegate;
}
@Override
public int hashCode() {
return delegate.hashCode();
}
}
| apache-2.0 |
tseen/Federated-HDFS | tseenliu/FedHDFS-hadoop-src/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/tools/TableListing.java | 8093 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.tools;
import java.util.ArrayList;
import java.util.LinkedList;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.apache.hadoop.classification.InterfaceAudience;
/**
* This class implements a "table listing" with column headers.
*
* Example:
*
* NAME OWNER GROUP MODE WEIGHT
* pool1 andrew andrew rwxr-xr-x 100
* pool2 andrew andrew rwxr-xr-x 100
* pool3 andrew andrew rwxr-xr-x 100
*
*/
@InterfaceAudience.Private
public class TableListing {
public enum Justification {
LEFT,
RIGHT;
}
private static class Column {
private final ArrayList<String> rows;
private final Justification justification;
private final boolean wrap;
private int wrapWidth = Integer.MAX_VALUE;
private int maxWidth;
Column(String title, Justification justification, boolean wrap) {
this.rows = new ArrayList<String>();
this.justification = justification;
this.wrap = wrap;
this.maxWidth = 0;
addRow(title);
}
private void addRow(String val) {
if (val == null) {
val = "";
}
if ((val.length() + 1) > maxWidth) {
maxWidth = val.length() + 1;
}
// Ceiling at wrapWidth, because it'll get wrapped
if (maxWidth > wrapWidth) {
maxWidth = wrapWidth;
}
rows.add(val);
}
private int getMaxWidth() {
return maxWidth;
}
private void setWrapWidth(int width) {
wrapWidth = width;
// Ceiling the maxLength at wrapWidth
if (maxWidth > wrapWidth) {
maxWidth = wrapWidth;
}
// Else we need to traverse through and find the real maxWidth
else {
maxWidth = 0;
for (int i=0; i<rows.size(); i++) {
int length = rows.get(i).length();
if (length > maxWidth) {
maxWidth = length;
}
}
}
}
/**
* Return the ith row of the column as a set of wrapped strings, each at
* most wrapWidth in length.
*/
String[] getRow(int idx) {
String raw = rows.get(idx);
// Line-wrap if it's too long
String[] lines = new String[] {raw};
if (wrap) {
lines = WordUtils.wrap(lines[0], wrapWidth, "\n", true).split("\n");
}
for (int i=0; i<lines.length; i++) {
if (justification == Justification.LEFT) {
lines[i] = StringUtils.rightPad(lines[i], maxWidth);
} else if (justification == Justification.RIGHT) {
lines[i] = StringUtils.leftPad(lines[i], maxWidth);
}
}
return lines;
}
}
public static class Builder {
private final LinkedList<Column> columns = new LinkedList<Column>();
private boolean showHeader = true;
private int wrapWidth = Integer.MAX_VALUE;
/**
* Create a new Builder.
*/
public Builder() {
}
public Builder addField(String title) {
return addField(title, Justification.LEFT, false);
}
public Builder addField(String title, Justification justification) {
return addField(title, justification, false);
}
public Builder addField(String title, boolean wrap) {
return addField(title, Justification.LEFT, wrap);
}
/**
* Add a new field to the Table under construction.
*
* @param title Field title.
* @param justification Right or left justification. Defaults to left.
* @param wrap Width at which to auto-wrap the content of the cell.
* Defaults to Integer.MAX_VALUE.
* @return This Builder object
*/
public Builder addField(String title, Justification justification,
boolean wrap) {
columns.add(new Column(title, justification, wrap));
return this;
}
/**
* Whether to hide column headers in table output
*/
public Builder hideHeaders() {
this.showHeader = false;
return this;
}
/**
* Whether to show column headers in table output. This is the default.
*/
public Builder showHeaders() {
this.showHeader = true;
return this;
}
/**
* Set the maximum width of a row in the TableListing. Must have one or
* more wrappable fields for this to take effect.
*/
public Builder wrapWidth(int width) {
this.wrapWidth = width;
return this;
}
/**
* Create a new TableListing.
*/
public TableListing build() {
return new TableListing(columns.toArray(new Column[0]), showHeader,
wrapWidth);
}
}
private final Column columns[];
private int numRows;
private final boolean showHeader;
private final int wrapWidth;
TableListing(Column columns[], boolean showHeader, int wrapWidth) {
this.columns = columns;
this.numRows = 0;
this.showHeader = showHeader;
this.wrapWidth = wrapWidth;
}
/**
* Add a new row.
*
* @param row The row of objects to add-- one per column.
*/
public void addRow(String... row) {
if (row.length != columns.length) {
throw new RuntimeException("trying to add a row with " + row.length +
" columns, but we have " + columns.length + " columns.");
}
for (int i = 0; i < columns.length; i++) {
columns[i].addRow(row[i]);
}
numRows++;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
// Calculate the widths of each column based on their maxWidths and
// the wrapWidth for the entire table
int width = (columns.length-1)*2; // inter-column padding
for (int i=0; i<columns.length; i++) {
width += columns[i].maxWidth;
}
// Decrease the column size of wrappable columns until the goal width
// is reached, or we can't decrease anymore
while (width > wrapWidth) {
boolean modified = false;
for (int i=0; i<columns.length; i++) {
Column column = columns[i];
if (column.wrap) {
int maxWidth = column.getMaxWidth();
if (maxWidth > 4) {
column.setWrapWidth(maxWidth-1);
modified = true;
width -= 1;
if (width <= wrapWidth) {
break;
}
}
}
}
if (!modified) {
break;
}
}
int startrow = 0;
if (!showHeader) {
startrow = 1;
}
String[][] columnLines = new String[columns.length][];
for (int i = startrow; i < numRows + 1; i++) {
int maxColumnLines = 0;
for (int j = 0; j < columns.length; j++) {
columnLines[j] = columns[j].getRow(i);
if (columnLines[j].length > maxColumnLines) {
maxColumnLines = columnLines[j].length;
}
}
for (int c = 0; c < maxColumnLines; c++) {
// First column gets no left-padding
String prefix = "";
for (int j = 0; j < columns.length; j++) {
// Prepend padding
builder.append(prefix);
prefix = " ";
if (columnLines[j].length > c) {
builder.append(columnLines[j][c]);
} else {
builder.append(StringUtils.repeat(" ", columns[j].maxWidth));
}
}
builder.append("\n");
}
}
return builder.toString();
}
}
| apache-2.0 |
ZhangXFeng/hadoop | src/hadoop-common-project/hadoop-nfs/src/main/java/org/apache/hadoop/nfs/nfs3/request/GETATTR3Request.java | 1365 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.nfs.nfs3.request;
import java.io.IOException;
import org.apache.hadoop.nfs.nfs3.FileHandle;
import org.apache.hadoop.oncrpc.XDR;
/**
* GETATTR3 Request
*/
public class GETATTR3Request extends RequestWithHandle {
public static GETATTR3Request deserialize(XDR xdr) throws IOException {
FileHandle handle = readHandle(xdr);
return new GETATTR3Request(handle);
}
public GETATTR3Request(FileHandle handle) {
super(handle);
}
@Override
public void serialize(XDR xdr) {
handle.serialize(xdr);
}
} | apache-2.0 |
tseen/Federated-HDFS | tseenliu/FedHDFS-hadoop-src/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestIndexedSort.java | 11139 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.util;
import java.io.IOException;
import java.util.Arrays;
import java.util.Random;
import junit.framework.TestCase;
import org.apache.hadoop.io.DataInputBuffer;
import org.apache.hadoop.io.DataOutputBuffer;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.WritableComparator;
public class TestIndexedSort extends TestCase {
public void sortAllEqual(IndexedSorter sorter) throws Exception {
final int SAMPLE = 500;
int[] values = new int[SAMPLE];
Arrays.fill(values, 10);
SampleSortable s = new SampleSortable(values);
sorter.sort(s, 0, SAMPLE);
int[] check = s.getSorted();
assertTrue(Arrays.toString(values) + "\ndoesn't match\n" +
Arrays.toString(check), Arrays.equals(values, check));
// Set random min/max, re-sort.
Random r = new Random();
int min = r.nextInt(SAMPLE);
int max = (min + 1 + r.nextInt(SAMPLE - 2)) % SAMPLE;
values[min] = 9;
values[max] = 11;
System.out.println("testAllEqual setting min/max at " + min + "/" + max +
"(" + sorter.getClass().getName() + ")");
s = new SampleSortable(values);
sorter.sort(s, 0, SAMPLE);
check = s.getSorted();
Arrays.sort(values);
assertTrue(check[0] == 9);
assertTrue(check[SAMPLE - 1] == 11);
assertTrue(Arrays.toString(values) + "\ndoesn't match\n" +
Arrays.toString(check), Arrays.equals(values, check));
}
public void sortSorted(IndexedSorter sorter) throws Exception {
final int SAMPLE = 500;
int[] values = new int[SAMPLE];
Random r = new Random();
long seed = r.nextLong();
r.setSeed(seed);
System.out.println("testSorted seed: " + seed +
"(" + sorter.getClass().getName() + ")");
for (int i = 0; i < SAMPLE; ++i) {
values[i] = r.nextInt(100);
}
Arrays.sort(values);
SampleSortable s = new SampleSortable(values);
sorter.sort(s, 0, SAMPLE);
int[] check = s.getSorted();
assertTrue(Arrays.toString(values) + "\ndoesn't match\n" +
Arrays.toString(check), Arrays.equals(values, check));
}
public void sortSequential(IndexedSorter sorter) throws Exception {
final int SAMPLE = 500;
int[] values = new int[SAMPLE];
for (int i = 0; i < SAMPLE; ++i) {
values[i] = i;
}
SampleSortable s = new SampleSortable(values);
sorter.sort(s, 0, SAMPLE);
int[] check = s.getSorted();
assertTrue(Arrays.toString(values) + "\ndoesn't match\n" +
Arrays.toString(check), Arrays.equals(values, check));
}
public void sortSingleRecord(IndexedSorter sorter) throws Exception {
final int SAMPLE = 1;
SampleSortable s = new SampleSortable(SAMPLE);
int[] values = s.getValues();
sorter.sort(s, 0, SAMPLE);
int[] check = s.getSorted();
assertTrue(Arrays.toString(values) + "\ndoesn't match\n" +
Arrays.toString(check), Arrays.equals(values, check));
}
public void sortRandom(IndexedSorter sorter) throws Exception {
final int SAMPLE = 256 * 1024;
SampleSortable s = new SampleSortable(SAMPLE);
long seed = s.getSeed();
System.out.println("sortRandom seed: " + seed +
"(" + sorter.getClass().getName() + ")");
int[] values = s.getValues();
Arrays.sort(values);
sorter.sort(s, 0, SAMPLE);
int[] check = s.getSorted();
assertTrue("seed: " + seed + "\ndoesn't match\n",
Arrays.equals(values, check));
}
public void sortWritable(IndexedSorter sorter) throws Exception {
final int SAMPLE = 1000;
WritableSortable s = new WritableSortable(SAMPLE);
long seed = s.getSeed();
System.out.println("sortWritable seed: " + seed +
"(" + sorter.getClass().getName() + ")");
String[] values = s.getValues();
Arrays.sort(values);
sorter.sort(s, 0, SAMPLE);
String[] check = s.getSorted();
assertTrue("seed: " + seed + "\ndoesn't match",
Arrays.equals(values, check));
}
public void testQuickSort() throws Exception {
QuickSort sorter = new QuickSort();
sortRandom(sorter);
sortSingleRecord(sorter);
sortSequential(sorter);
sortSorted(sorter);
sortAllEqual(sorter);
sortWritable(sorter);
// test degenerate case for median-of-three partitioning
// a_n, a_1, a_2, ..., a_{n-1}
final int DSAMPLE = 500;
int[] values = new int[DSAMPLE];
for (int i = 0; i < DSAMPLE; ++i) { values[i] = i; }
values[0] = values[DSAMPLE - 1] + 1;
SampleSortable s = new SampleSortable(values);
values = s.getValues();
final int DSS = (DSAMPLE / 2) * (DSAMPLE / 2);
// Worst case is (N/2)^2 comparisons, not including those effecting
// the median-of-three partitioning; impl should handle this case
MeasuredSortable m = new MeasuredSortable(s, DSS);
sorter.sort(m, 0, DSAMPLE);
System.out.println("QuickSort degen cmp/swp: " +
m.getCmp() + "/" + m.getSwp() +
"(" + sorter.getClass().getName() + ")");
Arrays.sort(values);
int[] check = s.getSorted();
assertTrue(Arrays.equals(values, check));
}
public void testHeapSort() throws Exception {
HeapSort sorter = new HeapSort();
sortRandom(sorter);
sortSingleRecord(sorter);
sortSequential(sorter);
sortSorted(sorter);
sortAllEqual(sorter);
sortWritable(sorter);
}
// Sortables //
private static class SampleSortable implements IndexedSortable {
private int[] valindex;
private int[] valindirect;
private int[] values;
private final long seed;
public SampleSortable() {
this(50);
}
public SampleSortable(int j) {
Random r = new Random();
seed = r.nextLong();
r.setSeed(seed);
values = new int[j];
valindex = new int[j];
valindirect = new int[j];
for (int i = 0; i < j; ++i) {
valindex[i] = valindirect[i] = i;
values[i] = r.nextInt(1000);
}
}
public SampleSortable(int[] values) {
this.values = values;
valindex = new int[values.length];
valindirect = new int[values.length];
for (int i = 0; i < values.length; ++i) {
valindex[i] = valindirect[i] = i;
}
seed = 0;
}
public long getSeed() {
return seed;
}
@Override
public int compare(int i, int j) {
// assume positive
return
values[valindirect[valindex[i]]] - values[valindirect[valindex[j]]];
}
@Override
public void swap(int i, int j) {
int tmp = valindex[i];
valindex[i] = valindex[j];
valindex[j] = tmp;
}
public int[] getSorted() {
int[] ret = new int[values.length];
for (int i = 0; i < ret.length; ++i) {
ret[i] = values[valindirect[valindex[i]]];
}
return ret;
}
public int[] getValues() {
int[] ret = new int[values.length];
System.arraycopy(values, 0, ret, 0, values.length);
return ret;
}
}
public static class MeasuredSortable implements IndexedSortable {
private int comparisions;
private int swaps;
private final int maxcmp;
private final int maxswp;
private IndexedSortable s;
public MeasuredSortable(IndexedSortable s) {
this(s, Integer.MAX_VALUE);
}
public MeasuredSortable(IndexedSortable s, int maxcmp) {
this(s, maxcmp, Integer.MAX_VALUE);
}
public MeasuredSortable(IndexedSortable s, int maxcmp, int maxswp) {
this.s = s;
this.maxcmp = maxcmp;
this.maxswp = maxswp;
}
public int getCmp() { return comparisions; }
public int getSwp() { return swaps; }
@Override
public int compare(int i, int j) {
assertTrue("Expected fewer than " + maxcmp + " comparisons",
++comparisions < maxcmp);
return s.compare(i, j);
}
@Override
public void swap(int i, int j) {
assertTrue("Expected fewer than " + maxswp + " swaps",
++swaps < maxswp);
s.swap(i, j);
}
}
private static class WritableSortable implements IndexedSortable {
private static Random r = new Random();
private final int eob;
private final int[] indices;
private final int[] offsets;
private final byte[] bytes;
private final WritableComparator comparator;
private final String[] check;
private final long seed;
public WritableSortable() throws IOException {
this(100);
}
public WritableSortable(int j) throws IOException {
seed = r.nextLong();
r.setSeed(seed);
Text t = new Text();
StringBuilder sb = new StringBuilder();
indices = new int[j];
offsets = new int[j];
check = new String[j];
DataOutputBuffer dob = new DataOutputBuffer();
for (int i = 0; i < j; ++i) {
indices[i] = i;
offsets[i] = dob.getLength();
genRandom(t, r.nextInt(15) + 1, sb);
t.write(dob);
check[i] = t.toString();
}
eob = dob.getLength();
bytes = dob.getData();
comparator = WritableComparator.get(Text.class);
}
public long getSeed() {
return seed;
}
private static void genRandom(Text t, int len, StringBuilder sb) {
sb.setLength(0);
for (int i = 0; i < len; ++i) {
sb.append(Integer.toString(r.nextInt(26) + 10, 36));
}
t.set(sb.toString());
}
@Override
public int compare(int i, int j) {
final int ii = indices[i];
final int ij = indices[j];
return comparator.compare(bytes, offsets[ii],
((ii + 1 == indices.length) ? eob : offsets[ii + 1]) - offsets[ii],
bytes, offsets[ij],
((ij + 1 == indices.length) ? eob : offsets[ij + 1]) - offsets[ij]);
}
@Override
public void swap(int i, int j) {
int tmp = indices[i];
indices[i] = indices[j];
indices[j] = tmp;
}
public String[] getValues() {
return check;
}
public String[] getSorted() throws IOException {
String[] ret = new String[indices.length];
Text t = new Text();
DataInputBuffer dib = new DataInputBuffer();
for (int i = 0; i < ret.length; ++i) {
int ii = indices[i];
dib.reset(bytes, offsets[ii],
((ii + 1 == indices.length) ? eob : offsets[ii + 1]) - offsets[ii]);
t.readFields(dib);
ret[i] = t.toString();
}
return ret;
}
}
}
| apache-2.0 |
asedunov/intellij-community | java/java-tests/testData/compileServer/incremental/generics/argumentContainment3/src/CaptureCreator2.java | 96 | public class CaptureCreator2 {
public void context(GenericBound<? extends Sub> p) {
}
}
| apache-2.0 |
lichenq/dubbo | dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/InvokerListener.java | 1293 | /*
* Copyright 1999-2011 Alibaba Group.
*
* 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.alibaba.dubbo.rpc;
import com.alibaba.dubbo.common.URL;
import com.alibaba.dubbo.common.extension.SPI;
/**
* InvokerListener. (SPI, Singleton, ThreadSafe)
*
* @author william.liangf
*/
@SPI
public interface InvokerListener {
/**
* The invoker referred
*
* @see com.alibaba.dubbo.rpc.Protocol#refer(Class, URL)
* @param invoker
* @throws RpcException
*/
void referred(Invoker<?> invoker) throws RpcException;
/**
* The invoker destroyed.
*
* @see com.alibaba.dubbo.rpc.Invoker#destroy()
* @param invoker
*/
void destroyed(Invoker<?> invoker);
} | apache-2.0 |
HackWars/hackwars-classic | HWTomcatServer/webapps/ROOT/WEB-INF/classes/Assignments/RemoteFunctionCall.java | 1401 | package Assignments;
import com.plink.dolphinnet.*;
import java.util.*;
import java.io.*;
import java.math.*;
import util.*;
/**
An implementation of the abstract base assignment...This is where the
processing to be distributed onto other computers should be placed.
Every instance of an assignment is distributed to a specific Reporter
(client). So the more Assignments the more division of work.
*/
public class RemoteFunctionCall extends Assignment implements Serializable{
private Object parameters;
private String function;
private int connectionID;
private byte[] byteFunction=null;
/////////////////////////
// Constructor.
public RemoteFunctionCall(int id,String function,Object parameters){
super(id);
if(function!=null)
byteFunction=Encryption.getInstance().encrypt(function.getBytes());
this.parameters = parameters;
}
/////////////////////////
// Getters.
public Object getParameters(){
return(parameters);
}
public String getFunction(){
return(function);
}
public void setFunction(String function){
this.function=function;
}
public void decryptFunction(Encryption MyEncryption,String ip){
this.function=new String(MyEncryption.decrypt(byteFunction,ip));
}
/** Run the assignments implemented task. */
public Object execute(DataHandler DH){
DH.addData(this);
finish();
return(null);
}
}
| isc |
io7m/jspatial | com.io7m.jspatial.tests/src/test/java/com/io7m/jspatial/tests/api/RayI3DTest.java | 10611 | /*
* Copyright © 2017 <code@io7m.com> http://io7m.com
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
* IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package com.io7m.jspatial.tests.api;
import com.io7m.jequality.AlmostEqualDouble;
import com.io7m.jequality.AlmostEqualDouble.ContextRelative;
import com.io7m.jspatial.api.Ray3D;
import com.io7m.jtensors.core.unparameterized.vectors.Vector3D;
import com.io7m.jtensors.core.unparameterized.vectors.Vectors3D;
import org.junit.Assert;
import org.junit.Test;
/**
* Tests for the Ray3D type.
*/
public final class RayI3DTest
{
@Test
public void testRayEqualsNotCase0()
{
final Ray3D ray0 = Ray3D.of(Vectors3D.zero(), Vectors3D.zero());
Assert.assertNotEquals(ray0, null);
}
@Test
public void testRayEqualsNotCase1()
{
final Ray3D ray0 = Ray3D.of(Vectors3D.zero(), Vectors3D.zero());
Assert.assertNotEquals(ray0, Integer.valueOf(23));
}
@Test
public void testRayEqualsNotCase2()
{
final Ray3D ray0 =
Ray3D.of(Vectors3D.zero(), Vectors3D.zero());
final Ray3D ray1 =
Ray3D.of(Vector3D.of(1.0, 2.0, 3.0), Vectors3D.zero());
Assert.assertNotEquals(ray0, ray1);
}
@Test
public void testRayEqualsNotCase3()
{
final Ray3D ray0 =
Ray3D.of(Vectors3D.zero(), Vectors3D.zero());
final Ray3D ray1 =
Ray3D.of(Vectors3D.zero(), Vector3D.of(1.0, 2.0, 3.0));
Assert.assertNotEquals(ray0, ray1);
}
@Test
public void testRayEqualsReflexive()
{
final Ray3D ray0 = Ray3D.of(Vectors3D.zero(), Vectors3D.zero());
Assert.assertEquals(ray0, ray0);
}
@Test
public void testRayEqualsSymmetric()
{
final Ray3D ray0 = Ray3D.of(Vectors3D.zero(), Vectors3D.zero());
final Ray3D ray1 = Ray3D.of(Vectors3D.zero(), Vectors3D.zero());
Assert.assertEquals(ray0, ray1);
Assert.assertEquals(ray1, ray0);
}
@Test
public void testRayEqualsTransitive()
{
final Ray3D ray0 = Ray3D.of(Vectors3D.zero(), Vectors3D.zero());
final Ray3D ray1 = Ray3D.of(Vectors3D.zero(), Vectors3D.zero());
final Ray3D ray2 = Ray3D.of(Vectors3D.zero(), Vectors3D.zero());
Assert.assertEquals(ray0, ray1);
Assert.assertEquals(ray1, ray2);
Assert.assertEquals(ray0, ray2);
}
@Test
public void testRayHashCodeEquals()
{
final Ray3D ray0 = Ray3D.of(Vectors3D.zero(), Vectors3D.zero());
final Ray3D ray1 = Ray3D.of(Vectors3D.zero(), Vectors3D.zero());
Assert.assertTrue(ray0.hashCode() == ray1.hashCode());
}
@Test
public void testRayToStringEquals()
{
final Ray3D ray0 = Ray3D.of(Vectors3D.zero(), Vectors3D.zero());
final Ray3D ray1 = Ray3D.of(Vectors3D.zero(), Vectors3D.zero());
Assert.assertTrue(ray0.toString().equals(ray1.toString()));
}
@Test
public void testRayToStringNotEquals()
{
final Ray3D ray0 =
Ray3D.of(Vectors3D.zero(), Vectors3D.zero());
final Ray3D ray1 =
Ray3D.of(Vectors3D.zero(), Vector3D.of(1.0, 2.0, 3.0));
Assert.assertFalse(ray0.toString().equals(ray1.toString()));
}
@Test
public void testRayZero()
{
final Ray3D ray = Ray3D.of(Vectors3D.zero(), Vectors3D.zero());
final ContextRelative context = new ContextRelative();
final Vector3D ray_origin = ray.origin();
final Vector3D ray_direction = ray.direction();
final Vector3D ray_direction_inv = ray.directionInverse();
Assert.assertTrue(AlmostEqualDouble.almostEqual(
context,
ray_origin.x(),
ray_origin.y()));
Assert.assertTrue(AlmostEqualDouble.almostEqual(
context,
ray_direction.x(),
ray_direction.y()));
Assert.assertTrue(AlmostEqualDouble.almostEqual(
context,
ray_origin.x(),
ray_origin.z()));
Assert.assertTrue(AlmostEqualDouble.almostEqual(
context,
ray_direction.x(),
ray_direction.z()));
Assert.assertTrue(ray_direction_inv.x() == Double.POSITIVE_INFINITY);
Assert.assertTrue(ray_direction_inv.y() == Double.POSITIVE_INFINITY);
Assert.assertTrue(ray_direction_inv.z() == Double.POSITIVE_INFINITY);
}
@Test
public void testRayIntersection()
{
final Vector3D lower = Vector3D.of(2.0, 2.0, 2.0);
final Vector3D upper = Vector3D.of(4.0, 4.0, 4.0);
{
// Intersect -X face in +X direction
final Vector3D origin = Vector3D.of(1.0, 3.0, 3.0);
final Vector3D direct =
Vectors3D.normalize(Vector3D.of(1.0, 0.0, 0.0));
final Ray3D ray = Ray3D.of(origin, direct);
final boolean i =
ray.intersectsVolume(
lower.x(),
lower.y(),
lower.z(),
upper.x(),
upper.y(),
upper.z());
Assert.assertTrue(i);
}
{
// Intersect +X face in -X direction
final Vector3D origin = Vector3D.of(6.0, 3.0, 3.0);
final Vector3D direct =
Vectors3D.normalize(Vector3D.of(-1.0, 0.0, 0.0));
final Ray3D ray = Ray3D.of(origin, direct);
final boolean i =
ray.intersectsVolume(
lower.x(),
lower.y(),
lower.z(),
upper.x(),
upper.y(),
upper.z());
Assert.assertTrue(i);
}
{
// Intersect +Y face in -Y direction
final Vector3D origin = Vector3D.of(3.0, 6.0, 3.0);
final Vector3D direct =
Vectors3D.normalize(Vector3D.of(0.0, -1.0, 0.0));
final Ray3D ray = Ray3D.of(origin, direct);
final boolean i =
ray.intersectsVolume(
lower.x(),
lower.y(),
lower.z(),
upper.x(),
upper.y(),
upper.z());
Assert.assertTrue(i);
}
{
// Intersect -Y face in +Y direction
final Vector3D origin = Vector3D.of(3.0, 1.0, 3.0);
final Vector3D direct =
Vectors3D.normalize(Vector3D.of(0.0, 1.0, 0.0));
final Ray3D ray = Ray3D.of(origin, direct);
final boolean i =
ray.intersectsVolume(
lower.x(),
lower.y(),
lower.z(),
upper.x(),
upper.y(),
upper.z());
Assert.assertTrue(i);
}
{
// Intersect -Z face in +Z direction
final Vector3D origin = Vector3D.of(3.0, 3.0, 1.0);
final Vector3D direct =
Vectors3D.normalize(Vector3D.of(0.0, 0.0, 1.0));
final Ray3D ray = Ray3D.of(origin, direct);
final boolean i =
ray.intersectsVolume(
lower.x(),
lower.y(),
lower.z(),
upper.x(),
upper.y(),
upper.z());
Assert.assertTrue(i);
}
{
// Intersect +Z face in -Z direction
final Vector3D origin = Vector3D.of(3.0, 3.0, 6.0);
final Vector3D direct =
Vectors3D.normalize(Vector3D.of(0.0, 0.0, -1.0));
final Ray3D ray = Ray3D.of(origin, direct);
final boolean i =
ray.intersectsVolume(
lower.x(),
lower.y(),
lower.z(),
upper.x(),
upper.y(),
upper.z());
Assert.assertTrue(i);
}
}
@Test
public void testRayNoIntersection()
{
final Vector3D lower = Vector3D.of(2.0, 2.0, 2.0);
final Vector3D upper = Vector3D.of(4.0, 4.0, 4.0);
{
// Do not intersect -X face in +X direction
final Vector3D origin = Vector3D.of(3.0, 0.0, 0.0);
final Vector3D direct =
Vectors3D.normalize(Vector3D.of(1.0, 0.0, 0.0));
final Ray3D ray = Ray3D.of(origin, direct);
final boolean i =
ray.intersectsVolume(
lower.x(),
lower.y(),
lower.z(),
upper.x(),
upper.y(),
upper.z());
Assert.assertFalse(i);
}
{
// Do not intersect +X face in -X direction
final Vector3D origin = Vector3D.of(6.0, 0.0, 0.0);
final Vector3D direct =
Vectors3D.normalize(Vector3D.of(-1.0, 0.0, 0.0));
final Ray3D ray = Ray3D.of(origin, direct);
final boolean i =
ray.intersectsVolume(
lower.x(),
lower.y(),
lower.z(),
upper.x(),
upper.y(),
upper.z());
Assert.assertFalse(i);
}
{
// Do not intersect +Y face in -Y direction
final Vector3D origin = Vector3D.of(3.0, 1.0, 3.0);
final Vector3D direct =
Vectors3D.normalize(Vector3D.of(0.0, -1.0, 0.0));
final Ray3D ray = Ray3D.of(origin, direct);
final boolean i =
ray.intersectsVolume(
lower.x(),
lower.y(),
lower.z(),
upper.x(),
upper.y(),
upper.z());
Assert.assertFalse(i);
}
{
// Do not intersect -Y face in +Y direction
final Vector3D origin = Vector3D.of(3.0, 6.0, 3.0);
final Vector3D direct =
Vectors3D.normalize(Vector3D.of(0.0, 1.0, 0.0));
final Ray3D ray = Ray3D.of(origin, direct);
final boolean i =
ray.intersectsVolume(
lower.x(),
lower.y(),
lower.z(),
upper.x(),
upper.y(),
upper.z());
Assert.assertFalse(i);
}
{
// Do not intersect -Z face in +Z direction
final Vector3D origin = Vector3D.of(3.0, 3.0, 6.0);
final Vector3D direct =
Vectors3D.normalize(Vector3D.of(0.0, 0.0, 1.0));
final Ray3D ray = Ray3D.of(origin, direct);
final boolean i =
ray.intersectsVolume(
lower.x(),
lower.y(),
lower.z(),
upper.x(),
upper.y(),
upper.z());
Assert.assertFalse(i);
}
{
// Do not intersect +Z face in -Z direction
final Vector3D origin = Vector3D.of(3.0, 3.0, 1.0);
final Vector3D direct =
Vectors3D.normalize(Vector3D.of(0.0, 0.0, -1.0));
final Ray3D ray = Ray3D.of(origin, direct);
final boolean i =
ray.intersectsVolume(
lower.x(),
lower.y(),
lower.z(),
upper.x(),
upper.y(),
upper.z());
Assert.assertFalse(i);
}
}
}
| isc |
Sigurs/MineCloud | core/src/main/java/io/minecloud/models/server/World.java | 1202 | /*
* Copyright (c) 2015, Mazen Kotb <email@mazenmc.io>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package io.minecloud.models.server;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Setter;
@AllArgsConstructor
@EqualsAndHashCode
public class World {
@Setter
private String name;
@Setter
private String version;
public World() {
}
public String name() {
return name;
}
public String version() {
return version;
}
}
| isc |
ekimual/croperino | crop-me/src/main/java/com/mikelau/croperino/ImageViewTouchBase.java | 11621 | package com.mikelau.croperino;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.widget.ImageView;
@SuppressLint("AppCompatCustomView")
abstract class ImageViewTouchBase extends ImageView {
// This is the base transformation which is used to show the image
// initially. The current computation for this shows the image in
// it's entirety, letterboxing as needed. One could choose to
// show the image as cropped instead.
//
// This matrix is recomputed when we go from the thumbnail image to
// the full size image.
protected Matrix mBaseMatrix = new Matrix();
// This is the supplementary transformation which reflects what
// the user has done in terms of zooming and panning.
//
// This matrix remains the same when we go from the thumbnail image
// to the full size image.
protected Matrix mSuppMatrix = new Matrix();
// This is the final matrix which is computed as the concatentation
// of the base matrix and the supplementary matrix.
private final Matrix mDisplayMatrix = new Matrix();
// Temporary buffer used for getting the values out of a matrix.
private final float[] mMatrixValues = new float[9];
// The current bitmap being displayed.
final protected RotateBitmap mBitmapDisplayed = new RotateBitmap(null);
private Recycler mRecycler;
protected Handler mHandler = new Handler();
private Runnable mOnLayoutRunnable = null;
int mThisWidth = -1, mThisHeight = -1;
int mLeft, mRight, mTop, mBottom;
float mMaxZoom;
static final float SCALE_RATE = 1.25F;
// ImageViewTouchBase will pass a Bitmap to the Recycler if it has finished
// its use of that Bitmap.
public interface Recycler {
void recycle(Bitmap b);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
mLeft = left;
mRight = right;
mTop = top;
mBottom = bottom;
mThisWidth = right - left;
mThisHeight = bottom - top;
Runnable r = mOnLayoutRunnable;
if (r != null) {
mOnLayoutRunnable = null;
r.run();
}
if (mBitmapDisplayed.getBitmap() != null) {
getProperBaseMatrix(mBitmapDisplayed, mBaseMatrix);
setImageMatrix(getImageViewMatrix());
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && getScale() > 1.0f) {
// If we're zoomed in, pressing Back jumps out to show the entire
// image, otherwise Back returns the user to the gallery.
zoomTo(1.0f);
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public void setImageBitmap(Bitmap bitmap) {
setImageBitmap(bitmap, 0);
}
private void setImageBitmap(Bitmap bitmap, int rotation) {
super.setImageBitmap(bitmap);
Drawable d = getDrawable();
if (d != null) {
d.setDither(true);
}
Bitmap old = mBitmapDisplayed.getBitmap();
mBitmapDisplayed.setBitmap(bitmap);
mBitmapDisplayed.setRotation(rotation);
if (old != null && old != bitmap && mRecycler != null) {
mRecycler.recycle(old);
}
}
public void clear() {
setImageBitmapResetBase(null, true);
}
// This function changes bitmap, reset base matrix according to the size
// of the bitmap, and optionally reset the supplementary matrix.
public void setImageBitmapResetBase(final Bitmap bitmap, final boolean resetSupp) {
setImageRotateBitmapResetBase(new RotateBitmap(bitmap), resetSupp);
}
public void setImageRotateBitmapResetBase(final RotateBitmap bitmap, final boolean resetSupp) {
final int viewWidth = getWidth();
if (viewWidth <= 0) {
mOnLayoutRunnable = new Runnable() {
public void run() {
setImageRotateBitmapResetBase(bitmap, resetSupp);
}
};
return;
}
if (bitmap.getBitmap() != null) {
getProperBaseMatrix(bitmap, mBaseMatrix);
setImageBitmap(bitmap.getBitmap(), bitmap.getRotation());
} else {
mBaseMatrix.reset();
setImageBitmap(null);
}
if (resetSupp) {
mSuppMatrix.reset();
}
setImageMatrix(getImageViewMatrix());
mMaxZoom = maxZoom();
}
// Center as much as possible in one or both axis. Centering is
// defined as follows: if the image is scaled down below the
// view's dimensions then center it (literally). If the image
// is scaled larger than the view and is translated out of view
// then translate it back into view (i.e. eliminate black bars).
protected void center(boolean horizontal, boolean vertical) {
if (mBitmapDisplayed.getBitmap() == null) {
return;
}
Matrix m = getImageViewMatrix();
RectF rect = new RectF(0, 0, mBitmapDisplayed.getBitmap().getWidth(), mBitmapDisplayed.getBitmap().getHeight());
m.mapRect(rect);
float height = rect.height();
float width = rect.width();
float deltaX = 0, deltaY = 0;
if (vertical) {
int viewHeight = getHeight();
if (height < viewHeight) {
deltaY = (viewHeight - height) / 2 - rect.top;
} else if (rect.top > 0) {
deltaY = -rect.top;
} else if (rect.bottom < viewHeight) {
deltaY = getHeight() - rect.bottom;
}
}
if (horizontal) {
int viewWidth = getWidth();
if (width < viewWidth) {
deltaX = (viewWidth - width) / 2 - rect.left;
} else if (rect.left > 0) {
deltaX = -rect.left;
} else if (rect.right < viewWidth) {
deltaX = viewWidth - rect.right;
}
}
postTranslate(deltaX, deltaY);
setImageMatrix(getImageViewMatrix());
}
public ImageViewTouchBase(Context context) {
super(context);
init();
}
public ImageViewTouchBase(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
setScaleType(ScaleType.MATRIX);
}
protected float getValue(Matrix matrix, int whichValue) {
matrix.getValues(mMatrixValues);
return mMatrixValues[whichValue];
}
// Get the scale factor out of the matrix.
protected float getScale(Matrix matrix) {
return getValue(matrix, Matrix.MSCALE_X);
}
protected float getScale() {
return getScale(mSuppMatrix);
}
// Setup the base matrix so that the image is centered and scaled properly.
private void getProperBaseMatrix(RotateBitmap bitmap, Matrix matrix) {
float viewWidth = getWidth();
float viewHeight = getHeight();
float w = bitmap.getWidth();
float h = bitmap.getHeight();
matrix.reset();
// We limit up-scaling to 2x otherwise the result may look bad if it's
// a small icon.
float widthScale = Math.min(viewWidth / w, 2.0f);
float heightScale = Math.min(viewHeight / h, 2.0f);
float scale = Math.min(widthScale, heightScale);
matrix.postConcat(bitmap.getRotateMatrix());
matrix.postScale(scale, scale);
matrix.postTranslate((viewWidth - w * scale) / 2F, (viewHeight - h * scale) / 2F);
}
// Combine the base matrix and the supp matrix to make the final matrix.
protected Matrix getImageViewMatrix() {
// The final matrix is computed as the concatentation of the base matrix
// and the supplementary matrix.
mDisplayMatrix.set(mBaseMatrix);
mDisplayMatrix.postConcat(mSuppMatrix);
return mDisplayMatrix;
}
// Sets the maximum zoom, which is a scale relative to the base matrix. It
// is calculated to show the image at 400% zoom regardless of screen or
// image orientation. If in the future we decode the full 3 megapixel image,
// rather than the current 1024x768, this should be changed down to 200%.
protected float maxZoom() {
if (mBitmapDisplayed.getBitmap() == null) {
return 1F;
}
float fw = (float) mBitmapDisplayed.getWidth() / (float) mThisWidth;
float fh = (float) mBitmapDisplayed.getHeight() / (float) mThisHeight;
return Math.max(fw, fh) * 4;
}
protected void zoomTo(float scale, float centerX, float centerY) {
if (scale > mMaxZoom) {
scale = mMaxZoom;
}
float oldScale = getScale();
float deltaScale = scale / oldScale;
mSuppMatrix.postScale(deltaScale, deltaScale, centerX, centerY);
setImageMatrix(getImageViewMatrix());
center(true, true);
}
protected void zoomTo(final float scale, final float centerX, final float centerY, final float durationMs) {
final float incrementPerMs = (scale - getScale()) / durationMs;
final float oldScale = getScale();
final long startTime = System.currentTimeMillis();
mHandler.post(new Runnable() {
public void run() {
long now = System.currentTimeMillis();
float currentMs = Math.min(durationMs, now - startTime);
float target = oldScale + (incrementPerMs * currentMs);
zoomTo(target, centerX, centerY);
if (currentMs < durationMs) {
mHandler.post(this);
}
}
});
}
protected void zoomTo(float scale) {
float cx = getWidth() / 2F;
float cy = getHeight() / 2F;
zoomTo(scale, cx, cy);
}
protected void zoomIn() {
zoomIn(SCALE_RATE);
}
protected void zoomOut() {
zoomOut(SCALE_RATE);
}
protected void zoomIn(float rate) {
if (getScale() >= mMaxZoom) {
return; // Don't let the user zoom into the molecular level.
}
if (mBitmapDisplayed.getBitmap() == null) {
return;
}
float cx = getWidth() / 2F;
float cy = getHeight() / 2F;
mSuppMatrix.postScale(rate, rate, cx, cy);
setImageMatrix(getImageViewMatrix());
}
protected void zoomOut(float rate) {
if (mBitmapDisplayed.getBitmap() == null) {
return;
}
float cx = getWidth() / 2F;
float cy = getHeight() / 2F;
// Zoom out to at most 1x.
Matrix tmp = new Matrix(mSuppMatrix);
tmp.postScale(1F / rate, 1F / rate, cx, cy);
if (getScale(tmp) < 1F) {
mSuppMatrix.setScale(1F, 1F, cx, cy);
} else {
mSuppMatrix.postScale(1F / rate, 1F / rate, cx, cy);
}
setImageMatrix(getImageViewMatrix());
center(true, true);
}
protected void postTranslate(float dx, float dy) {
mSuppMatrix.postTranslate(dx, dy);
}
protected void panBy(float dx, float dy) {
postTranslate(dx, dy);
setImageMatrix(getImageViewMatrix());
}
}
| mit |
heisedebaise/ranch | ranch-comment/src/main/java/org/lpw/ranch/comment/CommentService.java | 1275 | package org.lpw.ranch.comment;
import com.alibaba.fastjson.JSONObject;
import org.lpw.ranch.audit.AuditService;
import java.sql.Timestamp;
/**
* @author lpw
*/
public interface CommentService extends AuditService {
/**
* 检索评论信息集。
*
* @param audit 审核状态。
* @param owner 所有者ID值。
* @param author 作者ID值。
* @param start 开始时间。
* @param end 结束时间。
* @return 评论信息集。
*/
JSONObject query(int audit, String owner, String author, Timestamp start, Timestamp end);
/**
* 检索指定所有者的评论信息集。
*
* @param owner 所有者ID。
* @return 评论信息集。
*/
JSONObject queryByOwner(String owner);
/**
* 检索指定作者的评论信息集。
*
* @param author 作者ID。
* @return 评论信息集。
*/
JSONObject queryByAuthor(String author);
/**
* 获取评论信息集。
*
* @param ids ID集。
* @return 评论信息集。
*/
JSONObject get(String[] ids);
/**
* 创建新评论。
*
* @param comment 评论信息。
* @return 评论实例。
*/
JSONObject create(CommentModel comment);
}
| mit |
plum-umd/pasket | example/gui/src/tutorial/text_sampler_demo/Test.java | 229 | package tutorial.text_sampler_demo;
public class Test {
final static String tag = Test.class.getPackage().getName();
public static void main(String[] args) {
System.out.println(tag);
TextSamplerDemo.main();
}
}
| mit |
uq-eresearch/dataspace | data-registry-webapp/src/main/java/net/metadata/dataspace/data/model/record/Activity.java | 1180 | package net.metadata.dataspace.data.model.record;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import net.metadata.dataspace.data.model.version.ActivityVersion;
/**
* User: alabri
* Date: 27/10/2010
* Time: 10:30:02 AM
*/
@Entity
public class Activity extends AbstractRecordEntity<ActivityVersion> {
private static final long serialVersionUID = 1L;
public enum Type {
PROJECT,
PROGRAM
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinTable(name = "activity_same_as")
private Set<Activity> sameAs = new HashSet<Activity>();
public Activity() {
}
public Set<Collection> getHasOutput() {
return getMostRecentVersion().getHasOutput();
}
public Set<Agent> getHasParticipant() {
return getMostRecentVersion().getHasParticipants();
}
public Set<Activity> getSameAs() {
return sameAs;
}
public void setSameAs(Set<Activity> sameAs) {
this.sameAs = sameAs;
}
}
| mit |
archimatetool/archi | org.eclipse.draw2d/src/org/eclipse/draw2d/ScalableFigure.java | 962 | /*******************************************************************************
* Copyright (c) 2003, 2010 IBM Corporation 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
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.draw2d;
/**
* A figure that can be scaled.
*
* @author Eric Bordeau
* @since 2.1.1
*/
public interface ScalableFigure extends IFigure {
/**
* Returns the current scale.
*
* @return the current scale
*/
double getScale();
/**
* Sets the new scale factor.
*
* @param scale
* the scale
*/
void setScale(double scale);
}
| mit |
phptuts/Android_Tick_Tac_Toe | app/src/test/java/com/example/noahglaser/ticktactoe/ExampleUnitTest.java | 411 | package com.example.noahglaser.ticktactoe;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | mit |
TransCoders/The_Elucidated | app/src/androidTest/java/gr/edu/serres/TrancCoder_TheElucitated/CustomAdapterTest.java | 1101 | package gr.edu.serres.TrancCoder_TheElucitated;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.filters.SdkSuppress;
import android.support.test.uiautomator.UiDevice;
import android.test.InstrumentationTestCase;
import android.widget.ListAdapter;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.util.ArrayList;
import gr.edu.serres.TrancCoder_TheElucitated.Adapters.CustomAdapter;
/**
* Created by James Nikolaidis on 12/4/2016.
*/
@RunWith(JUnit4.class)
@SdkSuppress(minSdkVersion = 18)
public class CustomAdapterTest extends InstrumentationTestCase {
private Context testContext;
private ArrayList<String> test_array;
private UiDevice mDevice;
//Check getView with Null ArrayListObject
@Test
public void Testin_getView_1(){
testContext= InstrumentationRegistry.getContext();
ListAdapter test_adapter = new CustomAdapter(testContext,new ArrayList<String>());
}
@Test
public void getView() throws Exception {
}
} | mit |
VizGS/104-asia-java | 檢測1-50題缺31 33 37/src/Java026.java | 388 | import java.util.Scanner;
public class Java026 {
public static void main(String args[]) {
Scanner scn = new Scanner(System.in);
int m = scn.nextInt();
int n = scn.nextInt();
if (n > m) {
int a = m;
m = n;
n = a;
}
System.out.println(gcd(m, n));
}
public static int gcd(int m, int n) {
if (m % n == 0) {
return n;
} else {
return gcd(n, m % n);
}
}
} | mit |
AdapTeach/code-assesser-java | src/main/java/com/adapteach/codeassesser/compile/CompilationCheck.java | 1300 | package com.adapteach.codeassesser.compile;
import com.adapteach.codeassesser.verify.SubmissionResult;
import com.google.common.base.Preconditions;
import lombok.Data;
import java.util.List;
import java.util.stream.Collectors;
@Data
public class CompilationCheck {
private final List<String> compilationErrors;
private final List<CompilationUnit> missingCompilationUnits;
public CompilationCheck(MemoryClassLoader classLoader) {
this.compilationErrors = classLoader.getCompilationErrors();
this.missingCompilationUnits = classLoader.getMissingCompilationUnits();
}
public boolean passed() {
return compilationErrors.isEmpty() && missingCompilationUnits.isEmpty();
}
public SubmissionResult asSubmissionResult() {
Preconditions.checkState(!passed(), "This method should be called only for failing checks");
final SubmissionResult result = new SubmissionResult();
result.setPass(false);
result.getCompilationErrors().addAll(compilationErrors);
List<String> missingCompilationUnitMessages = missingCompilationUnits.stream().map(CompilationUnit::getMissingMessage).collect(Collectors.toList());
result.getCompilationErrors().addAll(missingCompilationUnitMessages);
return result;
}
}
| mit |
linlinyeyu/spring-boot-all | dreamroom/src/main/java/com/ybliu/controller/DemoInterceptor.java | 1082 | package com.ybliu.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
public class DemoInterceptor extends HandlerInterceptorAdapter{
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
// TODO Auto-generated method stub
long startTime = System.currentTimeMillis();
request.removeAttribute("startTime");
long endTime = System.currentTimeMillis();
System.out.println("本次请求处理时间为:"+new Long(endTime-startTime)+"ms");
request.setAttribute("handlingTime", endTime-startTime);
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
// TODO Auto-generated method stub
long startTime = System.currentTimeMillis();
request.setAttribute("startTime", startTime);
return true;
}
}
| mit |