repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
vdtidake/dyfaces | src/main/java/org/dyfaces/utils/package-info.java | 76 | /**
*
*/
/**
* @author invtidke
*
*/
package org.dyfaces.utils; | apache-2.0 |
osinstom/onos | cli/src/main/java/org/onosproject/cli/net/vnet/VirtualPortListCommand.java | 3118 | /*
* Copyright 2016-present Open Networking Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.cli.net.vnet;
import org.apache.karaf.shell.commands.Argument;
import org.apache.karaf.shell.commands.Command;
import org.onosproject.cli.AbstractShellCommand;
import org.onosproject.incubator.net.virtual.NetworkId;
import org.onosproject.incubator.net.virtual.VirtualNetworkService;
import org.onosproject.incubator.net.virtual.VirtualPort;
import org.onosproject.net.DeviceId;
import org.onosproject.utils.Comparators;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Lists all virtual ports for the network ID.
*/
@Command(scope = "onos", name = "vnet-ports",
description = "Lists all virtual ports in a virtual network.")
public class VirtualPortListCommand extends AbstractShellCommand {
private static final String FMT_VIRTUAL_PORT =
"virtual portNumber=%s, physical deviceId=%s, portNumber=%s, isEnabled=%s";
@Argument(index = 0, name = "networkId", description = "Network ID",
required = true, multiValued = false)
Long networkId = null;
@Argument(index = 1, name = "deviceId", description = "Virtual Device ID",
required = true, multiValued = false)
String deviceId = null;
@Override
protected void execute() {
getSortedVirtualPorts().forEach(this::printVirtualPort);
}
/**
* Returns the list of virtual ports sorted using the network identifier.
*
* @return sorted virtual port list
*/
private List<VirtualPort> getSortedVirtualPorts() {
VirtualNetworkService service = get(VirtualNetworkService.class);
List<VirtualPort> virtualPorts = new ArrayList<>();
virtualPorts.addAll(service.getVirtualPorts(NetworkId.networkId(networkId),
DeviceId.deviceId(deviceId)));
Collections.sort(virtualPorts, Comparators.VIRTUAL_PORT_COMPARATOR);
return virtualPorts;
}
/**
* Prints out each virtual port.
*
* @param virtualPort virtual port
*/
private void printVirtualPort(VirtualPort virtualPort) {
if (virtualPort.realizedBy() == null) {
print(FMT_VIRTUAL_PORT, virtualPort.number(), "None", "None", virtualPort.isEnabled());
} else {
print(FMT_VIRTUAL_PORT, virtualPort.number(),
virtualPort.realizedBy().deviceId(),
virtualPort.realizedBy().port(),
virtualPort.isEnabled());
}
}
}
| apache-2.0 |
asterisk-java/asterisk-java | src/test/java/org/asteriskjava/manager/internal/ManagerReaderImplTest.java | 13995 | /*
* Copyright 2004-2006 Stefan Reuter
*
* 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.asteriskjava.manager.internal;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.asteriskjava.manager.event.AgentCalledEvent;
import org.asteriskjava.manager.event.DisconnectEvent;
import org.asteriskjava.manager.event.ManagerEvent;
import org.asteriskjava.manager.event.ProtocolIdentifierReceivedEvent;
import org.asteriskjava.manager.event.RtcpReceivedEvent;
import org.asteriskjava.manager.event.StatusCompleteEvent;
import org.asteriskjava.manager.response.CommandResponse;
import org.asteriskjava.manager.response.ManagerResponse;
import org.asteriskjava.util.DateUtil;
import org.asteriskjava.util.SocketConnectionFacade;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class ManagerReaderImplTest
{
private Date now;
private MockedDispatcher dispatcher;
private SocketConnectionFacade socketConnectionFacade;
private ManagerReader managerReader;
@Before
public void setUp()
{
now = new Date();
DateUtil.overrideCurrentDate(now);
dispatcher = new MockedDispatcher();
managerReader = new ManagerReaderImpl(dispatcher, this);
socketConnectionFacade = createMock(SocketConnectionFacade.class);
}
@After
public void tearDown()
{
DateUtil.overrideCurrentDate(null);
}
@Test
public void testRunWithoutSocket()
{
try
{
managerReader.run();
fail("Must throw IllegalStateException");
}
catch (IllegalStateException e)
{
assertTrue("Exception must be of type IllegalStateException", e instanceof IllegalStateException);
}
}
@Test
public void testRunReceivingProtocolIdentifier() throws Exception
{
expect(socketConnectionFacade.readLine()).andReturn("Asterisk Call Manager/1.0");
expect(socketConnectionFacade.readLine()).andReturn(null);
replay(socketConnectionFacade);
managerReader.setSocket(socketConnectionFacade);
managerReader.run();
verify(socketConnectionFacade);
assertEquals("not exactly two events dispatched", 2, dispatcher.dispatchedEvents.size());
assertEquals("first event must be a ProtocolIdentifierReceivedEvent", ProtocolIdentifierReceivedEvent.class,
dispatcher.dispatchedEvents.get(0).getClass());
assertEquals("ProtocolIdentifierReceivedEvent contains incorrect protocol identifier",
"Asterisk Call Manager/1.0",
((ProtocolIdentifierReceivedEvent) dispatcher.dispatchedEvents.get(0)).getProtocolIdentifier());
assertEquals("ProtocolIdentifierReceivedEvent contains incorrect dateReceived", now,
dispatcher.dispatchedEvents.get(0).getDateReceived());
assertEquals("second event must be a DisconnectEvent", DisconnectEvent.class,
dispatcher.dispatchedEvents.get(1).getClass());
assertEquals("DisconnectEvent contains incorrect dateReceived", now,
dispatcher.dispatchedEvents.get(1).getDateReceived());
}
@Test
public void testRunReceivingEvent() throws Exception
{
expect(socketConnectionFacade.readLine()).andReturn("Event: StatusComplete");
expect(socketConnectionFacade.readLine()).andReturn("");
expect(socketConnectionFacade.readLine()).andReturn(null);
replay(socketConnectionFacade);
managerReader.setSocket(socketConnectionFacade);
managerReader.run();
verify(socketConnectionFacade);
assertEquals("not exactly two events dispatched", 2, dispatcher.dispatchedEvents.size());
assertEquals("first event must be a StatusCompleteEvent", StatusCompleteEvent.class,
dispatcher.dispatchedEvents.get(0).getClass());
assertEquals("second event must be a DisconnectEvent", DisconnectEvent.class,
dispatcher.dispatchedEvents.get(1).getClass());
}
@Test
public void testRunReceivingEventWithMapProperty() throws Exception
{
expect(socketConnectionFacade.readLine()).andReturn("Event: AgentCalled");
expect(socketConnectionFacade.readLine()).andReturn("Variable: var1=val1");
expect(socketConnectionFacade.readLine()).andReturn("Variable: var2=val2");
expect(socketConnectionFacade.readLine()).andReturn("");
expect(socketConnectionFacade.readLine()).andReturn(null);
replay(socketConnectionFacade);
managerReader.setSocket(socketConnectionFacade);
managerReader.run();
verify(socketConnectionFacade);
assertEquals("not exactly two events dispatched", 2, dispatcher.dispatchedEvents.size());
assertEquals("first event must be a AgentCalledEvent", AgentCalledEvent.class,
dispatcher.dispatchedEvents.get(0).getClass());
AgentCalledEvent event = (AgentCalledEvent) dispatcher.dispatchedEvents.get(0);
assertEquals("Returned event is of wrong type", AgentCalledEvent.class, event.getClass());
assertEquals("Property variables[var1] is not set correctly", "val1", event.getVariables().get("var1"));
assertEquals("Property variables[var2] is not set correctly", "val2", event.getVariables().get("var2"));
assertEquals("Invalid size of variables property", 2, event.getVariables().size());
assertEquals("second event must be an DisconnectEvent", DisconnectEvent.class,
dispatcher.dispatchedEvents.get(1).getClass());
}
@Test
public void testRunReceivingEventWithMapPropertyAndOnlyOneEntry() throws Exception
{
expect(socketConnectionFacade.readLine()).andReturn("Event: AgentCalled");
expect(socketConnectionFacade.readLine()).andReturn("Variable: var1=val1");
expect(socketConnectionFacade.readLine()).andReturn("");
expect(socketConnectionFacade.readLine()).andReturn(null);
replay(socketConnectionFacade);
managerReader.setSocket(socketConnectionFacade);
managerReader.run();
verify(socketConnectionFacade);
assertEquals("not exactly two events dispatched", 2, dispatcher.dispatchedEvents.size());
assertEquals("first event must be a AgentCalledEvent", AgentCalledEvent.class,
dispatcher.dispatchedEvents.get(0).getClass());
AgentCalledEvent event = (AgentCalledEvent) dispatcher.dispatchedEvents.get(0);
assertEquals("Returned event is of wrong type", AgentCalledEvent.class, event.getClass());
assertEquals("Property variables[var1] is not set correctly", "val1", event.getVariables().get("var1"));
assertEquals("Invalid size of variables property", 1, event.getVariables().size());
assertEquals("second event must be an DisconnectEvent", DisconnectEvent.class,
dispatcher.dispatchedEvents.get(1).getClass());
}
@Test
public void testWorkaroundForAsteriskBug13319() throws Exception
{
expect(socketConnectionFacade.readLine()).andReturn("Event: RTCPReceived");
expect(socketConnectionFacade.readLine()).andReturn("From 192.168.0.1:1234");
expect(socketConnectionFacade.readLine()).andReturn("HighestSequence: 999");
expect(socketConnectionFacade.readLine()).andReturn("");
expect(socketConnectionFacade.readLine()).andReturn(null);
replay(socketConnectionFacade);
managerReader.setSocket(socketConnectionFacade);
managerReader.run();
verify(socketConnectionFacade);
assertEquals("not exactly two events dispatched", 2, dispatcher.dispatchedEvents.size());
assertEquals("first event must be a RtcpReceivedEvent", RtcpReceivedEvent.class,
dispatcher.dispatchedEvents.get(0).getClass());
RtcpReceivedEvent rtcpReceivedEvent = (RtcpReceivedEvent) dispatcher.dispatchedEvents.get(0);
assertEquals("Invalid from address on RtcpReceivedEvent", "192.168.0.1",
rtcpReceivedEvent.getFromAddress().getHostAddress());
assertEquals("Invalid from port on RtcpReceivedEvent", new Integer(1234), rtcpReceivedEvent.getFromPort());
assertEquals("Invalid highest sequence on RtcpReceivedEvent", new Long(999),
rtcpReceivedEvent.getHighestSequence());
assertEquals("second event must be a DisconnectEvent", DisconnectEvent.class,
dispatcher.dispatchedEvents.get(1).getClass());
}
// todo fix testRunReceivingUserEvent
public void XtestRunReceivingUserEvent() throws Exception
{
managerReader.registerEventClass(MyUserEvent.class);
expect(socketConnectionFacade.readLine()).andReturn("Event: MyUser");
expect(socketConnectionFacade.readLine()).andReturn("");
expect(socketConnectionFacade.readLine()).andReturn(null);
replay(socketConnectionFacade);
managerReader.setSocket(socketConnectionFacade);
managerReader.run();
verify(socketConnectionFacade);
assertEquals("not exactly two events dispatched", 2, dispatcher.dispatchedEvents.size());
assertEquals("first event must be a MyUserEvent", MyUserEvent.class,
dispatcher.dispatchedEvents.get(0).getClass());
assertEquals("second event must be a DisconnectEvent", DisconnectEvent.class,
dispatcher.dispatchedEvents.get(1).getClass());
}
@Test
public void testRunReceivingResponse() throws Exception
{
expect(socketConnectionFacade.readLine()).andReturn("Response: Success");
expect(socketConnectionFacade.readLine()).andReturn("Message: Authentication accepted");
expect(socketConnectionFacade.readLine()).andReturn("");
expect(socketConnectionFacade.readLine()).andReturn(null);
replay(socketConnectionFacade);
managerReader.setSocket(socketConnectionFacade);
managerReader.run();
verify(socketConnectionFacade);
assertEquals("not exactly one response dispatched", 1, dispatcher.dispatchedResponses.size());
assertEquals("first response must be a ManagerResponse", ManagerResponse.class,
dispatcher.dispatchedResponses.get(0).getClass());
assertEquals("ManagerResponse contains incorrect response", "Success",
dispatcher.dispatchedResponses.get(0).getResponse());
assertEquals("ManagerResponse contains incorrect message", "Authentication accepted",
dispatcher.dispatchedResponses.get(0).getMessage());
assertEquals("ManagerResponse contains incorrect message (via getAttribute)", "Authentication accepted",
dispatcher.dispatchedResponses.get(0).getAttribute("MESSAGE"));
assertEquals("ManagerResponse contains incorrect dateReceived", now,
dispatcher.dispatchedResponses.get(0).getDateReceived());
assertEquals("not exactly one events dispatched", 1, dispatcher.dispatchedEvents.size());
assertEquals("first event must be a DisconnectEvent", DisconnectEvent.class,
dispatcher.dispatchedEvents.get(0).getClass());
}
@Test
public void testRunReceivingCommandResponse() throws Exception
{
List<String> result = new ArrayList<String>();
expect(socketConnectionFacade.readLine()).andReturn("Response: Follows");
expect(socketConnectionFacade.readLine()).andReturn("ActionID: 678#12345");
expect(socketConnectionFacade.readLine()).andReturn("Line1\nLine2\n--END COMMAND--");
expect(socketConnectionFacade.readLine()).andReturn("");
expect(socketConnectionFacade.readLine()).andReturn(null);
result.add("Line1");
result.add("Line2");
replay(socketConnectionFacade);
managerReader.setSocket(socketConnectionFacade);
managerReader.expectResponseClass("678", CommandResponse.class);
managerReader.run();
verify(socketConnectionFacade);
assertEquals("not exactly one response dispatched", 1, dispatcher.dispatchedResponses.size());
assertEquals("first response must be a CommandResponse", CommandResponse.class,
dispatcher.dispatchedResponses.get(0).getClass());
assertEquals("CommandResponse contains incorrect response", "Follows",
dispatcher.dispatchedResponses.get(0).getResponse());
assertEquals("CommandResponse contains incorrect actionId", "678#12345",
dispatcher.dispatchedResponses.get(0).getActionId());
assertEquals("CommandResponse contains incorrect actionId (via getAttribute)", "678#12345",
dispatcher.dispatchedResponses.get(0).getAttribute("actionId"));
assertEquals("CommandResponse contains incorrect result", result,
((CommandResponse) dispatcher.dispatchedResponses.get(0)).getResult());
assertEquals("CommandResponse contains incorrect dateReceived", now,
dispatcher.dispatchedResponses.get(0).getDateReceived());
}
@Test
public void testRunCatchingIOException() throws Exception
{
expect(socketConnectionFacade.readLine()).andThrow(new IOException("Something happened to the network..."));
replay(socketConnectionFacade);
managerReader.setSocket(socketConnectionFacade);
managerReader.run();
verify(socketConnectionFacade);
assertEquals("must not dispatch a response", 0, dispatcher.dispatchedResponses.size());
assertEquals("not exactly one events dispatched", 1, dispatcher.dispatchedEvents.size());
assertEquals("first event must be a DisconnectEvent", DisconnectEvent.class,
dispatcher.dispatchedEvents.get(0).getClass());
}
private class MockedDispatcher implements Dispatcher
{
List<ManagerEvent> dispatchedEvents;
List<ManagerResponse> dispatchedResponses;
public MockedDispatcher()
{
this.dispatchedEvents = new ArrayList<ManagerEvent>();
this.dispatchedResponses = new ArrayList<ManagerResponse>();
}
@Override
public void dispatchResponse(ManagerResponse response, Integer requiredHandlingTime)
{
dispatchedResponses.add(response);
}
@Override
public void dispatchEvent(ManagerEvent event, Integer requiredHandlingTime)
{
dispatchedEvents.add(event);
}
@Override
public void stop()
{
// NO_OP
}
}
}
| apache-2.0 |
Sellegit/j2objc | runtime/src/main/java/apple/coredata/NSMergeConflict.java | 1428 | package apple.coredata;
import java.io.*;
import java.nio.*;
import java.util.*;
import com.google.j2objc.annotations.*;
import com.google.j2objc.runtime.*;
import com.google.j2objc.runtime.block.*;
import apple.audiotoolbox.*;
import apple.corefoundation.*;
import apple.coregraphics.*;
import apple.coreservices.*;
import apple.foundation.*;
/**
* @since Available in iOS 5.0 and later.
*/
@Library("CoreData/CoreData.h") @Mapping("NSMergeConflict")
public class NSMergeConflict
extends NSObject
{
@Mapping("initWithSource:newVersion:oldVersion:cachedSnapshot:persistedSnapshot:")
public NSMergeConflict(NSManagedObject srcObject, @MachineSizedUInt long newvers, @MachineSizedUInt long oldvers, NSDictionary<?, ?> cachesnap, NSDictionary<?, ?> persnap) { }
@Mapping("init")
public NSMergeConflict() { }
@Mapping("sourceObject")
public native NSManagedObject getSourceObject();
@Mapping("objectSnapshot")
public native Map<String, NSObject> getObjectSnapshot();
@Mapping("cachedSnapshot")
public native Map<String, NSObject> getCachedSnapshot();
@Mapping("persistedSnapshot")
public native Map<String, NSObject> getPersistedSnapshot();
@Mapping("newVersionNumber")
public native @MachineSizedUInt long getNewVersionNumber();
@Mapping("oldVersionNumber")
public native @MachineSizedUInt long getOldVersionNumber();
}
| apache-2.0 |
piyush-malaviya/ClockView | app/src/main/java/com/pcm/clockview/DistanceRangeView.java | 1709 | package com.pcm.clockview;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
public class DistanceRangeView extends View {
private static final String TAG = DistanceRangeView.class.getSimpleName();
private static final int RADIUS_METER = 50; // 50 meter
private static int BAG_WIDTH = 50;
private static int BAG_HEIGHT = 50;
private static float RADIUS = 25;
private Bitmap bagIcon;
private Paint paintObject, paintBack;
public DistanceRangeView(Context context) {
super(context);
init();
}
public DistanceRangeView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public DistanceRangeView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
paintObject = new Paint(Paint.ANTI_ALIAS_FLAG);
paintBack = new Paint(Paint.ANTI_ALIAS_FLAG);
paintBack.setColor(Color.WHITE);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.save();
int centerX = getWidth() / 2;
int centerY = getHeight() / 2;
int displayCenter = centerX;
double pos = (displayCenter * 1) / RADIUS_METER;
float angle = (float) (Math.PI / 45f); // Need to convert to radians first
float startX = (float) (centerX + pos * Math.sin(angle));
float startY = (float) (centerY - pos * Math.cos(angle));
canvas.restore();
}
} | apache-2.0 |
AndroidBoySC/Mybilibili | app/src/main/java/com/songchao/mybilibili/util/GetDate.java | 569 | package com.songchao.mybilibili.util;
import java.util.Calendar;
/**
* Author: SongCHao
* Date: 2017/9/14/14:26
* Email: 15704762346@163.com
*/
public class GetDate {
public static StringBuilder getDate(){
StringBuilder stringBuilder = new StringBuilder();
Calendar now = Calendar.getInstance();
stringBuilder.append(now.get(Calendar.YEAR) + "年");
stringBuilder.append((int)(now.get(Calendar.MONTH) + 1) + "月");
stringBuilder.append(now.get(Calendar.DAY_OF_MONTH) + "日");
return stringBuilder;
}
}
| apache-2.0 |
baidubce/bce-sdk-java | src/main/java/com/baidubce/services/iothub/model/CreatePrincipalResponse.java | 1288 | /*
* Copyright 2016 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.baidubce.services.iothub.model;
/**
* Represent the create Principal request.
*/
public class CreatePrincipalResponse extends QueryPrincipalResponse {
private String password;
private String privateKey;
private String cert;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPrivateKey() {
return privateKey;
}
public void setPrivateKey(String privateKey) {
this.privateKey = privateKey;
}
public String getCert() {
return cert;
}
public void setCert(String cert) {
this.cert = cert;
}
}
| apache-2.0 |
iemejia/incubator-beam | sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/pubsub/TestPubsubSignal.java | 14124 | /*
* 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.beam.sdk.io.gcp.pubsub;
import static java.util.stream.Collectors.toList;
import static org.apache.beam.sdk.io.gcp.pubsub.TestPubsub.createTopicName;
import static org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Preconditions.checkState;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
import javax.annotation.Nullable;
import org.apache.beam.sdk.coders.Coder;
import org.apache.beam.sdk.io.gcp.pubsub.PubsubClient.IncomingMessage;
import org.apache.beam.sdk.io.gcp.pubsub.PubsubClient.SubscriptionPath;
import org.apache.beam.sdk.io.gcp.pubsub.PubsubClient.TopicPath;
import org.apache.beam.sdk.state.BagState;
import org.apache.beam.sdk.state.StateSpec;
import org.apache.beam.sdk.state.StateSpecs;
import org.apache.beam.sdk.testing.TestPipeline;
import org.apache.beam.sdk.testing.TestPipelineOptions;
import org.apache.beam.sdk.transforms.Create;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.PTransform;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.transforms.SerializableFunction;
import org.apache.beam.sdk.transforms.WithKeys;
import org.apache.beam.sdk.transforms.windowing.GlobalWindows;
import org.apache.beam.sdk.transforms.windowing.Window;
import org.apache.beam.sdk.values.KV;
import org.apache.beam.sdk.values.PBegin;
import org.apache.beam.sdk.values.PCollection;
import org.apache.beam.sdk.values.PDone;
import org.apache.beam.sdk.values.POutput;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Supplier;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Suppliers;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableSet;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Test rule which observes elements of the {@link PCollection} and checks whether they match the
* success criteria.
*
* <p>Uses a random temporary Pubsub topic for synchronization.
*/
public class TestPubsubSignal implements TestRule {
private static final Logger LOG = LoggerFactory.getLogger(TestPubsubSignal.class);
private static final String RESULT_TOPIC_NAME = "result";
private static final String RESULT_SUCCESS_MESSAGE = "SUCCESS";
private static final String START_TOPIC_NAME = "start";
private static final String START_SIGNAL_MESSAGE = "START SIGNAL";
private static final String NO_ID_ATTRIBUTE = null;
private static final String NO_TIMESTAMP_ATTRIBUTE = null;
PubsubClient pubsub;
private TestPubsubOptions pipelineOptions;
private @Nullable TopicPath resultTopicPath = null;
private @Nullable TopicPath startTopicPath = null;
/**
* Creates an instance of this rule.
*
* <p>Loads GCP configuration from {@link TestPipelineOptions}.
*/
public static TestPubsubSignal create() {
TestPubsubOptions options = TestPipeline.testingPipelineOptions().as(TestPubsubOptions.class);
return new TestPubsubSignal(options);
}
private TestPubsubSignal(TestPubsubOptions pipelineOptions) {
this.pipelineOptions = pipelineOptions;
}
@Override
public Statement apply(Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
if (TestPubsubSignal.this.pubsub != null) {
throw new AssertionError(
"Pubsub client was not shutdown in previous test. "
+ "Topic path is'"
+ resultTopicPath
+ "'. "
+ "Current test: "
+ description.getDisplayName());
}
try {
initializePubsub(description);
base.evaluate();
} finally {
tearDown();
}
}
};
}
private void initializePubsub(Description description) throws IOException {
pubsub =
PubsubGrpcClient.FACTORY.newClient(
NO_TIMESTAMP_ATTRIBUTE, NO_ID_ATTRIBUTE, pipelineOptions);
// Example topic name:
// integ-test-TestClassName-testMethodName-2018-12-11-23-32-333-<random-long>-result
TopicPath resultTopicPathTmp =
PubsubClient.topicPathFromName(
pipelineOptions.getProject(), createTopicName(description, RESULT_TOPIC_NAME));
TopicPath startTopicPathTmp =
PubsubClient.topicPathFromName(
pipelineOptions.getProject(), createTopicName(description, START_TOPIC_NAME));
pubsub.createTopic(resultTopicPathTmp);
pubsub.createTopic(startTopicPathTmp);
// Set these after successful creation; this signals that they need teardown
resultTopicPath = resultTopicPathTmp;
startTopicPath = startTopicPathTmp;
}
private void tearDown() throws IOException {
if (pubsub == null) {
return;
}
try {
if (resultTopicPath != null) {
pubsub.deleteTopic(resultTopicPath);
}
if (startTopicPath != null) {
pubsub.deleteTopic(startTopicPath);
}
} finally {
pubsub.close();
pubsub = null;
resultTopicPath = null;
}
}
/** Outputs a message that the pipeline has started. */
public PTransform<PBegin, PDone> signalStart() {
return new PublishStart(startTopicPath);
}
/**
* Outputs a success message when {@code successPredicate} is evaluated to true.
*
* <p>{@code successPredicate} is a {@link SerializableFunction} that accepts a set of currently
* captured events and returns true when the set satisfies the success criteria.
*
* <p>If {@code successPredicate} is evaluated to false, then it will be re-evaluated when next
* event becomes available.
*
* <p>If {@code successPredicate} is evaluated to true, then a success will be signaled and {@link
* #waitForSuccess(Duration)} will unblock.
*
* <p>If {@code successPredicate} throws, then failure will be signaled and {@link
* #waitForSuccess(Duration)} will unblock.
*/
public <T> PTransform<PCollection<? extends T>, POutput> signalSuccessWhen(
Coder<T> coder,
SerializableFunction<T, String> formatter,
SerializableFunction<Set<T>, Boolean> successPredicate) {
return new PublishSuccessWhen<>(coder, formatter, successPredicate, resultTopicPath);
}
/**
* Invocation of {@link #signalSuccessWhen(Coder, SerializableFunction, SerializableFunction)}
* with {@link Object#toString} as the formatter.
*/
public <T> PTransform<PCollection<? extends T>, POutput> signalSuccessWhen(
Coder<T> coder, SerializableFunction<Set<T>, Boolean> successPredicate) {
return signalSuccessWhen(coder, T::toString, successPredicate);
}
/**
* Future that waits for a start signal for {@code duration}.
*
* <p>This future must be created before running the pipeline. A subscription must exist prior to
* the start signal being published, which occurs immediately upon pipeline startup.
*/
public Supplier<Void> waitForStart(Duration duration) throws IOException {
SubscriptionPath startSubscriptionPath =
PubsubClient.subscriptionPathFromName(
pipelineOptions.getProject(),
"start-subscription-" + String.valueOf(ThreadLocalRandom.current().nextLong()));
pubsub.createSubscription(
startTopicPath, startSubscriptionPath, (int) duration.getStandardSeconds());
return Suppliers.memoize(
() -> {
try {
String result = pollForResultForDuration(startSubscriptionPath, duration);
checkState(START_SIGNAL_MESSAGE.equals(result));
return null;
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
/** Wait for a success signal for {@code duration}. */
public void waitForSuccess(Duration duration) throws IOException {
SubscriptionPath resultSubscriptionPath =
PubsubClient.subscriptionPathFromName(
pipelineOptions.getProject(),
"result-subscription-" + String.valueOf(ThreadLocalRandom.current().nextLong()));
pubsub.createSubscription(
resultTopicPath, resultSubscriptionPath, (int) duration.getStandardSeconds());
String result = pollForResultForDuration(resultSubscriptionPath, duration);
if (!RESULT_SUCCESS_MESSAGE.equals(result)) {
throw new AssertionError(result);
}
}
private String pollForResultForDuration(
SubscriptionPath signalSubscriptionPath, Duration duration) throws IOException {
List<PubsubClient.IncomingMessage> signal = null;
DateTime endPolling = DateTime.now().plus(duration.getMillis());
do {
try {
signal = pubsub.pull(DateTime.now().getMillis(), signalSubscriptionPath, 1, false);
pubsub.acknowledge(
signalSubscriptionPath, signal.stream().map(IncomingMessage::ackId).collect(toList()));
break;
} catch (StatusRuntimeException e) {
if (!Status.DEADLINE_EXCEEDED.equals(e.getStatus())) {
LOG.warn(
"(Will retry) Error while polling {} for signal: {}",
signalSubscriptionPath,
e.getStatus());
}
sleep(500);
}
} while (DateTime.now().isBefore(endPolling));
if (signal == null) {
throw new AssertionError(
String.format(
"Did not receive signal on %s in %ss",
signalSubscriptionPath, duration.getStandardSeconds()));
}
return signal.get(0).message().getData().toStringUtf8();
}
private void sleep(long t) {
try {
Thread.sleep(t);
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
}
/** {@link PTransform} that signals once when the pipeline has started. */
static class PublishStart extends PTransform<PBegin, PDone> {
private final TopicPath startTopicPath;
PublishStart(TopicPath startTopicPath) {
this.startTopicPath = startTopicPath;
}
@Override
public PDone expand(PBegin input) {
return input
.apply("Start signal", Create.of(START_SIGNAL_MESSAGE))
.apply(PubsubIO.writeStrings().to(startTopicPath.getPath()));
}
}
/** {@link PTransform} that for validates whether elements seen so far match success criteria. */
static class PublishSuccessWhen<T> extends PTransform<PCollection<? extends T>, POutput> {
private final Coder<T> coder;
private final SerializableFunction<T, String> formatter;
private final SerializableFunction<Set<T>, Boolean> successPredicate;
private final TopicPath resultTopicPath;
PublishSuccessWhen(
Coder<T> coder,
SerializableFunction<T, String> formatter,
SerializableFunction<Set<T>, Boolean> successPredicate,
TopicPath resultTopicPath) {
this.coder = coder;
this.formatter = formatter;
this.successPredicate = successPredicate;
this.resultTopicPath = resultTopicPath;
}
@Override
public POutput expand(PCollection<? extends T> input) {
return input
// assign a dummy key and global window,
// this is needed to accumulate all observed events in the same state cell
.apply(Window.into(new GlobalWindows()))
.apply(WithKeys.of("dummyKey"))
.apply(
"checkAllEventsForSuccess",
ParDo.of(new StatefulPredicateCheck<>(coder, formatter, successPredicate)))
// signal the success/failure to the result topic
.apply("publishSuccess", PubsubIO.writeStrings().to(resultTopicPath.getPath()));
}
}
/**
* Stateful {@link DoFn} which caches the elements it sees and checks whether they satisfy the
* predicate.
*
* <p>When predicate is satisfied outputs "SUCCESS". If predicate throws exception, outputs
* "FAILURE".
*/
static class StatefulPredicateCheck<T> extends DoFn<KV<String, ? extends T>, String> {
private final SerializableFunction<T, String> formatter;
private SerializableFunction<Set<T>, Boolean> successPredicate;
// keep all events seen so far in the state cell
private static final String SEEN_EVENTS = "seenEvents";
@StateId(SEEN_EVENTS)
private final StateSpec<BagState<T>> seenEvents;
StatefulPredicateCheck(
Coder<T> coder,
SerializableFunction<T, String> formatter,
SerializableFunction<Set<T>, Boolean> successPredicate) {
this.seenEvents = StateSpecs.bag(coder);
this.formatter = formatter;
this.successPredicate = successPredicate;
}
@ProcessElement
public void processElement(
ProcessContext context, @StateId(SEEN_EVENTS) BagState<T> seenEvents) {
seenEvents.add(context.element().getValue());
ImmutableSet<T> eventsSoFar = ImmutableSet.copyOf(seenEvents.read());
// check if all elements seen so far satisfy the success predicate
try {
if (successPredicate.apply(eventsSoFar)) {
context.output("SUCCESS");
}
} catch (Throwable e) {
context.output("FAILURE: " + e.getMessage());
}
}
}
}
| apache-2.0 |
groupon/odo | proxylib/src/main/java/com/groupon/odo/proxylib/ClientService.java | 24706 | /*
Copyright 2014 Groupon, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.groupon.odo.proxylib;
import com.groupon.odo.proxylib.models.Client;
import com.groupon.odo.proxylib.models.Profile;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ClientService {
private static final Logger logger = LoggerFactory.getLogger(ClientService.class);
private static SQLService sqlService = null;
private static ClientService serviceInstance = null;
public ClientService() {
}
public static ClientService getInstance() {
if (serviceInstance == null) {
serviceInstance = new ClientService();
try {
sqlService = SQLService.getInstance();
} catch (Exception e) {
e.printStackTrace();
}
}
return serviceInstance;
}
/**
* Return all Clients for a profile
*
* @param profileId ID of profile clients belong to
* @return collection of the Clients found
* @throws Exception exception
*/
public List<Client> findAllClients(int profileId) throws Exception {
ArrayList<Client> clients = new ArrayList<Client>();
PreparedStatement query = null;
ResultSet results = null;
try (Connection sqlConnection = sqlService.getConnection()) {
query = sqlConnection.prepareStatement(
"SELECT * FROM " + Constants.DB_TABLE_CLIENT +
" WHERE " + Constants.GENERIC_PROFILE_ID + " = ?"
);
query.setInt(1, profileId);
results = query.executeQuery();
while (results.next()) {
clients.add(this.getClientFromResultSet(results));
}
} catch (Exception e) {
throw e;
} finally {
try {
if (results != null) {
results.close();
}
} catch (Exception e) {
}
try {
if (query != null) {
query.close();
}
} catch (Exception e) {
}
}
return clients;
}
/**
* Returns a client object for a clientId
*
* @param clientId ID of client to return
* @return Client or null
* @throws Exception exception
*/
public Client getClient(int clientId) throws Exception {
Client client = null;
PreparedStatement statement = null;
ResultSet results = null;
try (Connection sqlConnection = sqlService.getConnection()) {
String queryString = "SELECT * FROM " + Constants.DB_TABLE_CLIENT +
" WHERE " + Constants.GENERIC_ID + " = ?";
statement = sqlConnection.prepareStatement(queryString);
statement.setInt(1, clientId);
results = statement.executeQuery();
if (results.next()) {
client = this.getClientFromResultSet(results);
}
} catch (Exception e) {
throw e;
} finally {
try {
if (results != null) {
results.close();
}
} catch (Exception e) {
}
try {
if (statement != null) {
statement.close();
}
} catch (Exception e) {
}
}
return client;
}
/**
* Returns a Client object for a clientUUID and profileId
*
* @param clientUUID UUID or friendlyName of client
* @param profileId - can be null, safer if it is not null
* @return Client object or null
* @throws Exception exception
*/
public Client findClient(String clientUUID, Integer profileId) throws Exception {
Client client = null;
/* ERROR CODE: 500 WHEN TRYING TO DELETE A SERVER GROUP.
THIS APPEARS TO BE BECAUSE CLIENT UUID IS NULL.
*/
/* CODE ADDED TO PREVENT NULL POINTERS. */
if (clientUUID == null) {
clientUUID = "";
}
// first see if the clientUUID is actually a uuid.. it might be a friendlyName and need conversion
/* A UUID IS A UNIVERSALLY UNIQUE IDENTIFIER. */
if (clientUUID.compareTo(Constants.PROFILE_CLIENT_DEFAULT_ID) != 0 &&
!clientUUID.matches("[\\w]{8}-[\\w]{4}-[\\w]{4}-[\\w]{4}-[\\w]{12}")) {
Client tmpClient = this.findClientFromFriendlyName(profileId, clientUUID);
// if we can't find a client then fall back to the default ID
if (tmpClient == null) {
clientUUID = Constants.PROFILE_CLIENT_DEFAULT_ID;
} else {
return tmpClient;
}
}
PreparedStatement statement = null;
ResultSet results = null;
try (Connection sqlConnection = sqlService.getConnection()) {
String queryString = "SELECT * FROM " + Constants.DB_TABLE_CLIENT +
" WHERE " + Constants.CLIENT_CLIENT_UUID + " = ?";
if (profileId != null) {
queryString += " AND " + Constants.GENERIC_PROFILE_ID + "=?";
}
statement = sqlConnection.prepareStatement(queryString);
statement.setString(1, clientUUID);
if (profileId != null) {
statement.setInt(2, profileId);
}
results = statement.executeQuery();
if (results.next()) {
client = this.getClientFromResultSet(results);
}
} catch (Exception e) {
throw e;
} finally {
try {
if (results != null) {
results.close();
}
} catch (Exception e) {
}
try {
if (statement != null) {
statement.close();
}
} catch (Exception e) {
}
}
return client;
}
/**
* Returns a client model from a ResultSet
*
* @param result resultset containing client information
* @return Client or null
* @throws Exception exception
*/
private Client getClientFromResultSet(ResultSet result) throws Exception {
Client client = new Client();
client.setId(result.getInt(Constants.GENERIC_ID));
client.setUUID(result.getString(Constants.CLIENT_CLIENT_UUID));
client.setFriendlyName(result.getString(Constants.CLIENT_FRIENDLY_NAME));
client.setProfile(ProfileService.getInstance().findProfile(result.getInt(Constants.GENERIC_PROFILE_ID)));
client.setIsActive(result.getBoolean(Constants.CLIENT_IS_ACTIVE));
client.setActiveServerGroup(result.getInt(Constants.CLIENT_ACTIVESERVERGROUP));
return client;
}
private String getUniqueClientUUID() {
String curClientUUID = UUID.randomUUID().toString();
PreparedStatement statement = null;
ResultSet results = null;
try (Connection sqlConnection = sqlService.getConnection()) {
while (true) {
statement = sqlConnection.prepareStatement("SELECT * FROM " + Constants.DB_TABLE_CLIENT +
" WHERE " + Constants.GENERIC_CLIENT_UUID + " = ?");
statement.setString(1, curClientUUID);
results = statement.executeQuery();
if (results.next()) {
curClientUUID = UUID.randomUUID().toString();
} else {
break;
}
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (results != null) {
results.close();
}
} catch (Exception e) {
}
try {
if (statement != null) {
statement.close();
}
} catch (Exception e) {
}
}
logger.info("ClientUUID of new client = {}", curClientUUID);
return curClientUUID;
}
/**
* Create a new client for profile
* There is a limit of Constants.CLIENT_CLIENTS_PER_PROFILE_LIMIT
* If this limit is reached an exception is thrown back to the caller
*
* @param profileId ID of profile to create a new client for
* @return The newly created client
* @throws Exception exception
*/
public Client add(int profileId) throws Exception {
Client client = null;
ArrayList<Integer> pathsToCopy = new ArrayList<Integer>();
String clientUUID = getUniqueClientUUID();
// get profile for profileId
Profile profile = ProfileService.getInstance().findProfile(profileId);
PreparedStatement statement = null;
ResultSet rs = null;
try (Connection sqlConnection = sqlService.getConnection()) {
// get the current count of clients
statement = sqlConnection.prepareStatement("SELECT COUNT(" + Constants.GENERIC_ID + ") FROM " +
Constants.DB_TABLE_CLIENT + " WHERE " + Constants.GENERIC_PROFILE_ID + "=?");
statement.setInt(1, profileId);
int clientCount = -1;
rs = statement.executeQuery();
if (rs.next()) {
clientCount = rs.getInt(1);
}
statement.close();
rs.close();
// check count
if (clientCount == -1) {
throw new Exception("Error querying clients for profileId=" + profileId);
}
if (clientCount >= Constants.CLIENT_CLIENTS_PER_PROFILE_LIMIT) {
throw new Exception("Profile(" + profileId + ") already contains 50 clients. Please remove clients before adding new ones.");
}
statement = sqlConnection.prepareStatement(
"INSERT INTO " + Constants.DB_TABLE_CLIENT +
" (" + Constants.CLIENT_CLIENT_UUID + ", " +
Constants.CLIENT_IS_ACTIVE + ", " +
Constants.CLIENT_PROFILE_ID + ")" +
" VALUES (?, ?, ?)", Statement.RETURN_GENERATED_KEYS
);
statement.setString(1, clientUUID);
statement.setBoolean(2, false);
statement.setInt(3, profile.getId());
statement.executeUpdate();
rs = statement.getGeneratedKeys();
int clientId = -1;
if (rs.next()) {
clientId = rs.getInt(1);
} else {
// something went wrong
throw new Exception("Could not add client");
}
rs.close();
statement.close();
// adding entries into request response table for this new client for every path
// basically a copy of what happens when a path gets created
statement = sqlConnection.prepareStatement(
"SELECT * FROM " + Constants.DB_TABLE_REQUEST_RESPONSE +
" WHERE " + Constants.GENERIC_PROFILE_ID + " = ?" +
" AND " + Constants.GENERIC_CLIENT_UUID + " = ?"
);
statement.setInt(1, profile.getId());
statement.setString(2, Constants.PROFILE_CLIENT_DEFAULT_ID);
rs = statement.executeQuery();
while (rs.next()) {
// collect up the pathIds we need to copy
pathsToCopy.add(rs.getInt(Constants.REQUEST_RESPONSE_PATH_ID));
}
client = new Client();
client.setIsActive(false);
client.setUUID(clientUUID);
client.setId(clientId);
client.setProfile(profile);
} catch (SQLException e) {
throw e;
} finally {
try {
if (rs != null) {
rs.close();
}
} catch (Exception e) {
}
try {
if (statement != null) {
statement.close();
}
} catch (Exception e) {
}
}
// add all of the request response items
for (Integer pathId : pathsToCopy) {
PathOverrideService.getInstance().addPathToRequestResponseTable(profile.getId(), client.getUUID(), pathId);
}
return client;
}
/**
* Set a friendly name for a client
*
* @param profileId profileId of the client
* @param clientUUID UUID of the client
* @param friendlyName friendly name of the client
* @return return Client object or null
* @throws Exception exception
*/
public Client setFriendlyName(int profileId, String clientUUID, String friendlyName) throws Exception {
// first see if this friendlyName is already in use
Client client = this.findClientFromFriendlyName(profileId, friendlyName);
if (client != null && !client.getUUID().equals(clientUUID)) {
throw new Exception("Friendly name already in use");
}
PreparedStatement statement = null;
int rowsAffected = 0;
try (Connection sqlConnection = sqlService.getConnection()) {
statement = sqlConnection.prepareStatement(
"UPDATE " + Constants.DB_TABLE_CLIENT +
" SET " + Constants.CLIENT_FRIENDLY_NAME + " = ?" +
" WHERE " + Constants.CLIENT_CLIENT_UUID + " = ?" +
" AND " + Constants.GENERIC_PROFILE_ID + " = ?"
);
statement.setString(1, friendlyName);
statement.setString(2, clientUUID);
statement.setInt(3, profileId);
rowsAffected = statement.executeUpdate();
} catch (Exception e) {
} finally {
try {
if (statement != null) {
statement.close();
}
} catch (Exception e) {
}
}
if (rowsAffected == 0) {
return null;
}
return this.findClient(clientUUID, profileId);
}
/**
* Get the client for a profileId/friendlyName
*
* @param profileId profile ID of the client
* @param friendlyName friendly name of the client
* @return Client or null
* @throws Exception exception
*/
public Client findClientFromFriendlyName(int profileId, String friendlyName) throws Exception {
Client client = null;
// Don't even try if the friendlyName is null/empty
if (friendlyName == null || friendlyName.compareTo("") == 0) {
return client;
}
PreparedStatement statement = null;
ResultSet results = null;
try (Connection sqlConnection = sqlService.getConnection()) {
String queryString = "SELECT * FROM " + Constants.DB_TABLE_CLIENT +
" WHERE " + Constants.CLIENT_FRIENDLY_NAME + " = ?" +
" AND " + Constants.GENERIC_PROFILE_ID + " = ?";
statement = sqlConnection.prepareStatement(queryString);
statement.setString(1, friendlyName);
statement.setInt(2, profileId);
results = statement.executeQuery();
if (results.next()) {
client = this.getClientFromResultSet(results);
}
} catch (SQLException e) {
throw e;
} finally {
try {
if (results != null) {
results.close();
}
} catch (Exception e) {
}
try {
if (statement != null) {
statement.close();
}
} catch (Exception e) {
}
}
return client;
}
/**
* Removes a client from the database
* Also clears all additional override information for the clientId
*
* @param profileId profile ID of client to remove
* @param clientUUID client UUID of client to remove
* @throws Exception exception
*/
public void remove(int profileId, String clientUUID) throws Exception {
PreparedStatement statement = null;
ResultSet results = null;
try (Connection sqlConnection = sqlService.getConnection()) {
// first try selecting the row we want to deal with
statement = sqlConnection.prepareStatement(
"SELECT * FROM " + Constants.DB_TABLE_CLIENT +
" WHERE " + Constants.GENERIC_CLIENT_UUID + " = ?" +
" AND " + Constants.CLIENT_PROFILE_ID + "= ?"
);
statement.setString(1, clientUUID);
statement.setInt(2, profileId);
results = statement.executeQuery();
if (!results.next()) {
throw new Exception("Could not find specified clientUUID: " + clientUUID);
}
} catch (Exception e) {
throw e;
} finally {
try {
if (results != null) {
results.close();
}
} catch (Exception e) {
}
try {
if (statement != null) {
statement.close();
}
} catch (Exception e) {
}
}
// delete from the client table
String queryString = "DELETE FROM " + Constants.DB_TABLE_CLIENT +
" WHERE " + Constants.CLIENT_CLIENT_UUID + " = ? " +
" AND " + Constants.CLIENT_PROFILE_ID + " = ?";
try (Connection sqlConnection = sqlService.getConnection()) {
statement = sqlConnection.prepareStatement(queryString);
statement.setString(1, clientUUID);
statement.setInt(2, profileId);
logger.info("Query: {}", statement.toString());
statement.executeUpdate();
} catch (Exception e) {
throw e;
} finally {
try {
if (statement != null) {
statement.close();
}
} catch (Exception e) {
}
}
// delete from other tables as appropriate
// need to delete from enabled_overrides and request_response
try (Connection sqlConnection = sqlService.getConnection()) {
statement = sqlConnection.prepareStatement(
"DELETE FROM " + Constants.DB_TABLE_REQUEST_RESPONSE +
" WHERE " + Constants.CLIENT_CLIENT_UUID + " = ? " +
" AND " + Constants.CLIENT_PROFILE_ID + " = ?"
);
statement.setString(1, clientUUID);
statement.setInt(2, profileId);
statement.executeUpdate();
} catch (Exception e) {
// ok to swallow this.. just means there wasn't any
}
try (Connection sqlConnection = sqlService.getConnection()) {
statement = sqlConnection.prepareStatement(
"DELETE FROM " + Constants.DB_TABLE_ENABLED_OVERRIDE +
" WHERE " + Constants.CLIENT_CLIENT_UUID + " = ? " +
" AND " + Constants.CLIENT_PROFILE_ID + " = ?"
);
statement.setString(1, clientUUID);
statement.setInt(2, profileId);
statement.executeUpdate();
} catch (Exception e) {
// ok to swallow this.. just means there wasn't any
} finally {
try {
if (statement != null) {
statement.close();
}
} catch (Exception e) {
}
}
}
/**
* disables the current active id, enables the new one selected
*
* @param profileId profile ID of the client
* @param clientUUID UUID of the client
* @param active true to make client active, false to make client inactive
* @throws Exception exception
*/
public void updateActive(int profileId, String clientUUID, Boolean active) throws Exception {
PreparedStatement statement = null;
try (Connection sqlConnection = sqlService.getConnection()) {
statement = sqlConnection.prepareStatement(
"UPDATE " + Constants.DB_TABLE_CLIENT +
" SET " + Constants.CLIENT_IS_ACTIVE + "= ?" +
" WHERE " + Constants.GENERIC_CLIENT_UUID + "= ? " +
" AND " + Constants.GENERIC_PROFILE_ID + "= ?"
);
statement.setBoolean(1, active);
statement.setString(2, clientUUID);
statement.setInt(3, profileId);
statement.executeUpdate();
} catch (Exception e) {
// ok to swallow this.. just means there wasn't any
} finally {
try {
if (statement != null) {
statement.close();
}
} catch (Exception e) {
}
}
}
/**
* Resets all override settings for the clientUUID and disables it
*
* @param profileId profile ID of the client
* @param clientUUID UUID of the client
* @throws Exception exception
*/
public void reset(int profileId, String clientUUID) throws Exception {
PreparedStatement statement = null;
// TODO: need a better way to do this than brute force.. but the iterative approach is too slow
try (Connection sqlConnection = sqlService.getConnection()) {
// first remove all enabled overrides with this client uuid
String queryString = "DELETE FROM " + Constants.DB_TABLE_ENABLED_OVERRIDE +
" WHERE " + Constants.GENERIC_CLIENT_UUID + "= ? " +
" AND " + Constants.GENERIC_PROFILE_ID + " = ?";
statement = sqlConnection.prepareStatement(queryString);
statement.setString(1, clientUUID);
statement.setInt(2, profileId);
statement.executeUpdate();
statement.close();
// clean up request response table for this uuid
queryString = "UPDATE " + Constants.DB_TABLE_REQUEST_RESPONSE +
" SET " + Constants.REQUEST_RESPONSE_CUSTOM_REQUEST + "=?, "
+ Constants.REQUEST_RESPONSE_CUSTOM_RESPONSE + "=?, "
+ Constants.REQUEST_RESPONSE_REPEAT_NUMBER + "=-1, "
+ Constants.REQUEST_RESPONSE_REQUEST_ENABLED + "=0, "
+ Constants.REQUEST_RESPONSE_RESPONSE_ENABLED + "=0 "
+ "WHERE " + Constants.GENERIC_CLIENT_UUID + "=? " +
" AND " + Constants.GENERIC_PROFILE_ID + "=?";
statement = sqlConnection.prepareStatement(queryString);
statement.setString(1, "");
statement.setString(2, "");
statement.setString(3, clientUUID);
statement.setInt(4, profileId);
statement.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (statement != null) {
statement.close();
}
} catch (Exception e) {
}
}
this.updateActive(profileId, clientUUID, false);
}
public String getClientUUIDfromId(int id) {
return (String) sqlService.getFromTable(Constants.CLIENT_CLIENT_UUID, Constants.GENERIC_ID, id, Constants.DB_TABLE_CLIENT);
}
public int getIdFromClientUUID(String uuid) {
return (Integer) sqlService.getFromTable(Constants.GENERIC_ID, Constants.CLIENT_CLIENT_UUID, uuid, Constants.DB_TABLE_CLIENT);
}
//gets the profile_name associated with a specific id
public String getProfileIdFromClientId(int id) {
return (String) sqlService.getFromTable(Constants.CLIENT_PROFILE_ID, Constants.GENERIC_ID, id, Constants.DB_TABLE_CLIENT);
}
}
| apache-2.0 |
marklogic/java-client-api | marklogic-client-api/src/main/java/com/marklogic/client/example/cookbook/AllCookbookExamples.java | 2707 | /*
* Copyright (c) 2019 MarkLogic Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.marklogic.client.example.cookbook;
import java.io.IOException;
import javax.xml.bind.JAXBException;
import javax.xml.xpath.XPathExpressionException;
import com.marklogic.client.FailedRequestException;
import com.marklogic.client.ForbiddenUserException;
import com.marklogic.client.ResourceNotFoundException;
import com.marklogic.client.ResourceNotResendableException;
import com.marklogic.client.example.cookbook.Util.ExampleProperties;
/**
* AllCookbookExamples executes all of the recipe examples in the cookbook.
* Please set up a REST server and configure Example.properties
* before running any example.
*/
public class AllCookbookExamples {
public static void main(String[] args)
throws IOException, JAXBException, ResourceNotFoundException, ForbiddenUserException, FailedRequestException, ResourceNotResendableException, XPathExpressionException {
ExampleProperties props = Util.loadProperties();
// execute the examples
ClientCreator.run( props );
DocumentWrite.run( props );
DocumentWriteServerURI.run( props );
DocumentRead.run( props );
DocumentMetadataWrite.run( props );
DocumentMetadataRead.run( props );
DocumentDelete.run( props );
DocumentFormats.run( props );
DocumentOutputStream.run( props );
JAXBDocument.run( props );
QueryOptions.run( props );
StringSearch.run( props );
StructuredSearch.run( props );
RawCombinedSearch.run( props );
SearchResponseTransform.run( props );
MultiStatementTransaction.run( props );
DocumentReadTransform.run( props );
DocumentWriteTransform.run( props );
OptimisticLocking.run( props );
RawClientAlert.run( props );
ResourceExtension.run( props );
// SSLClientCreator is not included in this list because it requires a change
// to the REST server that invalidates all of the other examples. See
// the comments in SSLClientCreator.
}
}
| apache-2.0 |
Yuijam/droidfan | app/src/main/java/com/arenas/droidfan/login/LoginActivity.java | 6785 | package com.arenas.droidfan.login;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import com.arenas.droidfan.Util.Utils;
import com.arenas.droidfan.api.Api;
import com.arenas.droidfan.api.ApiException;
import com.arenas.droidfan.AppContext;
import com.arenas.droidfan.R;
import com.arenas.droidfan.data.model.UserModel;
import com.arenas.droidfan.main.MainActivity;
import org.oauthsimple.model.OAuthToken;
import butterknife.BindView;
import butterknife.ButterKnife;
public class LoginActivity extends AppCompatActivity implements OnClickListener{
private static final String TAG = LoginActivity.class.getSimpleName();
private UserLoginTask mAuthTask = null;
// UI references.
@BindView(R.id.account) EditText mAccount;
@BindView(R.id.password) EditText mPassword;
@BindView(R.id.login_progress) ProgressBar mProgressView;
@BindView(R.id.login_button) Button loginButton;
@BindView(R.id.login_layout) LinearLayout loginLayout;
@BindView(R.id.version_code) TextView versionCode;
private Context mContext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
init();
if (AppContext.isVerified()){
showHomePage();
}
}
private void init(){
mContext = this;
ButterKnife.bind(this);
loginButton.setOnClickListener(this);
versionCode.setText(Utils.getVersionCode());
}
@Override
public void onClick(View view) {
if (view.getId() == R.id.login_button){
attemptLogin();
}
}
private void attemptLogin() {
if (mAuthTask != null) {
return;
}
String account = mAccount.getText().toString();
String password = mPassword.getText().toString();
if (account.trim().isEmpty() || password.trim().isEmpty()){
Toast.makeText(this , "用户名或者密码不能为空" , Toast.LENGTH_SHORT).show();
return;
}
Utils.hideKeyboard(LoginActivity.this , mPassword);
showProgress(true);
mAuthTask = new UserLoginTask(account, password);
mAuthTask.execute();
}
/**
* Shows the progress UI and hides the login form.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
loginLayout.setVisibility(show ? View.GONE : View.VISIBLE);
loginLayout.animate().setDuration(shortAnimTime).alpha(
show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
loginLayout.setVisibility(show ? View.GONE : View.VISIBLE);
}
});
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mProgressView.animate().setDuration(shortAnimTime).alpha(
show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
}
private void showHomePage(){
Intent intent = new Intent(mContext , MainActivity.class);
startActivity(intent);
finish();
}
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
public class UserLoginTask extends AsyncTask<Void, Integer, Boolean> {
private final String mEmail;
private final String mPassword;
UserLoginTask(String email, String password) {
mEmail = email;
mPassword = password;
}
@Override
protected Boolean doInBackground(Void... params) {
try {
final Api api = AppContext.getApi();
OAuthToken token = api.getOAuthAccessToken(mEmail, mPassword);
if (token != null){
publishProgress();
AppContext.updateAccessToken(mContext , token);
final UserModel u = api.verifyCredentials();
if (u != null){
AppContext.updateUserInfo(mContext , u);
AppContext.updateLoginInfo(mContext , mEmail , mPassword);
return true;
}else {
AppContext.clearAccountInfo(mContext);
return false;
}
}else {
Log.d(TAG , "token = null , login failed");
return false;
}
} catch (IOException e) {
Log.d(TAG , "IOException");
return false;
} catch (ApiException e){
Log.d(TAG , "ApiException : " + e.toString());
return false;
} catch (Exception e){
Log.d(TAG , "Exception");
return false;
}
}
@Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
Log.d(TAG , "onPostExecute success");
AppContext.setFirstLoad(true);
showHomePage();
finish();
} else {
Log.d(TAG , "onPostExecute failed");
Utils.showToast(mContext , "密码或者账号错误");
}
}
@Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
}
| apache-2.0 |
STRiDGE/dozer | core/src/test/java/org/dozer/vo/deepindex/B.java | 776 | /*
* Copyright 2005-2017 Dozer Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dozer.vo.deepindex;
public class B {
private C[] foo;
public C[] getFoo() {
return foo;
}
public void setFoo(C[] foo) {
this.foo = foo;
}
} | apache-2.0 |
gauthierj/dsm-webapi-client | dsm-webapi-client-filestation/src/main/java/com/github/gauthierj/dsm/webapi/client/filestation/info/FileStationInformation.java | 1515 | package com.github.gauthierj.dsm.webapi.client.filestation.info;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class FileStationInformation {
private boolean manager;
private List<String> supportedVirtualFileSystems = new ArrayList<>();
private boolean supportSharing;
private String hostname;
@JsonCreator
public FileStationInformation(
@JsonProperty("is_manager") boolean manager,
@JsonProperty("support_virtual") String supportedVirtualFileSystems,
@JsonProperty("support_sharing") boolean supportSharing,
@JsonProperty("hostname") String hostname) {
this.manager = manager;
if(!Strings.isNullOrEmpty(supportedVirtualFileSystems)) {
this.supportedVirtualFileSystems.addAll(Splitter.on(',').splitToList(supportedVirtualFileSystems));
}
this.supportSharing = supportSharing;
this.hostname = hostname;
}
public boolean isManager() {
return manager;
}
public List<String> getSupportedVirtualFileSystems() {
return Collections.unmodifiableList(supportedVirtualFileSystems);
}
public boolean isSupportSharing() {
return supportSharing;
}
public String getHostname() {
return hostname;
}
}
| apache-2.0 |
VincentVanGestel/osm-to-dot-converter | src/test/java/com/github/vincentvangestel/osmdot/pruner/RoundAboutPrunerTest.java | 4667 | package com.github.vincentvangestel.osmdot.pruner;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
import com.github.rinde.rinsim.geom.Connection;
import com.github.rinde.rinsim.geom.Graph;
import com.github.rinde.rinsim.geom.LengthData;
import com.github.rinde.rinsim.geom.MultiAttributeData;
import com.github.rinde.rinsim.geom.Point;
import com.github.rinde.rinsim.geom.TableGraph;
import com.google.common.collect.Lists;
public class RoundAboutPrunerTest {
static final double DELTA = 0.0001;
Graph<MultiAttributeData> graph;
static final MultiAttributeData data = MultiAttributeData.builder().setMaxSpeed(10).build();
static final RoundAboutPruner pruner = new RoundAboutPruner(100);
static final Connection<LengthData> DUMMY = Connection.create(
new Point(0, 0), new Point(1, 1));
@Before
public void setUp() {
graph = new TableGraph<>();
}
@Test
public void pruneCycleTest() {
Point A,B,C,D,E,F;
Point O,I,N;
Point Center;
A = new Point(10,10);
B = new Point(5,15);
C = new Point(10,20);
D = new Point(15,20);
E = new Point(20,15);
F = new Point(15,10);
Center = Point.centroid(Lists.newArrayList(A, B, C, D, E, F));
O = new Point(300,300);
I = new Point(300,150);
N = new Point(10,300);
graph.addConnection(A, B, data);
graph.addConnection(B, C, data);
graph.addConnection(C, D, data);
graph.addConnection(D, E, data);
graph.addConnection(E, F, data);
graph.addConnection(F, A, data); // The cycle
graph.addConnection(D, O, data); // Outgoing
graph.addConnection(I, E, data); // Incoming
graph.addConnection(C, N, data);
graph.addConnection(N, C, data); // Bi-directional
graph = pruner.prune(graph);
assertEquals(4,graph.getNumberOfNodes());
assertTrue(graph.hasConnection(Center, O)); // Outgoing
assertTrue(graph.hasConnection(I, Center)); // Incoming
assertTrue(graph.hasConnection(N, Center));
assertTrue(graph.hasConnection(Center, N)); // Bi-directional
}
@Test
public void pruneMultipleContainedCycleTest() {
Point A,B,C,D,E,F;
Point O,I,N,N2;
Point Center;
A = new Point(10,10);
B = new Point(5,15);
C = new Point(10,20);
D = new Point(15,20);
E = new Point(20,15);
F = new Point(15,10);
N = new Point(10, 30);
Center = Point.centroid(Lists.newArrayList(A, B, C, D, E, F, N));
O = new Point(300,300);
I = new Point(300,150);
N2 = new Point(10,300);
graph.addConnection(A, B, data);
graph.addConnection(B, C, data);
graph.addConnection(C, D, data);
graph.addConnection(D, E, data);
graph.addConnection(E, F, data);
graph.addConnection(F, A, data);
graph.addConnection(C, N, data);
graph.addConnection(N, C, data);// The cycle
graph.addConnection(D, O, data); // Outgoing
graph.addConnection(I, E, data); // Incoming
graph.addConnection(N, N2, data);
graph.addConnection(N2, N, data); // Bi-directional
graph = pruner.prune(graph);
assertEquals(4,graph.getNumberOfNodes());
assertTrue(graph.hasConnection(Center, O)); // Outgoing
assertTrue(graph.hasConnection(I, Center)); // Incoming
assertTrue(graph.hasConnection(N2, Center));
assertTrue(graph.hasConnection(Center, N2)); // Bi-directional
}
@Test
public void pruneMultipleTouchingCycleTest() {
Point A1,B1,C1,D1,E,F1;
Point A2,B2,C2,D2,F2;
Point Center1;
Point Center2;
A1 = new Point(10,10);
B1 = new Point(0,20);
C1 = new Point(10,30);
D1 = new Point(20,30);
E = new Point(30,20);
F1 = new Point(20,10);
A2 = new Point(50,10);
B2 = new Point(60,20);
C2 = new Point(50,30);
D2 = new Point(40,30);
F2 = new Point(40,10);
Center1 = Point.centroid(Lists.newArrayList(A1, B1, C1, D1, E, F1));
Center2 = Point.centroid(Lists.newArrayList(A2, B2, C2, D2, E, F2));
graph.addConnection(A1, B1, data);
graph.addConnection(B1, C1, data);
graph.addConnection(C1, D1, data);
graph.addConnection(D1, E, data);
graph.addConnection(E, F1, data);
graph.addConnection(F1, A1, data); // Cycle 1
graph.addConnection(A2, B2, data);
graph.addConnection(B2, C2, data);
graph.addConnection(C2, D2, data);
graph.addConnection(D2, E, data);
graph.addConnection(E, F2, data);
graph.addConnection(F2, A2, data); // Cycle 2
graph = pruner.prune(graph);
assertEquals(2,graph.getNumberOfNodes());
assertTrue(graph.hasConnection(Center1, Center2));
assertTrue(graph.hasConnection(Center2, Center1));
}
}
| apache-2.0 |
samueltardieu/cgeo | main/src/cgeo/geocaching/UsefulAppsActivity.java | 5244 | package cgeo.geocaching;
import butterknife.ButterKnife;
import butterknife.Bind;
import cgeo.geocaching.activity.AbstractActionBarActivity;
import cgeo.geocaching.compatibility.Compatibility;
import cgeo.geocaching.ui.AbstractViewHolder;
import cgeo.geocaching.utils.ProcessUtils;
import org.eclipse.jdt.annotation.NonNull;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class UsefulAppsActivity extends AbstractActionBarActivity {
@Bind(R.id.apps_list) protected ListView list;
protected static class ViewHolder extends AbstractViewHolder {
@Bind(R.id.title) protected TextView title;
@Bind(R.id.image) protected ImageView image;
@Bind(R.id.description) protected TextView description;
public ViewHolder(final View rowView) {
super(rowView);
}
}
private static class HelperApp {
private final int titleId;
private final int descriptionId;
private final int iconId;
@NonNull
private final String packageName;
public HelperApp(final int title, final int description, final int icon, @NonNull final String packageName) {
this.titleId = title;
this.descriptionId = description;
this.iconId = icon;
this.packageName = packageName;
}
}
private static final HelperApp[] HELPER_APPS = {
new HelperApp(R.string.helper_calendar_title, R.string.helper_calendar_description, R.drawable.cgeo, "cgeo.calendar"),
new HelperApp(R.string.helper_sendtocgeo_title, R.string.helper_sendtocgeo_description, R.drawable.cgeo, "http://send2.cgeo.org"),
new HelperApp(R.string.helper_contacts_title, R.string.helper_contacts_description, R.drawable.cgeo, "cgeo.contacts"),
new HelperApp(R.string.helper_wear_title, R.string.helper_wear_description, R.drawable.helper_wear, "com.javadog.cgeowear"),
new HelperApp(R.string.helper_pocketquery_title, R.string.helper_pocketquery_description, R.drawable.helper_pocketquery, "org.pquery"),
new HelperApp(R.string.helper_google_translate_title, R.string.helper_google_translate_description, R.drawable.helper_google_translate, "com.google.android.apps.translate"),
new HelperApp(R.string.helper_where_you_go_title, R.string.helper_where_you_go_description, R.drawable.helper_where_you_go, "menion.android.whereyougo"),
new HelperApp(R.string.helper_gpsstatus_title, R.string.helper_gpsstatus_description, R.drawable.helper_gpsstatus, "com.eclipsim.gpsstatus2"),
new HelperApp(R.string.helper_bluetoothgps_title, R.string.helper_bluetoothgps_description, R.drawable.helper_bluetoothgps, "googoo.android.btgps"),
new HelperApp(R.string.helper_barcode_title, R.string.helper_barcode_description, R.drawable.helper_barcode, "com.google.zxing.client.android"),
new HelperApp(R.string.helper_locus_title, R.string.helper_locus_description, R.drawable.helper_locus, "menion.android.locus"),
};
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState, R.layout.usefulapps_activity);
ButterKnife.bind(this);
list.setAdapter(new ArrayAdapter<HelperApp>(this, R.layout.usefulapps_item, HELPER_APPS) {
@Override
public View getView(final int position, final View convertView, final android.view.ViewGroup parent) {
View rowView = convertView;
if (rowView == null) {
rowView = getLayoutInflater().inflate(R.layout.usefulapps_item, parent, false);
}
ViewHolder holder = (ViewHolder) rowView.getTag();
if (holder == null) {
holder = new ViewHolder(rowView);
}
final HelperApp app = getItem(position);
fillViewHolder(holder, app);
return rowView;
}
private void fillViewHolder(final ViewHolder holder, final HelperApp app) {
holder.title.setText(res.getString(app.titleId));
holder.image.setImageDrawable(Compatibility.getDrawable(res, app.iconId));
holder.description.setText(Html.fromHtml(res.getString(app.descriptionId)));
}
});
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(final AdapterView<?> parent, final View view, final int position, final long id) {
final HelperApp helperApp = HELPER_APPS[position];
if (helperApp.packageName.startsWith("http")) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(helperApp.packageName)));
}
else {
ProcessUtils.openMarket(UsefulAppsActivity.this, helperApp.packageName);
}
}
});
}
}
| apache-2.0 |
adamrduffy/trinidad-1.0.x | trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/renderkit/core/xhtml/TableRenderer.java | 34745 | /*
* 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.myfaces.trinidadinternal.renderkit.core.xhtml;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.faces.component.NamingContainer;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.event.FacesEvent;
import org.apache.myfaces.trinidad.logging.TrinidadLogger;
import org.apache.myfaces.trinidad.bean.FacesBean;
import org.apache.myfaces.trinidad.bean.PropertyKey;
import org.apache.myfaces.trinidad.component.CollectionComponent;
import org.apache.myfaces.trinidad.component.TableUtils;
import org.apache.myfaces.trinidad.component.UIXCollection;
import org.apache.myfaces.trinidad.component.UIXColumn;
import org.apache.myfaces.trinidad.component.UIXTable;
import org.apache.myfaces.trinidad.component.core.data.CoreColumn;
import org.apache.myfaces.trinidad.component.core.data.CoreTable;
import org.apache.myfaces.trinidad.context.Agent;
import org.apache.myfaces.trinidad.context.FormData;
import org.apache.myfaces.trinidad.context.RequestContext;
import org.apache.myfaces.trinidad.context.PartialPageContext;
import org.apache.myfaces.trinidad.context.RenderingContext;
import org.apache.myfaces.trinidad.event.RowDisclosureEvent;
import org.apache.myfaces.trinidad.event.RangeChangeEvent;
import org.apache.myfaces.trinidad.event.SortEvent;
import org.apache.myfaces.trinidad.model.RowKeySet;
import org.apache.myfaces.trinidad.model.SortCriterion;
import org.apache.myfaces.trinidad.render.ClientRowKeyManager;
import org.apache.myfaces.trinidad.render.CoreRenderer;
import org.apache.myfaces.trinidadinternal.renderkit.core.xhtml.table.CellUtils;
import org.apache.myfaces.trinidadinternal.renderkit.core.xhtml.table.ColumnData;
import org.apache.myfaces.trinidadinternal.renderkit.core.xhtml.table.DetailColumnRenderer;
import org.apache.myfaces.trinidadinternal.renderkit.core.xhtml.table.RenderStage;
import org.apache.myfaces.trinidadinternal.renderkit.core.xhtml.table.SelectionColumnRenderer;
import org.apache.myfaces.trinidadinternal.renderkit.core.xhtml.table.SpecialColumnRenderer;
import org.apache.myfaces.trinidadinternal.renderkit.core.xhtml.table.TableRenderingContext;
import org.apache.myfaces.trinidadinternal.renderkit.core.xhtml.table.TableSelectManyRenderer;
import org.apache.myfaces.trinidadinternal.renderkit.core.xhtml.table.TableSelectOneRenderer;
import org.apache.myfaces.trinidadinternal.renderkit.core.xhtml.table.TreeUtils;
import org.apache.myfaces.trinidad.util.IntegerUtils;
abstract public class TableRenderer extends XhtmlRenderer
{
public TableRenderer(FacesBean.Type type)
{
super(type);
_resourceKeyMap = createResourceKeyMap();
}
@Override
protected void findTypeConstants(FacesBean.Type type)
{
super.findTypeConstants(type);
_widthKey = type.findKey("width");
_emptyTextKey = type.findKey("emptyText");
_navBarRenderer = new NavBar(type);
_selectRenderer = new SelectionColumnRenderer(type);
_selectOne = new TableSelectOneRenderer(type);
_selectMany = new TableSelectManyRenderer(type);
}
@Override
public boolean getRendersChildren()
{
return true;
}
@SuppressWarnings("unchecked")
@Override
public void decode(FacesContext context, UIComponent component)
{
decodeSelection(context, component);
Map<String, String> parameters =
context.getExternalContext().getRequestParameterMap();
String source = parameters.get(XhtmlConstants.SOURCE_PARAM);
String id = component.getClientId(context);
if (!id.equals(source))
return;
UIXTable table = (UIXTable) component;
Object eventParam = parameters.get(XhtmlConstants.EVENT_PARAM);
if (XhtmlConstants.GOTO_EVENT.equals(eventParam))
{
_decodeGoto(table, parameters);
}
else if (XhtmlConstants.HIDE_EVENT.equals(eventParam) ||
XhtmlConstants.SHOW_EVENT.equals(eventParam))
{
_decodeHideShow(table, parameters, eventParam);
}
else if (XhtmlConstants.SORT_EVENT.equals(eventParam))
{
_decodeSort(table, parameters);
}
RequestContext.getCurrentInstance().addPartialTarget(table);
}
protected final void decodeSelection(FacesContext context, UIComponent treeTable)
{
String selection = (String)
treeTable.getAttributes().get(CoreTable.ROW_SELECTION_KEY.getName());
if ("single".equals(selection))
_selectOne.decode(context, treeTable);
else if ("multiple".equals(selection))
_selectMany.decode(context, treeTable);
}
public static RangeChangeEvent createRangeChangeEvent(CollectionComponent table,
int newStart)
{
int newEnd = TableUtils.getLast(table, newStart);
return _createRangeChangeEvent(table, newStart, newEnd);
}
/**
* Returns the set of row keys identified by PPR. Returns
* the empty set if no row keys are present, and null
* if row keys could not be properly identified.
*/
static public Set<Object> getPartialRowKeys(
FacesContext context,
RenderingContext arc,
UIComponent component,
String clientId)
{
ClientRowKeyManager rowKeyManager = null;
if (component instanceof UIXCollection)
rowKeyManager = ((UIXCollection) component).getClientRowKeyManager();
Set<Object> rowKeys = null;
String tablePrefix = clientId + NamingContainer.SEPARATOR_CHAR;
// Search for any PPR targets that start with "<tableClientId>:"
PartialPageContext ppc = arc.getPartialPageContext();
Iterator<String> targets = ppc.getPartialTargets();
while (targets.hasNext())
{
String target = targets.next();
if (target == null)
continue;
if (target.startsWith(tablePrefix))
{
// If we don't have a rowkeymanager, we know that the table
// has partial targets, but we can't process the rows individually
if (rowKeyManager == null)
return null;
// Extract the client rowkey from the clientId
String clientRowKey = target.substring(tablePrefix.length());
int ncIndex = clientRowKey.indexOf(NamingContainer.SEPARATOR_CHAR);
// If we have a target that is in the table, but is not in a
// particular row, just repaint the whole table
if (ncIndex < 0)
return null;
clientRowKey = clientRowKey.substring(0, ncIndex);
// Try to turn it into a server rowkey
Object rowKey = rowKeyManager.getRowKey(context, component, clientRowKey);
// if this fails, we have to process the whole table
if (rowKey == null)
return null;
// We know this row exists, and needs to be processed
if (rowKeys == null)
rowKeys = new HashSet<Object>();
rowKeys.add(rowKey);
}
}
// If we never found a rowkey, return the empty set, indicating
// that there are no rows to process
if (rowKeys == null)
rowKeys = Collections.emptySet();
return rowKeys;
}
private static RangeChangeEvent _createRangeChangeEvent(
CollectionComponent table,
int newStart,
int newEnd)
{
int oldStart = table.getFirst();
int oldEnd = TableUtils.getLast(table) + 1;
return
new RangeChangeEvent((UIComponent) table, oldStart, oldEnd, newStart, newEnd);
}
private void _decodeSort(
UIXTable table,
Map<String, String> parameters)
{
String property = parameters.get(XhtmlConstants.VALUE_PARAM);
Object state = parameters.get(XhtmlConstants.STATE_PARAM);
boolean sortOrder = !XhtmlConstants.SORTABLE_ASCENDING.equals(state);
SortCriterion criterion = new SortCriterion(property, sortOrder);
SortEvent event =
new SortEvent(table, Collections.singletonList(criterion));
event.queue();
}
private void _decodeGoto(
UIXTable table,
Map<String, String> parameters)
{
String value = parameters.get(XhtmlConstants.VALUE_PARAM);
if (value != null)
{
final FacesEvent event;
if (XhtmlConstants.VALUE_SHOW_ALL.equals(value))
{
int newEnd = table.getRowCount();
if (newEnd >= 0)
event = _createRangeChangeEvent(table, 0, newEnd);
else
return;
}
else
{
int newStart = Integer.parseInt(value) - 1;
event = createRangeChangeEvent(table, newStart);
}
event.queue();
/* =-=AEW Don't set current value immediately - since that
would mean that validate/updateModelValues run on the
wrong rows!!! Queue an event.
System.out.println("DECODE: GOTO " + value);
component.setAttribute("currentValue",
new Integer(Integer.parseInt(value)));*/
// I don't believe we want to skip to "renderResponse()" here,
// since we want values to be applied!
// context.renderResponse();
}
}
@SuppressWarnings("unchecked")
private void _decodeHideShow(
UIXTable table,
Map<String, String> parameters,
Object eventParam)
{
boolean doExpand = XhtmlConstants.SHOW_EVENT.equals(eventParam);
Object value = parameters.get(XhtmlConstants.VALUE_PARAM);
if (value != null)
{
RowKeySet old = table.getDisclosedRowKeys();
RowKeySet newset = old.clone();
if ("all".equals(value))
{
if (doExpand)
newset.addAll();
else
newset.removeAll();
FacesEvent event = new RowDisclosureEvent(old, newset, table);
event.queue();
}
else
{
int rowIndex = Integer.parseInt((String) value);
int oldIndex = table.getRowIndex();
table.setRowIndex(rowIndex);
newset.setContained(doExpand);
FacesEvent event = new RowDisclosureEvent(old, newset, table);
event.queue();
table.setRowIndex(oldIndex);
}
}
}
@Override
protected void encodeAll(
FacesContext context,
RenderingContext arc,
UIComponent component,
FacesBean bean) throws IOException
{
Set<Object> keysToRender = null;
// See if we can skip rendering altogether
if (canSkipRendering(context, arc, component))
{
// If we're in here, then the table itself as a whole doesn't
// need to be re-rendered - but the contents might need to be!
keysToRender = getPartialRowKeys(context,
arc,
component,
getClientId(context, component));
// getPartialRowKeys() has a weird API. null means there are contents
// that need to be rendered, but we couldn't figure out what row key
// they match up to, so just re-render everything and let PPR figure it
// out. An empty set means *there's nothing*, so bail
//
if ((keysToRender != null) && keysToRender.isEmpty())
return;
// TODO: use keysToRender to only iterate onto rows
// that have targets
}
// save current skin resource map, if any, on the local property
Map<String, String> oldSkinResourceMap = arc.getSkinResourceKeyMap();
// store TableRenderer's skin resource map, so that called to
// context.getTranslatedValue will get the correct key.
arc.setSkinResourceKeyMap(_resourceKeyMap);
TableRenderingContext tContext = createRenderingContext(context,
arc,
component);
try
{
tContext.install();
ResponseWriter rw = context.getResponseWriter();
rw.startElement("div", component);
renderId(context, component);
renderAllAttributes(context, arc, bean);
// If we need to render a "special" empty table, then bail.
if (renderTableWithoutColumns(context, arc, tContext, component))
return;
// start the outer table:
rw.startElement(XhtmlConstants.TABLE_ELEMENT, null);
renderTableAttributes(context, arc, component, bean, "0", "0");
RenderStage renderStage = tContext.getRenderStage();
assert (renderStage.getStage()==RenderStage.INITIAL_STAGE);
// give the table's columns a chance to initialize:
renderSingleRow(context, arc, tContext, component);
// 1. render the header bars (title, controlbar and subcontrolbar)
renderNavigationHeaderBars(context, arc, tContext, component, bean);
// 2. render the table content
renderTableContent(context, arc, tContext, component);
// end the outertable:
rw.endElement(XhtmlConstants.TABLE_ELEMENT);
// gives some beans the chance to cleanup:
renderStage.setStage(RenderStage.END_STAGE);
renderSingleRow(context, arc, tContext, component);
String tid = tContext.getTableId();
FormData formData = arc.getFormData();
if (formData != null)
{
// Add sorting parameters.
// =-=AdamWiner FIXME: only really needed with sorting.
formData.addNeededValue(XhtmlConstants.STATE_PARAM);
formData.addNeededValue(XhtmlConstants.VALUE_PARAM);
//HKuhn - no need for scripts in printable mode
if (supportsScripting(arc))
{
rw.startElement(XhtmlConstants.SCRIPT_ELEMENT, null);
renderScriptDeferAttribute(context, arc);
// Bug #3426092:
// render the type="text/javascript" attribute in accessibility mode
renderScriptTypeAttribute(context, arc);
String formName = formData.getName();
rw.writeText(tContext.getJSVarName()+"="+
TreeUtils.createNewJSCollectionComponentState(formName, tid)+";", null);
rw.endElement(XhtmlConstants.SCRIPT_ELEMENT);
}
}
int first = tContext.getCollectionComponent().getFirst();
if (supportsScripting(arc))
{
XhtmlUtils.addLib(context, arc, "TableProxy()");
// Bug #2378405: Add a javascript variable giving the row number of
// the first row in the displayed rowset.
// Although it seems like we should check for existence here (to
// prevent duplication), we actually should not. If we have multiple
// tables on a page, they will all need independent value fields.
// We'd really like to use the flattened name here, but a colon doesn't
// work as part of a javascript variable name, so we have to build up a
// pseudo flattened name of the form _<tableName>_value.
// (=-=AEW Change code to write the value directly into the window,
// so a colon *would* work; however, if a field had an id of "value"
// in the table, we'd get a conflict; so don't change?)
// Also, since 1 is by far the most common value, don't bother
// writing it out: the Javascript will assume the value is 1 if
// it isn't.
int value = first + 1;
if (value != 1)
{
rw.startElement(XhtmlConstants.SCRIPT_NAME, null);
renderScriptDeferAttribute(context, arc);
// Bug #3426092:
// render the type="text/javascript" attribute in accessibility mode
renderScriptTypeAttribute(context, arc);
rw.writeText("window[\"_", null);
rw.writeText(tContext.getTableId(), null);
rw.writeText(_VALUE_FIELD_NAME, null);
rw.writeText("\"]=", null);
rw.writeText(IntegerUtils.getString(value), null);
rw.endElement(XhtmlConstants.SCRIPT_NAME);
}
}
OutputUtils.renderHiddenField(context,
tContext.getTableId() + ":rangeStart",
IntegerUtils.getString(first));
rw.endElement("div");
}
finally
{
// restore current skin resource map. Most likely there won't be one.
arc.setSkinResourceKeyMap(oldSkinResourceMap);
if (tContext != null)
tContext.release();
}
}
/**
* renders attributes on the outermost table element.
* this includes width, cellpadding, cellspacing, border.
*/
protected void renderTableAttributes(
FacesContext context,
RenderingContext arc,
UIComponent component,
FacesBean bean,
Object cellPadding,
Object border
) throws IOException
{
Object width = getWidth(bean);
OutputUtils.renderLayoutTableAttributes(context,
arc,
cellPadding,
"0", // cell spacing
border,
width); // table width
}
/**
* Creates the correct subclass of the TableRenderingContext to
* use for this Renderer.
*/
protected TableRenderingContext createRenderingContext(
FacesContext context,
RenderingContext arc,
UIComponent component
)
{
return new TableRenderingContext(context, arc, component);
}
protected abstract void renderSingleRow(
FacesContext context,
RenderingContext arc,
TableRenderingContext tContext,
UIComponent component) throws IOException;
/**
* Render an empty table, if necessary.
* @return true if the table was empty, and an alternative empty
* version was shown, false otherwise.
* @TODO COMPRESS JOINED STYLES
*/
protected boolean renderTableWithoutColumns(
FacesContext context,
RenderingContext arc,
TableRenderingContext tContext,
UIComponent component) throws IOException
{
ColumnData colData = tContext.getColumnData();
if (colData.getColumnCount() <= 0)
{
// see bug 2633464
if (_LOG.isWarning())
_LOG.warning("TABLE_HAS_NO_VISIABLE_COLUMN", tContext.getTableId());
ResponseWriter writer = context.getResponseWriter();
// render something so that the visual editor previewer will show a
// simple <table/> tag:
writer.startElement(XhtmlConstants.TABLE_ELEMENT, component);
writer.startElement(XhtmlConstants.TABLE_ROW_ELEMENT, null);
writer.startElement(XhtmlConstants.TABLE_DATA_ELEMENT, null);
writer.writeAttribute(XhtmlConstants.WIDTH_ATTRIBUTE, "30", null);
renderStyleClasses(context, arc,
new String[]{
SkinSelectors.AF_COLUMN_CELL_TEXT_STYLE,
CellUtils.getBorderClass(
true,
true,
true,
true)});
renderSpacer(context, arc, "30", "30");
writer.endElement(XhtmlConstants.TABLE_DATA_ELEMENT);
writer.endElement(XhtmlConstants.TABLE_ROW_ELEMENT);
writer.endElement(XhtmlConstants.TABLE_ELEMENT);
return true;
}
return false;
}
/**
* used to render special column headers, like select and details.
* @return the next physicalColumnIndex
*/
@SuppressWarnings("unchecked")
protected int renderSpecialColumns(
FacesContext context,
RenderingContext arc,
TableRenderingContext tContext,
UIComponent treeTable,
int physicalColumnIndex)
throws IOException
{
// renders a whole bunch of <TH>...</TH> elements, or <TD>..</TD> elements
// depending on the RenderStage
final ColumnData colData = tContext.getColumnData();
int[] hidden = tContext.getHiddenColumns();
List<UIComponent> children = treeTable.getChildren();
int colCount = children.size();
for (int i = 0; i < colCount; i++)
{
if (hidden[i] != TableRenderingContext.NORMAL_COLUMN)
continue;
UIComponent child = children.get(i);
if (!(child instanceof UIXColumn))
continue;
UIXColumn column = (UIXColumn) child;
boolean isRowHeader = Boolean.TRUE.equals(
column.getAttributes().get(CoreColumn.ROW_HEADER_KEY.getName()));
if (isRowHeader)
{
colData.setColumnIndex(physicalColumnIndex, i);
encodeChild(context, column);
// ColumnBeans automatically increment the physical and logical
// column indices (these may be increase by more than one, if
// there are columnGroups). So we must not increment the column
// indices here
physicalColumnIndex = colData.getPhysicalColumnIndex();
}
else
break;
}
// special case... render the selection column
if (tContext.hasSelection())
{
colData.setColumnIndex(physicalColumnIndex, ColumnData.SPECIAL_COLUMN_INDEX);
_renderSelectionColumn(context, arc, tContext);
physicalColumnIndex++;
}
// special case... render the detail column
UIComponent detail = tContext.getDetail();
if (detail != null)
{
colData.setColumnIndex(physicalColumnIndex, ColumnData.SPECIAL_COLUMN_INDEX);
_renderDetailColumn(context, arc);
physicalColumnIndex++;
}
return physicalColumnIndex;
}
private void _renderDetailColumn(
FacesContext context,
RenderingContext arc) throws IOException
{
UIComponent column = _detailRenderer.getSpecialColumn();
delegateRenderer(context, arc, column,
getFacesBean(column), _detailRenderer);
}
private void _renderSelectionColumn(
FacesContext context,
RenderingContext arc,
TableRenderingContext tContext) throws IOException
{
Map<String, String> originalResourceKeyMap = arc.getSkinResourceKeyMap();
setSelectionResourceKeyMap(arc, tContext);
try
{
UIComponent column = _selectRenderer.getSpecialColumn();
delegateRenderer(context, arc, column,
getFacesBean(column), _selectRenderer);
}
finally
{
arc.setSkinResourceKeyMap(originalResourceKeyMap);
}
}
/**
* Render the navigation header bars, i.e. all the bars that appear above the
* actual data table. eg. title, controlbar and subcontrolbar
*/
protected void renderNavigationHeaderBars(
FacesContext context,
RenderingContext arc,
TableRenderingContext tContext,
UIComponent component,
FacesBean bean) throws IOException
{
// 2. render the upper control bar - must render tableActions even
// if table is empty
_renderControlBar(context, arc, tContext, component, true); //isUpper
// render the sub control bar. we need to to this even if the table is empty
// because we need to render the filter area. bug 3757395
renderSubControlBar(context, arc, tContext, component, true);
}
/**
* @todo Decide if we really want to support "repeating" regions
*/
private void _renderControlBar(
FacesContext context,
RenderingContext arc,
TableRenderingContext tContext,
UIComponent component,
boolean isUpper) throws IOException
{
// indicate that this is a repeating region, so that beans like the
// choiceBean can stay synchronized
arc.getProperties().put(XhtmlConstants.REPEAT_PROPERTY,
Boolean.TRUE);
RenderStage rs = tContext.getRenderStage();
rs.setStage(isUpper
? RenderStage.UPPER_CONTROL_BAR_STAGE
: RenderStage.LOWER_CONTROL_BAR_STAGE);
// Due to layout problems that occur when performing a partial
// page replacement of a TableBean (2275703), we need to also perform
// an explicit partial replacement of the upper navigation bar. This
// means that we need to generate a unique ID for the upper
// navigation bar. Since we may not actually have a TableRenderingContext
// when fetching the navigation bar's ID (we may have a
// PartialRenderingContext - which is another problem altOgether),
// we just generate the ID here and store it away on the RenderingContext.
if (isUpper)
{
// We only generate the navigation bar ID if the agent is IE
// and partial rendering is enabled.
Object id = tContext.getTableId();
Agent agent = arc.getAgent();
if ((agent.getAgentName() == Agent.AGENT_IE) &&
PartialPageUtils.isPPRActive(context))
{
String navBarID = id.toString() + "-nb";
setRenderingProperty(arc, _UPPER_NAV_BAR_ID_PROPERTY, navBarID);
}
}
renderControlBar(context, arc, tContext, component);
// no longer a repeating region
arc.getProperties().remove(XhtmlConstants.REPEAT_PROPERTY);
if (isUpper)
setRenderingProperty(arc, _UPPER_NAV_BAR_ID_PROPERTY, null);
}
/**
* Renders the control bar
*/
protected abstract void renderControlBar(
FacesContext context,
RenderingContext arc,
TableRenderingContext tContext,
UIComponent component)
throws IOException;
/**
* Render sthe area with the filter and links, if necessary
*/
protected abstract void renderSubControlBar(
FacesContext context,
RenderingContext arc,
TableRenderingContext tContext,
UIComponent component,
boolean isUpper) throws IOException;
/**
* Renders the actual table content, with headers
*/
protected abstract void renderTableContent(
FacesContext context,
RenderingContext arc,
TableRenderingContext tContext,
UIComponent component) throws IOException;
protected String getEmptyText(FacesBean bean)
{
return toString(bean.getProperty(_emptyTextKey));
}
protected Object getWidth(FacesBean bean)
{
return bean.getProperty(_widthKey);
}
/**
* Returns the shared UINode used to render detail hide/show
*/
protected final CoreRenderer getSharedHideShowNode()
{
return null;
}
/**
* Returns the shared Renderer used to render navbars
*/
protected CoreRenderer getSharedNavBarRenderer()
{
return _navBarRenderer;
}
/**
*/
public static String getRowHeaderFormatClass()
{
return SkinSelectors.AF_COLUMN_ROW_HEADER_TEXT_STYLE;
}
/**
* @param isColumnHeader true if the style for a column header is needed.
* @todo Eliminate this method altogether; row headers are static,
* and column headers should just call
* ColumnGroupRenderer.getHeaderStyleClass()
*/
public static String getHeaderFormatClass(TableRenderingContext tContext,
boolean isColumnHeader)
{
if (isColumnHeader)
throw new IllegalStateException(_LOG.getMessage(
"DONOT_CALL_THIS_FOR_COLUMN_HEADERS"));
return SkinSelectors.AF_COLUMN_ROW_HEADER_TEXT_STYLE;
}
/**
* Sets the skinResourceKeyMap on the RenderingContext with a map
* which maps SkinSelectors.AF_COLUMN_CELL* styles to SkinSelectors.AF_TABLE_SELECT_MANY or
* SkinSelectors.AF_TABLE_SELECT_ONE styles. We look at the selectionNode to figure
* out if it is tableSelectOne or tableSelectMany
* @todo Can this be private?
* @todo reuse these Maps!
*/
public static void setSelectionResourceKeyMap(
RenderingContext arc,
TableRenderingContext tContext)
{
if (tContext.hasSelection())
{
Map<String, String> selectionColumnStylesMap =
new HashMap<String, String>();
// if selection is multiple-selection:
if (tContext.hasSelectAll())
{
selectionColumnStylesMap.put(SkinSelectors.AF_COLUMN_CELL_ICON_FORMAT_STYLE,
SkinSelectors.AF_TABLE_SELECT_MANY_CELL_ICON_FORMAT_STYLE);
selectionColumnStylesMap.put(SkinSelectors.AF_COLUMN_CELL_ICON_BAND_STYLE,
SkinSelectors.AF_TABLE_SELECT_MANY_CELL_ICON_BAND_STYLE);
}
else
{
selectionColumnStylesMap.put(SkinSelectors.AF_COLUMN_CELL_ICON_FORMAT_STYLE,
SkinSelectors.AF_TABLE_SELECT_ONE_CELL_ICON_FORMAT_STYLE);
selectionColumnStylesMap.put(SkinSelectors.AF_COLUMN_CELL_ICON_BAND_STYLE,
SkinSelectors.AF_TABLE_SELECT_ONE_CELL_ICON_BAND_STYLE);
}
arc.setSkinResourceKeyMap(selectionColumnStylesMap);
}
}
@Override
protected boolean shouldRenderId(FacesContext context, UIComponent component)
{
return true;
}
protected Map<String, String> createResourceKeyMap()
{
// map the skin resource keys that are used in components used
// by the table renderer to table keys.
// This way the table can be customized separately from other
// components that it uses within it. For example, we can customize
// af_table.DISCLOSED translation key
// separately from af_showDetail.DISCLOSED.
Map<String, String> map = new HashMap<String, String>(6);
map.put("af_showDetail.DISCLOSED",
"af_table.DISCLOSED");
map.put("af_showDetail.UNDISCLOSED",
"af_table.UNDISCLOSED");
map.put("af_showDetail.DISCLOSED_TIP",
"af_table.DISCLOSED_TIP");
map.put("af_showDetail.UNDISCLOSED_TIP",
"af_table.UNDISCLOSED_TIP");
map.put(SkinSelectors.AF_SHOW_DETAIL_DISCLOSED_ICON_NAME,
SkinSelectors.AF_TABLE_SD_DISCLOSED_ICON_NAME);
map.put(SkinSelectors.AF_SHOW_DETAIL_UNDISCLOSED_ICON_NAME,
SkinSelectors.AF_TABLE_SD_UNDISCLOSED_ICON_NAME);
map.put(SkinSelectors.AF_SELECT_RANGE_CHOICE_BAR_PREV_ICON_NAME,
SkinSelectors.AF_TABLE_NB_PREV_ICON_NAME);
map.put(SkinSelectors.AF_SELECT_RANGE_CHOICE_BAR_NEXT_ICON_NAME,
SkinSelectors.AF_TABLE_NB_NEXT_ICON_NAME);
map.put(SkinSelectors.AF_SELECT_RANGE_CHOICE_BAR_PREV_DISABLED_ICON_NAME,
SkinSelectors.AF_TABLE_NB_PREV_DISABLED_ICON_NAME);
map.put(SkinSelectors.AF_SELECT_RANGE_CHOICE_BAR_NEXT_DISABLED_ICON_NAME,
SkinSelectors.AF_TABLE_NB_NEXT_DISABLED_ICON_NAME);
return Collections.unmodifiableMap(map);
}
static private class NavBar extends SelectRangeChoiceBarRenderer
{
public NavBar(FacesBean.Type type)
{
super(type);
}
@Override
protected void renderAllAttributes(
FacesContext context, RenderingContext arc, FacesBean bean)
{
}
@Override
protected boolean getShowAll(FacesBean bean)
{
TableRenderingContext tContext =
TableRenderingContext.getCurrentInstance();
UIComponent component = tContext.getTable();
if (component instanceof UIXTable)
{
UIXTable table = (UIXTable) component;
return table.isShowAll();
}
return false;
}
// For now, disable showAll except on UIXTable
@Override
protected boolean showAllSupported()
{
TableRenderingContext tContext =
TableRenderingContext.getCurrentInstance();
UIComponent component = tContext.getTable();
return (component instanceof UIXTable);
}
@Override
protected String getSource()
{
TableRenderingContext tContext =
TableRenderingContext.getCurrentInstance();
return tContext.getTableId();
}
/**
* @todo Deal with repeating!
*/
@Override
protected String getClientId(FacesContext context, UIComponent component)
{
TableRenderingContext tContext =
TableRenderingContext.getCurrentInstance();
return tContext.getTableId() + "-nb";
}
@Override
protected String getVar(FacesBean bean)
{
return null;
}
// No support for range labels
@Override
protected UIComponent getRangeLabel(UIComponent component)
{
return null;
}
@Override
protected int getRowCount(UIComponent component)
{
return ((CollectionComponent) component).getRowCount();
}
@Override
protected int getRowIndex(UIComponent component)
{
return ((CollectionComponent) component).getRowIndex();
}
@Override
protected void setRowIndex(UIComponent component, int index)
{
((CollectionComponent) component).setRowIndex(index);
}
@Override
protected boolean isRowAvailable(UIComponent component)
{
return ((CollectionComponent) component).isRowAvailable();
}
@Override
protected boolean isRowAvailable(UIComponent component, int rowIndex)
{
return ((UIXCollection) component).isRowAvailable(rowIndex);
}
@Override
protected Object getRowData(UIComponent component)
{
return ((CollectionComponent) component).getRowData();
}
@Override
protected int getRows(UIComponent component, FacesBean bean)
{
return ((CollectionComponent) component).getRows();
}
@Override
protected int getFirst(UIComponent component, FacesBean bean)
{
return ((CollectionComponent) component).getFirst();
}
}
private PropertyKey _widthKey;
private PropertyKey _emptyTextKey;
private final Map<String, String> _resourceKeyMap;
// Key for RenderingContext property used to store the generated ID
// to use for the upper navigation bar. (Part of fix for 2275703.)
private static final Object _UPPER_NAV_BAR_ID_PROPERTY = new Object();
private static final String _VALUE_FIELD_NAME = "_value";
private final SpecialColumnRenderer _detailRenderer = new DetailColumnRenderer();
private SpecialColumnRenderer _selectRenderer;
private CoreRenderer _navBarRenderer;
private CoreRenderer _selectOne;
private CoreRenderer _selectMany;
private static final TrinidadLogger _LOG = TrinidadLogger.createTrinidadLogger(TableRenderer.class);
}
| apache-2.0 |
terrancesnyder/solr-analytics | solr/core/src/test/org/apache/solr/spelling/DirectSolrSpellCheckerTest.java | 4838 | package org.apache.solr.spelling;
/*
* 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.
*/
import java.util.Collection;
import java.util.Map;
import org.apache.lucene.analysis.Token;
import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.common.params.CommonParams;
import org.apache.solr.common.params.SpellingParams;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.core.SolrCore;
import org.apache.solr.handler.component.SpellCheckComponent;
import org.apache.solr.request.LocalSolrQueryRequest;
import org.apache.solr.search.SolrIndexSearcher;
import org.apache.solr.util.RefCounted;
import org.apache.solr.util.TestHarness;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* Simple tests for {@link DirectSolrSpellChecker}
*/
public class DirectSolrSpellCheckerTest extends SolrTestCaseJ4 {
private static SpellingQueryConverter queryConverter;
@BeforeClass
public static void beforeClass() throws Exception {
initCore("solrconfig-spellcheckcomponent.xml","schema.xml");
//Index something with a title
assertNull(h.validateUpdate(adoc("id", "0", "teststop", "This is a title")));
assertNull(h.validateUpdate(adoc("id", "1", "teststop", "The quick reb fox jumped over the lazy brown dogs.")));
assertNull(h.validateUpdate(adoc("id", "2", "teststop", "This is a Solr")));
assertNull(h.validateUpdate(adoc("id", "3", "teststop", "solr foo")));
assertNull(h.validateUpdate(adoc("id", "4", "teststop", "another foo")));
assertNull(h.validateUpdate(commit()));
queryConverter = new SimpleQueryConverter();
queryConverter.init(new NamedList());
}
@Test
public void test() throws Exception {
DirectSolrSpellChecker checker = new DirectSolrSpellChecker();
NamedList spellchecker = new NamedList();
spellchecker.add("classname", DirectSolrSpellChecker.class.getName());
spellchecker.add(SolrSpellChecker.FIELD, "teststop");
spellchecker.add(DirectSolrSpellChecker.MINQUERYLENGTH, 2); // we will try "fob"
SolrCore core = h.getCore();
checker.init(spellchecker, core);
RefCounted<SolrIndexSearcher> searcher = core.getSearcher();
Collection<Token> tokens = queryConverter.convert("fob");
SpellingOptions spellOpts = new SpellingOptions(tokens, searcher.get().getIndexReader());
SpellingResult result = checker.getSuggestions(spellOpts);
assertTrue("result is null and it shouldn't be", result != null);
Map<String, Integer> suggestions = result.get(tokens.iterator().next());
Map.Entry<String, Integer> entry = suggestions.entrySet().iterator().next();
assertTrue(entry.getKey() + " is not equal to " + "foo", entry.getKey().equals("foo") == true);
assertFalse(entry.getValue() + " equals: " + SpellingResult.NO_FREQUENCY_INFO, entry.getValue() == SpellingResult.NO_FREQUENCY_INFO);
spellOpts.tokens = queryConverter.convert("super");
result = checker.getSuggestions(spellOpts);
assertTrue("result is null and it shouldn't be", result != null);
suggestions = result.get(tokens.iterator().next());
assertTrue("suggestions is not null and it should be", suggestions == null);
searcher.decref();
}
@Test
public void testOnlyMorePopularWithExtendedResults() throws Exception {
assertQ(req("q", "teststop:fox", "qt", "spellCheckCompRH", SpellCheckComponent.COMPONENT_NAME, "true", SpellingParams.SPELLCHECK_DICT, "direct", SpellingParams.SPELLCHECK_EXTENDED_RESULTS, "true", SpellingParams.SPELLCHECK_ONLY_MORE_POPULAR, "true"),
"//lst[@name='spellcheck']/lst[@name='suggestions']/lst[@name='fox']/int[@name='origFreq']=1",
"//lst[@name='spellcheck']/lst[@name='suggestions']/lst[@name='fox']/arr[@name='suggestion']/lst/str[@name='word']='foo'",
"//lst[@name='spellcheck']/lst[@name='suggestions']/lst[@name='fox']/arr[@name='suggestion']/lst/int[@name='freq']=2",
"//lst[@name='spellcheck']/lst[@name='suggestions']/bool[@name='correctlySpelled']='true'"
);
}
}
| apache-2.0 |
NovaOrdis/playground | jee/ejb/ejb-over-rest/wrapper-servlet-and-caller-ejb/src/main/java/io/novaordis/playground/jee/ejb/ejb2rest/restclient/BasicAuthConfigurator.java | 3222 | package io.novaordis.playground.jee.ejb.ejb2rest.restclient;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.protocol.BasicHttpContext;
/**
* Uses basic authentication with the provided username and password.
*/
@SuppressWarnings("unused")
public class BasicAuthConfigurator implements Configurator {
// Constants -------------------------------------------------------------------------------------------------------
// Static ----------------------------------------------------------------------------------------------------------
// Attributes ------------------------------------------------------------------------------------------------------
/**
* Username for authentication.
*/
private final String username;
/**
* Password for authentication.
*/
private final String password;
// Constructors ----------------------------------------------------------------------------------------------------
public BasicAuthConfigurator(String username, String password) {
this.username = username;
this.password = password;
}
// Configuration implementation ------------------------------------------------------------------------------------
@Override
public BasicHttpContext createContext(HttpHost targetHost) {
final AuthCache authCache = new BasicAuthCache();
final BasicScheme basicAuth = new BasicScheme();
authCache.put(targetHost, basicAuth);
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
// OPTIMIZED
credentialsProvider
.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
// NON-OPTIMIZED
// credentialsProvider.setCredentials(
// new AuthScope(targetHost.getHostName(), targetHost.getPort()),
// new UsernamePasswordCredentials(username, password));
final BasicHttpContext context = new BasicHttpContext();
context.setAttribute(HttpClientContext.AUTH_CACHE, authCache);
context.setAttribute(HttpClientContext.CREDS_PROVIDER, credentialsProvider);
return context;
}
// Public ----------------------------------------------------------------------------------------------------------
// Package protected -----------------------------------------------------------------------------------------------
// Protected -------------------------------------------------------------------------------------------------------
// Private ---------------------------------------------------------------------------------------------------------
// Inner classes ---------------------------------------------------------------------------------------------------
}
| apache-2.0 |
citywander/pinpoint | web/src/main/java/com/navercorp/pinpoint/web/view/LinkSerializer.java | 9255 | /*
* Copyright 2014 NAVER Corp.
*
* 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.navercorp.pinpoint.web.view;
import com.navercorp.pinpoint.common.trace.ServiceType;
import com.navercorp.pinpoint.web.applicationmap.Link;
import com.navercorp.pinpoint.web.applicationmap.Node;
import com.navercorp.pinpoint.web.applicationmap.ServerInstanceList;
import com.navercorp.pinpoint.web.applicationmap.histogram.Histogram;
import com.navercorp.pinpoint.web.applicationmap.rawdata.AgentHistogram;
import com.navercorp.pinpoint.web.applicationmap.rawdata.AgentHistogramList;
import com.navercorp.pinpoint.web.security.ServerMapDataFilter;
import com.navercorp.pinpoint.web.vo.Application;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
/**
* @author emeroad
* @author netspider
*/
public class LinkSerializer extends JsonSerializer<Link> {
@Autowired(required=false)
private ServerMapDataFilter serverMapDataFilter;
@Override
public void serialize(Link link, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
final boolean isAuthFromApp = check(link.getFrom().getApplication());
final boolean isAuthToApp = check(link.getTo().getApplication());
jgen.writeStartObject();
jgen.writeStringField("key", link.getLinkName(isAuthFromApp, isAuthToApp)); // for servermap
jgen.writeStringField("from", link.getFrom().getNodeName(isAuthFromApp)); // necessary for go.js
jgen.writeStringField("to", link.getTo().getNodeName(isAuthToApp)); // necessary for go.js
// for FilterWizard. from, to agent mapping data
writeAgentId("fromAgent", link.getFrom(), jgen, isAuthFromApp);
writeAgentId("toAgent", link.getTo(), jgen, isAuthToApp);
writeSimpleNode("sourceInfo", link.getFrom(), jgen, isAuthFromApp);
writeSimpleNode("targetInfo", link.getTo(), jgen, isAuthToApp);
writeFilterApplicationInfo(link, jgen);
if (link.isWasToWasLink()) {
writeWasToWasTargetRpcList(link, jgen, isAuthToApp);
}
Histogram histogram = link.getHistogram();
jgen.writeNumberField("totalCount", histogram.getTotalCount()); // for go.js
jgen.writeNumberField("errorCount", histogram.getTotalErrorCount());
jgen.writeNumberField("slowCount", histogram.getSlowCount());
jgen.writeObjectField("histogram", histogram);
// data showing how agents call each of their respective links
writeAgentHistogram("sourceHistogram", link.getSourceList(), jgen, isAuthFromApp);
writeAgentHistogram("targetHistogram", link.getTargetList(), jgen, isAuthToApp);
writeTimeSeriesHistogram(link, jgen);
writeSourceAgentTimeSeriesHistogram(link, jgen, isAuthFromApp);
// String state = link.getLinkState();
// jgen.writeStringField("state", state); // for go.js
jgen.writeBooleanField("hasAlert", link.getLinkAlert()); // for go.js
jgen.writeEndObject();
}
private void writeFilterApplicationInfo(Link link, JsonGenerator jgen) throws IOException {
Application application = link.getFilterApplication();
jgen.writeStringField("filterApplicationName", application.getName());
if (check(application)) {
jgen.writeNumberField("filterApplicationServiceTypeCode", application.getServiceTypeCode());
jgen.writeStringField("filterApplicationServiceTypeName", application.getServiceType().getName());
} else {
jgen.writeNumberField("filterApplicationServiceTypeCode", ServiceType.UNAUTHORIZED.getCode());
jgen.writeStringField("filterApplicationServiceTypeName", ServiceType.UNAUTHORIZED.getName());
}
}
private boolean check(Application application) {
if (serverMapDataFilter != null && serverMapDataFilter.filter(application)) {
return false;
}
return true;
}
private void writeAgentId(String fieldName, Node node, JsonGenerator jgen, boolean isAuthorized) throws IOException {
if (node.getServiceType().isWas()) {
jgen.writeFieldName(fieldName);
jgen.writeStartArray();
if (isAuthorized) {
ServerInstanceList serverInstanceList = node.getServerInstanceList();
if (serverInstanceList!= null) {
for (String agentId : serverInstanceList.getAgentIdList()) {
jgen.writeObject(agentId);
}
}
} else {
jgen.writeString("UNKNOWN_AGENT");
}
jgen.writeEndArray();
}
}
private void writeWasToWasTargetRpcList(Link link, JsonGenerator jgen, boolean isAuthorized) throws IOException {
// write additional information to be used for filtering failed WAS -> WAS call events.
jgen.writeFieldName("filterTargetRpcList");
jgen.writeStartArray();
if (isAuthorized) {
Collection<Application> sourceLinkTargetAgentList = link.getSourceLinkTargetAgentList();
for (Application application : sourceLinkTargetAgentList) {
jgen.writeStartObject();
jgen.writeStringField("rpc", application.getName());
if (check(application)) {
jgen.writeNumberField("rpcServiceTypeCode", application.getServiceTypeCode());
}
else {
}
jgen.writeEndObject();
}
}
jgen.writeEndArray();
}
private void writeTimeSeriesHistogram(Link link, JsonGenerator jgen) throws IOException {
List<ResponseTimeViewModel> sourceApplicationTimeSeriesHistogram = link.getLinkApplicationTimeSeriesHistogram();
jgen.writeFieldName("timeSeriesHistogram");
jgen.writeObject(sourceApplicationTimeSeriesHistogram);
}
private void writeAgentHistogram(String fieldName, AgentHistogramList agentHistogramList, JsonGenerator jgen, boolean isAuthorized) throws IOException {
jgen.writeFieldName(fieldName);
jgen.writeStartObject();
if (isAuthorized) {
for (AgentHistogram agentHistogram : agentHistogramList.getAgentHistogramList()) {
jgen.writeFieldName(agentHistogram.getId());
jgen.writeObject(agentHistogram.getHistogram());
}
} else {
AgentHistogram mergeHistogram = new AgentHistogram(new Application("UNKONWN_AGENT", ServiceType.UNAUTHORIZED));
for (AgentHistogram agentHistogram : agentHistogramList.getAgentHistogramList()) {
mergeHistogram.addTimeHistogram(agentHistogram.getTimeHistogram());
}
jgen.writeFieldName(mergeHistogram.getId());
jgen.writeObject(mergeHistogram.getHistogram());
}
jgen.writeEndObject();
}
private void writeSourceAgentTimeSeriesHistogram(Link link, JsonGenerator jgen, boolean isAuthorized) throws IOException {
AgentResponseTimeViewModelList sourceAgentTimeSeriesHistogram = link.getSourceAgentTimeSeriesHistogram();
sourceAgentTimeSeriesHistogram.setFieldName("sourceTimeSeriesHistogram");
if (isAuthorized) {
jgen.writeObject(sourceAgentTimeSeriesHistogram);
} else {
jgen.writeFieldName("sourceTimeSeriesHistogram");
jgen.writeStartObject();
jgen.writeEndObject();
}
}
private void writeSimpleNode(String fieldName, Node node, JsonGenerator jgen, boolean isAuthorized) throws IOException {
jgen.writeFieldName(fieldName);
jgen.writeStartObject();
Application application = node.getApplication();
jgen.writeStringField("applicationName", application.getName());
if (isAuthorized) {
jgen.writeStringField("serviceType", application.getServiceType().toString());
jgen.writeNumberField("serviceTypeCode", application.getServiceTypeCode());
} else {
jgen.writeStringField("serviceType", ServiceType.UNAUTHORIZED.toString());
jgen.writeNumberField("serviceTypeCode", ServiceType.UNAUTHORIZED.getCode());
}
jgen.writeBooleanField("isWas", application.getServiceType().isWas());
jgen.writeEndObject();
}
}
| apache-2.0 |
google/brailleback | braille/libraries/utils/src/com/googlecode/eyesfree/utils/SparseIterableArray.java | 1632 | /*
* Copyright (C) 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.googlecode.eyesfree.utils;
import android.support.v4.util.SparseArrayCompat;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Extension of {@link SparseArrayCompat} that implements {@link Iterable}.
*/
public class SparseIterableArray<T> extends SparseArrayCompat<T> implements Iterable<T> {
@Override
public Iterator<T> iterator() {
return new SparseIterator();
}
private class SparseIterator implements Iterator<T> {
private int mIndex = 0;
@Override
public boolean hasNext() {
return (mIndex < size());
}
@Override
public T next() {
if (mIndex >= size()) {
throw new NoSuchElementException();
}
return valueAt(mIndex++);
}
@Override
public void remove() {
if ((mIndex < 0) || (mIndex >= size())) {
throw new IllegalStateException();
}
removeAt(mIndex--);
}
}
}
| apache-2.0 |
murick/Algorithms | Java/src/main/java/string/alter/snake/Solution1.java | 1811 | /*
* Copyright (C) 2015 Imran Mammadli
*
* 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 string.alter.snake;
public class Solution1
{
/**
* Returns "snake" representation of the string argument.
*
* <p>This method reads a string argument left-to-right and top-down
* in a sinusoidal manner. For example, the string "Java is awesome!"
* is transformed into the "aiwmJv saeoea s!". Here's how it is done:
*
* a i w m
* J v _ s a e o e
* a _ s !
*
* first, the letters of the top row are added. Then letters of the
* middle row. And finally, the letters of the bottom row.
*
* QUESTIONS:
* What if we repeat snake process? Can we get to the original snake?
* After how many iterations?
*
* @param s input string
* @return snake-string
*
* @time <i>O(n)</i>
* @space <i>O(1)</i>
**/
public static String snakeString(String s)
{
StringBuilder sb = new StringBuilder();
if (s != null)
{
for (int i = 1; i < s.length(); i+= 4)
{
sb.append(s.charAt(i));
}
for (int i = 0; i < s.length(); i+= 2)
{
sb.append(s.charAt(i));
}
for (int i = 3; i < s.length(); i+= 4)
{
sb.append(s.charAt(i));
}
}
return sb.toString();
}
} | apache-2.0 |
yintaoxue/read-open-source-code | kettle4.3/src/org/pentaho/di/ui/trans/steps/calculator/CalculatorDialog.java | 16440 | /*******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2012 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.ui.trans.steps.calculator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMeta;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStepMeta;
import org.pentaho.di.trans.step.StepDialogInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.steps.calculator.CalculatorMeta;
import org.pentaho.di.trans.steps.calculator.CalculatorMetaFunction;
import org.pentaho.di.ui.core.dialog.EnterSelectionDialog;
import org.pentaho.di.ui.core.widget.ColumnInfo;
import org.pentaho.di.ui.core.widget.TableView;
import org.pentaho.di.ui.trans.step.BaseStepDialog;
public class CalculatorDialog extends BaseStepDialog implements StepDialogInterface
{
private static Class<?> PKG = CalculatorMeta.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$
private Label wlStepname;
private Text wStepname;
private FormData fdlStepname, fdStepname;
private Label wlFields;
private TableView wFields;
private FormData fdlFields, fdFields;
private CalculatorMeta currentMeta;
private CalculatorMeta originalMeta;
private Map<String, Integer> inputFields;
private ColumnInfo[] colinf;
public CalculatorDialog(Shell parent, Object in, TransMeta tr, String sname)
{
super(parent, (BaseStepMeta)in, tr, sname);
// The order here is important... currentMeta is looked at for changes
currentMeta=(CalculatorMeta)in;
originalMeta=(CalculatorMeta)currentMeta.clone();
inputFields =new HashMap<String, Integer>();
}
public String open()
{
Shell parent = getParent();
Display display = parent.getDisplay();
shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MIN | SWT.MAX);
props.setLook(shell);
setShellImage(shell, currentMeta);
ModifyListener lsMod = new ModifyListener()
{
public void modifyText(ModifyEvent e)
{
currentMeta.setChanged();
}
};
changed = currentMeta.hasChanged();
FormLayout formLayout = new FormLayout ();
formLayout.marginWidth = Const.FORM_MARGIN;
formLayout.marginHeight = Const.FORM_MARGIN;
shell.setLayout(formLayout);
shell.setText(BaseMessages.getString(PKG, "CalculatorDialog.DialogTitle"));
int middle = props.getMiddlePct();
int margin = Const.MARGIN;
// Stepname line
wlStepname=new Label(shell, SWT.RIGHT);
wlStepname.setText(BaseMessages.getString(PKG, "System.Label.StepName"));
props.setLook(wlStepname);
fdlStepname=new FormData();
fdlStepname.left = new FormAttachment(0, 0);
fdlStepname.right= new FormAttachment(middle, -margin);
fdlStepname.top = new FormAttachment(0, margin);
wlStepname.setLayoutData(fdlStepname);
wStepname=new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wStepname.setText(stepname);
props.setLook(wStepname);
wStepname.addModifyListener(lsMod);
fdStepname=new FormData();
fdStepname.left = new FormAttachment(middle, 0);
fdStepname.top = new FormAttachment(0, margin);
fdStepname.right= new FormAttachment(100, 0);
wStepname.setLayoutData(fdStepname);
wlFields=new Label(shell, SWT.NONE);
wlFields.setText(BaseMessages.getString(PKG, "CalculatorDialog.Fields.Label"));
props.setLook(wlFields);
fdlFields=new FormData();
fdlFields.left = new FormAttachment(0, 0);
fdlFields.top = new FormAttachment(wStepname, margin);
wlFields.setLayoutData(fdlFields);
final int FieldsRows=currentMeta.getCalculation()!=null ? currentMeta.getCalculation().length : 1;
colinf=new ColumnInfo[]
{
new ColumnInfo(BaseMessages.getString(PKG, "CalculatorDialog.NewFieldColumn.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false),
new ColumnInfo(BaseMessages.getString(PKG, "CalculatorDialog.CalculationColumn.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false),
new ColumnInfo(BaseMessages.getString(PKG, "CalculatorDialog.FieldAColumn.Column"), ColumnInfo.COLUMN_TYPE_CCOMBO, new String[] { "" }, false),
new ColumnInfo(BaseMessages.getString(PKG, "CalculatorDialog.FieldBColumn.Column"), ColumnInfo.COLUMN_TYPE_CCOMBO, new String[] { "" }, false),
new ColumnInfo(BaseMessages.getString(PKG, "CalculatorDialog.FieldCColumn.Column"), ColumnInfo.COLUMN_TYPE_CCOMBO, new String[] { "" }, false),
new ColumnInfo(BaseMessages.getString(PKG, "CalculatorDialog.ValueTypeColumn.Column"), ColumnInfo.COLUMN_TYPE_CCOMBO, ValueMeta.getTypes() ),
new ColumnInfo(BaseMessages.getString(PKG, "CalculatorDialog.LengthColumn.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false),
new ColumnInfo(BaseMessages.getString(PKG, "CalculatorDialog.PrecisionColumn.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false),
new ColumnInfo(BaseMessages.getString(PKG, "CalculatorDialog.RemoveColumn.Column"), ColumnInfo.COLUMN_TYPE_CCOMBO, new String[] { BaseMessages.getString(PKG, "System.Combo.No"), BaseMessages.getString(PKG, "System.Combo.Yes") } ),
new ColumnInfo(BaseMessages.getString(PKG, "CalculatorDialog.ConversionMask.Column"), ColumnInfo.COLUMN_TYPE_FORMAT, 6),
new ColumnInfo(BaseMessages.getString(PKG, "CalculatorDialog.DecimalSymbol.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false),
new ColumnInfo(BaseMessages.getString(PKG, "CalculatorDialog.GroupingSymbol.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false),
new ColumnInfo(BaseMessages.getString(PKG, "CalculatorDialog.CurrencySymbol.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false),
};
colinf[1].setSelectionAdapter(
new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
EnterSelectionDialog esd = new EnterSelectionDialog(shell, CalculatorMetaFunction.calcLongDesc, BaseMessages.getString(PKG, "CalculatorDialog.SelectCalculationType.Title"), BaseMessages.getString(PKG, "CalculatorDialog.SelectCalculationType.Message"));
String string = esd.open();
if (string!=null)
{
TableView tv = (TableView)e.widget;
tv.setText(string, e.x, e.y);
currentMeta.setChanged();
}
}
}
);
wFields=new TableView(transMeta, shell,
SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI,
colinf,
FieldsRows,
lsMod,
props
);
fdFields=new FormData();
fdFields.left = new FormAttachment(0, 0);
fdFields.top = new FormAttachment(wlFields, margin);
fdFields.right = new FormAttachment(100, 0);
fdFields.bottom= new FormAttachment(100, -50);
wFields.setLayoutData(fdFields);
//
// Search the fields in the background
//
final Runnable runnable = new Runnable()
{
public void run()
{
StepMeta stepMeta = transMeta.findStep(stepname);
if (stepMeta!=null)
{
try
{
RowMetaInterface row = transMeta.getPrevStepFields(stepMeta);
// Remember these fields...
for (int i=0;i<row.size();i++)
{
inputFields.put(row.getValueMeta(i).getName(), Integer.valueOf(i));
}
setComboBoxes();
}
catch(KettleException e)
{
logError(BaseMessages.getString(PKG, "CalculatorDialog.Log.UnableToFindInput"));
}
}
}
};
new Thread(runnable).start();
wFields.addModifyListener(new ModifyListener()
{
public void modifyText(ModifyEvent arg0)
{
// Now set the combo's
shell.getDisplay().asyncExec(new Runnable()
{
public void run()
{
setComboBoxes();
}
});
}
}
);
// Some buttons
wOK=new Button(shell, SWT.PUSH);
wOK.setText(BaseMessages.getString(PKG, "System.Button.OK"));
wCancel=new Button(shell, SWT.PUSH);
wCancel.setText(BaseMessages.getString(PKG, "System.Button.Cancel"));
setButtonPositions(new Button[] { wOK, wCancel }, margin, null);
// Add listeners
lsCancel = new Listener() { public void handleEvent(Event e) { cancel(); } };
lsOK = new Listener() { public void handleEvent(Event e) { ok(); } };
wCancel.addListener(SWT.Selection, lsCancel);
wOK.addListener (SWT.Selection, lsOK );
lsDef=new SelectionAdapter() { public void widgetDefaultSelected(SelectionEvent e) { ok(); } };
wStepname.addSelectionListener( lsDef );
// Detect X or ALT-F4 or something that kills this window...
shell.addShellListener( new ShellAdapter() { public void shellClosed(ShellEvent e) { cancel(); } } );
// Set the shell size, based upon previous time...
setSize();
getData();
currentMeta.setChanged(changed);
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch()) display.sleep();
}
return stepname;
}
protected void setComboBoxes()
{
// Something was changed in the row.
//
final Map<String, Integer> fields = new HashMap<String, Integer>();
// Add the currentMeta fields...
fields.putAll(inputFields);
shell.getDisplay().syncExec(new Runnable()
{
public void run()
{
// Add the newly create fields.
//
int nrNonEmptyFields = wFields.nrNonEmpty();
for (int i=0;i<nrNonEmptyFields;i++)
{
TableItem item = wFields.getNonEmpty(i);
fields.put(item.getText(1), Integer.valueOf(1000000+i)); // The number is just to debug the origin of the fieldname
}
}
}
);
Set<String> keySet = fields.keySet();
List<String> entries = new ArrayList<String>(keySet);
String fieldNames[] = (String[]) entries.toArray(new String[entries.size()]);
Const.sortStrings(fieldNames);
colinf[2].setComboValues(fieldNames);
colinf[3].setComboValues(fieldNames);
colinf[4].setComboValues(fieldNames);
}
/**
* Copy information from the meta-data currentMeta to the dialog fields.
*/
public void getData()
{
wStepname.selectAll();
if (currentMeta.getCalculation()!=null)
for (int i=0;i<currentMeta.getCalculation().length;i++)
{
CalculatorMetaFunction fn = currentMeta.getCalculation()[i];
TableItem item = wFields.table.getItem(i);
item.setText( 1, Const.NVL(fn.getFieldName(), ""));
item.setText( 2, Const.NVL(fn.getCalcTypeLongDesc(), ""));
item.setText( 3, Const.NVL(fn.getFieldA(), ""));
item.setText( 4, Const.NVL(fn.getFieldB(), ""));
item.setText( 5, Const.NVL(fn.getFieldC(), ""));
item.setText( 6, Const.NVL(ValueMeta.getTypeDesc(fn.getValueType()), ""));
if (fn.getValueLength()>=0) {
item.setText( 7, ""+fn.getValueLength());
}
if (fn.getValuePrecision()>=0) {
item.setText( 8, ""+fn.getValuePrecision());
}
item.setText( 9, fn.isRemovedFromResult()?BaseMessages.getString(PKG, "System.Combo.Yes"):BaseMessages.getString(PKG, "System.Combo.No"));
item.setText(10, Const.NVL(fn.getConversionMask(), ""));
item.setText(11, Const.NVL(fn.getDecimalSymbol(), ""));
item.setText(12, Const.NVL(fn.getGroupingSymbol(), ""));
item.setText(13, Const.NVL(fn.getCurrencySymbol(), ""));
}
wFields.setRowNums();
wFields.optWidth(true);
}
private void cancel()
{
stepname=null;
currentMeta.setChanged(changed);
dispose();
}
private void ok()
{
if (Const.isEmpty(wStepname.getText())) return;
stepname = wStepname.getText(); // return value
int nrNonEmptyFields = wFields.nrNonEmpty();
currentMeta.allocate(nrNonEmptyFields);
for (int i=0;i<nrNonEmptyFields;i++)
{
TableItem item = wFields.getNonEmpty(i);
String fieldName = item.getText(1);
int calcType = CalculatorMetaFunction.getCalcFunctionType(item.getText(2));
String fieldA = item.getText(3);
String fieldB = item.getText(4);
String fieldC = item.getText(5);
int valueType = ValueMeta.getType( item.getText(6) );
int valueLength = Const.toInt( item.getText(7), -1 );
int valuePrecision = Const.toInt( item.getText(8), -1 );
boolean removed = BaseMessages.getString(PKG, "System.Combo.Yes").equalsIgnoreCase( item.getText(9) );
String conversionMask = item.getText(10);
String decimalSymbol = item.getText(11);
String groupingSymbol = item.getText(12);
String currencySymbol = item.getText(13);
currentMeta.getCalculation()[i] = new CalculatorMetaFunction(fieldName, calcType, fieldA, fieldB, fieldC, valueType, valueLength, valuePrecision, removed, conversionMask, decimalSymbol, groupingSymbol, currencySymbol);
}
if ( ! originalMeta.equals(currentMeta) )
{
currentMeta.setChanged();
changed = currentMeta.hasChanged();
}
dispose();
}
}
| apache-2.0 |
dsalinux/web-ifad | src/main/java/br/edu/ifnmg/ifad/entity/vo/ClasseVO.java | 1290 | package br.edu.ifnmg.ifad.entity.vo;
import java.util.List;
import java.util.Objects;
public class ClasseVO {
private String id;
private String name;
private List<ProfessorVO> teachers;
public List<ProfessorVO> getTeachers() {
return teachers;
}
public void setTeachers(List<ProfessorVO> teachers) {
this.teachers = teachers;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int hashCode() {
int hash = 7;
hash = 29 * hash + Objects.hashCode(this.id);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final ClasseVO other = (ClasseVO) obj;
if (!Objects.equals(this.id, other.id)) {
return false;
}
return true;
}
@Override
public String toString() {
return "Class: "+name;
}
}
| apache-2.0 |
mox601/functionaljava-spike | functionaljava-spike/src/test/java/fm/mox/spikes/functionaljava/state/account/commands/Command.java | 224 | package fm.mox.spikes.functionaljava.state.account.commands;
/**
* Created by matteo (dot) moci (at) gmail (dot) com
*/
public interface Command {
boolean isDeposit();
boolean isWithdraw();
int getAmount();
}
| apache-2.0 |
Vilsol/NMSWrapper | src/main/java/me/vilsol/nmswrapper/wraps/unparsed/NMSWorldGenReed.java | 884 | package me.vilsol.nmswrapper.wraps.unparsed;
import me.vilsol.nmswrapper.NMSWrapper;
import me.vilsol.nmswrapper.reflections.ReflectiveClass;
import me.vilsol.nmswrapper.reflections.ReflectiveMethod;
import java.util.Random;
@ReflectiveClass(name = "WorldGenReed")
public class NMSWorldGenReed extends NMSWorldGenerator {
public NMSWorldGenReed(Object nmsObject){
super(nmsObject);
}
/**
* @see net.minecraft.server.v1_9_R1.WorldGenReed#generate(net.minecraft.server.v1_9_R1.World, java.util.Random, net.minecraft.server.v1_9_R1.BlockPosition)
*/
@ReflectiveMethod(name = "generate", types = {NMSWorld.class, Random.class, NMSBlockPosition.class})
public boolean generate(NMSWorld world, Random random, NMSBlockPosition blockPosition){
return (boolean) NMSWrapper.getInstance().exec(nmsObject, world, random, blockPosition);
}
} | apache-2.0 |
pengtaolin/school1 | src/com/lin/school1/bean/Download.java | 2046 | package com.lin.school1.bean;
import java.io.Serializable;
import java.util.Date;
/**
* 下载信息表
* @author Administrator
*
*/
public class Download implements Serializable{
private static final long serialVersionUID = 7311213221723983856L;
/**
* 下载Id
*/
private int downloadId;
/**
* 下载名称
*/
private String downloadName;
/**
* 下载量
*/
private int downloadNumber;
/**
* 上传时间
*/
private Date downloadTime;
/**
* 文件地址
*/
private String downloadUrl;
/**
* 所属文章
*/
private Article article;
/**
* 下载状态
*/
private int downloadState;
public int getDownloadId() {
return downloadId;
}
public void setDownloadId(int downloadId) {
this.downloadId = downloadId;
}
public String getDownloadName() {
return downloadName;
}
public void setDownloadName(String downloadName) {
this.downloadName = downloadName;
}
public int getDownloadNumber() {
return downloadNumber;
}
public void setDownloadNumber(int downloadNumber) {
this.downloadNumber = downloadNumber;
}
public Date getDownloadTime() {
return downloadTime;
}
public void setDownloadTime(Date downloadTime) {
this.downloadTime = downloadTime;
}
public String getDownloadUrl() {
return downloadUrl;
}
public void setDownloadUrl(String downloadUrl) {
this.downloadUrl = downloadUrl;
}
public Article getArticle() {
return article;
}
public void setArticle(Article article) {
this.article = article;
}
public int getDownloadState() {
return downloadState;
}
public void setDownloadState(int downloadState) {
this.downloadState = downloadState;
}
@Override
public String toString() {
return "Download [downloadId=" + downloadId + ", downloadName=" + downloadName + ", downloadNumber="
+ downloadNumber + ", downloadTime=" + downloadTime + ", downloadUrl=" + downloadUrl + ", article="
+ article + ", downloadState=" + downloadState + "]";
}
}
| apache-2.0 |
NikitaFeodonit/bqtj | src/com/BibleQuote/bqtj/utils/modules/LinkConverter.java | 2891 | package com.BibleQuote.bqtj.utils.modules;
import com.BibleQuote.bqtj.controllers.IBookController;
import com.BibleQuote.bqtj.controllers.IModuleController;
import com.BibleQuote.bqtj.entity.BibleBooksID;
import com.BibleQuote.bqtj.entity.BibleReference;
import com.BibleQuote.bqtj.exceptions.BookNotFoundException;
import com.BibleQuote.bqtj.exceptions.OpenModuleException;
import com.BibleQuote.bqtj.modules.Book;
import com.BibleQuote.bqtj.modules.Module;
public class LinkConverter {
public static String getOSIStoHuman(String linkOSIS, IModuleController moduleCtrl,
IBookController bookCtrl) throws BookNotFoundException,
OpenModuleException {
String[] param = linkOSIS.split("\\.");
if (param.length < 3) {
return "";
}
String moduleID = param[0];
String bookID = param[1];
String chapter = param[2];
Module currModule;
try {
currModule = moduleCtrl.getModuleByID(moduleID);
} catch (OpenModuleException e) {
return "";
}
Book currBook = bookCtrl.getBookByID(currModule, bookID);
if (currBook == null) {
return "";
}
String humanLink = moduleID + ": " + currBook.getShortName() + " "
+ chapter;
if (param.length > 3) {
humanLink += ":" + param[3];
}
return humanLink;
}
public static String getOSIStoHuman(BibleReference reference, IModuleController moduleCtrl,
IBookController bookCtrl) {
if (reference.getFromVerse() != reference.getToVerse()) {
return String.format("%1$s %2$s:%3$s-%4$s",
reference.getBookFullName(), reference.getChapter(),
reference.getFromVerse(), reference.getToVerse());
} else {
return String.format("%1$s %2$s:%3$s",
reference.getBookFullName(), reference.getChapter(), reference.getFromVerse());
}
}
public static String getHumanToOSIS(String humanLink) {
String linkOSIS = "";
// Получим имя модуля
int position = humanLink.indexOf(":");
if (position == -1) {
return "";
}
linkOSIS = humanLink.substring(0, position).trim();
humanLink = humanLink.substring(position + 1).trim();
if (humanLink.length() == 0) {
return "";
}
// Получим имя книги
position = humanLink.indexOf(" ");
if (position == -1) {
return "";
}
linkOSIS += "."
+ BibleBooksID.getID(humanLink.substring(0, position).trim());
humanLink = humanLink.substring(position).trim();
if (humanLink.length() == 0) {
return linkOSIS + ".1";
}
// Получим номер главы
position = humanLink.indexOf(":");
if (position == -1) {
return "";
}
linkOSIS += "."
+ humanLink.substring(0, position).trim().replaceAll("\\D", "");
humanLink = humanLink.substring(position).trim().replaceAll("\\D", "");
if (humanLink.length() == 0) {
return linkOSIS;
} else {
// Оставшийся кусок - номер стиха
return linkOSIS + "." + humanLink;
}
}
}
| apache-2.0 |
martenscs/optaplanner-osgi | org.optaplanner.examples.vehicle.routing/src/org/optaplanner/examples/vehiclerouting/domain/timewindowed/TimeWindowedVehicleRoutingSolution.java | 1007 | /*
* Copyright 2015 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.optaplanner.examples.vehiclerouting.domain.timewindowed;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import org.optaplanner.examples.vehiclerouting.domain.VehicleRoutingSolution;
@XStreamAlias("VrpTimeWindowedVehicleRoutingSolution")
public class TimeWindowedVehicleRoutingSolution extends VehicleRoutingSolution {
/**
*
*/
private static final long serialVersionUID = 1L;
}
| apache-2.0 |
leafclick/intellij-community | platform/platform-impl/src/com/intellij/openapi/keymap/impl/ui/QuickListPanel.java | 6349 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.keymap.impl.ui;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.ex.QuickList;
import com.intellij.openapi.actionSystem.ex.QuickListsManager;
import com.intellij.openapi.keymap.KeyMapBundle;
import com.intellij.openapi.keymap.KeymapManager;
import com.intellij.ui.AnActionButton;
import com.intellij.ui.AnActionButtonRunnable;
import com.intellij.ui.CollectionListModel;
import com.intellij.ui.ToolbarDecorator;
import com.intellij.ui.components.JBList;
import com.intellij.util.ArrayUtilRt;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.util.List;
class QuickListPanel {
private final CollectionListModel<Object> actionsModel;
private JPanel myPanel;
private final JBList myActionsList;
JTextField myName;
private JTextField myDescription;
private JPanel myListPanel;
QuickList item;
QuickListPanel(@NotNull final CollectionListModel<QuickList> model) {
actionsModel = new CollectionListModel<>();
myActionsList = new JBList(actionsModel);
myActionsList.setCellRenderer(new MyListCellRenderer());
myActionsList.getEmptyText().setText(KeyMapBundle.message("no.actions"));
myActionsList.setEnabled(true);
myListPanel.add(ToolbarDecorator.createDecorator(myActionsList)
.setAddAction(new AnActionButtonRunnable() {
@Override
public void run(AnActionButton button) {
List<QuickList> items = model.getItems();
ChooseActionsDialog dialog = new ChooseActionsDialog(myActionsList, KeymapManager.getInstance().getActiveKeymap(), items.toArray(
new QuickList[0]));
if (dialog.showAndGet()) {
String[] ids = dialog.getTreeSelectedActionIds();
for (String id : ids) {
includeActionId(id);
}
List<Object> list = actionsModel.getItems();
int size = list.size();
ListSelectionModel selectionModel = myActionsList.getSelectionModel();
if (size > 0) {
selectionModel.removeIndexInterval(0, size - 1);
}
for (String id1 : ids) {
int idx = list.lastIndexOf(id1);
if (idx >= 0) {
selectionModel.addSelectionInterval(idx, idx);
}
}
}
}
})
.addExtraAction(new AnActionButton(KeyMapBundle.lazyMessage("action.AnActionButton.text.add.separator"),
AllIcons.General.SeparatorH) {
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
actionsModel.add(QuickList.SEPARATOR_ID);
}
})
.setButtonComparator("Add", "Add Separator", "Remove", "Up", "Down")
.createPanel(), BorderLayout.CENTER);
}
public void apply() {
if (item == null) {
return;
}
item.setName(myName.getText().trim());
item.setDescription(myDescription.getText().trim());
ListModel model = myActionsList.getModel();
int size = model.getSize();
String[] ids;
if (size == 0) {
ids = ArrayUtilRt.EMPTY_STRING_ARRAY;
}
else {
ids = new String[size];
for (int i = 0; i < size; i++) {
ids[i] = (String)model.getElementAt(i);
}
}
item.setActionIds(ids);
}
public void setItem(@Nullable QuickList item) {
apply();
this.item = item;
if (item == null) {
return;
}
myName.setText(item.getName());
myName.setEnabled(QuickListsManager.getInstance().getSchemeManager().isMetadataEditable(item));
myDescription.setText(item.getDescription());
actionsModel.removeAll();
for (String id : item.getActionIds()) {
includeActionId(id);
}
}
private void includeActionId(@NotNull String id) {
if (QuickList.SEPARATOR_ID.equals(id) || actionsModel.getElementIndex(id) == -1) {
actionsModel.add(id);
}
}
public JPanel getPanel() {
return myPanel;
}
private static class MyListCellRenderer extends DefaultListCellRenderer {
@NotNull
@Override
public Component getListCellRendererComponent(@NotNull JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
Icon icon = null;
String actionId = (String)value;
if (QuickList.SEPARATOR_ID.equals(actionId)) {
setText("-------------");
}
else {
AnAction action = ActionManager.getInstance().getAction(actionId);
setText(action != null ? action.getTemplatePresentation().getText() : actionId);
if (action != null) {
Icon actionIcon = action.getTemplatePresentation().getIcon();
if (actionIcon != null) {
icon = actionIcon;
}
}
if (actionId.startsWith(QuickList.QUICK_LIST_PREFIX)) {
icon = null; // AllIcons.Actions.QuickList;
}
setIcon(ActionsTree.getEvenIcon(icon));
}
return this;
}
@Override
public Dimension getPreferredSize() {
return UIUtil.updateListRowHeight(super.getPreferredSize());
}
}
}
| apache-2.0 |
pravega/pravega | cli/admin/src/test/java/io/pravega/cli/admin/controller/ControllerCommandsTest.java | 10654 | /**
* Copyright Pravega 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 io.pravega.cli.admin.controller;
import com.google.common.base.Preconditions;
import io.pravega.cli.admin.AdminCommandState;
import io.pravega.cli.admin.CommandArgs;
import io.pravega.cli.admin.Parser;
import io.pravega.cli.admin.utils.CLIConfig;
import io.pravega.cli.admin.utils.TestUtils;
import io.pravega.client.ClientConfig;
import io.pravega.client.admin.StreamManager;
import io.pravega.client.connection.impl.ConnectionPool;
import io.pravega.client.connection.impl.ConnectionPoolImpl;
import io.pravega.client.connection.impl.SocketConnectionFactoryImpl;
import io.pravega.client.stream.ScalingPolicy;
import io.pravega.client.stream.StreamConfiguration;
import io.pravega.shared.security.auth.DefaultCredentials;
import io.pravega.common.Exceptions;
import io.pravega.common.cluster.Host;
import io.pravega.controller.server.SegmentHelper;
import io.pravega.controller.store.client.StoreClientFactory;
import io.pravega.controller.store.host.HostControllerStore;
import io.pravega.controller.store.host.HostMonitorConfig;
import io.pravega.controller.store.host.HostStoreFactory;
import io.pravega.controller.store.host.impl.HostMonitorConfigImpl;
import io.pravega.controller.util.Config;
import io.pravega.test.integration.demo.ClusterWrapper;
import lombok.Cleanup;
import lombok.SneakyThrows;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryOneTime;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static io.pravega.cli.admin.utils.TestUtils.createAdminCLIConfig;
import static io.pravega.cli.admin.utils.TestUtils.createPravegaCluster;
import static io.pravega.cli.admin.utils.TestUtils.getCLIControllerRestUri;
import static io.pravega.cli.admin.utils.TestUtils.getCLIControllerUri;
import static io.pravega.cli.admin.utils.TestUtils.prepareValidClientConfig;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* Validate basic controller commands.
*/
public class ControllerCommandsTest extends SecureControllerCommandsTest {
private static final ClusterWrapper CLUSTER = createPravegaCluster(false, false);
private static final AdminCommandState STATE;
private static final ClientConfig CLIENT_CONFIG;
// The controller REST URI is generated only after the Pravega cluster has been started. So to maintain STATE as
// static final, we use this instead of @BeforeClass.
static {
CLUSTER.start();
STATE = createAdminCLIConfig(getCLIControllerRestUri(CLUSTER.controllerRestUri()),
getCLIControllerUri(CLUSTER.controllerUri()), CLUSTER.zookeeperConnectString(), CLUSTER.getContainerCount(),
false, false, CLUSTER.getAccessTokenTtl());
String scope = "testScope";
String testStream = "testStream";
CLIENT_CONFIG = prepareValidClientConfig(CLUSTER.controllerUri(), false, false);
// Generate the scope and stream required for testing.
@Cleanup
StreamManager streamManager = StreamManager.create(CLIENT_CONFIG);
assertNotNull(streamManager);
boolean isScopeCreated = streamManager.createScope(scope);
// Check if scope created successfully.
assertTrue("Failed to create scope", isScopeCreated);
boolean isStreamCreated = streamManager.createStream(scope, testStream, StreamConfiguration.builder()
.scalingPolicy(ScalingPolicy.fixed(1))
.build());
// Check if stream created successfully.
assertTrue("Failed to create the stream ", isStreamCreated);
}
@Override
protected AdminCommandState cliConfig() {
return STATE;
}
@AfterClass
public static void shutDown() {
if (CLUSTER != null) {
CLUSTER.close();
}
STATE.close();
}
@Override
@Test
@SneakyThrows
public void testDescribeReaderGroupCommand() {
// Check that the system reader group can be listed.
String commandResult = TestUtils.executeCommand("controller describe-readergroup _system commitStreamReaders", cliConfig());
Assert.assertTrue(commandResult.contains("commitStreamReaders"));
Assert.assertNotNull(ControllerDescribeReaderGroupCommand.descriptor());
}
@Test
@SneakyThrows
public void testDescribeStreamCommand() {
String scope = "testScope";
String testStream = "testStream";
String commandResult = executeCommand("controller describe-stream " + scope + " " + testStream, cliConfig());
Assert.assertTrue(commandResult.contains("stream_config"));
Assert.assertTrue(commandResult.contains("stream_state"));
Assert.assertTrue(commandResult.contains("segment_count"));
Assert.assertTrue(commandResult.contains("is_sealed"));
Assert.assertTrue(commandResult.contains("active_epoch"));
Assert.assertTrue(commandResult.contains("truncation_record"));
Assert.assertTrue(commandResult.contains("scaling_info"));
// Exercise actual instantiateSegmentHelper
CommandArgs commandArgs = new CommandArgs(Arrays.asList(scope, testStream), cliConfig());
ControllerDescribeStreamCommand command = new ControllerDescribeStreamCommand(commandArgs);
@Cleanup
CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient(CLUSTER.zookeeperConnectString(),
new RetryOneTime(5000));
curatorFramework.start();
@Cleanup
ConnectionPool pool = new ConnectionPoolImpl(CLIENT_CONFIG, new SocketConnectionFactoryImpl(CLIENT_CONFIG));
@Cleanup
SegmentHelper sh = command.instantiateSegmentHelper(curatorFramework, pool);
Assert.assertNotNull(sh);
// Try the Zookeeper backend, which is expected to fail and be handled by the command.
Properties properties = new Properties();
properties.setProperty("cli.store.metadata.backend", CLIConfig.MetadataBackends.ZOOKEEPER.name());
cliConfig().getConfigBuilder().include(properties);
commandArgs = new CommandArgs(Arrays.asList(scope, testStream), cliConfig());
new ControllerDescribeStreamCommand(commandArgs).execute();
properties.setProperty("cli.store.metadata.backend", CLIConfig.MetadataBackends.SEGMENTSTORE.name());
cliConfig().getConfigBuilder().include(properties);
}
static String executeCommand(String inputCommand, AdminCommandState state) throws Exception {
Parser.Command pc = Parser.parse(inputCommand);
Assert.assertNotNull(pc.toString());
CommandArgs args = new CommandArgs(pc.getArgs(), state);
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
TestingDescribeStreamCommand cmd = new TestingDescribeStreamCommand(args);
try (PrintStream ps = new PrintStream(baos, true, StandardCharsets.UTF_8)) {
cmd.setOut(ps);
cmd.execute();
}
return new String(baos.toByteArray(), StandardCharsets.UTF_8);
}
private static class TestingDescribeStreamCommand extends ControllerDescribeStreamCommand {
/**
* Creates a new instance of the Command class.
*
* @param args The arguments for the command.
*/
public TestingDescribeStreamCommand(CommandArgs args) {
super(args);
}
@Override
public SegmentHelper instantiateSegmentHelper(CuratorFramework zkClient, ConnectionPool pool) {
HostMonitorConfig hostMonitorConfig = HostMonitorConfigImpl.builder()
.hostMonitorEnabled(false)
.hostContainerMap(getHostContainerMap(Collections.singletonList("localhost:" + CLUSTER.getSegmentStorePort()),
getServiceConfig().getContainerCount()))
.hostMonitorMinRebalanceInterval(Config.CLUSTER_MIN_REBALANCE_INTERVAL)
.containerCount(getServiceConfig().getContainerCount())
.build();
HostControllerStore hostStore = HostStoreFactory.createStore(hostMonitorConfig, StoreClientFactory.createZKStoreClient(zkClient));
ClientConfig clientConfig = ClientConfig.builder()
.controllerURI(URI.create(getCLIControllerConfig().getControllerGrpcURI()))
.validateHostName(false)
.credentials(new DefaultCredentials(getCLIControllerConfig().getPassword(),
getCLIControllerConfig().getUserName()))
.build();
return new SegmentHelper(pool, hostStore, pool.getInternalExecutor());
}
private Map<Host, Set<Integer>> getHostContainerMap(List<String> uri, int containerCount) {
Exceptions.checkNotNullOrEmpty(uri, "uri");
Map<Host, Set<Integer>> hostContainerMap = new HashMap<>();
uri.forEach(x -> {
// Get the host and port from the URI
String host = x.split(":")[0];
int port = Integer.parseInt(x.split(":")[1]);
Preconditions.checkNotNull(host, "host");
Preconditions.checkArgument(port > 0, "port");
Preconditions.checkArgument(containerCount > 0, "containerCount");
hostContainerMap.put(new Host(host, port, null), IntStream.range(0, containerCount).boxed().collect(Collectors.toSet()));
});
return hostContainerMap;
}
@Override
public void execute() {
super.execute();
}
}
}
| apache-2.0 |
sindicate/solidstack | test/src/solidstack/httpclient/Response.java | 2213 | /*--
* Copyright 2012 René M. de Bloois
*
* 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 solidstack.httpclient;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import solidstack.httpserver.HttpBodyInputStream;
import solidstack.io.FatalIOException;
public class Response
{
private String httpVersion;
private int status;
private String reason;
private InputStream in;
private HttpBodyInputStream bodyIn;
private Map<String, String> headers = new HashMap<>();
// TODO Multivalued headers
public Response()
{
}
public void setHttpVersion( String httpVersion )
{
this.httpVersion = httpVersion;
}
public String getHttpVersion()
{
return this.httpVersion;
}
public void setStatus( int status )
{
this.status = status;
}
public int getStatus()
{
return this.status;
}
public void setReason( String reason )
{
this.reason = reason;
}
public String getReason()
{
return this.reason;
}
public void addHeader( String name, String value )
{
this.headers.put( name, value );
}
public String getHeader( String name )
{
return this.headers.get( name ); // TODO Case insensitivity
}
public Map<String, String> getHeaders()
{
return this.headers;
}
public void print()
{
byte[] buffer = new byte[ 4096 ];
try
{
int len = this.bodyIn.read( buffer );
while( len >= 0 )
{
System.out.write( buffer, 0, len );
len = this.bodyIn.read( buffer );
}
}
catch( IOException e )
{
throw new FatalIOException( e );
}
}
public void setInputStream( InputStream in )
{
this.in = in;
}
public InputStream getInputStream()
{
return this.in;
}
}
| apache-2.0 |
bazelbuild/bazel-buildfarm | src/main/java/build/buildfarm/common/ExecutionWrappers.java | 3369 | // Copyright 2021 The Bazel Authors. 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 build.buildfarm.common;
/**
* @class Execution Wrappers
* @brief Execution wrappers understood and used by buildfarm.
* @details These are the program names chosen when indicated through execution properties which
* wrappers to use. Users can still configure their own unique execution wrappers as execution
* policies in the worker configuration file.
*/
public class ExecutionWrappers {
/**
* @field CGROUPS
* @brief The program to use when running actions under cgroups.
* @details This program is expected to be packaged with the worker image.
*/
public static final String CGROUPS = "/usr/bin/cgexec";
/**
* @field UNSHARE
* @brief The program to use when desiring to unshare namespaces from the action.
* @details This program is expected to be packaged with the worker image.
*/
public static final String UNSHARE = "/usr/bin/unshare";
/**
* @field LINUX_SANDBOX
* @brief The program to use when running actions under bazel's sandbox.
* @details This program is expected to be packaged with the worker image.
*/
public static final String LINUX_SANDBOX = "/app/build_buildfarm/linux-sandbox";
/**
* @field AS_NOBODY
* @brief The program to use when running actions as "as-nobody".
* @details This program is expected to be packaged with the worker image. The linux-sandbox is
* also capable of doing what this standalone programs does and may be chosen instead.
*/
public static final String AS_NOBODY = "/app/build_buildfarm/as-nobody";
/**
* @field PROCESS_WRAPPER
* @brief The program to use when running actions under bazel's process-wrapper
* @details This program is expected to be packaged with the worker image.
*/
public static final String PROCESS_WRAPPER = "/app/build_buildfarm/process-wrapper";
/**
* @field SKIP_SLEEP
* @brief The program to use when running actions under bazel's skip sleep wrapper.
* @details This program is expected to be packaged with the worker image.
*/
public static final String SKIP_SLEEP = "/app/build_buildfarm/skip_sleep";
/**
* @field SKIP_SLEEP_PRELOAD
* @brief The shared object that the skip sleep wrapper uses to spoof syscalls.
* @details The shared object needs passed to the program which will LD_PRELOAD it.
*/
public static final String SKIP_SLEEP_PRELOAD = "/app/build_buildfarm/skip_sleep_preload.so";
/**
* @field DELAY
* @brief The program to used to timeshift actions when running under skip_sleep.
* @details This program is expected to be packaged with the worker image. Warning: This wrapper
* is only intended to be used with skip_sleep.
*/
public static final String DELAY = "/app/build_buildfarm/delay.sh";
}
| apache-2.0 |
CMPUT301F15T01/YesWeCandroid | app/src/main/java/ca/ualberta/trinkettrader/Friends/FriendsListController.java | 3442 | // Copyright 2015 Andrea McIntosh, Dylan Ashley, Anju Eappen, Jenna Hatchard, Kirsten Svidal, Raghav Vamaraju
//
// 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 ca.ualberta.trinkettrader.Friends;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import ca.ualberta.trinkettrader.ApplicationState;
import ca.ualberta.trinkettrader.Friends.TrackedFriends.TrackedFriendsListActivity;
import ca.ualberta.trinkettrader.User.LoggedInUser;
/**
* Controller for handling interactions from the FriendsListActivity. The controller manages clicks to
* the "Find Friends", "View Tradcked Friends" buttons in the FriendsListActivity's layout.
* Clicking the Find Friends button will add the friend to the friends list, and the View Tracked Friends
* starts the TrackedFriendsListActivity.
*/
public class FriendsListController {
private FriendsListActivity activity;
public FriendsListController(FriendsListActivity activity) {
this.activity = activity;
}
/**
* onClick method for searching and adding friends.
*/
public void findFriendsOnClick() {
EditText textField = activity.getFindFriendTextField();
String username = textField.getText().toString();
Friend newFriend = new Friend(username);
if (!username.isEmpty() && username.contains("@")) {
// TODO testing for offline purposes only - will redo once web service intact
LoggedInUser.getInstance().getFriendsList().add(newFriend);
}
}
/**
* Sets click listener for the items in the friends list ListView. Will direct to the friend's profile activity.
*/
public void setFriendsListViewItemOnClick() {
ListView friendsListView = activity.getFriendsListView();
friendsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> v, View view, int position, long id) {
Friend clickedFriend = LoggedInUser.getInstance().getFriendsList().get(position);
ApplicationState.getInstance().setClickedFriend(clickedFriend);
Intent intent = new Intent(activity, FriendsProfileActivity.class);
activity.startActivity(intent);
}
});
}
/**
* onClick method for the view tracked friends button. Navigates to Tracked Friends List activity.
*/
public void viewTrackedFriendsOnClick() {
Intent intent = new Intent(activity, TrackedFriendsListActivity.class);
activity.startActivity(intent);
}
/**
* OnClick Method to view and browse the inventories of all Friendsa
*/
public void allInventoriesOnClick() {
Intent intent = new Intent(activity, AllFriendsInventoriesActivity.class);
activity.startActivity(intent);
}
}
| apache-2.0 |
haikuowuya/android_system_code | gen/android/app/ITransientNotification.java | 2806 | /*
* This file is auto-generated. DO NOT MODIFY.
* Original file: E:\\android_workspace2\\system_code\\src\\android\\app\\ITransientNotification.aidl
*/
package android.app;
/** @hide */
public interface ITransientNotification extends android.os.IInterface
{
/** Local-side IPC implementation stub class. */
public static abstract class Stub extends android.os.Binder implements android.app.ITransientNotification
{
private static final java.lang.String DESCRIPTOR = "android.app.ITransientNotification";
/** Construct the stub at attach it to the interface. */
public Stub()
{
this.attachInterface(this, DESCRIPTOR);
}
/**
* Cast an IBinder object into an android.app.ITransientNotification interface,
* generating a proxy if needed.
*/
public static android.app.ITransientNotification asInterface(android.os.IBinder obj)
{
if ((obj==null)) {
return null;
}
android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
if (((iin!=null)&&(iin instanceof android.app.ITransientNotification))) {
return ((android.app.ITransientNotification)iin);
}
return new android.app.ITransientNotification.Stub.Proxy(obj);
}
@Override public android.os.IBinder asBinder()
{
return this;
}
@Override public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException
{
switch (code)
{
case INTERFACE_TRANSACTION:
{
reply.writeString(DESCRIPTOR);
return true;
}
case TRANSACTION_show:
{
data.enforceInterface(DESCRIPTOR);
this.show();
return true;
}
case TRANSACTION_hide:
{
data.enforceInterface(DESCRIPTOR);
this.hide();
return true;
}
}
return super.onTransact(code, data, reply, flags);
}
private static class Proxy implements android.app.ITransientNotification
{
private android.os.IBinder mRemote;
Proxy(android.os.IBinder remote)
{
mRemote = remote;
}
@Override public android.os.IBinder asBinder()
{
return mRemote;
}
public java.lang.String getInterfaceDescriptor()
{
return DESCRIPTOR;
}
@Override public void show() throws android.os.RemoteException
{
android.os.Parcel _data = android.os.Parcel.obtain();
try {
_data.writeInterfaceToken(DESCRIPTOR);
mRemote.transact(Stub.TRANSACTION_show, _data, null, android.os.IBinder.FLAG_ONEWAY);
}
finally {
_data.recycle();
}
}
@Override public void hide() throws android.os.RemoteException
{
android.os.Parcel _data = android.os.Parcel.obtain();
try {
_data.writeInterfaceToken(DESCRIPTOR);
mRemote.transact(Stub.TRANSACTION_hide, _data, null, android.os.IBinder.FLAG_ONEWAY);
}
finally {
_data.recycle();
}
}
}
static final int TRANSACTION_show = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);
static final int TRANSACTION_hide = (android.os.IBinder.FIRST_CALL_TRANSACTION + 1);
}
public void show() throws android.os.RemoteException;
public void hide() throws android.os.RemoteException;
}
| apache-2.0 |
ConsecroMUD/ConsecroMUD | com/suscipio_solutions/consecro_mud/Items/interfaces/DoorKey.java | 168 | package com.suscipio_solutions.consecro_mud.Items.interfaces;
public interface DoorKey extends Item
{
public void setKey(String keyName);
public String getKey();
}
| apache-2.0 |
ParaskP7/sample-code-posts | app/src/main/java/io/petros/posts/datastore/SaveActions.java | 174 | package io.petros.posts.datastore;
import java.util.List;
import io.petros.posts.model.User;
public interface SaveActions {
boolean users(final List<User> users);
}
| apache-2.0 |
AnneGoncalo/helppettest | src/main/java/br/edu/ifrn/helppet/dominio/PessoaFisica.java | 1829 | /*
* Copyright 2017 HelpPet.
*
* 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 br.edu.ifrn.helppet.dominio;
import java.io.Serializable;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.SequenceGenerator;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
/**
*
* @author anne
*/
@Getter
@Setter
@ToString
@EqualsAndHashCode
@Builder
@AllArgsConstructor(access = AccessLevel.PUBLIC)
@NoArgsConstructor(access = AccessLevel.PUBLIC)
@Entity
@SequenceGenerator(sequenceName = "seq_pessoafisica", name = "ID_SEQUENCE", allocationSize = 1)
public class PessoaFisica implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "ID_SEQUENCE")
private Long id;
private String cpf;
@OneToOne
private Usuario usuario;
@OneToMany(mappedBy = "adotante")
private Set<Encontro> encontros;
}
| apache-2.0 |
SVFBr/HackerRank | 05-Loops/src/Solution.java | 258 | import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int N = in.nextInt();
for (int i = 1; i <= 10; i++) {
System.out.println(N + " x " + i + " = " + (N * i));
}
}
}
| apache-2.0 |
Tomorrowhi/THDemo | THDemo/app/src/main/java/com/tomorrowhi/thdemo/util/voiceUtils/TransferThread.java | 1096 | package com.tomorrowhi.thdemo.util.voiceUtils;
import android.content.Context;
import android.os.Environment;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by zhaotaotao on 2017/7/17.
*/
public class TransferThread extends Thread {
private TransferCallback callback;
private Context context;
public TransferThread(Context context, TransferCallback callback) {
this.callback = callback;
this.context = context;
}
@Override
public void run() {
transfer();
}
private void transfer() {
String rootPath = Environment.getExternalStorageDirectory().getPath();
String amrPath = rootPath + "/test.amr";
try {
InputStream pcmStream = context.getAssets().open("test.pcm");
AmrEncoder.pcm2Amr(pcmStream, amrPath);
callback.onSuccess();
} catch (IOException e) {
callback.onFailed();
e.printStackTrace();
}
}
public static interface TransferCallback {
void onSuccess();
void onFailed();
}
}
| apache-2.0 |
LittleLazyCat/TXEYXXK | 2017workspace/go-public/go-core/src/main/java/com/ansteel/dhtmlx/widget/form/Settings.java | 2882 | package com.ansteel.dhtmlx.widget.form;
import com.ansteel.core.constant.DHtmlxConstants;
/**
* 创 建 人:gugu
* 创建日期:2015-06-18
* 修 改 人:
* 修改日 期:
* 描 述:dhtmlx表单类。
*/
public class Settings extends Form{
public Settings() {
super(DHtmlxConstants.SETTINGS);
}
/**
* 项内容(数)的偏移量。对于块项目唯一
*/
private Number blockOffset ;
/**
* 设置输入的高度。默认值是自动
*/
private Integer inputHeight ;
/**
* 设置输入的宽度。默认值是自动
*/
private Integer inputWidth ;
/**
* (左,右或中心)(left, right or center) 的标签定义的宽度内的对准
*/
private String labelAlign ;
/**
* (整数或自动)设置标签的高度。默认值是自动
*/
private String labelHeight ;
/**
* (整数或自动)设置标签的宽度。默认值是自动
*/
private Integer labelWidth ;
/**
* (整数或自动)设置的细节的宽度方框(其被放置在输入下)
*/
private Integer noteWidth ;
/**
* (整数)设置在左侧的相对项的偏移(两个输入和标签)
*/
private Integer offsetLeft ;
/**
* (整数)设置顶相对项的偏移(两个输入和标签)
*/
private Integer offsetTop ;
/**
* (标签左,标签右,标记顶或绝对)(label-left, label-right, label-top or absolute) 定义相对于输入标签的位置
*/
private String position ;
public Number getBlockOffset() {
return blockOffset;
}
public void setBlockOffset(Number blockOffset) {
this.blockOffset = blockOffset;
}
public Integer getInputHeight() {
return inputHeight;
}
public void setInputHeight(Integer inputHeight) {
this.inputHeight = inputHeight;
}
public Integer getInputWidth() {
return inputWidth;
}
public void setInputWidth(Integer inputWidth) {
this.inputWidth = inputWidth;
}
public String getLabelAlign() {
return labelAlign;
}
public void setLabelAlign(String labelAlign) {
this.labelAlign = labelAlign;
}
public String getLabelHeight() {
return labelHeight;
}
public void setLabelHeight(String labelHeight) {
this.labelHeight = labelHeight;
}
public Integer getLabelWidth() {
return labelWidth;
}
public void setLabelWidth(Integer labelWidth) {
this.labelWidth = labelWidth;
}
public Integer getNoteWidth() {
return noteWidth;
}
public void setNoteWidth(Integer noteWidth) {
this.noteWidth = noteWidth;
}
public Integer getOffsetLeft() {
return offsetLeft;
}
public void setOffsetLeft(Integer offsetLeft) {
this.offsetLeft = offsetLeft;
}
public Integer getOffsetTop() {
return offsetTop;
}
public void setOffsetTop(Integer offsetTop) {
this.offsetTop = offsetTop;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
}
| apache-2.0 |
dbflute-test/dbflute-test-active-hangar | src/main/java/org/docksidestage/hangar/simpleflute/dto/SummaryWithdrawalDto.java | 476 | package org.docksidestage.hangar.simpleflute.dto;
import org.docksidestage.hangar.simpleflute.dto.bs.BsSummaryWithdrawalDto;
/**
* The entity of SUMMARY_WITHDRAWAL.
* <p>
* You can implement your original methods here.
* This class remains when re-generating.
* </p>
* @author DBFlute(AutoGenerator)
*/
public class SummaryWithdrawalDto extends BsSummaryWithdrawalDto {
/** Serial version UID. (Default) */
private static final long serialVersionUID = 1L;
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-lookoutequipment/src/main/java/com/amazonaws/services/lookoutequipment/model/DescribeModelRequest.java | 3584 | /*
* Copyright 2017-2022 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.lookoutequipment.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/lookoutequipment-2020-12-15/DescribeModel" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeModelRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The name of the ML model to be described.
* </p>
*/
private String modelName;
/**
* <p>
* The name of the ML model to be described.
* </p>
*
* @param modelName
* The name of the ML model to be described.
*/
public void setModelName(String modelName) {
this.modelName = modelName;
}
/**
* <p>
* The name of the ML model to be described.
* </p>
*
* @return The name of the ML model to be described.
*/
public String getModelName() {
return this.modelName;
}
/**
* <p>
* The name of the ML model to be described.
* </p>
*
* @param modelName
* The name of the ML model to be described.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeModelRequest withModelName(String modelName) {
setModelName(modelName);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getModelName() != null)
sb.append("ModelName: ").append(getModelName());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof DescribeModelRequest == false)
return false;
DescribeModelRequest other = (DescribeModelRequest) obj;
if (other.getModelName() == null ^ this.getModelName() == null)
return false;
if (other.getModelName() != null && other.getModelName().equals(this.getModelName()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getModelName() == null) ? 0 : getModelName().hashCode());
return hashCode;
}
@Override
public DescribeModelRequest clone() {
return (DescribeModelRequest) super.clone();
}
}
| apache-2.0 |
ThilinaManamgoda/incubator-taverna-workbench | taverna-results-view/src/main/java/org/apache/taverna/workbench/views/results/saveactions/SaveAllResultsAsXML.java | 2323 | package org.apache.taverna.workbench.views.results.saveactions;
/*
* 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.
*/
import static org.apache.taverna.workbench.icons.WorkbenchIcons.xmlNodeIcon;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Map;
import javax.swing.AbstractAction;
import org.apache.taverna.results.BaclavaDocumentPathHandler;
/**
* Stores the entire map of result objects to disk as a single XML data
* document. For the most part, this class delegates to
* {@link BaclavaDocumentPathHandler}
*
* @author Tom Oinn
* @author Alex Nenadic
* @author Stuart Owen
* @author David Withers
*/
public class SaveAllResultsAsXML extends SaveAllResultsSPI {
private static final long serialVersionUID = 452360182978773176L;
private BaclavaDocumentPathHandler baclavaDocumentHandler = new BaclavaDocumentPathHandler();
public SaveAllResultsAsXML() {
super();
putValue(NAME, "Save in single XML document");
putValue(SMALL_ICON, xmlNodeIcon);
}
@Override
public AbstractAction getAction() {
return new SaveAllResultsAsXML();
}
/**
* Saves the result data to an XML Baclava file.
*
* @throws IOException
*/
@Override
protected void saveData(File file) throws IOException {
baclavaDocumentHandler.saveData(file);
}
@Override
public void setChosenReferences(Map<String, Path> chosenReferences) {
super.setChosenReferences(chosenReferences);
baclavaDocumentHandler.setChosenReferences(chosenReferences);
}
@Override
protected String getFilter() {
return "xml";
}
}
| apache-2.0 |
KonradOliwer/SimpleGeneticAITest | GeneticAlgorithm/src/main/java/pwr/om/geneticalgorithm/integer/DummyValidationChromosome.java | 966 | /*
* Copyright 2014 KonradOliwer.
*
* 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 pwr.om.geneticalgorithm.integer;
/**
*
* @author KonradOliwer
*/
class DummyValidationChromosome implements ChromosomeValidatior {
@Override
public boolean isValid(int[] chromosome, int gene) {
return true;
}
@Override
public boolean isValid(int[] chromosome) {
return true;
}
}
| apache-2.0 |
bluemixmg/upy-3 | src/main/java/com/upy/model/Ruta.java | 476 | package com.upy.model;
public class Ruta {
private SolicitudServicio solicitudServicio;
public Ruta() {
super();
}
public Ruta(SolicitudServicio solicitudServicio) {
super();
this.solicitudServicio = solicitudServicio;
}
public SolicitudServicio getSolicitudServicio() {
return solicitudServicio;
}
public void setSolicitudServicio(SolicitudServicio solicitudServicio) {
this.solicitudServicio = solicitudServicio;
}
}
| apache-2.0 |
parshimers/incubator-asterixdb | asterix-aql/src/main/java/edu/uci/ics/asterix/aql/expression/ExternalDetailsDecl.java | 2114 | /*
* Copyright 2009-2013 by The Regents of the University of California
* 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 from
*
* 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 edu.uci.ics.asterix.aql.expression;
import java.util.Map;
public class ExternalDetailsDecl implements IDatasetDetailsDecl {
private Map<String, String> properties;
private String adapter;
private Identifier nodegroupName;
private String compactionPolicy;
private Map<String, String> compactionPolicyProperties;
public void setAdapter(String adapter) {
this.adapter = adapter;
}
public void setProperties(Map<String, String> properties) {
this.properties = properties;
}
public String getAdapter() {
return adapter;
}
public Map<String, String> getProperties() {
return properties;
}
@Override
public Identifier getNodegroupName() {
return nodegroupName;
}
public void setNodegroupName(Identifier nodegroupName) {
this.nodegroupName = nodegroupName;
}
@Override
public String getCompactionPolicy() {
return compactionPolicy;
}
public void setCompactionPolicy(String compactionPolicy) {
this.compactionPolicy = compactionPolicy;
}
@Override
public Map<String, String> getCompactionPolicyProperties() {
return compactionPolicyProperties;
}
@Override
public boolean isTemp() {
return false;
}
public void setCompactionPolicyProperties(Map<String, String> compactionPolicyProperties) {
this.compactionPolicyProperties = compactionPolicyProperties;
}
}
| apache-2.0 |
vaektor/Loqale | backend/src/main/java/net/nfiniteloop/loqale/backend/RegistrationEndpoint.java | 3164 | package net.nfiniteloop.loqale.backend;
import com.google.api.server.spi.config.Api;
import com.google.api.server.spi.config.ApiMethod;
import com.google.api.server.spi.config.ApiNamespace;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger;
import javax.inject.Named;
import static net.nfiniteloop.loqale.backend.OfyService.ofy;
/**
* A registration endpoint class we are exposing for a device's GCM registration id on the backend
*
* For more information, see
* https://developers.google.com/appengine/docs/java/endpoints/
*
* NOTE: This endpoint does not use any form of authorization or
* authentication! If this app is deployed, anyone can access this endpoint! If
* you'd like to add authentication, take a look at the documentation.
*/
@Api(name = "registration", version = "v1", namespace =
@ApiNamespace(ownerDomain = "backend.loqale.nfiniteloop.net",
ownerName = "backend.loqale.nfiniteloop.net", packagePath=""))
public class RegistrationEndpoint {
private static final Logger log = Logger.getLogger(RegistrationEndpoint.class.getName());
/**
* Register a device to the backend
*
* @param regId The Google Cloud Messaging registration Id to add
*/
@ApiMethod(name = "register")
public void registerDevice(@Named("regId") String regId, User userInfo) {
if (findRecord(regId) != null) {
log.info("Device " + regId + " already registered, skipping register");
return;
}
RegistrationRecord record = new RegistrationRecord();
record.setRegId(regId);
userInfo.setUserId(regId);
ofy().save().entity(record).now();
ofy().save().entity(userInfo).now();
//TagUtil.recordEvent(1, "Welcome to Loqale!", userInfo);
}
/**
* Unregister a device from the backend
*
* @param regId The Google Cloud Messaging registration Id to remove
*/
@ApiMethod(name = "unregister")
public void unregisterDevice(@Named("regId") String regId) {
RegistrationRecord record = findRecord(regId);
if(record == null) {
log.info("Device " + regId + " not registered, skipping unregister");
return;
}
ofy().delete().entity(record).now();
}
/**
* Return a collection of registered devices
*
* @param count The number of devices to list
* @return a list of Google Cloud Messaging registration Ids
*/
@ApiMethod(name = "listDevices")
public Collection<RegistrationRecord> listDevices(@Named("count") int count) {
List<RegistrationRecord> records = ofy().load().type(RegistrationRecord.class).limit(count).list();
Collection<RegistrationRecord> col = new LinkedList<RegistrationRecord>();
col.addAll(records);
//return CollectionResponse.<RegistrationRecord>builder().setItems(records).build();
return col;
}
private RegistrationRecord findRecord(String regId) {
return ofy().load().type(RegistrationRecord.class).filter("regId", regId).first().now();
}
} | apache-2.0 |
yoelglus/presentation-patterns-using-rx | app/src/main/java/com/yoelglus/presentation/patterns/rmvp/RmvpAddItemActivity.java | 1979 | package com.yoelglus.presentation.patterns.rmvp;
import com.yoelglus.presentation.patterns.R;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import rx.Observable;
import static com.jakewharton.rxbinding.view.RxView.clicks;
import static com.jakewharton.rxbinding.widget.RxTextView.textChangeEvents;
import static com.memoizrlabs.Shank.provideNew;
public class RmvpAddItemActivity extends AppCompatActivity implements AddItemPresenter.View {
private AddItemPresenter presenter;
private View addButton;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
presenter = provideNew(AddItemPresenter.class, this);
setContentView(R.layout.activity_add_item);
addButton = findViewById(R.id.add_button);
presenter.takeView(this);
}
@Override
protected void onStop() {
super.onStop();
presenter.dropView(this);
}
@Override
public void setAddButtonEnabled(boolean enabled) {
addButton.setEnabled(enabled);
}
@Override
public Observable<String> contentTextChanged() {
return getObservableForTextView(R.id.content);
}
@Override
public Observable<String> detailTextChanged() {
return getObservableForTextView(R.id.detail);
}
@Override
public Observable<Void> addButtonClicks() {
return clicks(addButton);
}
@Override
public Observable<Void> cancelButtonClicks() {
return clicks(findViewById(R.id.cancel_button));
}
@NonNull
private Observable<String> getObservableForTextView(int viewId) {
return textChangeEvents((TextView) findViewById(viewId))
.map(textViewTextChangeEvent -> textViewTextChangeEvent.text().toString());
}
}
| apache-2.0 |
martinpiz097/genericServer | src/org/martin/defaultServer/interfaces/Receivable.java | 424 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.martin.defaultServer.interfaces;
import java.io.IOException;
/**
*
* @author martin
*/
@FunctionalInterface
public interface Receivable {
public Object getReceivedObject() throws IOException, ClassNotFoundException;
}
| apache-2.0 |
condast/AieonF | Workspace/org.aieonf.concept/src/org/aieonf/concept/context/IContextAieon.java | 2639 | package org.aieonf.concept.context;
import java.net.URI;
import org.aieonf.commons.strings.StringStyler;
import org.aieonf.concept.IConcept;
public interface IContextAieon extends IConcept
{
//The name of the root concept
public static final String S_APPLICATION = "Application";
public static final String S_DATABASE = "Database";
public static final String S_CONFIG = "config";
public static final String S_USER_HOME_PROPERTY = "user.home";
/**
* Specifies different types of locations.
* - Local: the context aieon is stored locally (e.g. within a plugin)
* - Application: the context aieon is stored in the application root
* - User: the context aieon is stored in a user directory
* - URI: the context is stored as a URI.
* @author keesp
*
*/
public enum LocationType
{
LOCAL,
APPLICATION,
USER,
URI;
@Override
public String toString() {
return StringStyler.prettyString( super.toString() );
}
}
/**
* The basic elements of an application aieon
*/
public enum Attributes
{
APPLICATION_NAME,
APPLICATION_ID,
APPLICATION_VERSION,
APPLICATION_DOMAIN,
CONTEXT,
LOCATION_TYPE,
ORGANISATION,
WEBSITE,
LICENSE;
@Override
public String toString() {
return StringStyler.prettyString( super.toString());
}
public static boolean isValid( String str ){
for( Attributes attr: values() ){
if( attr.name().equals( str ))
return true;
}
return false;
}
}
/**
* Get the application database
* @return
*/
public abstract String getApplicationDatabaseSource();
/**
* Get the name of the application
*
* @return String
*/
public abstract String getApplicationName();
/**
* Get the id of the application
*
* @return String
*/
public abstract String getApplicationID();
/**
* Get the version of the application
*
* @return String
*/
public abstract String getApplicationVersion();
/**
* Get the application domain. By default this is the bundle id.
*
* @return String
*/
public abstract String getApplicationDomain();
/**
* Get the context within the application
* @return
*/
public String getContext();
/**
* Get the user database source
* @return
*/
public URI getUserDatabaseSource();
/**
* Get the user database source
* @return
*/
public URI getNamedUserDatabaseSource( String name );
/**
* Get the user directory
*
* @return String
*/
public URI getUserDirectory();
public void verify() throws NullPointerException;
} | apache-2.0 |
yanzhijun/jclouds-aliyun | apis/openstack-trove/src/main/java/org/jclouds/openstack/trove/v1/domain/Flavor.java | 4164 | /*
* 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.jclouds.openstack.trove.v1.domain;
import java.beans.ConstructorProperties;
import java.util.List;
import org.jclouds.openstack.v2_0.domain.Link;
import com.google.common.base.Objects;
import com.google.common.base.Objects.ToStringHelper;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
/**
* An Openstack Trove Flavor.
*/
public class Flavor implements Comparable<Flavor>{
private final int id;
private final Optional<String> name;
private final int ram;
private final List<Link> links;
@ConstructorProperties({
"id", "name", "ram", "links"
})
protected Flavor(int id, String name, int ram, List<Link> links) {
this.id = id;
this.name = Optional.fromNullable(name);
this.ram = ram;
this.links = links;
}
/**
* @return the id of this flavor.
*/
public int getId() {
return this.id;
}
/**
* @return the name of this flavor.
*/
public String getName() {
return this.name.orNull();
}
/**
* @return the RAM amount for this flavor.
*/
public int getRam() {
return this.ram;
}
/**
* @return the flavor links for this flavor. These are used during database instance creation.
*/
public List<Link> getLinks() {
return this.links;
}
@Override
public int hashCode() {
return Objects.hashCode(id);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Flavor that = Flavor.class.cast(obj);
return Objects.equal(this.id, that.id);
}
protected ToStringHelper string() {
return Objects.toStringHelper(this)
.add("id", id).add("name", name).add("ram", ram);
}
@Override
public String toString() {
return string().toString();
}
@Override
public int compareTo(Flavor that) {
if (that == null)
return 1;
if (this == that)
return 0;
return this.getId() > that.getId() ? +1 : this.getId() < this.getId() ? -1 : 0;
}
public static Builder builder() {
return new Builder();
}
public Builder toBuilder() {
return new Builder().fromFlavor(this);
}
public static class Builder {
protected int id;
protected String name;
protected int ram;
protected List<Link> links;
/**
* @see Flavor#getId()
*/
public Builder id(int id) {
this.id = id;
return this;
}
/**
* @see Flavor#getName()
*/
public Builder name(String name) {
this.name = name;
return this;
}
/**
* @see Flavor#getRam()
*/
public Builder ram(int ram) {
this.ram = ram;
return this;
}
/**
* @see Flavor#getLinks()
*/
public Builder links(List<Link> links) {
this.links = ImmutableList.copyOf(links);
return this;
}
public Flavor build() {
return new Flavor(id, name, ram, links);
}
public Builder fromFlavor(Flavor in) {
return this
.id(in.getId())
.name(in.getName())
.ram(in.getRam())
.links(in.getLinks());
}
}
}
| apache-2.0 |
floodlight/loxigen-artifacts | openflowj/gen-src/main/java/org/projectfloodlight/openflow/protocol/ver15/OFBsnVlanCounterStatsRequestVer15.java | 15285 | // Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University
// Copyright (c) 2011, 2012 Open Networking Foundation
// Copyright (c) 2012, 2013 Big Switch Networks, Inc.
// This library was generated by the LoxiGen Compiler.
// See the file LICENSE.txt which should have been included in the source distribution
// Automatically generated by LOXI from template of_class.java
// Do not modify
package org.projectfloodlight.openflow.protocol.ver15;
import org.projectfloodlight.openflow.protocol.*;
import org.projectfloodlight.openflow.protocol.action.*;
import org.projectfloodlight.openflow.protocol.actionid.*;
import org.projectfloodlight.openflow.protocol.bsntlv.*;
import org.projectfloodlight.openflow.protocol.errormsg.*;
import org.projectfloodlight.openflow.protocol.meterband.*;
import org.projectfloodlight.openflow.protocol.instruction.*;
import org.projectfloodlight.openflow.protocol.instructionid.*;
import org.projectfloodlight.openflow.protocol.match.*;
import org.projectfloodlight.openflow.protocol.stat.*;
import org.projectfloodlight.openflow.protocol.oxm.*;
import org.projectfloodlight.openflow.protocol.oxs.*;
import org.projectfloodlight.openflow.protocol.queueprop.*;
import org.projectfloodlight.openflow.types.*;
import org.projectfloodlight.openflow.util.*;
import org.projectfloodlight.openflow.exceptions.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Set;
import com.google.common.collect.ImmutableSet;
import io.netty.buffer.ByteBuf;
import com.google.common.hash.PrimitiveSink;
import com.google.common.hash.Funnel;
class OFBsnVlanCounterStatsRequestVer15 implements OFBsnVlanCounterStatsRequest {
private static final Logger logger = LoggerFactory.getLogger(OFBsnVlanCounterStatsRequestVer15.class);
// version: 1.5
final static byte WIRE_VERSION = 6;
final static int LENGTH = 26;
private final static long DEFAULT_XID = 0x0L;
private final static Set<OFStatsRequestFlags> DEFAULT_FLAGS = ImmutableSet.<OFStatsRequestFlags>of();
private final static int DEFAULT_VLAN_VID = 0x0;
// OF message fields
private final long xid;
private final Set<OFStatsRequestFlags> flags;
private final int vlanVid;
//
// Immutable default instance
final static OFBsnVlanCounterStatsRequestVer15 DEFAULT = new OFBsnVlanCounterStatsRequestVer15(
DEFAULT_XID, DEFAULT_FLAGS, DEFAULT_VLAN_VID
);
// package private constructor - used by readers, builders, and factory
OFBsnVlanCounterStatsRequestVer15(long xid, Set<OFStatsRequestFlags> flags, int vlanVid) {
if(flags == null) {
throw new NullPointerException("OFBsnVlanCounterStatsRequestVer15: property flags cannot be null");
}
this.xid = U32.normalize(xid);
this.flags = flags;
this.vlanVid = U16.normalize(vlanVid);
}
// Accessors for OF message fields
@Override
public OFVersion getVersion() {
return OFVersion.OF_15;
}
@Override
public OFType getType() {
return OFType.STATS_REQUEST;
}
@Override
public long getXid() {
return xid;
}
@Override
public OFStatsType getStatsType() {
return OFStatsType.EXPERIMENTER;
}
@Override
public Set<OFStatsRequestFlags> getFlags() {
return flags;
}
@Override
public long getExperimenter() {
return 0x5c16c7L;
}
@Override
public long getSubtype() {
return 0x9L;
}
@Override
public int getVlanVid() {
return vlanVid;
}
public OFBsnVlanCounterStatsRequest.Builder createBuilder() {
return new BuilderWithParent(this);
}
static class BuilderWithParent implements OFBsnVlanCounterStatsRequest.Builder {
final OFBsnVlanCounterStatsRequestVer15 parentMessage;
// OF message fields
private boolean xidSet;
private long xid;
private boolean flagsSet;
private Set<OFStatsRequestFlags> flags;
private boolean vlanVidSet;
private int vlanVid;
BuilderWithParent(OFBsnVlanCounterStatsRequestVer15 parentMessage) {
this.parentMessage = parentMessage;
}
@Override
public OFVersion getVersion() {
return OFVersion.OF_15;
}
@Override
public OFType getType() {
return OFType.STATS_REQUEST;
}
@Override
public long getXid() {
return xid;
}
@Override
public OFBsnVlanCounterStatsRequest.Builder setXid(long xid) {
this.xid = xid;
this.xidSet = true;
return this;
}
@Override
public OFStatsType getStatsType() {
return OFStatsType.EXPERIMENTER;
}
@Override
public Set<OFStatsRequestFlags> getFlags() {
return flags;
}
@Override
public OFBsnVlanCounterStatsRequest.Builder setFlags(Set<OFStatsRequestFlags> flags) {
this.flags = flags;
this.flagsSet = true;
return this;
}
@Override
public long getExperimenter() {
return 0x5c16c7L;
}
@Override
public long getSubtype() {
return 0x9L;
}
@Override
public int getVlanVid() {
return vlanVid;
}
@Override
public OFBsnVlanCounterStatsRequest.Builder setVlanVid(int vlanVid) {
this.vlanVid = vlanVid;
this.vlanVidSet = true;
return this;
}
@Override
public OFBsnVlanCounterStatsRequest build() {
long xid = this.xidSet ? this.xid : parentMessage.xid;
Set<OFStatsRequestFlags> flags = this.flagsSet ? this.flags : parentMessage.flags;
if(flags == null)
throw new NullPointerException("Property flags must not be null");
int vlanVid = this.vlanVidSet ? this.vlanVid : parentMessage.vlanVid;
//
return new OFBsnVlanCounterStatsRequestVer15(
xid,
flags,
vlanVid
);
}
}
static class Builder implements OFBsnVlanCounterStatsRequest.Builder {
// OF message fields
private boolean xidSet;
private long xid;
private boolean flagsSet;
private Set<OFStatsRequestFlags> flags;
private boolean vlanVidSet;
private int vlanVid;
@Override
public OFVersion getVersion() {
return OFVersion.OF_15;
}
@Override
public OFType getType() {
return OFType.STATS_REQUEST;
}
@Override
public long getXid() {
return xid;
}
@Override
public OFBsnVlanCounterStatsRequest.Builder setXid(long xid) {
this.xid = xid;
this.xidSet = true;
return this;
}
@Override
public OFStatsType getStatsType() {
return OFStatsType.EXPERIMENTER;
}
@Override
public Set<OFStatsRequestFlags> getFlags() {
return flags;
}
@Override
public OFBsnVlanCounterStatsRequest.Builder setFlags(Set<OFStatsRequestFlags> flags) {
this.flags = flags;
this.flagsSet = true;
return this;
}
@Override
public long getExperimenter() {
return 0x5c16c7L;
}
@Override
public long getSubtype() {
return 0x9L;
}
@Override
public int getVlanVid() {
return vlanVid;
}
@Override
public OFBsnVlanCounterStatsRequest.Builder setVlanVid(int vlanVid) {
this.vlanVid = vlanVid;
this.vlanVidSet = true;
return this;
}
//
@Override
public OFBsnVlanCounterStatsRequest build() {
long xid = this.xidSet ? this.xid : DEFAULT_XID;
Set<OFStatsRequestFlags> flags = this.flagsSet ? this.flags : DEFAULT_FLAGS;
if(flags == null)
throw new NullPointerException("Property flags must not be null");
int vlanVid = this.vlanVidSet ? this.vlanVid : DEFAULT_VLAN_VID;
return new OFBsnVlanCounterStatsRequestVer15(
xid,
flags,
vlanVid
);
}
}
final static Reader READER = new Reader();
static class Reader implements OFMessageReader<OFBsnVlanCounterStatsRequest> {
@Override
public OFBsnVlanCounterStatsRequest readFrom(ByteBuf bb) throws OFParseError {
int start = bb.readerIndex();
// fixed value property version == 6
byte version = bb.readByte();
if(version != (byte) 0x6)
throw new OFParseError("Wrong version: Expected=OFVersion.OF_15(6), got="+version);
// fixed value property type == 18
byte type = bb.readByte();
if(type != (byte) 0x12)
throw new OFParseError("Wrong type: Expected=OFType.STATS_REQUEST(18), got="+type);
int length = U16.f(bb.readShort());
if(length != 26)
throw new OFParseError("Wrong length: Expected=26(26), got="+length);
if(bb.readableBytes() + (bb.readerIndex() - start) < length) {
// Buffer does not have all data yet
bb.readerIndex(start);
return null;
}
if(logger.isTraceEnabled())
logger.trace("readFrom - length={}", length);
long xid = U32.f(bb.readInt());
// fixed value property statsType == 65535
short statsType = bb.readShort();
if(statsType != (short) 0xffff)
throw new OFParseError("Wrong statsType: Expected=OFStatsType.EXPERIMENTER(65535), got="+statsType);
Set<OFStatsRequestFlags> flags = OFStatsRequestFlagsSerializerVer15.readFrom(bb);
// pad: 4 bytes
bb.skipBytes(4);
// fixed value property experimenter == 0x5c16c7L
int experimenter = bb.readInt();
if(experimenter != 0x5c16c7)
throw new OFParseError("Wrong experimenter: Expected=0x5c16c7L(0x5c16c7L), got="+experimenter);
// fixed value property subtype == 0x9L
int subtype = bb.readInt();
if(subtype != 0x9)
throw new OFParseError("Wrong subtype: Expected=0x9L(0x9L), got="+subtype);
int vlanVid = U16.f(bb.readShort());
OFBsnVlanCounterStatsRequestVer15 bsnVlanCounterStatsRequestVer15 = new OFBsnVlanCounterStatsRequestVer15(
xid,
flags,
vlanVid
);
if(logger.isTraceEnabled())
logger.trace("readFrom - read={}", bsnVlanCounterStatsRequestVer15);
return bsnVlanCounterStatsRequestVer15;
}
}
public void putTo(PrimitiveSink sink) {
FUNNEL.funnel(this, sink);
}
final static OFBsnVlanCounterStatsRequestVer15Funnel FUNNEL = new OFBsnVlanCounterStatsRequestVer15Funnel();
static class OFBsnVlanCounterStatsRequestVer15Funnel implements Funnel<OFBsnVlanCounterStatsRequestVer15> {
private static final long serialVersionUID = 1L;
@Override
public void funnel(OFBsnVlanCounterStatsRequestVer15 message, PrimitiveSink sink) {
// fixed value property version = 6
sink.putByte((byte) 0x6);
// fixed value property type = 18
sink.putByte((byte) 0x12);
// fixed value property length = 26
sink.putShort((short) 0x1a);
sink.putLong(message.xid);
// fixed value property statsType = 65535
sink.putShort((short) 0xffff);
OFStatsRequestFlagsSerializerVer15.putTo(message.flags, sink);
// skip pad (4 bytes)
// fixed value property experimenter = 0x5c16c7L
sink.putInt(0x5c16c7);
// fixed value property subtype = 0x9L
sink.putInt(0x9);
sink.putInt(message.vlanVid);
}
}
public void writeTo(ByteBuf bb) {
WRITER.write(bb, this);
}
final static Writer WRITER = new Writer();
static class Writer implements OFMessageWriter<OFBsnVlanCounterStatsRequestVer15> {
@Override
public void write(ByteBuf bb, OFBsnVlanCounterStatsRequestVer15 message) {
// fixed value property version = 6
bb.writeByte((byte) 0x6);
// fixed value property type = 18
bb.writeByte((byte) 0x12);
// fixed value property length = 26
bb.writeShort((short) 0x1a);
bb.writeInt(U32.t(message.xid));
// fixed value property statsType = 65535
bb.writeShort((short) 0xffff);
OFStatsRequestFlagsSerializerVer15.writeTo(bb, message.flags);
// pad: 4 bytes
bb.writeZero(4);
// fixed value property experimenter = 0x5c16c7L
bb.writeInt(0x5c16c7);
// fixed value property subtype = 0x9L
bb.writeInt(0x9);
bb.writeShort(U16.t(message.vlanVid));
}
}
@Override
public String toString() {
StringBuilder b = new StringBuilder("OFBsnVlanCounterStatsRequestVer15(");
b.append("xid=").append(xid);
b.append(", ");
b.append("flags=").append(flags);
b.append(", ");
b.append("vlanVid=").append(vlanVid);
b.append(")");
return b.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
OFBsnVlanCounterStatsRequestVer15 other = (OFBsnVlanCounterStatsRequestVer15) obj;
if( xid != other.xid)
return false;
if (flags == null) {
if (other.flags != null)
return false;
} else if (!flags.equals(other.flags))
return false;
if( vlanVid != other.vlanVid)
return false;
return true;
}
@Override
public boolean equalsIgnoreXid(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
OFBsnVlanCounterStatsRequestVer15 other = (OFBsnVlanCounterStatsRequestVer15) obj;
// ignore XID
if (flags == null) {
if (other.flags != null)
return false;
} else if (!flags.equals(other.flags))
return false;
if( vlanVid != other.vlanVid)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * (int) (xid ^ (xid >>> 32));
result = prime * result + ((flags == null) ? 0 : flags.hashCode());
result = prime * result + vlanVid;
return result;
}
@Override
public int hashCodeIgnoreXid() {
final int prime = 31;
int result = 1;
// ignore XID
result = prime * result + ((flags == null) ? 0 : flags.hashCode());
result = prime * result + vlanVid;
return result;
}
}
| apache-2.0 |
googleapis/java-bigquerymigration | proto-google-cloud-bigquerymigration-v2alpha/src/main/java/com/google/cloud/bigquery/migration/v2alpha/AssessmentTaskDetailsOrBuilder.java | 3531 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/bigquery/migration/v2alpha/assessment_task.proto
package com.google.cloud.bigquery.migration.v2alpha;
public interface AssessmentTaskDetailsOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.cloud.bigquery.migration.v2alpha.AssessmentTaskDetails)
com.google.protobuf.MessageOrBuilder {
/**
*
*
* <pre>
* Required. The Cloud Storage path for assessment input files.
* </pre>
*
* <code>string input_path = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The inputPath.
*/
java.lang.String getInputPath();
/**
*
*
* <pre>
* Required. The Cloud Storage path for assessment input files.
* </pre>
*
* <code>string input_path = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for inputPath.
*/
com.google.protobuf.ByteString getInputPathBytes();
/**
*
*
* <pre>
* Required. The BigQuery dataset for output.
* </pre>
*
* <code>string output_dataset = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The outputDataset.
*/
java.lang.String getOutputDataset();
/**
*
*
* <pre>
* Required. The BigQuery dataset for output.
* </pre>
*
* <code>string output_dataset = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for outputDataset.
*/
com.google.protobuf.ByteString getOutputDatasetBytes();
/**
*
*
* <pre>
* Optional. An optional Cloud Storage path to write the query logs (which is
* then used as an input path on the translation task)
* </pre>
*
* <code>string querylogs_path = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The querylogsPath.
*/
java.lang.String getQuerylogsPath();
/**
*
*
* <pre>
* Optional. An optional Cloud Storage path to write the query logs (which is
* then used as an input path on the translation task)
* </pre>
*
* <code>string querylogs_path = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for querylogsPath.
*/
com.google.protobuf.ByteString getQuerylogsPathBytes();
/**
*
*
* <pre>
* Required. The data source or data warehouse type (eg: TERADATA/REDSHIFT)
* from which the input data is extracted.
* </pre>
*
* <code>string data_source = 4 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The dataSource.
*/
java.lang.String getDataSource();
/**
*
*
* <pre>
* Required. The data source or data warehouse type (eg: TERADATA/REDSHIFT)
* from which the input data is extracted.
* </pre>
*
* <code>string data_source = 4 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for dataSource.
*/
com.google.protobuf.ByteString getDataSourceBytes();
}
| apache-2.0 |
jwcarman/akka-introduction | java/src/test/java/com/carmanconsulting/akka/HelloAkkaTest.java | 344 | package com.carmanconsulting.akka;
import akka.actor.ActorRef;
import org.junit.Test;
public class HelloAkkaTest extends AkkaTestCase {
@Test
public void testHelloAkka() {
ActorRef hello = system().actorOf(HelloAkka.props(), "hello");
hello.tell("Akka", testActor());
expectMsgEquals("Hello, Akka!");
}
}
| apache-2.0 |
joewalnes/idea-community | java/java-tests/testSrc/com/intellij/refactoring/MockIntroduceFieldHandler.java | 1476 | package com.intellij.refactoring;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.codeStyle.SuggestedNameInfo;
import com.intellij.psi.codeStyle.VariableKind;
import com.intellij.refactoring.introduceField.IntroduceFieldHandler;
/**
* @author ven
*/
public class MockIntroduceFieldHandler extends IntroduceFieldHandler {
private final InitializationPlace myInitializationPlace;
private final boolean myDeclareStatic;
public MockIntroduceFieldHandler(final InitializationPlace initializationPlace, final boolean declareStatic) {
myInitializationPlace = initializationPlace;
myDeclareStatic = declareStatic;
}
@Override
protected Settings showRefactoringDialog(Project project, Editor editor, PsiClass parentClass, PsiExpression expr, PsiType type,
PsiExpression[] occurences, PsiElement anchorElement, PsiElement anchorElementIfAll) {
SuggestedNameInfo name = JavaCodeStyleManager.getInstance(project).suggestVariableName(VariableKind.FIELD, null, expr, type);
return new Settings(name.names[0], true, myDeclareStatic, true, myInitializationPlace,
PsiModifier.PUBLIC,
null,
getFieldType(type), true, (TargetDestination)null, false, false);
}
protected PsiType getFieldType(PsiType type) {
return type;
}
}
| apache-2.0 |
yelshater/hadoop-2.3.0 | hadoop-yarn-server-resourcemanager-2.3.0-cdh5.1.0/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fifo/FifoScheduler.java | 36422 | /**
* 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.fifo;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.classification.InterfaceAudience.LimitedPrivate;
import org.apache.hadoop.classification.InterfaceStability.Evolving;
import org.apache.hadoop.conf.Configurable;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.authorize.AccessControlList;
import org.apache.hadoop.yarn.api.records.ApplicationAttemptId;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.ApplicationResourceUsageReport;
import org.apache.hadoop.yarn.api.records.Container;
import org.apache.hadoop.yarn.api.records.ContainerId;
import org.apache.hadoop.yarn.api.records.ContainerStatus;
import org.apache.hadoop.yarn.api.records.NodeId;
import org.apache.hadoop.yarn.api.records.Priority;
import org.apache.hadoop.yarn.api.records.QueueACL;
import org.apache.hadoop.yarn.api.records.QueueInfo;
import org.apache.hadoop.yarn.api.records.QueueState;
import org.apache.hadoop.yarn.api.records.QueueUserACLInfo;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.api.records.ResourceRequest;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.exceptions.YarnRuntimeException;
import org.apache.hadoop.yarn.factories.RecordFactory;
import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider;
import org.apache.hadoop.yarn.server.resourcemanager.RMAuditLogger;
import org.apache.hadoop.yarn.server.resourcemanager.RMAuditLogger.AuditConstants;
import org.apache.hadoop.yarn.server.resourcemanager.RMContext;
import org.apache.hadoop.yarn.server.resourcemanager.recovery.RMStateStore.RMState;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppEvent;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppEventType;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppState;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptEvent;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptEventType;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptState;
import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer;
import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerEventType;
import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerState;
import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode;
import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNodeCleanContainerEvent;
import org.apache.hadoop.yarn.server.resourcemanager.rmnode.UpdatedContainerInfo;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.AbstractYarnScheduler;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ActiveUsersManager;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.Allocation;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.NodeType;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.Queue;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.QueueMetrics;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerAppReport;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerAppUtils;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerApplication;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerApplicationAttempt.ContainersAndNMTokensAllocation;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerNodeReport;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerUtils;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.fica.FiCaSchedulerApp;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.fica.FiCaSchedulerNode;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.AppAddedSchedulerEvent;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.AppAttemptAddedSchedulerEvent;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.AppAttemptRemovedSchedulerEvent;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.AppRemovedSchedulerEvent;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.ContainerExpiredSchedulerEvent;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeAddedSchedulerEvent;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeRemovedSchedulerEvent;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeUpdateSchedulerEvent;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.SchedulerEvent;
import org.apache.hadoop.yarn.server.utils.BuilderUtils;
import org.apache.hadoop.yarn.server.utils.Lock;
import org.apache.hadoop.yarn.util.resource.DefaultResourceCalculator;
import org.apache.hadoop.yarn.util.resource.ResourceCalculator;
import org.apache.hadoop.yarn.util.resource.Resources;
import com.google.common.annotations.VisibleForTesting;
@LimitedPrivate("yarn")
@Evolving
@SuppressWarnings("unchecked")
public class FifoScheduler extends AbstractYarnScheduler implements
Configurable {
private static final Log LOG = LogFactory.getLog(FifoScheduler.class);
private static final RecordFactory recordFactory =
RecordFactoryProvider.getRecordFactory(null);
Configuration conf;
protected Map<NodeId, FiCaSchedulerNode> nodes = new ConcurrentHashMap<NodeId, FiCaSchedulerNode>();
private boolean initialized;
private Resource minimumAllocation;
private Resource maximumAllocation;
private boolean usePortForNodeName;
private ActiveUsersManager activeUsersManager;
private static final String DEFAULT_QUEUE_NAME = "default";
private QueueMetrics metrics;
private final ResourceCalculator resourceCalculator = new DefaultResourceCalculator();
private final Queue DEFAULT_QUEUE = new Queue() {
@Override
public String getQueueName() {
return DEFAULT_QUEUE_NAME;
}
@Override
public QueueMetrics getMetrics() {
return metrics;
}
@Override
public QueueInfo getQueueInfo(
boolean includeChildQueues, boolean recursive) {
QueueInfo queueInfo = recordFactory.newRecordInstance(QueueInfo.class);
queueInfo.setQueueName(DEFAULT_QUEUE.getQueueName());
queueInfo.setCapacity(1.0f);
if (clusterResource.getMemory() == 0) {
queueInfo.setCurrentCapacity(0.0f);
} else {
queueInfo.setCurrentCapacity((float) usedResource.getMemory()
/ clusterResource.getMemory());
}
queueInfo.setMaximumCapacity(1.0f);
queueInfo.setChildQueues(new ArrayList<QueueInfo>());
queueInfo.setQueueState(QueueState.RUNNING);
return queueInfo;
}
public Map<QueueACL, AccessControlList> getQueueAcls() {
Map<QueueACL, AccessControlList> acls =
new HashMap<QueueACL, AccessControlList>();
for (QueueACL acl : QueueACL.values()) {
acls.put(acl, new AccessControlList("*"));
}
return acls;
}
@Override
public List<QueueUserACLInfo> getQueueUserAclInfo(
UserGroupInformation unused) {
QueueUserACLInfo queueUserAclInfo =
recordFactory.newRecordInstance(QueueUserACLInfo.class);
queueUserAclInfo.setQueueName(DEFAULT_QUEUE_NAME);
queueUserAclInfo.setUserAcls(Arrays.asList(QueueACL.values()));
return Collections.singletonList(queueUserAclInfo);
}
@Override
public boolean hasAccess(QueueACL acl, UserGroupInformation user) {
return getQueueAcls().get(acl).isUserAllowed(user);
}
@Override
public ActiveUsersManager getActiveUsersManager() {
return activeUsersManager;
}
};
@Override
public synchronized void setConf(Configuration conf) {
this.conf = conf;
}
private void validateConf(Configuration conf) {
// validate scheduler memory allocation setting
int minMem = conf.getInt(
YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_MB,
YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_MB);
int maxMem = conf.getInt(
YarnConfiguration.RM_SCHEDULER_MAXIMUM_ALLOCATION_MB,
YarnConfiguration.DEFAULT_RM_SCHEDULER_MAXIMUM_ALLOCATION_MB);
if (minMem <= 0 || minMem > maxMem) {
throw new YarnRuntimeException("Invalid resource scheduler memory"
+ " allocation configuration"
+ ", " + YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_MB
+ "=" + minMem
+ ", " + YarnConfiguration.RM_SCHEDULER_MAXIMUM_ALLOCATION_MB
+ "=" + maxMem + ", min and max should be greater than 0"
+ ", max should be no smaller than min.");
}
}
@Override
public synchronized Configuration getConf() {
return conf;
}
@Override
public Resource getMinimumResourceCapability() {
return minimumAllocation;
}
@Override
public int getNumClusterNodes() {
return nodes.size();
}
@Override
public Resource getMaximumResourceCapability() {
return maximumAllocation;
}
@Override
public synchronized void
reinitialize(Configuration conf, RMContext rmContext) throws IOException
{
setConf(conf);
if (!this.initialized) {
validateConf(conf);
this.rmContext = rmContext;
//Use ConcurrentSkipListMap because applications need to be ordered
this.applications =
new ConcurrentSkipListMap<ApplicationId, SchedulerApplication>();
this.minimumAllocation =
Resources.createResource(conf.getInt(
YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_MB,
YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_MB));
this.maximumAllocation =
Resources.createResource(conf.getInt(
YarnConfiguration.RM_SCHEDULER_MAXIMUM_ALLOCATION_MB,
YarnConfiguration.DEFAULT_RM_SCHEDULER_MAXIMUM_ALLOCATION_MB));
this.usePortForNodeName = conf.getBoolean(
YarnConfiguration.RM_SCHEDULER_INCLUDE_PORT_IN_NODE_NAME,
YarnConfiguration.DEFAULT_RM_SCHEDULER_USE_PORT_FOR_NODE_NAME);
this.metrics = QueueMetrics.forQueue(DEFAULT_QUEUE_NAME, null, false,
conf);
this.activeUsersManager = new ActiveUsersManager(metrics);
this.initialized = true;
}
}
@Override
public Allocation allocate(
ApplicationAttemptId applicationAttemptId, List<ResourceRequest> ask,
List<ContainerId> release, List<String> blacklistAdditions, List<String> blacklistRemovals) {
FiCaSchedulerApp application = getApplicationAttempt(applicationAttemptId);
if (application == null) {
LOG.error("Calling allocate on removed " +
"or non existant application " + applicationAttemptId);
return EMPTY_ALLOCATION;
}
// Sanity check
SchedulerUtils.normalizeRequests(ask, resourceCalculator,
clusterResource, minimumAllocation, maximumAllocation);
// Release containers
for (ContainerId releasedContainer : release) {
RMContainer rmContainer = getRMContainer(releasedContainer);
if (rmContainer == null) {
RMAuditLogger.logFailure(application.getUser(),
AuditConstants.RELEASE_CONTAINER,
"Unauthorized access or invalid container", "FifoScheduler",
"Trying to release container not owned by app or with invalid id",
application.getApplicationId(), releasedContainer);
}
containerCompleted(rmContainer,
SchedulerUtils.createAbnormalContainerStatus(
releasedContainer,
SchedulerUtils.RELEASED_CONTAINER),
RMContainerEventType.RELEASED);
}
synchronized (application) {
// make sure we aren't stopping/removing the application
// when the allocate comes in
if (application.isStopped()) {
LOG.info("Calling allocate on a stopped " +
"application " + applicationAttemptId);
return EMPTY_ALLOCATION;
}
if (!ask.isEmpty()) {
LOG.debug("allocate: pre-update" +
" applicationId=" + applicationAttemptId +
" application=" + application);
application.showRequests();
// Update application requests
application.updateResourceRequests(ask);
LOG.debug("allocate: post-update" +
" applicationId=" + applicationAttemptId +
" application=" + application);
application.showRequests();
LOG.debug("allocate:" +
" applicationId=" + applicationAttemptId +
" #ask=" + ask.size());
}
application.updateBlacklist(blacklistAdditions, blacklistRemovals);
ContainersAndNMTokensAllocation allocation =
application.pullNewlyAllocatedContainersAndNMTokens();
return new Allocation(allocation.getContainerList(),
application.getHeadroom(), null, null, null,
allocation.getNMTokenList());
}
}
@VisibleForTesting
FiCaSchedulerApp getApplicationAttempt(ApplicationAttemptId applicationAttemptId) {
SchedulerApplication app =
applications.get(applicationAttemptId.getApplicationId());
if (app != null) {
return (FiCaSchedulerApp) app.getCurrentAppAttempt();
}
return null;
}
@Override
public SchedulerAppReport getSchedulerAppInfo(
ApplicationAttemptId applicationAttemptId) {
FiCaSchedulerApp app = getApplicationAttempt(applicationAttemptId);
return app == null ? null : new SchedulerAppReport(app);
}
@Override
public ApplicationResourceUsageReport getAppResourceUsageReport(
ApplicationAttemptId applicationAttemptId) {
FiCaSchedulerApp app = getApplicationAttempt(applicationAttemptId);
return app == null ? null : app.getResourceUsageReport();
}
private FiCaSchedulerNode getNode(NodeId nodeId) {
return nodes.get(nodeId);
}
private synchronized void addApplication(ApplicationId applicationId,
String queue, String user) {
SchedulerApplication application =
new SchedulerApplication(DEFAULT_QUEUE, user);
applications.put(applicationId, application);
metrics.submitApp(user);
LOG.info("Accepted application " + applicationId + " from user: " + user
+ ", currently num of applications: " + applications.size());
rmContext.getDispatcher().getEventHandler()
.handle(new RMAppEvent(applicationId, RMAppEventType.APP_ACCEPTED));
}
private synchronized void
addApplicationAttempt(ApplicationAttemptId appAttemptId,
boolean transferStateFromPreviousAttempt) {
SchedulerApplication application =
applications.get(appAttemptId.getApplicationId());
String user = application.getUser();
// TODO: Fix store
FiCaSchedulerApp schedulerApp =
new FiCaSchedulerApp(appAttemptId, user, DEFAULT_QUEUE,
activeUsersManager, this.rmContext);
if (transferStateFromPreviousAttempt) {
schedulerApp.transferStateFromPreviousAttempt(application
.getCurrentAppAttempt());
}
application.setCurrentAppAttempt(schedulerApp);
metrics.submitAppAttempt(user);
LOG.info("Added Application Attempt " + appAttemptId
+ " to scheduler from user " + application.getUser());
rmContext.getDispatcher().getEventHandler().handle(
new RMAppAttemptEvent(appAttemptId,
RMAppAttemptEventType.ATTEMPT_ADDED));
}
private synchronized void doneApplication(ApplicationId applicationId,
RMAppState finalState) {
SchedulerApplication application = applications.get(applicationId);
if (application == null){
LOG.warn("Couldn't find application " + applicationId);
return;
}
// Inform the activeUsersManager
activeUsersManager.deactivateApplication(application.getUser(),
applicationId);
application.stop(finalState);
applications.remove(applicationId);
}
private synchronized void doneApplicationAttempt(
ApplicationAttemptId applicationAttemptId,
RMAppAttemptState rmAppAttemptFinalState, boolean keepContainers)
throws IOException {
FiCaSchedulerApp attempt = getApplicationAttempt(applicationAttemptId);
SchedulerApplication application =
applications.get(applicationAttemptId.getApplicationId());
if (application == null || attempt == null) {
throw new IOException("Unknown application " + applicationAttemptId +
" has completed!");
}
// Kill all 'live' containers
for (RMContainer container : attempt.getLiveContainers()) {
if (keepContainers
&& container.getState().equals(RMContainerState.RUNNING)) {
// do not kill the running container in the case of work-preserving AM
// restart.
LOG.info("Skip killing " + container.getContainerId());
continue;
}
containerCompleted(container,
SchedulerUtils.createAbnormalContainerStatus(
container.getContainerId(), SchedulerUtils.COMPLETED_APPLICATION),
RMContainerEventType.KILL);
}
// Clean up pending requests, metrics etc.
attempt.stop(rmAppAttemptFinalState);
}
/**
* Heart of the scheduler...
*
* @param node node on which resources are available to be allocated
*/
private void assignContainers(FiCaSchedulerNode node) {
LOG.debug("assignContainers:" +
" node=" + node.getRMNode().getNodeAddress() +
" #applications=" + applications.size());
// Try to assign containers to applications in fifo order
for (Map.Entry<ApplicationId, SchedulerApplication> e : applications
.entrySet()) {
FiCaSchedulerApp application =
(FiCaSchedulerApp) e.getValue().getCurrentAppAttempt();
LOG.debug("pre-assignContainers");
application.showRequests();
synchronized (application) {
// Check if this resource is on the blacklist
if (SchedulerAppUtils.isBlacklisted(application, node, LOG)) {
continue;
}
for (Priority priority : application.getPriorities()) {
int maxContainers =
getMaxAllocatableContainers(application, priority, node,
NodeType.OFF_SWITCH);
// Ensure the application needs containers of this priority
if (maxContainers > 0) {
int assignedContainers =
assignContainersOnNode(node, application, priority);
// Do not assign out of order w.r.t priorities
if (assignedContainers == 0) {
break;
}
}
}
}
LOG.debug("post-assignContainers");
application.showRequests();
// Done
if (Resources.lessThan(resourceCalculator, clusterResource,
node.getAvailableResource(), minimumAllocation)) {
break;
}
}
// Update the applications' headroom to correctly take into
// account the containers assigned in this update.
for (SchedulerApplication application : applications.values()) {
FiCaSchedulerApp attempt =
(FiCaSchedulerApp) application.getCurrentAppAttempt();
attempt.setHeadroom(Resources.subtract(clusterResource, usedResource));
}
}
private int getMaxAllocatableContainers(FiCaSchedulerApp application,
Priority priority, FiCaSchedulerNode node, NodeType type) {
ResourceRequest offSwitchRequest =
application.getResourceRequest(priority, ResourceRequest.ANY);
int maxContainers = offSwitchRequest.getNumContainers();
if (type == NodeType.OFF_SWITCH) {
return maxContainers;
}
if (type == NodeType.RACK_LOCAL) {
ResourceRequest rackLocalRequest =
application.getResourceRequest(priority, node.getRMNode().getRackName());
if (rackLocalRequest == null) {
return maxContainers;
}
maxContainers = Math.min(maxContainers, rackLocalRequest.getNumContainers());
}
if (type == NodeType.NODE_LOCAL) {
ResourceRequest nodeLocalRequest =
application.getResourceRequest(priority, node.getRMNode().getNodeAddress());
if (nodeLocalRequest != null) {
maxContainers = Math.min(maxContainers, nodeLocalRequest.getNumContainers());
}
}
return maxContainers;
}
private int assignContainersOnNode(FiCaSchedulerNode node,
FiCaSchedulerApp application, Priority priority
) {
// Data-local
int nodeLocalContainers =
assignNodeLocalContainers(node, application, priority);
// Rack-local
int rackLocalContainers =
assignRackLocalContainers(node, application, priority);
// Off-switch
int offSwitchContainers =
assignOffSwitchContainers(node, application, priority);
LOG.debug("assignContainersOnNode:" +
" node=" + node.getRMNode().getNodeAddress() +
" application=" + application.getApplicationId().getId() +
" priority=" + priority.getPriority() +
" #assigned=" +
(nodeLocalContainers + rackLocalContainers + offSwitchContainers));
return (nodeLocalContainers + rackLocalContainers + offSwitchContainers);
}
private int assignNodeLocalContainers(FiCaSchedulerNode node,
FiCaSchedulerApp application, Priority priority) {
int assignedContainers = 0;
ResourceRequest request =
application.getResourceRequest(priority, node.getNodeName());
if (request != null) {
// Don't allocate on this node if we don't need containers on this rack
ResourceRequest rackRequest =
application.getResourceRequest(priority,
node.getRMNode().getRackName());
if (rackRequest == null || rackRequest.getNumContainers() <= 0) {
return 0;
}
int assignableContainers =
Math.min(
getMaxAllocatableContainers(application, priority, node,
NodeType.NODE_LOCAL),
request.getNumContainers());
assignedContainers =
assignContainer(node, application, priority,
assignableContainers, request, NodeType.NODE_LOCAL);
}
return assignedContainers;
}
private int assignRackLocalContainers(FiCaSchedulerNode node,
FiCaSchedulerApp application, Priority priority) {
int assignedContainers = 0;
ResourceRequest request =
application.getResourceRequest(priority, node.getRMNode().getRackName());
if (request != null) {
// Don't allocate on this rack if the application doens't need containers
ResourceRequest offSwitchRequest =
application.getResourceRequest(priority, ResourceRequest.ANY);
if (offSwitchRequest.getNumContainers() <= 0) {
return 0;
}
int assignableContainers =
Math.min(
getMaxAllocatableContainers(application, priority, node,
NodeType.RACK_LOCAL),
request.getNumContainers());
assignedContainers =
assignContainer(node, application, priority,
assignableContainers, request, NodeType.RACK_LOCAL);
}
return assignedContainers;
}
private int assignOffSwitchContainers(FiCaSchedulerNode node,
FiCaSchedulerApp application, Priority priority) {
int assignedContainers = 0;
ResourceRequest request =
application.getResourceRequest(priority, ResourceRequest.ANY);
if (request != null) {
assignedContainers =
assignContainer(node, application, priority,
request.getNumContainers(), request, NodeType.OFF_SWITCH);
}
return assignedContainers;
}
private int assignContainer(FiCaSchedulerNode node, FiCaSchedulerApp application,
Priority priority, int assignableContainers,
ResourceRequest request, NodeType type) {
LOG.debug("assignContainers:" +
" node=" + node.getRMNode().getNodeAddress() +
" application=" + application.getApplicationId().getId() +
" priority=" + priority.getPriority() +
" assignableContainers=" + assignableContainers +
" request=" + request + " type=" + type);
Resource capability = request.getCapability();
int availableContainers =
node.getAvailableResource().getMemory() / capability.getMemory(); // TODO: A buggy
// application
// with this
// zero would
// crash the
// scheduler.
int assignedContainers =
Math.min(assignableContainers, availableContainers);
if (assignedContainers > 0) {
for (int i=0; i < assignedContainers; ++i) {
NodeId nodeId = node.getRMNode().getNodeID();
ContainerId containerId = BuilderUtils.newContainerId(application
.getApplicationAttemptId(), application.getNewContainerId());
// Create the container
Container container =
BuilderUtils.newContainer(containerId, nodeId, node.getRMNode()
.getHttpAddress(), capability, priority, null);
// Allocate!
// Inform the application
RMContainer rmContainer =
application.allocate(type, node, priority, request, container);
// Inform the node
node.allocateContainer(application.getApplicationId(),
rmContainer);
// Update usage for this container
Resources.addTo(usedResource, capability);
}
}
return assignedContainers;
}
private synchronized void nodeUpdate(RMNode rmNode) {
FiCaSchedulerNode node = getNode(rmNode.getNodeID());
// Update resource if any change
SchedulerUtils.updateResourceIfChanged(node, rmNode, clusterResource, LOG);
List<UpdatedContainerInfo> containerInfoList = rmNode.pullContainerUpdates();
List<ContainerStatus> newlyLaunchedContainers = new ArrayList<ContainerStatus>();
List<ContainerStatus> completedContainers = new ArrayList<ContainerStatus>();
for(UpdatedContainerInfo containerInfo : containerInfoList) {
newlyLaunchedContainers.addAll(containerInfo.getNewlyLaunchedContainers());
completedContainers.addAll(containerInfo.getCompletedContainers());
}
// Processing the newly launched containers
for (ContainerStatus launchedContainer : newlyLaunchedContainers) {
containerLaunchedOnNode(launchedContainer.getContainerId(), node);
}
// Process completed containers
for (ContainerStatus completedContainer : completedContainers) {
ContainerId containerId = completedContainer.getContainerId();
LOG.debug("Container FINISHED: " + containerId);
containerCompleted(getRMContainer(containerId),
completedContainer, RMContainerEventType.FINISHED);
}
if (Resources.greaterThanOrEqual(resourceCalculator, clusterResource,
node.getAvailableResource(),minimumAllocation)) {
LOG.debug("Node heartbeat " + rmNode.getNodeID() +
" available resource = " + node.getAvailableResource());
assignContainers(node);
LOG.debug("Node after allocation " + rmNode.getNodeID() + " resource = "
+ node.getAvailableResource());
}
metrics.setAvailableResourcesToQueue(
Resources.subtract(clusterResource, usedResource));
}
@Override
public void handle(SchedulerEvent event) {
switch(event.getType()) {
case NODE_ADDED:
{
NodeAddedSchedulerEvent nodeAddedEvent = (NodeAddedSchedulerEvent)event;
addNode(nodeAddedEvent.getAddedRMNode());
}
break;
case NODE_REMOVED:
{
NodeRemovedSchedulerEvent nodeRemovedEvent = (NodeRemovedSchedulerEvent)event;
removeNode(nodeRemovedEvent.getRemovedRMNode());
}
break;
case NODE_UPDATE:
{
NodeUpdateSchedulerEvent nodeUpdatedEvent =
(NodeUpdateSchedulerEvent)event;
nodeUpdate(nodeUpdatedEvent.getRMNode());
}
break;
case APP_ADDED:
{
AppAddedSchedulerEvent appAddedEvent = (AppAddedSchedulerEvent) event;
addApplication(appAddedEvent.getApplicationId(),
appAddedEvent.getQueue(), appAddedEvent.getUser());
}
break;
case APP_REMOVED:
{
AppRemovedSchedulerEvent appRemovedEvent = (AppRemovedSchedulerEvent)event;
doneApplication(appRemovedEvent.getApplicationID(),
appRemovedEvent.getFinalState());
}
break;
case APP_ATTEMPT_ADDED:
{
AppAttemptAddedSchedulerEvent appAttemptAddedEvent =
(AppAttemptAddedSchedulerEvent) event;
addApplicationAttempt(appAttemptAddedEvent.getApplicationAttemptId(),
appAttemptAddedEvent.getTransferStateFromPreviousAttempt());
}
break;
case APP_ATTEMPT_REMOVED:
{
AppAttemptRemovedSchedulerEvent appAttemptRemovedEvent =
(AppAttemptRemovedSchedulerEvent) event;
try {
doneApplicationAttempt(
appAttemptRemovedEvent.getApplicationAttemptID(),
appAttemptRemovedEvent.getFinalAttemptState(),
appAttemptRemovedEvent.getKeepContainersAcrossAppAttempts());
} catch(IOException ie) {
LOG.error("Unable to remove application "
+ appAttemptRemovedEvent.getApplicationAttemptID(), ie);
}
}
break;
case CONTAINER_EXPIRED:
{
ContainerExpiredSchedulerEvent containerExpiredEvent =
(ContainerExpiredSchedulerEvent) event;
ContainerId containerid = containerExpiredEvent.getContainerId();
containerCompleted(getRMContainer(containerid),
SchedulerUtils.createAbnormalContainerStatus(
containerid,
SchedulerUtils.EXPIRED_CONTAINER),
RMContainerEventType.EXPIRE);
}
break;
default:
LOG.error("Invalid eventtype " + event.getType() + ". Ignoring!");
}
}
private void containerLaunchedOnNode(ContainerId containerId, FiCaSchedulerNode node) {
// Get the application for the finished container
FiCaSchedulerApp application = getCurrentAttemptForContainer(containerId);
if (application == null) {
LOG.info("Unknown application "
+ containerId.getApplicationAttemptId().getApplicationId()
+ " launched container " + containerId + " on node: " + node);
// Some unknown container sneaked into the system. Kill it.
this.rmContext.getDispatcher().getEventHandler()
.handle(new RMNodeCleanContainerEvent(node.getNodeID(), containerId));
return;
}
application.containerLaunchedOnNode(containerId, node.getNodeID());
}
@Lock(FifoScheduler.class)
private synchronized void containerCompleted(RMContainer rmContainer,
ContainerStatus containerStatus, RMContainerEventType event) {
if (rmContainer == null) {
LOG.info("Null container completed...");
return;
}
// Get the application for the finished container
Container container = rmContainer.getContainer();
FiCaSchedulerApp application =
getCurrentAttemptForContainer(container.getId());
ApplicationId appId =
container.getId().getApplicationAttemptId().getApplicationId();
// Get the node on which the container was allocated
FiCaSchedulerNode node = getNode(container.getNodeId());
if (application == null) {
LOG.info("Unknown application: " + appId +
" released container " + container.getId() +
" on node: " + node +
" with event: " + event);
return;
}
// Inform the application
application.containerCompleted(rmContainer, containerStatus, event);
// Inform the node
node.releaseContainer(container);
// Update total usage
Resources.subtractFrom(usedResource, container.getResource());
LOG.info("Application attempt " + application.getApplicationAttemptId() +
" released container " + container.getId() +
" on node: " + node +
" with event: " + event);
}
private Resource clusterResource = recordFactory.newRecordInstance(Resource.class);
private Resource usedResource = recordFactory.newRecordInstance(Resource.class);
private synchronized void removeNode(RMNode nodeInfo) {
FiCaSchedulerNode node = getNode(nodeInfo.getNodeID());
if (node == null) {
return;
}
// Kill running containers
for(RMContainer container : node.getRunningContainers()) {
containerCompleted(container,
SchedulerUtils.createAbnormalContainerStatus(
container.getContainerId(),
SchedulerUtils.LOST_CONTAINER),
RMContainerEventType.KILL);
}
//Remove the node
this.nodes.remove(nodeInfo.getNodeID());
// Update cluster metrics
Resources.subtractFrom(clusterResource, node.getRMNode().getTotalCapability());
}
@Override
public QueueInfo getQueueInfo(String queueName,
boolean includeChildQueues, boolean recursive) {
return DEFAULT_QUEUE.getQueueInfo(false, false);
}
@Override
public List<QueueUserACLInfo> getQueueUserAclInfo() {
return DEFAULT_QUEUE.getQueueUserAclInfo(null);
}
private synchronized void addNode(RMNode nodeManager) {
this.nodes.put(nodeManager.getNodeID(), new FiCaSchedulerNode(nodeManager,
usePortForNodeName));
Resources.addTo(clusterResource, nodeManager.getTotalCapability());
}
@Override
public void recover(RMState state) {
// NOT IMPLEMENTED
}
@Override
public synchronized SchedulerNodeReport getNodeReport(NodeId nodeId) {
FiCaSchedulerNode node = getNode(nodeId);
return node == null ? null : new SchedulerNodeReport(node);
}
@Override
public RMContainer getRMContainer(ContainerId containerId) {
FiCaSchedulerApp attempt = getCurrentAttemptForContainer(containerId);
return (attempt == null) ? null : attempt.getRMContainer(containerId);
}
private FiCaSchedulerApp getCurrentAttemptForContainer(
ContainerId containerId) {
SchedulerApplication app =
applications.get(containerId.getApplicationAttemptId()
.getApplicationId());
if (app != null) {
return (FiCaSchedulerApp) app.getCurrentAppAttempt();
}
return null;
}
@Override
public QueueMetrics getRootQueueMetrics() {
return DEFAULT_QUEUE.getMetrics();
}
@Override
public synchronized boolean checkAccess(UserGroupInformation callerUGI,
QueueACL acl, String queueName) {
return DEFAULT_QUEUE.hasAccess(acl, callerUGI);
}
@Override
public synchronized List<ApplicationAttemptId> getAppsInQueue(String queueName) {
if (queueName.equals(DEFAULT_QUEUE.getQueueName())) {
List<ApplicationAttemptId> attempts = new ArrayList<ApplicationAttemptId>(
applications.size());
for (SchedulerApplication app : applications.values()) {
attempts.add(app.getCurrentAppAttempt().getApplicationAttemptId());
}
return attempts;
} else {
return null;
}
}
}
| apache-2.0 |
pac4j/pac4j | pac4j-core/src/main/java/org/pac4j/core/profile/converter/StringConverter.java | 276 | package org.pac4j.core.profile.converter;
/**
* This class only keeps String objects.
*
* @author Jerome Leleu
* @since 1.1.0
*/
public final class StringConverter extends AbstractAttributeConverter {
public StringConverter() {
super(String.class);
}
}
| apache-2.0 |
mayonghui2112/helloWorld | sourceCode/OnJava8-Examples-master/collections/CrossCollectionIteration.java | 1075 | // collections/CrossCollectionIteration.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
import typeinfo.pets.*;
import java.util.*;
public class CrossCollectionIteration {
public static void display(Iterator<Pet> it) {
while(it.hasNext()) {
Pet p = it.next();
System.out.print(p.id() + ":" + p + " ");
}
System.out.println();
}
public static void main(String[] args) {
List<Pet> pets = Pets.list(8);
LinkedList<Pet> petsLL = new LinkedList<>(pets);
HashSet<Pet> petsHS = new HashSet<>(pets);
TreeSet<Pet> petsTS = new TreeSet<>(pets);
display(pets.iterator());
display(petsLL.iterator());
display(petsHS.iterator());
display(petsTS.iterator());
}
}
/* Output:
0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug
7:Manx
0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug
7:Manx
0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug
7:Manx
5:Cymric 2:Cymric 7:Manx 1:Manx 3:Mutt 6:Pug 4:Pug
0:Rat
*/
| apache-2.0 |
LorenzReinhart/ONOSnew | apps/segmentrouting/src/test/java/org/onosproject/segmentrouting/HostHandlerTest.java | 23877 | /*
* Copyright 2017-present Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.segmentrouting;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.junit.Before;
import org.junit.Test;
import org.onlab.packet.IpAddress;
import org.onlab.packet.IpPrefix;
import org.onlab.packet.MacAddress;
import org.onlab.packet.VlanId;
import org.onosproject.core.DefaultApplicationId;
import org.onosproject.incubator.net.intf.Interface;
import org.onosproject.incubator.net.intf.InterfaceServiceAdapter;
import org.onosproject.net.ConnectPoint;
import org.onosproject.net.DefaultHost;
import org.onosproject.net.DeviceId;
import org.onosproject.net.Host;
import org.onosproject.net.HostId;
import org.onosproject.net.HostLocation;
import org.onosproject.net.PortNumber;
import org.onosproject.net.config.NetworkConfigRegistryAdapter;
import org.onosproject.net.flow.TrafficSelector;
import org.onosproject.net.flow.TrafficTreatment;
import org.onosproject.net.flow.criteria.Criterion;
import org.onosproject.net.flow.criteria.EthCriterion;
import org.onosproject.net.flow.criteria.VlanIdCriterion;
import org.onosproject.net.flow.instructions.Instruction;
import org.onosproject.net.flow.instructions.Instructions;
import org.onosproject.net.flow.instructions.L2ModificationInstruction;
import org.onosproject.net.flowobjective.FlowObjectiveServiceAdapter;
import org.onosproject.net.flowobjective.ForwardingObjective;
import org.onosproject.net.flowobjective.Objective;
import org.onosproject.net.host.HostEvent;
import org.onosproject.net.host.InterfaceIpAddress;
import org.onosproject.net.provider.ProviderId;
import org.onosproject.segmentrouting.config.DeviceConfiguration;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.*;
/**
* Unit test for {@link HostHandler}.
*/
public class HostHandlerTest {
private SegmentRoutingManager srManager;
private HostHandler hostHandler;
// Mocked routing and bridging tables
private Map<BridingTableKey, BridingTableValue> bridgingTable = Maps.newConcurrentMap();
private Map<RoutingTableKey, RoutingTableValue> routingTable = Maps.newConcurrentMap();
// Mocked Next Id
private Map<Integer, TrafficTreatment> nextTable = Maps.newConcurrentMap();
private AtomicInteger atomicNextId = new AtomicInteger();
// Host information
private static final ProviderId PROVIDER_ID = ProviderId.NONE;
private static final MacAddress HOST_MAC = MacAddress.valueOf("00:00:00:00:00:01");
private static final VlanId HOST_VLAN_UNTAGGED = VlanId.NONE;
private static final HostId HOST_ID_UNTAGGED = HostId.hostId(HOST_MAC, HOST_VLAN_UNTAGGED);
private static final VlanId HOST_VLAN_TAGGED = VlanId.vlanId((short) 20);
private static final HostId HOST_ID_TAGGED = HostId.hostId(HOST_MAC, HOST_VLAN_TAGGED);
private static final IpAddress HOST_IP1 = IpAddress.valueOf("10.0.1.1");
private static final IpAddress HOST_IP2 = IpAddress.valueOf("10.0.2.1");
private static final IpAddress HOST_IP3 = IpAddress.valueOf("10.0.1.2");
// Untagged interface
private static final ConnectPoint CP1 = new ConnectPoint(DeviceId.deviceId("of:0000000000000001"),
PortNumber.portNumber(10));
private static final HostLocation HOST_LOC1 = new HostLocation(CP1, 0);
private static final IpPrefix INTF_PREFIX1 = IpPrefix.valueOf("10.0.1.254/24");
private static final InterfaceIpAddress INTF_IP1 = new InterfaceIpAddress(INTF_PREFIX1.address(),
INTF_PREFIX1);
private static final VlanId INTF_VLAN_UNTAGGED = VlanId.vlanId((short) 10);
// Another untagged interface with same subnet and vlan
private static final ConnectPoint CP3 = new ConnectPoint(DeviceId.deviceId("of:0000000000000002"),
PortNumber.portNumber(30));
private static final HostLocation HOST_LOC3 = new HostLocation(CP3, 0);
// Tagged/Native interface
private static final ConnectPoint CP2 = new ConnectPoint(DeviceId.deviceId("of:0000000000000001"),
PortNumber.portNumber(20));
private static final HostLocation HOST_LOC2 = new HostLocation(CP2, 0);
private static final IpPrefix INTF_PREFIX2 = IpPrefix.valueOf("10.0.2.254/24");
private static final InterfaceIpAddress INTF_IP2 = new InterfaceIpAddress(INTF_PREFIX2.address(),
INTF_PREFIX2);
private static final Set<VlanId> INTF_VLAN_TAGGED = Sets.newHashSet(VlanId.vlanId((short) 20));
private static final VlanId INTF_VLAN_NATIVE = VlanId.vlanId((short) 30);
@Before
public void setUp() throws Exception {
srManager = new MockSegmentRoutingManager();
srManager.cfgService = new NetworkConfigRegistryAdapter();
srManager.deviceConfiguration = new DeviceConfiguration(srManager);
srManager.flowObjectiveService = new MockFlowObjectiveService();
srManager.routingRulePopulator = new MockRoutingRulePopulator();
srManager.interfaceService = new MockInterfaceService();
hostHandler = new HostHandler(srManager);
routingTable.clear();
bridgingTable.clear();
}
@Test
public void init() throws Exception {
// TODO Implement test for init()
}
@Test
public void testHostAdded() throws Exception {
Host subject;
// Untagged host discovered on untagged port
// Expect: add one routing rule and one bridging rule
subject = new DefaultHost(PROVIDER_ID, HOST_ID_UNTAGGED, HOST_MAC, HOST_VLAN_UNTAGGED,
Sets.newHashSet(HOST_LOC1), Sets.newHashSet(HOST_IP1), false);
hostHandler.processHostAddedEvent(new HostEvent(HostEvent.Type.HOST_ADDED, subject));
assertEquals(1, routingTable.size());
assertNotNull(routingTable.get(new RoutingTableKey(HOST_LOC1.deviceId(), HOST_IP1.toIpPrefix())));
assertEquals(1, bridgingTable.size());
assertNotNull(bridgingTable.get(new BridingTableKey(HOST_LOC1.deviceId(), HOST_MAC, INTF_VLAN_UNTAGGED)));
// Untagged host discovered on tagged/native port
// Expect: add one routing rule and one bridging rule
subject = new DefaultHost(PROVIDER_ID, HOST_ID_UNTAGGED, HOST_MAC, HOST_VLAN_UNTAGGED,
Sets.newHashSet(HOST_LOC2), Sets.newHashSet(HOST_IP2), false);
hostHandler.processHostAddedEvent(new HostEvent(HostEvent.Type.HOST_ADDED, subject));
assertEquals(2, routingTable.size());
assertNotNull(routingTable.get(new RoutingTableKey(HOST_LOC2.deviceId(), HOST_IP2.toIpPrefix())));
assertEquals(2, bridgingTable.size());
assertNotNull(bridgingTable.get(new BridingTableKey(HOST_LOC2.deviceId(), HOST_MAC, INTF_VLAN_NATIVE)));
// Tagged host discovered on untagged port
// Expect: ignore the host. No rule is added.
subject = new DefaultHost(PROVIDER_ID, HOST_ID_TAGGED, HOST_MAC, HOST_VLAN_TAGGED,
Sets.newHashSet(HOST_LOC1), Sets.newHashSet(HOST_IP1), false);
hostHandler.processHostAddedEvent(new HostEvent(HostEvent.Type.HOST_ADDED, subject));
assertEquals(2, routingTable.size());
assertEquals(2, bridgingTable.size());
// Tagged host discovered on tagged port with the same IP
// Expect: update existing route, add one bridging rule
subject = new DefaultHost(PROVIDER_ID, HOST_ID_TAGGED, HOST_MAC, HOST_VLAN_TAGGED,
Sets.newHashSet(HOST_LOC2), Sets.newHashSet(HOST_IP2), false);
hostHandler.processHostAddedEvent(new HostEvent(HostEvent.Type.HOST_ADDED, subject));
assertEquals(2, routingTable.size());
assertNotNull(routingTable.get(new RoutingTableKey(HOST_LOC2.deviceId(), HOST_IP2.toIpPrefix())));
assertEquals(HOST_VLAN_TAGGED, routingTable.get(new RoutingTableKey(HOST_LOC2.deviceId(),
HOST_IP2.toIpPrefix())).vlanId);
assertEquals(3, bridgingTable.size());
assertNotNull(bridgingTable.get(new BridingTableKey(HOST_LOC2.deviceId(), HOST_MAC, HOST_VLAN_TAGGED)));
}
@Test
public void testHostRemoved() throws Exception {
Host subject = new DefaultHost(PROVIDER_ID, HOST_ID_UNTAGGED, HOST_MAC, HOST_VLAN_UNTAGGED,
Sets.newHashSet(HOST_LOC1), Sets.newHashSet(HOST_IP1), false);
// Add a host
// Expect: add one routing rule and one bridging rule
hostHandler.processHostAddedEvent(new HostEvent(HostEvent.Type.HOST_ADDED, subject));
assertEquals(1, routingTable.size());
assertNotNull(routingTable.get(new RoutingTableKey(HOST_LOC1.deviceId(), HOST_IP1.toIpPrefix())));
assertEquals(1, bridgingTable.size());
assertNotNull(bridgingTable.get(new BridingTableKey(HOST_LOC1.deviceId(), HOST_MAC, INTF_VLAN_UNTAGGED)));
// Remove the host
// Expect: add the routing rule and the bridging rule
hostHandler.processHostRemoveEvent(new HostEvent(HostEvent.Type.HOST_REMOVED, subject));
assertEquals(0, routingTable.size());
assertNull(routingTable.get(new RoutingTableKey(HOST_LOC1.deviceId(), HOST_IP2.toIpPrefix())));
assertEquals(0, bridgingTable.size());
assertNull(bridgingTable.get(new BridingTableKey(HOST_LOC1.deviceId(), HOST_MAC, INTF_VLAN_UNTAGGED)));
}
@Test
public void testHostMoved() throws Exception {
Host host1 = new DefaultHost(PROVIDER_ID, HOST_ID_UNTAGGED, HOST_MAC, HOST_VLAN_UNTAGGED,
Sets.newHashSet(HOST_LOC1), Sets.newHashSet(HOST_IP1), false);
Host host2 = new DefaultHost(PROVIDER_ID, HOST_ID_UNTAGGED, HOST_MAC, HOST_VLAN_UNTAGGED,
Sets.newHashSet(HOST_LOC2), Sets.newHashSet(HOST_IP1), false);
Host host3 = new DefaultHost(PROVIDER_ID, HOST_ID_UNTAGGED, HOST_MAC, HOST_VLAN_UNTAGGED,
Sets.newHashSet(HOST_LOC3), Sets.newHashSet(HOST_IP1), false);
// Add a host
// Expect: add a new routing rule. no change to bridging rule.
hostHandler.processHostAddedEvent(new HostEvent(HostEvent.Type.HOST_ADDED, host1));
assertEquals(1, routingTable.size());
assertNotNull(routingTable.get(new RoutingTableKey(HOST_LOC1.deviceId(), HOST_IP1.toIpPrefix())));
assertNull(routingTable.get(new RoutingTableKey(HOST_LOC1.deviceId(), HOST_IP2.toIpPrefix())));
assertNull(routingTable.get(new RoutingTableKey(HOST_LOC1.deviceId(), HOST_IP3.toIpPrefix())));
assertEquals(1, bridgingTable.size());
assertNotNull(bridgingTable.get(new BridingTableKey(HOST_LOC1.deviceId(), HOST_MAC, INTF_VLAN_UNTAGGED)));
assertNull(bridgingTable.get(new BridingTableKey(HOST_LOC3.deviceId(), HOST_MAC, INTF_VLAN_UNTAGGED)));
// Move the host to CP2, which has different subnet setting
// Expect: remove routing rule. Change vlan in bridging rule.
hostHandler.processHostMovedEvent(new HostEvent(HostEvent.Type.HOST_MOVED, host2, host1));
assertEquals(0, routingTable.size());
assertNull(routingTable.get(new RoutingTableKey(HOST_LOC1.deviceId(), HOST_IP1.toIpPrefix())));
assertNull(routingTable.get(new RoutingTableKey(HOST_LOC2.deviceId(), HOST_IP1.toIpPrefix())));
assertNull(routingTable.get(new RoutingTableKey(HOST_LOC3.deviceId(), HOST_IP1.toIpPrefix())));
assertEquals(1, bridgingTable.size());
assertNotNull(bridgingTable.get(new BridingTableKey(HOST_LOC2.deviceId(), HOST_MAC, INTF_VLAN_NATIVE)));
assertNull(bridgingTable.get(new BridingTableKey(HOST_LOC3.deviceId(), HOST_MAC, INTF_VLAN_UNTAGGED)));
// Move the host to CP3, which has same subnet setting
// Expect: add a new routing rule. Change vlan in bridging rule.
hostHandler.processHostMovedEvent(new HostEvent(HostEvent.Type.HOST_MOVED, host3, host2));
assertEquals(1, routingTable.size());
assertNull(routingTable.get(new RoutingTableKey(HOST_LOC1.deviceId(), HOST_IP1.toIpPrefix())));
assertNull(routingTable.get(new RoutingTableKey(HOST_LOC2.deviceId(), HOST_IP1.toIpPrefix())));
assertNotNull(routingTable.get(new RoutingTableKey(HOST_LOC3.deviceId(), HOST_IP1.toIpPrefix())));
assertEquals(1, bridgingTable.size());
assertNull(bridgingTable.get(new BridingTableKey(HOST_LOC1.deviceId(), HOST_MAC, INTF_VLAN_UNTAGGED)));
assertNotNull(bridgingTable.get(new BridingTableKey(HOST_LOC3.deviceId(), HOST_MAC, INTF_VLAN_UNTAGGED)));
}
@Test
public void testHostUpdated() throws Exception {
Host host1 = new DefaultHost(PROVIDER_ID, HOST_ID_UNTAGGED, HOST_MAC, HOST_VLAN_UNTAGGED,
Sets.newHashSet(HOST_LOC1), Sets.newHashSet(HOST_IP1), false);
Host host2 = new DefaultHost(PROVIDER_ID, HOST_ID_UNTAGGED, HOST_MAC, HOST_VLAN_UNTAGGED,
Sets.newHashSet(HOST_LOC1), Sets.newHashSet(HOST_IP2), false);
Host host3 = new DefaultHost(PROVIDER_ID, HOST_ID_UNTAGGED, HOST_MAC, HOST_VLAN_UNTAGGED,
Sets.newHashSet(HOST_LOC1), Sets.newHashSet(HOST_IP3), false);
// Add a host
// Expect: add a new routing rule. no change to bridging rule.
hostHandler.processHostAddedEvent(new HostEvent(HostEvent.Type.HOST_ADDED, host1));
assertEquals(1, routingTable.size());
assertNotNull(routingTable.get(new RoutingTableKey(HOST_LOC1.deviceId(), HOST_IP1.toIpPrefix())));
assertNull(routingTable.get(new RoutingTableKey(HOST_LOC1.deviceId(), HOST_IP2.toIpPrefix())));
assertNull(routingTable.get(new RoutingTableKey(HOST_LOC1.deviceId(), HOST_IP3.toIpPrefix())));
assertEquals(1, bridgingTable.size());
assertNotNull(bridgingTable.get(new BridingTableKey(HOST_LOC1.deviceId(), HOST_MAC, INTF_VLAN_UNTAGGED)));
// Update the host IP to same subnet
// Expect: update routing rule with new IP. No change to bridging rule.
hostHandler.processHostUpdatedEvent(new HostEvent(HostEvent.Type.HOST_UPDATED, host3, host1));
assertEquals(1, routingTable.size());
assertNull(routingTable.get(new RoutingTableKey(HOST_LOC1.deviceId(), HOST_IP1.toIpPrefix())));
assertNull(routingTable.get(new RoutingTableKey(HOST_LOC1.deviceId(), HOST_IP2.toIpPrefix())));
assertNotNull(routingTable.get(new RoutingTableKey(HOST_LOC1.deviceId(), HOST_IP3.toIpPrefix())));
assertEquals(1, bridgingTable.size());
assertNotNull(bridgingTable.get(new BridingTableKey(HOST_LOC1.deviceId(), HOST_MAC, INTF_VLAN_UNTAGGED)));
// Update the host IP to different subnet
// Expect: Remove routing rule. No change to bridging rule.
hostHandler.processHostUpdatedEvent(new HostEvent(HostEvent.Type.HOST_UPDATED, host2, host3));
assertEquals(0, routingTable.size());
assertNull(routingTable.get(new RoutingTableKey(HOST_LOC1.deviceId(), HOST_IP1.toIpPrefix())));
assertNull(routingTable.get(new RoutingTableKey(HOST_LOC1.deviceId(), HOST_IP2.toIpPrefix())));
assertNull(routingTable.get(new RoutingTableKey(HOST_LOC1.deviceId(), HOST_IP3.toIpPrefix())));
assertEquals(1, bridgingTable.size());
assertNotNull(bridgingTable.get(new BridingTableKey(HOST_LOC1.deviceId(), HOST_MAC, INTF_VLAN_UNTAGGED)));
}
class MockSegmentRoutingManager extends SegmentRoutingManager {
MockSegmentRoutingManager() {
appId = new DefaultApplicationId(1, SegmentRoutingManager.APP_NAME);
}
@Override
public int getPortNextObjectiveId(DeviceId deviceId, PortNumber portNum,
TrafficTreatment treatment,
TrafficSelector meta,
boolean createIfMissing) {
int nextId = atomicNextId.incrementAndGet();
nextTable.put(nextId, treatment);
return nextId;
}
}
class MockInterfaceService extends InterfaceServiceAdapter {
@Override
public Set<Interface> getInterfacesByPort(ConnectPoint cp) {
Interface intf = null;
if (CP1.equals(cp)) {
intf = new Interface(null, CP1, Lists.newArrayList(INTF_IP1), MacAddress.NONE, null,
INTF_VLAN_UNTAGGED, null, null);
} else if (CP2.equals(cp)) {
intf = new Interface(null, CP2, Lists.newArrayList(INTF_IP2), MacAddress.NONE, null,
null, INTF_VLAN_TAGGED, INTF_VLAN_NATIVE);
} else if (CP3.equals(cp)) {
intf = new Interface(null, CP3, Lists.newArrayList(INTF_IP1), MacAddress.NONE, null,
INTF_VLAN_UNTAGGED, null, null);
}
return Objects.nonNull(intf) ? Sets.newHashSet(intf) : Sets.newHashSet();
}
}
class MockFlowObjectiveService extends FlowObjectiveServiceAdapter {
@Override
public void forward(DeviceId deviceId, ForwardingObjective forwardingObjective) {
TrafficSelector selector = forwardingObjective.selector();
TrafficTreatment treatment = nextTable.get(forwardingObjective.nextId());
MacAddress macAddress = ((EthCriterion) selector.getCriterion(Criterion.Type.ETH_DST)).mac();
VlanId vlanId = ((VlanIdCriterion) selector.getCriterion(Criterion.Type.VLAN_VID)).vlanId();
boolean popVlan = treatment.allInstructions().stream()
.filter(instruction -> instruction.type().equals(Instruction.Type.L2MODIFICATION))
.anyMatch(instruction -> ((L2ModificationInstruction) instruction).subtype()
.equals(L2ModificationInstruction.L2SubType.VLAN_POP));
PortNumber portNumber = treatment.allInstructions().stream()
.filter(instruction -> instruction.type().equals(Instruction.Type.OUTPUT))
.map(instruction -> ((Instructions.OutputInstruction) instruction).port()).findFirst().orElse(null);
if (portNumber == null) {
throw new IllegalArgumentException();
}
Objective.Operation op = forwardingObjective.op();
BridingTableKey btKey = new BridingTableKey(deviceId, macAddress, vlanId);
BridingTableValue btValue = new BridingTableValue(popVlan, portNumber);
if (op.equals(Objective.Operation.ADD)) {
bridgingTable.put(btKey, btValue);
} else if (op.equals(Objective.Operation.REMOVE)) {
bridgingTable.remove(btKey, btValue);
} else {
throw new IllegalArgumentException();
}
}
}
class MockRoutingRulePopulator extends RoutingRulePopulator {
MockRoutingRulePopulator() {
super(srManager);
}
@Override
public void populateRoute(DeviceId deviceId, IpPrefix prefix,
MacAddress hostMac, VlanId hostVlanId, PortNumber outPort) {
RoutingTableKey rtKey = new RoutingTableKey(deviceId, prefix);
RoutingTableValue rtValue = new RoutingTableValue(outPort, hostMac, hostVlanId);
routingTable.put(rtKey, rtValue);
}
@Override
public void revokeRoute(DeviceId deviceId, IpPrefix prefix,
MacAddress hostMac, VlanId hostVlanId, PortNumber outPort) {
RoutingTableKey rtKey = new RoutingTableKey(deviceId, prefix);
RoutingTableValue rtValue = new RoutingTableValue(outPort, hostMac, hostVlanId);
routingTable.remove(rtKey, rtValue);
}
}
class BridingTableKey {
DeviceId deviceId;
MacAddress macAddress;
VlanId vlanId;
BridingTableKey(DeviceId deviceId, MacAddress macAddress, VlanId vlanId) {
this.deviceId = deviceId;
this.macAddress = macAddress;
this.vlanId = vlanId;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof BridingTableKey)) {
return false;
}
final BridingTableKey other = (BridingTableKey) obj;
return Objects.equals(this.macAddress, other.macAddress) &&
Objects.equals(this.deviceId, other.deviceId) &&
Objects.equals(this.vlanId, other.vlanId);
}
@Override
public int hashCode() {
return Objects.hash(macAddress, vlanId);
}
}
class BridingTableValue {
boolean popVlan;
PortNumber portNumber;
BridingTableValue(boolean popVlan, PortNumber portNumber) {
this.popVlan = popVlan;
this.portNumber = portNumber;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof BridingTableValue)) {
return false;
}
final BridingTableValue other = (BridingTableValue) obj;
return Objects.equals(this.popVlan, other.popVlan) &&
Objects.equals(this.portNumber, other.portNumber);
}
@Override
public int hashCode() {
return Objects.hash(popVlan, portNumber);
}
}
class RoutingTableKey {
DeviceId deviceId;
IpPrefix ipPrefix;
RoutingTableKey(DeviceId deviceId, IpPrefix ipPrefix) {
this.deviceId = deviceId;
this.ipPrefix = ipPrefix;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof RoutingTableKey)) {
return false;
}
final RoutingTableKey other = (RoutingTableKey) obj;
return Objects.equals(this.deviceId, other.deviceId) &&
Objects.equals(this.ipPrefix, other.ipPrefix);
}
@Override
public int hashCode() {
return Objects.hash(deviceId, ipPrefix);
}
}
class RoutingTableValue {
PortNumber portNumber;
MacAddress macAddress;
VlanId vlanId;
RoutingTableValue(PortNumber portNumber, MacAddress macAddress, VlanId vlanId) {
this.portNumber = portNumber;
this.macAddress = macAddress;
this.vlanId = vlanId;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof RoutingTableValue)) {
return false;
}
final RoutingTableValue other = (RoutingTableValue) obj;
return Objects.equals(this.portNumber, other.portNumber) &&
Objects.equals(this.macAddress, other.macAddress) &&
Objects.equals(this.vlanId, other.vlanId);
}
@Override
public int hashCode() {
return Objects.hash(portNumber, macAddress, vlanId);
}
}
} | apache-2.0 |
Guo-Dong-Ba-Team/guodong | app/src/main/java/com/guodong/activity/RegisterActivity.java | 6921 | package com.guodong.activity;
/**
* Created by blarrow on 2015/10/21.
*/
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.guodong.R;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class RegisterActivity extends Activity
{
private Context mContext;
private EditText regisname;
private EditText regisphone;
private EditText pswd;
private EditText pswdconfirm;
private Button btn_complete;
private ProgressDialog mDialog;
public Handler handler = new Handler()
{
public void handleMessage(Message message)
{
switch (message.what)
{
case 0:
{
//注册成功,跳转到登录页面
mDialog.dismiss();
Toast.makeText(mContext, "注册成功,为您跳转到登录页面", Toast.LENGTH_LONG).show();
Intent intent = new Intent(mContext, LoginActivity.class);
startActivity(intent);
finish();
break;
}
case 1:
{
//这个手机号已经被注册,弹出提示:去登录或忘记密码
mDialog.dismiss();
Toast.makeText(mContext, "该手机号已经注册,请直接登录", Toast.LENGTH_LONG).show();
Intent intent = new Intent(mContext, LoginActivity.class);
startActivity(intent);
break;
}
case 2:
{
mDialog.dismiss();
Toast.makeText(mContext, "额,出了点小意外,请再试一次~", Toast.LENGTH_LONG).show();
break;
}
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_register);
mContext = this;
regisname = (EditText) findViewById(R.id.username);
regisphone = (EditText) findViewById(R.id.et_phone);
pswd = (EditText) findViewById(R.id.pswd);
pswdconfirm = (EditText) findViewById(R.id.pswdconfirm);
btn_complete = (Button) findViewById(R.id.submit);
}
public void register(View v)
{
final String username = regisname.getText().toString();
final String password = pswd.getText().toString();
final String phone = regisphone.getText().toString();
final String confirmPswd = pswdconfirm.getText().toString();
if ("".equals(phone.trim()) || "".equals(username.trim()) || "".equals(password.trim()) || "".equals(confirmPswd.trim()))
{
Toast.makeText(mContext, "信息请填写完整", Toast.LENGTH_SHORT).show();
} else if (username.trim().length() > 10 || password.trim().length() < 3 || password.trim().length() > 10)
{
Toast.makeText(mContext, "用户名或密码位数不正确", Toast.LENGTH_SHORT).show();
} else if (phone.trim().length() > 11)
{
Toast.makeText(mContext, "手机号码过长", Toast.LENGTH_SHORT).show();
} else if (!confirmPswd.equals(password))
{
Toast.makeText(mContext, "两次密码不一致", Toast.LENGTH_SHORT).show();
} else
{
mDialog = new ProgressDialog(RegisterActivity.this);
mDialog.setTitle("提交");
mDialog.setMessage("正在提交注册信息,请稍候...");
mDialog.show();
new Thread()
{
public void run()
{
//System.out.println("======================================================");
registerByGet(username, password, phone);
}
}.start();
}
}
public void registerByGet(String regisname, String password, String regisphone)
{
try
{
//genymotion 模拟器可以通过10.0.3.2连接到电脑localhost上
String spec = "http://182.61.8.185:8080/register" + "?username=" + regisname + "&password=" + password + "&phone=" + regisphone;
// 根据地址创建URL对象(网络访问的url)
URL url = new URL(spec);
// url.openConnection()打开网络链接
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setRequestMethod("GET");// 设置请求的方式
urlConnection.setReadTimeout(5000);// 设置超时的时间
urlConnection.setConnectTimeout(5000);// 设置链接超时的时间
// 设置请求的头
urlConnection.setRequestProperty("User-Agent",
"Mozilla/5.0 (Windows NT 6.3; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0");
// 获取响应的状态码 404 200 505 302
System.out.println(urlConnection.getResponseCode());
if (urlConnection.getResponseCode() == 200)
{
// 获取响应的输入流对象
InputStream is = urlConnection.getInputStream();
// 创建字节输出流对象
ByteArrayOutputStream os = new ByteArrayOutputStream();
// 定义读取的长度
int len = 0;
// 定义缓冲区
byte buffer[] = new byte[1024];
// 按照缓冲区的大小,循环读取
while ((len = is.read(buffer)) != -1)
{
// 根据读取的长度写入到os对象中
os.write(buffer, 0, len);
}
// 释放资源
is.close();
os.close();
// 返回字符串
String result = new String(os.toByteArray());
System.out.println("***************" + result
+ "******************");
Message message = new Message();
message.what = Integer.parseInt(result);
handler.sendMessage(message);
}
} catch (Exception e)
{
e.printStackTrace();
}
}
}
| apache-2.0 |
alexTrifonov/atrifonov | chapter_008/src/main/java/ru/job4j/vacancyparser/Main.java | 1674 | package ru.job4j.vacancyparser;
import java.sql.*;
import java.util.concurrent.*;
/**
* Entry point of application.
* @author atrifonov.
* @version 1.
* @since 27.11.2017.
*/
public class Main {
/**
* psvm.
* @param args arguments.
*/
public static void main(String[] args) {
Connection conn = null;
Statement statm = null;
MapConnDB mapConnDB = new MapConnDB();
mapConnDB.fillMapCommand();
try {
conn = ConnectionFactory.getDatabaseConnection();
statm = conn.createStatement();
statm.execute(MapConnDB.getMapCommand().get("create_table"));
} catch (SQLException e) {
e.printStackTrace();
return;
} finally {
if(statm != null) {
try {
statm.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
int period = Integer.parseInt(MapConnDB.getMapCommand().get("period"));
TimeUnit timeUnit = TimeUnit.valueOf(MapConnDB.getMapCommand().get("TimeUnit"));
executor.scheduleAtFixedRate(new One(), 0, period, timeUnit);
try {
timeUnit.sleep(period * 3);
} catch (InterruptedException e) {
e.printStackTrace();
}
executor.shutdown();
}
}
| apache-2.0 |
gridgain/apache-ignite | modules/core/src/main/java/org/apache/ignite/IgniteQueue.java | 6809 | /*
* 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;
import java.io.*;
import java.util.*;
import java.util.concurrent.*;
/**
* This interface provides a rich API for working with distributed queues based on In-Memory Data Grid.
* <p>
* <h1 class="header">Overview</h1>
* Cache queue provides an access to cache elements using typical queue API. Cache queue also implements
* {@link Collection} interface and provides all methods from collections including
* {@link Collection#addAll(Collection)}, {@link Collection#removeAll(Collection)}, and
* {@link Collection#retainAll(Collection)} methods for bulk operations. Note that all
* {@link Collection} methods in the queue may throw {@link IgniteException} in case
* of failure.
* <p>
* All queue operations have synchronous and asynchronous counterparts.
* <h1 class="header">Bounded vs Unbounded</h1>
* Queues can be {@code unbounded} or {@code bounded}. {@code Bounded} queues can
* have maximum capacity. Queue capacity can be set at creation time and cannot be
* changed later. Here is an example of how to create {@code bounded} {@code LIFO} queue with
* capacity of {@code 1000} items.
* <pre name="code" class="java">
* IgniteQueue<String> queue = cache().queue("anyName", LIFO, 1000);
* ...
* queue.add("item");
* </pre>
* For {@code bounded} queues <b>blocking</b> operations, such as {@link #take()} or {@link #put(Object)}
* are available. These operations will block until queue capacity changes to make the operation
* possible.
* <h1 class="header">Collocated vs Non-collocated</h1>
* Queue items can be placed on one node or distributed throughout grid nodes
* (governed by {@code collocated} parameter). {@code Non-collocated} mode is provided only
* for partitioned caches. If {@code collocated} parameter is {@code true}, then all queue items
* will be collocated on one node, otherwise items will be distributed through all grid nodes.
* Unless explicitly specified, by default queues are {@code collocated}.
* <p>
* Here is an example of how create {@code unbounded} queue
* in non-collocated mode.
* <pre name="code" class="java">
* IgniteQueue<String> queue = cache().queue("anyName", 0 /*unbounded*/, false /*non-collocated*/);
* ...
* queue.add("item");
* </pre>
* <h1 class="header">Creating Cache Queues</h1>
* Instances of distributed cache queues can be created by calling the following method
* on {@link Ignite} API:
* <ul>
* <li>{@link Ignite#queue(String, CollectionConfiguration, int, boolean)}</li>
* </ul>
* @see Ignite#queue(String, CollectionConfiguration, int, boolean)
*/
public interface IgniteQueue<T> extends BlockingQueue<T>, Closeable {
/**
* Gets queue name.
*
* @return Queue name.
*/
public String name();
/** {@inheritDoc} */
@Override public boolean add(T item) throws IgniteException;
/** {@inheritDoc} */
@Override public boolean offer(T item) throws IgniteException;
/** {@inheritDoc} */
@Override public boolean offer(T item, long timeout, TimeUnit unit) throws IgniteException;
/** {@inheritDoc} */
@Override public boolean addAll(Collection<? extends T> items) throws IgniteException;
/** {@inheritDoc} */
@Override public boolean contains(Object item) throws IgniteException;
/** {@inheritDoc} */
@Override public boolean containsAll(Collection<?> items) throws IgniteException;
/** {@inheritDoc} */
@Override public void clear() throws IgniteException;
/** {@inheritDoc} */
@Override public boolean remove(Object item) throws IgniteException;
/** {@inheritDoc} */
@Override public boolean removeAll(Collection<?> items) throws IgniteException;
/** {@inheritDoc} */
@Override public boolean isEmpty() throws IgniteException;
/** {@inheritDoc} */
@Override public Iterator<T> iterator() throws IgniteException;
/** {@inheritDoc} */
@Override public Object[] toArray() throws IgniteException;
/** {@inheritDoc} */
@Override public <T> T[] toArray(T[] a) throws IgniteException;
/** {@inheritDoc} */
@Override public boolean retainAll(Collection<?> items) throws IgniteException;
/** {@inheritDoc} */
@Override public int size() throws IgniteException;
/** {@inheritDoc} */
@Override public T poll() throws IgniteException;
/** {@inheritDoc} */
@Override public T peek() throws IgniteException;
/** {@inheritDoc} */
@Override public void put(T item) throws IgniteException;
/** {@inheritDoc} */
@Override public T take() throws IgniteException;
/** {@inheritDoc} */
@Override public T poll(long timeout, TimeUnit unit) throws IgniteException;
/**
* Removes all of the elements from this queue. Method is used in massive queues with huge numbers of elements.
*
* @param batchSize Batch size.
* @throws IgniteException if operation failed.
*/
public void clear(int batchSize) throws IgniteException;
/**
* Removes this queue.
*
* @throws IgniteException if operation failed.
*/
@Override public void close() throws IgniteException;
/**
* Gets maximum number of elements of the queue.
*
* @return Maximum number of elements. If queue is unbounded {@code Integer.MAX_SIZE} will return.
*/
public int capacity();
/**
* Returns {@code true} if this queue is bounded.
*
* @return {@code true} if this queue is bounded.
*/
public boolean bounded();
/**
* Returns {@code true} if this queue can be kept on the one node only.
* Returns {@code false} if this queue can be kept on the many nodes.
*
* @return {@code true} if this queue is in {@code collocated} mode {@code false} otherwise.
*/
public boolean collocated();
/**
* Gets status of queue.
*
* @return {@code true} if queue was removed from cache {@code false} otherwise.
*/
public boolean removed();
}
| apache-2.0 |
spring-cloud/spring-cloud-contract | spring-cloud-contract-wiremock/src/test/java/org/springframework/cloud/contract/wiremock/issues/sameConfigsDifferentTests/SecondTests.java | 3000 | /*
* Copyright 2013-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.contract.wiremock.issues.sameConfigsDifferentTests;
import java.nio.charset.Charset;
import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.stubbing.StubMapping;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.contract.wiremock.AutoConfigureWireMock;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.StreamUtils;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringRunner.class)
@SpringBootTest(properties = "service.port=${wiremock.server.port}", classes = SecondTests.Config.class)
@AutoConfigureWireMock(port = 0)
public class SecondTests {
@Value("classpath:example-mappings/shouldMarkClientAsNotFraud.json")
private Resource markClientAsNotFraud;
@Autowired
private WireMockServer server;
@Test
public void shouldBeRejectedDueToAbnormalLoanAmount() throws Exception {
server.addStubMapping(StubMapping
.buildFrom(StreamUtils.copyToString(markClientAsNotFraud.getInputStream(), Charset.forName("UTF-8"))));
// given:
LoanApplication loanApplication = new LoanApplication(new Client("1234567890"), 123.123);
// when:
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add(HttpHeaders.CONTENT_TYPE, "application/vnd.fraud.v1+json");
ResponseEntity<FraudServiceResponse> response = new RestTemplate().exchange(
"http://localhost:" + server.port() + "/fraudcheck", HttpMethod.PUT,
new HttpEntity<>(new FraudServiceRequest(loanApplication), httpHeaders), FraudServiceResponse.class);
// then:
assertThat(response.getBody().getFraudCheckStatus()).isEqualTo(FraudCheckStatus.OK);
}
@EnableAutoConfiguration
@Configuration
static class Config {
}
}
| apache-2.0 |
Fabric3/spring-samples | apps/bigbank/bigbank-loan/src/main/java/org/fabric3/samples/bigbank/loan/store/StoreException.java | 456 | package org.fabric3.samples.bigbank.loan.store;
/**
* @version $Revision$ $Date$
*/
public class StoreException extends Exception {
private static final long serialVersionUID = 5946877131537880818L;
public StoreException(Throwable cause) {
super(cause);
}
public StoreException(String message, Throwable cause) {
super(message, cause);
}
public StoreException(String message) {
super(message);
}
}
| apache-2.0 |
cristiani/encuestame | enme-core/src/main/java/org/encuestame/core/search/GlobalSearchItem.java | 7183 | /*
************************************************************************************
* Copyright (C) 2001-2011 encuestame: system online surveys Copyright (C) 2011
* encuestame Development Team.
* Licensed under the Apache Software License version 2.0
* 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.encuestame.core.search;
import java.util.Date;
import org.encuestame.utils.enums.TypeSearchResult;
/**
* Represent a global search item on results list.
* @author Picado, Juan juanATencuestame.org
* @since Mar 23, 2011
*/
public class GlobalSearchItem {
/**
* Id.
*/
private Long id;
/**
* URI path.
*/
private String urlLocation;
/**
* The username of the owner.
*/
private String itemPattern;
/**
*
*/
private Date dateCreated;
/**
* Score.
*/
private Long score = 0L;
/**
* Score hits.
*/
private Long hits = 0L;
/**
* {@link TypeSearchResult}.
*/
private TypeSearchResult typeSearchResult;
/**
* Item search title.
*/
private String itemSearchTitle;
/**
* Description.
*/
private String itemSearchDescription;
/**
* @return the urlLocation
*/
public String getUrlLocation() {
return urlLocation;
}
/**
* @param urlLocation
* the urlLocation to set
*/
public void setUrlLocation(String urlLocation) {
this.urlLocation = urlLocation;
}
/**
* @return the score
*/
public Long getScore() {
return score;
}
/**
* @param score
* the score to set
*/
public void setScore(Long score) {
this.score = score;
}
/**
* @return the hits
*/
public Long getHits() {
return hits;
}
/**
* @param hits
* the hits to set
*/
public void setHits(Long hits) {
this.hits = hits;
}
/**
* @return the typeSearchResult
*/
public TypeSearchResult getTypeSearchResult() {
return typeSearchResult;
}
/**
* @param typeSearchResult
* the typeSearchResult to set
*/
public void setTypeSearchResult(TypeSearchResult typeSearchResult) {
this.typeSearchResult = typeSearchResult;
}
/**
* @return the itemSearchTitle
*/
public String getItemSearchTitle() {
return itemSearchTitle;
}
/**
* @param itemSearchTitle
* the itemSearchTitle to set
*/
public void setItemSearchTitle(String itemSearchTitle) {
this.itemSearchTitle = itemSearchTitle;
}
/**
* @return the itemSearchDescription
*/
public String getItemSearchDescription() {
return itemSearchDescription;
}
/**
* @param itemSearchDescription
* the itemSearchDescription to set
*/
public void setItemSearchDescription(String itemSearchDescription) {
this.itemSearchDescription = itemSearchDescription;
}
/**
* @return the id
*/
public Long getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(Long id) {
this.id = id;
}
/**
* @return the dateCreated
*/
public Date getDateCreated() {
return dateCreated;
}
/**
* @param dateCreated the dateCreated to set
*/
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
/**
* @return the itemPattern
*/
public String getItemPattern() {
return itemPattern;
}
/**
* @param itemPattern the itemPattern to set
*/
public void setItemPattern(String itemPattern) {
this.itemPattern = itemPattern;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((hits == null) ? 0 : hits.hashCode());
result = prime
* result
+ ((itemSearchDescription == null) ? 0 : itemSearchDescription
.hashCode());
result = prime * result
+ ((itemSearchTitle == null) ? 0 : itemSearchTitle.hashCode());
result = prime * result + ((score == null) ? 0 : score.hashCode());
result = prime
* result
+ ((typeSearchResult == null) ? 0 : typeSearchResult.hashCode());
result = prime * result
+ ((urlLocation == null) ? 0 : urlLocation.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null) {
return false;
}
if (!(obj instanceof GlobalSearchItem)){
return false;
}
final GlobalSearchItem other = (GlobalSearchItem) obj;
if (hits == null) {
if (other.hits != null) {
return false;
}
} else if (!hits.equals(other.hits)) {
return false;
}
if (itemSearchDescription == null) {
if (other.itemSearchDescription != null) {
return false;
}
} else if (!itemSearchDescription.equals(other.itemSearchDescription))
return false;
if (itemSearchTitle == null) {
if (other.itemSearchTitle != null) {
return false;
}
} else if (!itemSearchTitle.equals(other.itemSearchTitle))
return false;
if (score == null) {
if (other.score != null) {
return false;
}
} else if (!score.equals(other.score))
return false;
if (typeSearchResult != other.typeSearchResult) {
return false;
}
if (urlLocation == null) {
if (other.urlLocation != null) {
return false;
}
} else if (!urlLocation.equals(other.urlLocation)) {
return false;
}
return true;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "GlobalSearchItem [urlLocation=" + urlLocation + ", score="
+ score + ", hits=" + hits + ", typeSearchResult="
+ typeSearchResult + ", itemSearchTitle=" + itemSearchTitle
+ ", itemSearchDescription=" + itemSearchDescription + "]";
}
}
| apache-2.0 |
devmil/parrot-zik-2-supercharge | 03_project/Zik Widget/src/main/java/de/devmil/parrotzik2supercharge/widget/BootReceiver.java | 378 | package de.devmil.parrotzik2supercharge.widget;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class BootReceiver extends BroadcastReceiver {
public BootReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
WidgetUpdateService.triggerUpdate(context);
}
}
| apache-2.0 |
zhou-jg/Algorithm | test/util/GPairTest.java | 427 | package util;
import static org.junit.Assert.*;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
public class GPairTest {
@Test
public void test() {
Map<GPair<String, String>, Integer> map = new HashMap<GPair<String, String>, Integer>();
map.put(new GPair<String, String>("D", "A"), 5);
assertEquals(Integer.valueOf(5), map.get(new GPair<String, String>("D", "A")));
}
}
| apache-2.0 |
oldpatricka/Gridway | src/drmaa/drmaa1.0/org/ggf/drmaa/DrmsExitException.java | 1835 | /* -------------------------------------------------------------------------- */
/* Copyright 2002-2007 GridWay Team, Distributed Systems Architecture */
/* Group, Universidad Complutense de Madrid */
/* */
/* 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.ggf.drmaa;
/**
* Thrown when a problem was encountered while trying to exit the session.
*/
public class DrmsExitException extends DrmaaException
{
public DrmsExitException()
{
super();
}
public DrmsExitException(java.lang.String message)
{
super(message);
}
}
| apache-2.0 |
alanfgates/hive | ql/src/java/org/apache/hadoop/hive/ql/plan/ReloadFunctionDesc.java | 1031 | /*
* 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.hive.ql.plan;
import java.io.Serializable;
@Explain(displayName = "Reload Function")
public class ReloadFunctionDesc implements Serializable {
private static final long serialVersionUID = 1L;
}
| apache-2.0 |
thankjava/smartqq-agreement-core | src/main/java/com/thankjava/wqq/core/action/LoginAction.java | 10236 | package com.thankjava.wqq.core.action;
import com.alibaba.fastjson.JSONObject;
import com.thankjava.toolkit3d.bean.http.AsyncResponse;
import com.thankjava.wqq.consts.ConfigParams;
import com.thankjava.wqq.consts.ConstsParams;
import com.thankjava.wqq.consts.DataResRegx;
import com.thankjava.wqq.core.event.MsgPollEvent;
import com.thankjava.wqq.core.request.RequestBuilder;
import com.thankjava.wqq.core.request.api.*;
import com.thankjava.wqq.entity.Session;
import com.thankjava.wqq.entity.enums.LoginResultStatus;
import com.thankjava.wqq.extend.ActionListener;
import com.thankjava.wqq.extend.CallBackListener;
import com.thankjava.wqq.factory.ActionFactory;
import com.thankjava.wqq.factory.RequestFactory;
import com.thankjava.wqq.util.RegexUtil;
import org.apache.http.cookie.Cookie;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.imageio.ImageIO;
import java.io.ByteArrayInputStream;
import java.io.IOException;
public class LoginAction {
private static final Logger logger = LoggerFactory.getLogger(LoginAction.class);
private Session session = Session.getSession();
private RequestBuilder getLoginQRcode = RequestFactory.getInstance(GetLoginQRcode.class);
private RequestBuilder checkSig = RequestFactory.getInstance(CheckSig.class);
private RequestBuilder getVfWebqq = RequestFactory.getInstance(GetVfWebqq.class);
private RequestBuilder login2 = RequestFactory.getInstance(Login2.class);
private RequestBuilder checkLoginQRcodeStatus = RequestFactory.getInstance(CheckLoginQRcodeStatus.class);
private GetInfoAction getInfo = ActionFactory.getInstance(GetInfoAction.class);
public void login(final CallBackListener getQrListener, final CallBackListener loginListener) {
AsyncResponse asyncResponse = getLoginQRcode.doRequest(null);
if (asyncResponse == null) {
logger.error("获取二维码失败,执行重试");
login(getQrListener, loginListener);
}
ActionListener actionListener = null;
try {
// 得到二维码数据
actionListener = new ActionListener(ImageIO.read(new ByteArrayInputStream(asyncResponse.getDataByteArray())));
} catch (IOException e) {
logger.error("获取二维码数据失败", e);
loginListener.onListener(new ActionListener(LoginResultStatus.exception));
}
getQrListener.onListener(actionListener);
logger.debug("获取二维码完成,启动二维码状态检查");
checkLoginQRcodeStatus(getQrListener, loginListener);
}
/**
* 检查当前的二维码的状态
* <p>Function: checkLoginQRcodeStatus</p>
* <p>Description: </p>
*
* @return
* @author zhaoxy@thankjava.com
* @date 2016年12月19日 下午4:19:00
* @version 1.0
*/
private void checkLoginQRcodeStatus(CallBackListener getQRListener, CallBackListener loginListener) {
try {
Thread.sleep(ConstsParams.CHECK_QRCODE_WITE_TIME);
} catch (InterruptedException e) {
logger.error("检查当前的二维码的状态线程等待异常", e);
loginListener.onListener(new ActionListener(LoginResultStatus.exception));
}
String[] data = RegexUtil.doRegex(checkLoginQRcodeStatus.doRequest(null).getDataString(), DataResRegx.check_login_qrcode_status);
if (data == null) {
logger.error("解析二维码状态失败,重试二维码状态检查");
checkLoginQRcodeStatus(getQRListener, loginListener);
}
Integer statusCode = Integer.valueOf(data[0]);
if (statusCode == null) {
logger.error("无法解析出有效的二维码状态码,重试二维码状态检查");
checkLoginQRcodeStatus(getQRListener, loginListener);
}
switch (statusCode) {
case 0: // 二维码认证成功
logger.debug("二维码验证完成");
session.setCheckSigUrl(data[2]);
if (beginLogin()) {
loginListener.onListener(new ActionListener(LoginResultStatus.success));
} else {
logger.error("登录失败");
loginListener.onListener(new ActionListener(LoginResultStatus.failed));
}
break;
case 65: // 二维码认证过期
if (ConfigParams.AUTO_REFRESH_QR_CODE) { // 如果指定过期自动刷新二维码
logger.debug("二维码已过期, 重新获取二维码...");
login(getQRListener, loginListener);
break;
}
logger.debug("当前二维码已过期, 并且未设置自动重刷二维码, 登录失败");
loginListener.onListener(new ActionListener(LoginResultStatus.failed));
break;
default: // 二维码处于认证中|等待认证
logger.debug("二维码状态: " + data[4]);
checkLoginQRcodeStatus(getQRListener, loginListener);
break;
}
}
/**
* 扫码认证完成后执行登录态相关的认证登录
* <p>Function: beginLogin</p>
* <p>Description: </p>
*
* @author zhaoxy@thankjava.com
* @date 2016年12月20日 下午2:49:21
* @version 1.0
*/
private boolean beginLogin() {
// checkSig
AsyncResponse asyncResponse = checkSig.doRequest(null);
// checkSig 成功后 从cookie中得到ptwebqq 确切的说其实这个cookie是检查qrcode成功后服务器下发的
Cookie cookie = asyncResponse.getCookies().getCookie("ptwebqq");
if (cookie == null) {
logger.error("未能获取到ptwebqq数据");
return false;
}
String ptwebqq = cookie.getValue();
if (ptwebqq == null || ptwebqq.length() == 0) {
logger.error("未能成功获取ptwebqq数据");
return false;
}
// getvfWebqq
session.setPtwebqq(ptwebqq);
asyncResponse = getVfWebqq.doRequest(null);
if (asyncResponse.isEmptyDataString()) {
logger.error("未能成功获取vfwebqq数据");
return false;
}
String content = asyncResponse.getDataString();
JSONObject jsonObject, result;
try {
jsonObject = JSONObject.parseObject(content);
result = (JSONObject) jsonObject.get("result");
session.setVfwebqq(result.get("vfwebqq").toString());
} catch (Exception e) {
logger.error("未能成功解析vfwebqq数据", e);
return false;
}
// login2
asyncResponse = login2.doRequest(null);
if (asyncResponse.isEmptyDataString()) {
logger.error("未能成功获取登录数据");
return false;
}
content = asyncResponse.getDataString();
try {
jsonObject = JSONObject.parseObject(content);
result = (JSONObject) jsonObject.get("result");
session.setUin(result.getLongValue("uin"));
session.setPsessionid(result.getString("psessionid"));
} catch (Exception e) {
logger.error("未能成功解析登录数据", e);
return false;
}
if (ConfigParams.INIT_LOGIN_INFO) {
getInfo.getFriendsList(new CallBackListener() {
@Override
public void onListener(ActionListener actionListener) {
if (actionListener.getData() == null) {
logger.error("获取好友列表失败");
} else {
logger.debug("获取好友列表成功");
getInfo.getOnlineStatus(new CallBackListener() {
@Override
public void onListener(ActionListener actionListener) {
if (actionListener.getData() == null) {
logger.error("查询好友状态失败");
} else {
logger.debug("查询好友状态成功");
}
}
});
}
}
});
getInfo.getGroupsList(new CallBackListener() {
@Override
public void onListener(ActionListener actionListener) {
if (actionListener.getData() != null) {
logger.debug("获取群列表成功");
} else {
logger.error("获取群列表失败");
}
}
});
getInfo.getSelfInfo(new CallBackListener() {
@Override
public void onListener(ActionListener actionListener) {
if (actionListener.getData() != null) {
logger.debug("获取个人信息成功");
} else {
logger.error("获取个人信息失败");
}
}
});
getInfo.getDiscusList(new CallBackListener() {
@Override
public void onListener(ActionListener actionListener) {
if (actionListener.getData() != null) {
logger.debug("获取讨论组列表成功");
} else {
logger.error("获取讨论组列表失败");
}
}
});
}
// 启动消息Poll
new Thread(new Runnable() {
@Override
public void run() {
ActionFactory.getInstance(MsgPollEvent.class).poll();
}
}).start();
return true;
}
}
| apache-2.0 |
machak/rave | rave-components/rave-web/src/main/java/org/apache/rave/portal/web/model/NavigationItem.java | 3781 | /*
* 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.rave.portal.web.model;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Bean to build up a navigation menu
*/
public class NavigationItem {
private static final String PARAM_NAME = "name";
private static final String PARAM_URL = "url";
private Map<String, String> parameters;
private List<NavigationItem> childNavigationItems;
private boolean selected;
private boolean expanded;
public NavigationItem() {
this(null, null);
}
public NavigationItem(String name, String url) {
super();
this.parameters = new HashMap<String, String>();
this.childNavigationItems = new ArrayList<NavigationItem>();
this.setName(name);
this.setUrl(url);
}
/**
* @return name of the navigation item, can be a translation key
*/
public String getName() {
return parameters.get(PARAM_NAME);
}
public void setName(String name) {
this.parameters.put(PARAM_NAME, name);
}
/**
* @return url the navigation item should link to
*/
public String getUrl() {
return parameters.get(PARAM_URL);
}
public void setUrl(String url) {
this.parameters.put(PARAM_URL, url);
}
public Map<String, String> getParameters() {
return parameters;
}
public void setParameters(Map<String, String> parameters) {
this.parameters = parameters;
}
/**
* Flag that defines if this navigation item is equal to the requested page
*
* @return {@literal true} if this navigation item is pointing to the current page
*/
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
/**
* Flag that defines if a descendant navigation item is equal to the current request
*
* @return {@literal true} if this navigation item is an ancestor of the current requested page
*/
public boolean isExpanded() {
return expanded;
}
public void setExpanded(boolean expanded) {
this.expanded = expanded;
}
/**
* @return a List of Navigation items that are a level deeper (recursive)
*/
public List<NavigationItem> getChildNavigationItems() {
return childNavigationItems;
}
public void setChildNavigationItems(List<NavigationItem> childNavigationItems) {
this.childNavigationItems = childNavigationItems;
}
/**
* Adds a single NavigationItem to the List of child navigation items
*
* @param navigationItem child node/tree of the current NavigationItem
*/
public void addChildNavigationItem(NavigationItem navigationItem) {
this.childNavigationItems.add(navigationItem);
}
public boolean isHasChildren() {
return !this.childNavigationItems.isEmpty();
}
}
| apache-2.0 |
0570dev/flickr-glass | src/com/googlecode/flickrjandroid/groups/GroupList.java | 486 | package com.googlecode.flickrjandroid.groups;
import com.googlecode.flickrjandroid.SearchResultList;
public class GroupList extends SearchResultList<Group> {
private static final long serialVersionUID = 3344960036515265775L;
public Group [] getGroupsArray() {
return (Group[]) toArray(new Group[size()]);
}
public boolean add(Group obj) {
// forces type to be group. Otherwise a class cast exception is thrown
return super.add(obj);
}
}
| apache-2.0 |
firefly-math/firefly-math-precision | src/main/java/com/fireflysemantics/math/precision/PrecisionConstants.java | 2034 | /**
* 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.fireflysemantics.math.precision;
/**
* Supports comparison of double values.
*/
public class PrecisionConstants {
/**
* <p>
* Largest double-precision floating-point number such that
* {@code 1 + EPSILON} is numerically equal to 1. This value is an upper
* bound on the relative error due to rounding real numbers to double
* precision floating-point numbers.
* </p>
* <p>
* In IEEE 754 arithmetic, this is 2<sup>-53</sup>.
* </p>
*
* @see <a href="http://en.wikipedia.org/wiki/Machine_epsilon">Machine
* epsilon</a>
*/
public static final double EPSILON;
/**
* Safe minimum, such that {@code 1 / SAFE_MIN} does not overflow. <br/>
* In IEEE 754 arithmetic, this is also the smallest normalized number 2
* <sup>-1022</sup>.
*/
public static final double SAFE_MIN;
/** Exponent offset in IEEE754 representation. */
private static final long EXPONENT_OFFSET = 1023l;
static {
/*
* This was previously expressed as = 0x1.0p-53; However, OpenJDK (Sparc
* Solaris) cannot handle such small constants: MATH-721
*/
EPSILON = Double.longBitsToDouble((EXPONENT_OFFSET
- 53l) << 52);
/*
* This was previously expressed as = 0x1.0p-1022; However, OpenJDK
* (Sparc Solaris) cannot handle such small constants: MATH-721
*/
SAFE_MIN = Double.longBitsToDouble((EXPONENT_OFFSET
- 1022l) << 52);
}
/**
* Private constructor.
*/
private PrecisionConstants() {
}
}
| apache-2.0 |
bckfnn/mvel-async-template | src/main/java/io/github/bckfnn/mvel/template/io/AbstractTemplateLoader.java | 3081 | /**
* Copyright (c) 2012-2013 Edgar Espina
*
* This file is part of Handlebars.java.
*
* 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 io.github.bckfnn.mvel.template.io;
/**
* <p>
* Strategy interface for loading resources from class path, file system, etc.
* </p>
* <h3>Templates prefix and suffix</h3>
* <p>
* A <code>TemplateLoader</code> provides two important properties:
* </p>
* <ul>
* <li>prefix: useful for setting a default prefix where templates are stored.</li>
* <li>suffix: useful for setting a default suffix or file extension for your templates. Default is:
* <code>'.hbs'</code></li>
* </ul>
* @author edgar.espina
* @since 1.0.0
*/
public abstract class AbstractTemplateLoader implements TemplateLoader {
/**
* The prefix that gets prepended to view names when building a URI.
*/
private String prefix = DEFAULT_PREFIX;
/**
* The suffix that gets appended to view names when building a URI.
*/
private String suffix = DEFAULT_SUFFIX;
/**
* Resolve the uri to an absolute location.
*
* @param uri The candidate uri.
* @return Resolve the uri to an absolute location.
*/
@Override
public String resolve(final String uri) {
return prefix + normalize(uri) + suffix;
}
/**
* Normalize the location by removing '/' at the beginning.
*
* @param location The candidate location.
* @return A location without '/' at the beginning.
*/
protected String normalize(final String location) {
if (location.toString().startsWith("/")) {
return location.substring(1);
}
return location;
}
/**
* Set the prefix that gets prepended to view names when building a URI.
*
* @param prefix The prefix that gets prepended to view names when building a
* URI.
*/
public void setPrefix(final String prefix) {
this.prefix = prefix;
if (!this.prefix.endsWith("/")) {
this.prefix += "/";
}
}
/**
* Set the suffix that gets appended to view names when building a URI.
*
* @param suffix The suffix that gets appended to view names when building a
* URI.
*/
public void setSuffix(final String suffix) {
this.suffix = suffix;
}
/**
* @return The prefix that gets prepended to view names when building a URI.
*/
@Override
public String getPrefix() {
return prefix;
}
/**
* @return The suffix that gets appended to view names when building a
* URI.
*/
@Override
public String getSuffix() {
return suffix;
}
}
| apache-2.0 |
openwide-java/owsi-core-parent | owsi-core/owsi-core-components/owsi-core-component-spring/src/main/java/fr/openwide/core/spring/notification/service/INotificationBuilderReplyToState.java | 357 | package fr.openwide.core.spring.notification.service;
import fr.openwide.core.spring.notification.model.INotificationRecipient;
public interface INotificationBuilderReplyToState extends INotificationBuilderToState {
INotificationBuilderToState replyToAddress(String replyTo);
INotificationBuilderToState replyTo(INotificationRecipient replyTo);
}
| apache-2.0 |
kneubi/fscrawler | src/main/java/fr/pilato/elasticsearch/crawler/fs/meta/settings/TimeValueSerializer.java | 1426 | /*
* Licensed to David Pilato (the "Author") under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Author 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 fr.pilato.elasticsearch.crawler.fs.meta.settings;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import java.io.IOException;
/**
* Jackson Serializer for TimeValue object
*/
public class TimeValueSerializer extends StdSerializer<TimeValue> {
public TimeValueSerializer() {
super(TimeValue.class);
}
@Override
public void serialize(TimeValue value, JsonGenerator gen, SerializerProvider provider) throws IOException {
gen.writeString(value.toString());
}
}
| apache-2.0 |
openfurther/further-open-core | core/core-xml/src/main/java/edu/utah/further/core/xml/jaxb/adapter/StringAttributeAdapter.java | 1554 | /**
* Copyright (C) [2013] [The FURTHeR 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 edu.utah.further.core.xml.jaxb.adapter;
/**
* A JAXB adapter of an optional string attribute.
* <p>
* -----------------------------------------------------------------------------------<br>
* (c) 2008-2013 FURTHeR Project, Health Sciences IT, University of Utah<br>
* Contact: {@code <further@utah.edu>}<br>
* Biomedical Informatics, 26 South 2000 East<br>
* Room 5775 HSEB, Salt Lake City, UT 84112<br>
* Day Phone: 1-801-581-4080<br>
* -----------------------------------------------------------------------------------
*
* @author Oren E. Livne {@code <oren.livne@utah.edu>}
* @version Aug 18, 2010
*/
public final class StringAttributeAdapter extends AbstractAttributeAdapter<String>
{
// ========================= CONSTRUCTORS ==============================
/**
* A no-argument constructor is required by JAXB.
*/
public StringAttributeAdapter()
{
super(null, new StringUnmarshallingAdapter());
}
}
| apache-2.0 |
argv0/cloudstack | awsapi/src/com/cloud/bridge/service/controller/s3/S3ObjectAction.java | 52580 | // 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 com.cloud.bridge.service.controller.s3;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.UUID;
import javax.activation.DataHandler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.DatatypeConverter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.stream.XMLStreamException;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.amazon.s3.CopyObjectResponse;
import com.amazon.s3.GetObjectAccessControlPolicyResponse;
import com.cloud.bridge.io.MTOMAwareResultStreamWriter;
import com.cloud.bridge.model.SAcl;
import com.cloud.bridge.model.SBucket;
import com.cloud.bridge.persist.dao.MultipartLoadDao;
import com.cloud.bridge.persist.dao.SBucketDao;
import com.cloud.bridge.service.S3Constants;
import com.cloud.bridge.service.S3RestServlet;
import com.cloud.bridge.service.UserContext;
import com.cloud.bridge.service.core.s3.S3AccessControlList;
import com.cloud.bridge.service.core.s3.S3AccessControlPolicy;
import com.cloud.bridge.service.core.s3.S3AuthParams;
import com.cloud.bridge.service.core.s3.S3ConditionalHeaders;
import com.cloud.bridge.service.core.s3.S3CopyObjectRequest;
import com.cloud.bridge.service.core.s3.S3CopyObjectResponse;
import com.cloud.bridge.service.core.s3.S3DeleteObjectRequest;
import com.cloud.bridge.service.core.s3.S3Engine;
import com.cloud.bridge.service.core.s3.S3GetObjectAccessControlPolicyRequest;
import com.cloud.bridge.service.core.s3.S3GetObjectRequest;
import com.cloud.bridge.service.core.s3.S3GetObjectResponse;
import com.cloud.bridge.service.core.s3.S3Grant;
import com.cloud.bridge.service.core.s3.S3MetaDataEntry;
import com.cloud.bridge.service.core.s3.S3MultipartPart;
import com.cloud.bridge.service.core.s3.S3PolicyContext;
import com.cloud.bridge.service.core.s3.S3PutObjectInlineRequest;
import com.cloud.bridge.service.core.s3.S3PutObjectInlineResponse;
import com.cloud.bridge.service.core.s3.S3PutObjectRequest;
import com.cloud.bridge.service.core.s3.S3Response;
import com.cloud.bridge.service.core.s3.S3SetBucketAccessControlPolicyRequest;
import com.cloud.bridge.service.core.s3.S3SetObjectAccessControlPolicyRequest;
import com.cloud.bridge.service.core.s3.S3PolicyAction.PolicyActions;
import com.cloud.bridge.service.exception.PermissionDeniedException;
import com.cloud.bridge.util.Converter;
import com.cloud.bridge.util.DateHelper;
import com.cloud.bridge.util.HeaderParam;
import com.cloud.bridge.util.ServletRequestDataSource;
import com.cloud.bridge.util.OrderedPair;
/**
* @author Kelven Yang, John Zucker
*/
public class S3ObjectAction implements ServletAction {
protected final static Logger logger = Logger.getLogger(S3ObjectAction.class);
private DocumentBuilderFactory dbf = null;
public S3ObjectAction() {
dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware( true );
}
public void execute(HttpServletRequest request, HttpServletResponse response)
throws IOException, XMLStreamException
{
String method = request.getMethod();
String queryString = request.getQueryString();
String copy = null;
response.addHeader( "x-amz-request-id", UUID.randomUUID().toString());
if ( method.equalsIgnoreCase( "GET" ))
{
if ( queryString != null && queryString.length() > 0 )
{
if (queryString.contains("acl")) executeGetObjectAcl(request, response);
else if (queryString.contains("uploadId")) executeListUploadParts(request, response);
else executeGetObject(request, response);
}
else executeGetObject(request, response);
}
else if (method.equalsIgnoreCase( "PUT" ))
{
if ( queryString != null && queryString.length() > 0 )
{
if (queryString.contains("acl")) executePutObjectAcl(request, response);
else if (queryString.contains("partNumber")) executeUploadPart(request, response);
else executePutObject(request, response);
}
else if ( null != (copy = request.getHeader( "x-amz-copy-source" )))
{
executeCopyObject(request, response, copy.trim());
}
else executePutObject(request, response);
}
else if (method.equalsIgnoreCase( "DELETE" ))
{
if ( queryString != null && queryString.length() > 0 )
{
if (queryString.contains("uploadId")) executeAbortMultipartUpload(request, response);
else executeDeleteObject(request, response);
}
else executeDeleteObject(request, response);
}
else if (method.equalsIgnoreCase( "HEAD" ))
{
executeHeadObject(request, response);
}
else if (method.equalsIgnoreCase( "POST" ))
{
if ( queryString != null && queryString.length() > 0 )
{
if (queryString.contains("uploads")) executeInitiateMultipartUpload(request, response);
else if (queryString.contains("uploadId")) executeCompleteMultipartUpload(request, response);
}
else if ( request.getAttribute(S3Constants.PLAIN_POST_ACCESS_KEY) !=null )
executePlainPostObject (request, response);
// TODO - Having implemented the request, now provide an informative HTML page response
else
executePostObject(request, response);
}
else throw new IllegalArgumentException( "Unsupported method in REST request");
}
private void executeCopyObject(HttpServletRequest request, HttpServletResponse response, String copy)
throws IOException, XMLStreamException
{
S3CopyObjectRequest engineRequest = new S3CopyObjectRequest();
String versionId = null;
String bucketName = (String)request.getAttribute(S3Constants.BUCKET_ATTR_KEY);
String key = (String)request.getAttribute(S3Constants.OBJECT_ATTR_KEY);
String sourceBucketName = null;
String sourceKey = null;
// [A] Parse the x-amz-copy-source header into usable pieces
// Check to find a ?versionId= value if any
int index = copy.indexOf( '?' );
if (-1 != index)
{
versionId = copy.substring( index+1 );
if (versionId.startsWith( "versionId=" )) engineRequest.setVersion( versionId.substring( 10 ));
copy = copy.substring( 0, index );
}
// The value of copy should look like: "bucket-name/object-name"
index = copy.indexOf( '/' );
// In case it looks like "/bucket-name/object-name" discard a leading '/' if it exists
if ( 0 == index )
{
copy = copy.substring(1);
index = copy.indexOf( '/' );
}
if ( -1 == index )
throw new IllegalArgumentException( "Invalid x-amz-copy-source header value [" + copy + "]" );
sourceBucketName = copy.substring( 0, index );
sourceKey = copy.substring( index+1 );
// [B] Set the object used in the SOAP request so it can do the bulk of the work for us
engineRequest.setSourceBucketName( sourceBucketName );
engineRequest.setSourceKey( sourceKey );
engineRequest.setDestinationBucketName( bucketName );
engineRequest.setDestinationKey( key );
engineRequest.setDataDirective( request.getHeader( "x-amz-metadata-directive" ));
engineRequest.setMetaEntries( extractMetaData( request ));
engineRequest.setCannedAccess( request.getHeader( "x-amz-acl" ));
engineRequest.setConditions( conditionalRequest( request, true ));
// [C] Do the actual work and return the result
S3CopyObjectResponse engineResponse = ServiceProvider.getInstance().getS3Engine().handleRequest( engineRequest );
versionId = engineResponse.getCopyVersion();
if (null != versionId) response.addHeader( "x-amz-copy-source-version-id", versionId );
versionId = engineResponse.getPutVersion();
if (null != versionId) response.addHeader( "x-amz-version-id", versionId );
// To allow the copy object result to be serialized via Axiom classes
CopyObjectResponse allBuckets = S3SerializableServiceImplementation.toCopyObjectResponse( engineResponse );
OutputStream outputStream = response.getOutputStream();
response.setStatus(200);
response.setContentType("application/xml");
// The content-type literally should be "application/xml; charset=UTF-8"
// but any compliant JVM supplies utf-8 by default;
MTOMAwareResultStreamWriter resultWriter = new MTOMAwareResultStreamWriter ("CopyObjectResult", outputStream );
resultWriter.startWrite();
resultWriter.writeout(allBuckets);
resultWriter.stopWrite();
}
private void executeGetObjectAcl(HttpServletRequest request, HttpServletResponse response) throws IOException, XMLStreamException
{
String bucketName = (String)request.getAttribute(S3Constants.BUCKET_ATTR_KEY);
String key = (String)request.getAttribute(S3Constants.OBJECT_ATTR_KEY);
S3GetObjectAccessControlPolicyRequest engineRequest = new S3GetObjectAccessControlPolicyRequest();
engineRequest.setBucketName( bucketName );
engineRequest.setKey( key );
// -> is this a request for a specific version of the object? look for "versionId=" in the query string
String queryString = request.getQueryString();
if (null != queryString) engineRequest.setVersion( returnParameter( queryString, "versionId=" ));
S3AccessControlPolicy engineResponse = ServiceProvider.getInstance().getS3Engine().handleRequest(engineRequest);
int resultCode = engineResponse.getResultCode();
if (200 != resultCode) {
response.setStatus( resultCode );
return;
}
String version = engineResponse.getVersion();
if (null != version) response.addHeader( "x-amz-version-id", version );
// To allow the get object acl policy result to be serialized via Axiom classes
GetObjectAccessControlPolicyResponse onePolicy = S3SerializableServiceImplementation.toGetObjectAccessControlPolicyResponse( engineResponse );
OutputStream outputStream = response.getOutputStream();
response.setStatus(200);
response.setContentType("application/xml");
// The content-type literally should be "application/xml; charset=UTF-8"
// but any compliant JVM supplies utf-8 by default;
MTOMAwareResultStreamWriter resultWriter = new MTOMAwareResultStreamWriter ("GetObjectAccessControlPolicyResult", outputStream );
resultWriter.startWrite();
resultWriter.writeout(onePolicy);
resultWriter.stopWrite();
}
private void executePutObjectAcl(HttpServletRequest request, HttpServletResponse response) throws IOException
{
// [A] Determine that there is an applicable bucket which might have an ACL set
String bucketName = (String)request.getAttribute(S3Constants.BUCKET_ATTR_KEY);
String key = (String)request.getAttribute(S3Constants.OBJECT_ATTR_KEY);
SBucketDao bucketDao = new SBucketDao();
SBucket bucket = bucketDao.getByName( bucketName );
String owner = null;
if ( null != bucket )
owner = bucket.getOwnerCanonicalId();
if (null == owner)
{
logger.error( "ACL update failed since " + bucketName + " does not exist" );
throw new IOException("ACL update failed");
}
if (null == key)
{
logger.error( "ACL update failed since " + bucketName + " does not contain the expected key" );
throw new IOException("ACL update failed");
}
// [B] Obtain the grant request which applies to the acl request string. This latter is supplied as the value of the x-amz-acl header.
S3SetObjectAccessControlPolicyRequest engineRequest = new S3SetObjectAccessControlPolicyRequest();
S3Grant grantRequest = new S3Grant();
S3AccessControlList aclRequest = new S3AccessControlList();
String aclRequestString = request.getHeader("x-amz-acl");
OrderedPair <Integer,Integer> accessControlsForObjectOwner = SAcl.getCannedAccessControls(aclRequestString,"SObject");
grantRequest.setPermission(accessControlsForObjectOwner.getFirst());
grantRequest.setGrantee(accessControlsForObjectOwner.getSecond());
grantRequest.setCanonicalUserID(owner);
aclRequest.addGrant(grantRequest);
engineRequest.setAcl(aclRequest);
engineRequest.setBucketName(bucketName);
engineRequest.setKey(key);
// [C] Allow an S3Engine to handle the S3SetObjectAccessControlPolicyRequest
S3Response engineResponse = ServiceProvider.getInstance().getS3Engine().handleRequest(engineRequest);
response.setStatus( engineResponse.getResultCode());
}
private void executeGetObject(HttpServletRequest request, HttpServletResponse response) throws IOException
{
String bucket = (String) request.getAttribute(S3Constants.BUCKET_ATTR_KEY);
String key = (String) request.getAttribute(S3Constants.OBJECT_ATTR_KEY);
S3GetObjectRequest engineRequest = new S3GetObjectRequest();
engineRequest.setBucketName(bucket);
engineRequest.setKey(key);
engineRequest.setInlineData(true);
engineRequest.setReturnData(true);
//engineRequest.setReturnMetadata(true);
engineRequest = setRequestByteRange( request, engineRequest );
// -> is this a request for a specific version of the object? look for "versionId=" in the query string
String queryString = request.getQueryString();
if (null != queryString) engineRequest.setVersion( returnParameter( queryString, "versionId=" ));
S3GetObjectResponse engineResponse = ServiceProvider.getInstance().getS3Engine().handleRequest( engineRequest );
response.setStatus( engineResponse.getResultCode());
if (engineResponse.getResultCode() >=400 ) {
return;
}
String deleteMarker = engineResponse.getDeleteMarker();
if ( null != deleteMarker ) {
response.addHeader( "x-amz-delete-marker", "true" );
response.addHeader( "x-amz-version-id", deleteMarker );
}
else {
String version = engineResponse.getVersion();
if (null != version) response.addHeader( "x-amz-version-id", version );
}
// -> was the get conditional?
if (!conditionPassed( request, response, engineResponse.getLastModified().getTime(), engineResponse.getETag()))
return;
// -> is there data to return
// -> from the Amazon REST documentation it appears that Meta data is only returned as part of a HEAD request
//returnMetaData( engineResponse, response );
DataHandler dataHandler = engineResponse.getData();
if (dataHandler != null) {
response.addHeader("ETag", "\"" + engineResponse.getETag() + "\"");
response.addHeader("Last-Modified", DateHelper.getDateDisplayString(
DateHelper.GMT_TIMEZONE, engineResponse.getLastModified().getTime(), "E, d MMM yyyy HH:mm:ss z"));
response.setContentLength((int)engineResponse.getContentLength());
S3RestServlet.writeResponse(response, dataHandler.getInputStream());
}
}
private void executePutObject(HttpServletRequest request, HttpServletResponse response) throws IOException
{
String continueHeader = request.getHeader( "Expect" );
if (continueHeader != null && continueHeader.equalsIgnoreCase("100-continue")) {
S3RestServlet.writeResponse(response, "HTTP/1.1 100 Continue\r\n");
}
long contentLength = Converter.toLong(request.getHeader("Content-Length"), 0);
String bucket = (String) request.getAttribute(S3Constants.BUCKET_ATTR_KEY);
String key = (String) request.getAttribute(S3Constants.OBJECT_ATTR_KEY);
S3PutObjectInlineRequest engineRequest = new S3PutObjectInlineRequest();
engineRequest.setBucketName(bucket);
engineRequest.setKey(key);
engineRequest.setContentLength(contentLength);
engineRequest.setMetaEntries( extractMetaData( request ));
engineRequest.setCannedAccess( request.getHeader( "x-amz-acl" ));
DataHandler dataHandler = new DataHandler(new ServletRequestDataSource(request));
engineRequest.setData(dataHandler);
S3PutObjectInlineResponse engineResponse = ServiceProvider.getInstance().getS3Engine().handleRequest(engineRequest);
response.setHeader("ETag", "\"" + engineResponse.getETag() + "\"");
String version = engineResponse.getVersion();
if (null != version) response.addHeader( "x-amz-version-id", version );
}
/**
* Once versioining is turned on then to delete an object requires specifying a version
* parameter. A deletion marker is set once versioning is turned on in a bucket.
*/
private void executeDeleteObject(HttpServletRequest request, HttpServletResponse response) throws IOException
{
String bucket = (String) request.getAttribute(S3Constants.BUCKET_ATTR_KEY);
String key = (String) request.getAttribute(S3Constants.OBJECT_ATTR_KEY);
S3DeleteObjectRequest engineRequest = new S3DeleteObjectRequest();
engineRequest.setBucketName(bucket);
engineRequest.setKey(key);
// -> is this a request for a specific version of the object? look for "versionId=" in the query string
String queryString = request.getQueryString();
if (null != queryString) engineRequest.setVersion( returnParameter( queryString, "versionId=" ));
S3Response engineResponse = ServiceProvider.getInstance().getS3Engine().handleRequest( engineRequest );
response.setStatus( engineResponse.getResultCode());
String version = engineRequest.getVersion();
if (null != version) response.addHeader( "x-amz-version-id", version );
}
/*
* The purpose of a plain POST operation is to add an object to a specified bucket using HTML forms.
* The capability is for developer and tester convenience providing a simple browser-based upload
* feature as an alternative to using PUTs.
* In the case of PUTs the upload information is passed through HTTP headers. However in the case of a
* POST this information must be supplied as form fields. Many of these are mandatory or otherwise
* the POST request will be rejected.
* The requester using the HTML page must submit valid credentials sufficient for checking that
* the bucket to which the object is to be added has WRITE permission for that user. The AWS access
* key field on the form is taken to be synonymous with the user canonical ID for this purpose.
*/
private void executePlainPostObject(HttpServletRequest request, HttpServletResponse response) throws IOException
{
String continueHeader = request.getHeader( "Expect" );
if (continueHeader != null && continueHeader.equalsIgnoreCase("100-continue")) {
S3RestServlet.writeResponse(response, "HTTP/1.1 100 Continue\r\n");
}
long contentLength = Converter.toLong(request.getHeader("Content-Length"), 0);
String bucket = (String) request.getAttribute(S3Constants.BUCKET_ATTR_KEY);
String key = (String) request.getAttribute(S3Constants.OBJECT_ATTR_KEY);
String accessKey = (String) request.getAttribute(S3Constants.PLAIN_POST_ACCESS_KEY);
String signature = (String) request.getAttribute(S3Constants.PLAIN_POST_SIGNATURE);
S3Grant grant = new S3Grant();
grant.setCanonicalUserID(accessKey);
grant.setGrantee(SAcl.GRANTEE_USER);
grant.setPermission(SAcl.PERMISSION_FULL);
S3AccessControlList acl = new S3AccessControlList();
acl.addGrant(grant);
S3PutObjectInlineRequest engineRequest = new S3PutObjectInlineRequest();
engineRequest.setBucketName(bucket);
engineRequest.setKey(key);
engineRequest.setAcl(acl);
engineRequest.setContentLength(contentLength);
engineRequest.setMetaEntries( extractMetaData( request ));
engineRequest.setCannedAccess( request.getHeader( "x-amz-acl" ));
DataHandler dataHandler = new DataHandler(new ServletRequestDataSource(request));
engineRequest.setData(dataHandler);
S3PutObjectInlineResponse engineResponse = ServiceProvider.getInstance().getS3Engine().handleRequest(engineRequest);
response.setHeader("ETag", "\"" + engineResponse.getETag() + "\"");
String version = engineResponse.getVersion();
if (null != version) response.addHeader( "x-amz-version-id", version );
}
private void executeHeadObject(HttpServletRequest request, HttpServletResponse response) throws IOException
{
String bucket = (String) request.getAttribute(S3Constants.BUCKET_ATTR_KEY);
String key = (String) request.getAttribute(S3Constants.OBJECT_ATTR_KEY);
S3GetObjectRequest engineRequest = new S3GetObjectRequest();
engineRequest.setBucketName(bucket);
engineRequest.setKey(key);
engineRequest.setInlineData(true); // -> need to set so we get ETag etc returned
engineRequest.setReturnData(true);
engineRequest.setReturnMetadata(true);
engineRequest = setRequestByteRange( request, engineRequest );
// -> is this a request for a specific version of the object? look for "versionId=" in the query string
String queryString = request.getQueryString();
if (null != queryString) engineRequest.setVersion( returnParameter( queryString, "versionId=" ));
S3GetObjectResponse engineResponse = ServiceProvider.getInstance().getS3Engine().handleRequest( engineRequest );
response.setStatus( engineResponse.getResultCode());
String deleteMarker = engineResponse.getDeleteMarker();
if ( null != deleteMarker ) {
response.addHeader( "x-amz-delete-marker", "true" );
response.addHeader( "x-amz-version-id", deleteMarker );
}
else {
String version = engineResponse.getVersion();
if (null != version) response.addHeader( "x-amz-version-id", version );
}
// -> was the head request conditional?
if (!conditionPassed( request, response, engineResponse.getLastModified().getTime(), engineResponse.getETag()))
return;
// -> for a head request we return everything except the data
returnMetaData( engineResponse, response );
DataHandler dataHandler = engineResponse.getData();
if (dataHandler != null) {
response.addHeader("ETag", "\"" + engineResponse.getETag() + "\"");
response.addHeader("Last-Modified", DateHelper.getDateDisplayString(
DateHelper.GMT_TIMEZONE, engineResponse.getLastModified().getTime(), "E, d MMM yyyy HH:mm:ss z"));
response.setContentLength((int)engineResponse.getContentLength());
}
}
// There is a problem with POST since the 'Signature' and 'AccessKey' parameters are not
// determined until we hit this function (i.e., they are encoded in the body of the message
// they are not HTTP request headers). All the values we used to get in the request headers
// are not encoded in the request body.
//
// add ETag header computed as Base64 MD5 whenever object is uploaded or updated
//
private void executePostObject( HttpServletRequest request, HttpServletResponse response ) throws IOException
{
String bucket = (String) request.getAttribute(S3Constants.BUCKET_ATTR_KEY);
String contentType = request.getHeader( "Content-Type" );
int boundaryIndex = contentType.indexOf( "boundary=" );
String boundary = "--" + (contentType.substring( boundaryIndex + 9 ));
String lastBoundary = boundary + "--";
InputStreamReader isr = new InputStreamReader( request.getInputStream());
BufferedReader br = new BufferedReader( isr );
StringBuffer temp = new StringBuffer();
String oneLine = null;
String name = null;
String value = null;
String metaName = null; // -> after stripped off the x-amz-meta-
boolean isMetaTag = false;
int countMeta = 0;
int state = 0;
// [A] First parse all the parts out of the POST request and message body
// -> bucket name is still encoded in a Host header
S3AuthParams params = new S3AuthParams();
List<S3MetaDataEntry> metaSet = new ArrayList<S3MetaDataEntry>();
S3PutObjectInlineRequest engineRequest = new S3PutObjectInlineRequest();
engineRequest.setBucketName( bucket );
// -> the last body part contains the content that is used to write the S3 object, all
// other body parts are header values
while( null != (oneLine = br.readLine()))
{
if ( oneLine.startsWith( lastBoundary ))
{
// -> this is the data of the object to put
if (0 < temp.length())
{
value = temp.toString();
temp.setLength( 0 );
engineRequest.setContentLength( value.length());
engineRequest.setDataAsString( value );
}
break;
}
else if ( oneLine.startsWith( boundary ))
{
// -> this is the header data
if (0 < temp.length())
{
value = temp.toString().trim();
temp.setLength( 0 );
//System.out.println( "param: " + name + " = " + value );
if (name.equalsIgnoreCase( "key" )) {
engineRequest.setKey( value );
}
else if (name.equalsIgnoreCase( "x-amz-acl" )) {
engineRequest.setCannedAccess( value );
}
else if (isMetaTag) {
S3MetaDataEntry oneMeta = new S3MetaDataEntry();
oneMeta.setName( metaName );
oneMeta.setValue( value );
metaSet.add( oneMeta );
countMeta++;
metaName = null;
}
// -> build up the headers so we can do authentication on this POST
HeaderParam oneHeader = new HeaderParam();
oneHeader.setName( name );
oneHeader.setValue( value );
params.addHeader( oneHeader );
}
state = 1;
}
else if (1 == state && 0 == oneLine.length())
{
// -> data of a body part starts here
state = 2;
}
else if (1 == state)
{
// -> the name of the 'name-value' pair is encoded in the Content-Disposition header
if (oneLine.startsWith( "Content-Disposition: form-data;"))
{
isMetaTag = false;
int nameOffset = oneLine.indexOf( "name=" );
if (-1 != nameOffset)
{
name = oneLine.substring( nameOffset+5 );
if (name.startsWith( "\"" )) name = name.substring( 1 );
if (name.endsWith( "\"" )) name = name.substring( 0, name.length()-1 );
name = name.trim();
if (name.startsWith( "x-amz-meta-" )) {
metaName = name.substring( 11 );
isMetaTag = true;
}
}
}
}
else if (2 == state)
{
// -> the body parts data may take up multiple lines
//System.out.println( oneLine.length() + " body data: " + oneLine );
temp.append( oneLine );
}
// else System.out.println( oneLine.length() + " preamble: " + oneLine );
}
// [B] Authenticate the POST request after we have all the headers
try {
S3RestServlet.authenticateRequest( request, params );
}
catch( Exception e ) {
throw new IOException( e.toString());
}
// [C] Perform the request
if (0 < countMeta) engineRequest.setMetaEntries( metaSet.toArray(new S3MetaDataEntry[0]));
S3PutObjectInlineResponse engineResponse = ServiceProvider.getInstance().getS3Engine().handleRequest( engineRequest );
response.setHeader("ETag", "\"" + engineResponse.getETag() + "\"");
String version = engineResponse.getVersion();
if (null != version) response.addHeader( "x-amz-version-id", version );
}
/**
* Save all the information about the multipart upload request in the database so once it is finished
* (in the future) we can create the real S3 object.
*
* @throws IOException
*/
private void executeInitiateMultipartUpload( HttpServletRequest request, HttpServletResponse response ) throws IOException
{
// This request is via a POST which typically has its auth parameters inside the message
try {
S3RestServlet.authenticateRequest( request, S3RestServlet.extractRequestHeaders( request ));
}
catch( Exception e ) {
throw new IOException( e.toString());
}
String bucket = (String) request.getAttribute(S3Constants.BUCKET_ATTR_KEY);
String key = (String) request.getAttribute(S3Constants.OBJECT_ATTR_KEY);
String cannedAccess = request.getHeader( "x-amz-acl" );
S3MetaDataEntry[] meta = extractMetaData( request );
// -> the S3 engine has easy access to all the privileged checking code
S3PutObjectInlineRequest engineRequest = new S3PutObjectInlineRequest();
engineRequest.setBucketName(bucket);
engineRequest.setKey(key);
engineRequest.setCannedAccess( cannedAccess );
engineRequest.setMetaEntries( meta );
S3PutObjectInlineResponse engineResponse = ServiceProvider.getInstance().getS3Engine().initiateMultipartUpload( engineRequest );
int result = engineResponse.getResultCode();
response.setStatus( result );
if (200 != result) return;
// -> there is no SOAP version of this function
StringBuffer xml = new StringBuffer();
xml.append( "<?xml version=\"1.0\" encoding=\"utf-8\"?>" );
xml.append( "<InitiateMultipartUploadResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">" );
xml.append( "<Bucket>" ).append( bucket ).append( "</Bucket>" );
xml.append( "<Key>" ).append( key ).append( "</Key>" );
xml.append( "<UploadId>" ).append( engineResponse.getUploadId()).append( "</UploadId>" );
xml.append( "</InitiateMultipartUploadResult>" );
response.setContentType("text/xml; charset=UTF-8");
S3RestServlet.endResponse(response, xml.toString());
}
private void executeUploadPart( HttpServletRequest request, HttpServletResponse response ) throws IOException
{
String continueHeader = request.getHeader( "Expect" );
if (continueHeader != null && continueHeader.equalsIgnoreCase("100-continue")) {
S3RestServlet.writeResponse(response, "HTTP/1.1 100 Continue\r\n");
}
String bucket = (String) request.getAttribute(S3Constants.BUCKET_ATTR_KEY);
String key = (String) request.getAttribute(S3Constants.OBJECT_ATTR_KEY);
int partNumber = -1;
int uploadId = -1;
long contentLength = Converter.toLong(request.getHeader("Content-Length"), 0);
String temp = request.getParameter("uploadId");
if (null != temp) uploadId = Integer.parseInt( temp );
temp = request.getParameter("partNumber");
if (null != temp) partNumber = Integer.parseInt( temp );
if (partNumber < 1 || partNumber > 10000) {
logger.error("uploadPart invalid part number " + partNumber );
response.setStatus(416);
return;
}
// -> verification
try {
MultipartLoadDao uploadDao = new MultipartLoadDao();
if (null == uploadDao.multipartExits( uploadId )) {
response.setStatus(404);
return;
}
// -> another requirement is that only the upload initiator can upload parts
String initiator = uploadDao.getInitiator( uploadId );
if (null == initiator || !initiator.equals( UserContext.current().getAccessKey())) {
response.setStatus(403);
return;
}
}
catch( Exception e ) {
logger.error("executeUploadPart failed due to " + e.getMessage(), e);
response.setStatus(500);
return;
}
S3PutObjectInlineRequest engineRequest = new S3PutObjectInlineRequest();
engineRequest.setBucketName(bucket);
engineRequest.setKey(key);
engineRequest.setContentLength(contentLength);
DataHandler dataHandler = new DataHandler(new ServletRequestDataSource(request));
engineRequest.setData(dataHandler);
S3PutObjectInlineResponse engineResponse = ServiceProvider.getInstance().getS3Engine().saveUploadPart( engineRequest, uploadId, partNumber );
if (null != engineResponse.getETag()) response.setHeader("ETag", "\"" + engineResponse.getETag() + "\"");
response.setStatus(engineResponse.getResultCode());
}
/**
* This function is required to both parsing XML on the request and return XML as part of its result.
*
* @param request
* @param response
* @throws IOException
*/
private void executeCompleteMultipartUpload( HttpServletRequest request, HttpServletResponse response ) throws IOException
{
// [A] This request is via a POST which typically has its auth parameters inside the message
try {
S3RestServlet.authenticateRequest( request, S3RestServlet.extractRequestHeaders( request ));
}
catch( Exception e ) {
throw new IOException( e.toString());
}
String bucket = (String) request.getAttribute(S3Constants.BUCKET_ATTR_KEY);
String key = (String) request.getAttribute(S3Constants.OBJECT_ATTR_KEY);
S3MultipartPart[] parts = null;
S3MetaDataEntry[] meta = null;
String cannedAccess = null;
int uploadId = -1;
// AWS S3 specifies that the keep alive connection is by sending whitespace characters until done
// Therefore the XML version prolog is prepended to the stream in advance
OutputStream outputStream = response.getOutputStream();
outputStream.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>".getBytes());
String temp = request.getParameter("uploadId");
if (null != temp) uploadId = Integer.parseInt( temp );
// [B] Look up all the uploaded body parts and related info
try {
MultipartLoadDao uploadDao = new MultipartLoadDao();
if (null == uploadDao.multipartExits( uploadId )) {
response.setStatus(404);
returnErrorXML( 404, "NotFound", outputStream );
return;
}
// -> another requirement is that only the upload initiator can upload parts
String initiator = uploadDao.getInitiator( uploadId );
if (null == initiator || !initiator.equals( UserContext.current().getAccessKey())) {
response.setStatus(403);
returnErrorXML( 403, "Forbidden", outputStream );
return;
}
parts = uploadDao.getParts( uploadId, 10000, 0 );
meta = uploadDao.getMeta( uploadId );
cannedAccess = uploadDao.getCannedAccess( uploadId );
}
catch( Exception e ) {
logger.error("executeCompleteMultipartUpload failed due to " + e.getMessage(), e);
response.setStatus(500);
returnErrorXML( 500, "InternalError", outputStream );
return;
}
// [C] Parse the given XML body part and perform error checking
OrderedPair<Integer,String> match = verifyParts( request.getInputStream(), parts );
if (200 != match.getFirst().intValue()) {
response.setStatus(match.getFirst().intValue());
returnErrorXML( match.getFirst().intValue(), match.getSecond(), outputStream );
return;
}
// [D] Ask the engine to create a newly re-constituted object
S3PutObjectInlineRequest engineRequest = new S3PutObjectInlineRequest();
engineRequest.setBucketName(bucket);
engineRequest.setKey(key);
engineRequest.setMetaEntries(meta);
engineRequest.setCannedAccess(cannedAccess);
S3PutObjectInlineResponse engineResponse = ServiceProvider.getInstance().getS3Engine().concatentateMultipartUploads( response, engineRequest, parts, outputStream );
int result = engineResponse.getResultCode();
// -> free all multipart state since we now have one concatentated object
if (200 == result) ServiceProvider.getInstance().getS3Engine().freeUploadParts( bucket, uploadId, false );
// If all successful then clean up all left over parts
// Notice that "<?xml version=\"1.0\" encoding=\"utf-8\"?>" has already been written into the servlet output stream at the beginning of section [A]
if ( 200 == result )
{
StringBuffer xml = new StringBuffer();
xml.append( "<CompleteMultipartUploadResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">" );
xml.append( "<Location>" ).append( "http://" + bucket + ".s3.amazonaws.com/" + key ).append( "</Location>" );
xml.append( "<Bucket>" ).append( bucket ).append( "</Bucket>" );
xml.append( "<Key>" ).append( key ).append( "</Key>" );
xml.append( "<ETag>\"" ).append( engineResponse.getETag()).append( "\"</ETag>" );
xml.append( "</CompleteMultipartUploadResult>" );
String xmlString = xml.toString().replaceAll("^\\s+", ""); // Remove leading whitespace characters
outputStream.write( xmlString.getBytes());
outputStream.close();
}
else returnErrorXML( result, null, outputStream );
}
private void executeAbortMultipartUpload( HttpServletRequest request, HttpServletResponse response ) throws IOException
{
String bucket = (String) request.getAttribute(S3Constants.BUCKET_ATTR_KEY);
int uploadId = -1;
String temp = request.getParameter("uploadId");
if (null != temp) uploadId = Integer.parseInt( temp );
int result = ServiceProvider.getInstance().getS3Engine().freeUploadParts( bucket, uploadId, true );
response.setStatus( result );
}
private void executeListUploadParts( HttpServletRequest request, HttpServletResponse response ) throws IOException
{
String bucketName = (String) request.getAttribute(S3Constants.BUCKET_ATTR_KEY);
String key = (String) request.getAttribute(S3Constants.OBJECT_ATTR_KEY);
String owner = null;
String initiator = null;
S3MultipartPart[] parts = null;
int remaining = 0;
int uploadId = -1;
int maxParts = 1000;
int partMarker = 0;
int nextMarker = 0;
String temp = request.getParameter("uploadId");
if (null != temp) uploadId = Integer.parseInt( temp );
temp = request.getParameter("max-parts");
if (null != temp) {
maxParts = Integer.parseInt( temp );
if (maxParts > 1000 || maxParts < 0) maxParts = 1000;
}
temp = request.getParameter("part-number-marker");
if (null != temp) partMarker = Integer.parseInt( temp );
// -> does the bucket exist, we may need it to verify access permissions
SBucketDao bucketDao = new SBucketDao();
SBucket bucket = bucketDao.getByName(bucketName);
if (bucket == null) {
logger.error( "listUploadParts failed since " + bucketName + " does not exist" );
response.setStatus(404);
return;
}
try {
MultipartLoadDao uploadDao = new MultipartLoadDao();
OrderedPair<String,String> exists = uploadDao.multipartExits( uploadId );
if (null == exists) {
response.setStatus(404);
return;
}
owner = exists.getFirst();
// -> the multipart initiator or bucket owner can do this action
initiator = uploadDao.getInitiator( uploadId );
if (null == initiator || !initiator.equals( UserContext.current().getAccessKey()))
{
try {
// -> write permission on a bucket allows a PutObject / DeleteObject action on any object in the bucket
S3PolicyContext context = new S3PolicyContext( PolicyActions.ListMultipartUploadParts, bucketName );
context.setKeyName( exists.getSecond());
S3Engine.verifyAccess( context, "SBucket", bucket.getId(), SAcl.PERMISSION_WRITE );
}
catch (PermissionDeniedException e) {
response.setStatus(403);
return;
}
}
parts = uploadDao.getParts( uploadId, maxParts, partMarker );
remaining = uploadDao.numParts( uploadId, partMarker+maxParts );
}
catch( Exception e ) {
logger.error("List Uploads failed due to " + e.getMessage(), e);
response.setStatus(500);
}
StringBuffer xml = new StringBuffer();
xml.append( "<?xml version=\"1.0\" encoding=\"utf-8\"?>" );
xml.append( "<ListPartsResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">" );
xml.append( "<Bucket>" ).append( bucket ).append( "</Bucket>" );
xml.append( "<Key>" ).append( key ).append( "</Key>" );
xml.append( "<UploadId>" ).append( uploadId ).append( "</UploadId>" );
// -> currently we just have the access key and have no notion of a display name
xml.append( "<Initiator>" );
xml.append( "<ID>" ).append( initiator ).append( "</ID>" );
xml.append( "<DisplayName></DisplayName>" );
xml.append( "</Initiator>" );
xml.append( "<Owner>" );
xml.append( "<ID>" ).append( owner ).append( "</ID>" );
xml.append( "<DisplayName></DisplayName>" );
xml.append( "</Owner>" );
StringBuffer partsList = new StringBuffer();
for( int i=0; i < parts.length; i++ )
{
S3MultipartPart onePart = parts[i];
if (null == onePart) break;
nextMarker = onePart.getPartNumber();
partsList.append( "<Part>" );
partsList.append( "<PartNumber>" ).append( nextMarker ).append( "</PartNumber>" );
partsList.append( "<LastModified>" ).append( DatatypeConverter.printDateTime( onePart.getLastModified())).append( "</LastModified>" );
partsList.append( "<ETag>\"" ).append( onePart.getETag()).append( "\"</ETag>" );
partsList.append( "<Size>" ).append( onePart.getSize()).append( "</Size>" );
partsList.append( "</Part>" );
}
xml.append( "<StorageClass>STANDARD</StorageClass>" );
xml.append( "<PartNumberMarker>" ).append( partMarker ).append( "</PartNumberMarker>" );
xml.append( "<NextPartNumberMarker>" ).append( nextMarker ).append( "</NextPartNumberMarker>" );
xml.append( "<MaxParts>" ).append( maxParts ).append( "</MaxParts>" );
xml.append( "<IsTruncated>" ).append((0 < remaining ? "true" : "false" )).append( "</IsTruncated>" );
xml.append( partsList.toString());
xml.append( "</ListPartsResult>" );
response.setStatus(200);
response.setContentType("text/xml; charset=UTF-8");
S3RestServlet.endResponse(response, xml.toString());
}
/**
* Support the "Range: bytes=0-399" header with just one byte range.
* @param request
* @param engineRequest
* @return
*/
private S3GetObjectRequest setRequestByteRange( HttpServletRequest request, S3GetObjectRequest engineRequest )
{
String temp = request.getHeader( "Range" );
if (null == temp) return engineRequest;
int offset = temp.indexOf( "=" );
if (-1 != offset)
{
String range = temp.substring( offset+1 );
String[] parts = range.split( "-" );
if (2 >= parts.length) {
// -> the end byte is inclusive
engineRequest.setByteRangeStart( Long.parseLong(parts[0]));
engineRequest.setByteRangeEnd( Long.parseLong(parts[1])+1);
}
}
return engineRequest;
}
private S3ConditionalHeaders conditionalRequest( HttpServletRequest request, boolean isCopy )
{
S3ConditionalHeaders headers = new S3ConditionalHeaders();
if (isCopy) {
headers.setModifiedSince( request.getHeader( "x-amz-copy-source-if-modified-since" ));
headers.setUnModifiedSince( request.getHeader( "x-amz-copy-source-if-unmodified-since" ));
headers.setMatch( request.getHeader( "x-amz-copy-source-if-match" ));
headers.setNoneMatch( request.getHeader( "x-amz-copy-source-if-none-match" ));
}
else {
headers.setModifiedSince( request.getHeader( "If-Modified-Since" ));
headers.setUnModifiedSince( request.getHeader( "If-Unmodified-Since" ));
headers.setMatch( request.getHeader( "If-Match" ));
headers.setNoneMatch( request.getHeader( "If-None-Match" ));
}
return headers;
}
private boolean conditionPassed( HttpServletRequest request, HttpServletResponse response, Date lastModified, String ETag )
{
S3ConditionalHeaders ifCond = conditionalRequest( request, false );
if (0 > ifCond.ifModifiedSince( lastModified )) {
response.setStatus( 304 );
return false;
}
if (0 > ifCond.ifUnmodifiedSince( lastModified )) {
response.setStatus( 412 );
return false;
}
if (0 > ifCond.ifMatchEtag( ETag )) {
response.setStatus( 412 );
return false;
}
if (0 > ifCond.ifNoneMatchEtag( ETag )) {
response.setStatus( 412 );
return false;
}
return true;
}
/**
* Return the saved object's meta data back to the client as HTTP "x-amz-meta-" headers.
* This function is constructing an HTTP header and these headers have a defined syntax
* as defined in rfc2616. Any characters that could cause an invalid HTTP header will
* prevent that meta data from being returned via the REST call (as is defined in the Amazon
* spec). These characters can be defined if using the SOAP API as well as the REST API.
*
* @param engineResponse
* @param response
*/
private void returnMetaData( S3GetObjectResponse engineResponse, HttpServletResponse response )
{
boolean ignoreMeta = false;
int ignoredCount = 0;
S3MetaDataEntry[] metaSet = engineResponse.getMetaEntries();
for( int i=0; null != metaSet && i < metaSet.length; i++ )
{
String name = metaSet[i].getName();
String value = metaSet[i].getValue();
byte[] nameBytes = name.getBytes();
ignoreMeta = false;
// -> cannot have control characters (octets 0 - 31) and DEL (127), in an HTTP header
for( int j=0; j < name.length(); j++ ) {
if ((0 <= nameBytes[j] && 31 >= nameBytes[j]) || 127 == nameBytes[j]) {
ignoreMeta = true;
break;
}
}
// -> cannot have HTTP separators in an HTTP header
if (-1 != name.indexOf('(') || -1 != name.indexOf(')') || -1 != name.indexOf('@') ||
-1 != name.indexOf('<') || -1 != name.indexOf('>') || -1 != name.indexOf('\"') ||
-1 != name.indexOf('[') || -1 != name.indexOf(']') || -1 != name.indexOf('=') ||
-1 != name.indexOf(',') || -1 != name.indexOf(';') || -1 != name.indexOf(':') ||
-1 != name.indexOf('\\') || -1 != name.indexOf('/') || -1 != name.indexOf(' ') ||
-1 != name.indexOf('{') || -1 != name.indexOf('}') || -1 != name.indexOf('?') ||
-1 != name.indexOf('\t')
) ignoreMeta = true;
if ( ignoreMeta )
ignoredCount++;
else response.addHeader( "x-amz-meta-" + name, value );
}
if (0 < ignoredCount) response.addHeader( "x-amz-missing-meta", new String( "" + ignoredCount ));
}
/**
* Extract the name and value of all meta data so it can be written with the
* object that is being 'PUT'.
*
* @param request
* @return
*/
private S3MetaDataEntry[] extractMetaData( HttpServletRequest request )
{
List<S3MetaDataEntry> metaSet = new ArrayList<S3MetaDataEntry>();
int count = 0;
Enumeration headers = request.getHeaderNames();
while( headers.hasMoreElements())
{
String key = (String)headers.nextElement();
if (key.startsWith( "x-amz-meta-" ))
{
String name = key.substring( 11 );
String value = request.getHeader( key );
if (null != value) {
S3MetaDataEntry oneMeta = new S3MetaDataEntry();
oneMeta.setName( name );
oneMeta.setValue( value );
metaSet.add( oneMeta );
count++;
}
}
}
if ( 0 < count )
return metaSet.toArray(new S3MetaDataEntry[0]);
else return null;
}
/**
* Parameters on the query string may or may not be name-value pairs.
* For example: "?acl&versionId=2", notice that "acl" has no value other
* than it is present.
*
* @param queryString - from a URL to locate the 'find' parameter
* @param find - name string to return first found
* @return the value matching the found name
*/
private String returnParameter( String queryString, String find )
{
int offset = queryString.indexOf( find );
if (-1 != offset)
{
String temp = queryString.substring( offset );
String[] paramList = temp.split( "[&=]" );
if (null != paramList && 2 <= paramList.length) return paramList[1];
}
return null;
}
private void returnErrorXML( int errorCode, String errorDescription, OutputStream os ) throws IOException
{
StringBuffer xml = new StringBuffer();
xml.append( "<?xml version=\"1.0\" encoding=\"utf-8\"?>" );
xml.append( "<Error>" );
if ( null != errorDescription )
xml.append( "<Code>" ).append( errorDescription ).append( "</Code>" );
else xml.append( "<Code>" ).append( errorCode ).append( "</Code>" );
xml.append( "<Message>" ).append( "" ).append( "</Message>" );
xml.append( "<RequestId>" ).append( "" ).append( "</RequestId>" );
xml.append( "<HostId>" ).append( "" ).append( "</<HostId>" );
xml.append( "</Error>" );
os.write( xml.toString().getBytes());
os.close();
}
/**
* The Complete Multipart Upload function pass in the request body a list of
* all uploaded body parts. It is required that we verify that list matches
* what was uploaded.
*
* @param is
* @param parts
* @return error code, and error string
* @throws ParserConfigurationException, IOException, SAXException
*/
private OrderedPair<Integer,String> verifyParts( InputStream is, S3MultipartPart[] parts )
{
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware( true );
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse( is );
Node parent = null;
Node contents = null;
NodeList children = null;
String temp = null;
String element = null;
String eTag = null;
int lastNumber = -1;
int partNumber = -1;
int count = 0;
// -> handle with and without a namespace
NodeList nodeSet = doc.getElementsByTagNameNS( "http://s3.amazonaws.com/doc/2006-03-01/", "Part" );
count = nodeSet.getLength();
if (0 == count) {
nodeSet = doc.getElementsByTagName( "Part" );
count = nodeSet.getLength();
}
if (count != parts.length) return new OrderedPair<Integer, String>(400, "InvalidPart");
// -> get a list of all the children elements of the 'Part' parent element
for( int i=0; i < count; i++ )
{
partNumber = -1;
eTag = null;
parent = nodeSet.item(i);
if (null != (children = parent.getChildNodes()))
{
int numChildren = children.getLength();
for( int j=0; j < numChildren; j++ )
{
contents = children.item( j );
element = contents.getNodeName().trim();
if ( element.endsWith( "PartNumber" ))
{
temp = contents.getFirstChild().getNodeValue();
if (null != temp) partNumber = Integer.parseInt( temp );
//System.out.println( "part: " + partNumber );
}
else if (element.endsWith( "ETag" ))
{
eTag = contents.getFirstChild().getNodeValue();
//System.out.println( "etag: " + eTag );
}
}
}
// -> do the parts given in the call XML match what was previously uploaded?
if (lastNumber >= partNumber) {
return new OrderedPair<Integer, String>(400, "InvalidPartOrder");
}
if (partNumber != parts[i].getPartNumber() ||
eTag == null ||
!eTag.equalsIgnoreCase( "\"" + parts[i].getETag() + "\"" )) {
return new OrderedPair<Integer, String>(400, "InvalidPart");
}
lastNumber = partNumber;
}
return new OrderedPair<Integer, String>(200, "Success");
}
catch( Exception e ) {
return new OrderedPair<Integer, String>(500, e.toString());
}
}
}
| apache-2.0 |
joaogithub/Testes | src/com/testes/activity/AdsActivity.java | 337 | package com.testes.activity;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import com.testes.android.R;
public class AdsActivity extends ActionBarActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ad_layout);
}
}
| apache-2.0 |
cping/LGame | Java/old/OpenGL-1.0(old_ver)/Loon-backend-Android/src/loon/core/timer/GameTime.java | 1663 | /**
* Copyright 2008 - 2012
*
* 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.
*
* @project loon
* @author cping
* @email:javachenpeng@yahoo.com
* @version 0.3.3
*/
package loon.core.timer;
public class GameTime {
float _elapsedTime;
float _totalTime;
boolean _running;
public GameTime() {
_elapsedTime = _totalTime = 0f;
}
public GameTime(float totalGameTime, float elapsedGameTime) {
_totalTime = totalGameTime;
_elapsedTime = elapsedGameTime;
}
public GameTime(float totalRealTime, float elapsedRealTime,
boolean isRunningSlowly) {
_totalTime = totalRealTime;
_elapsedTime = elapsedRealTime;
_running = isRunningSlowly;
}
public void update(float elapsed) {
_elapsedTime = elapsed;
_totalTime += elapsed;
}
public void update(LTimerContext context) {
update(context.getMilliseconds());
}
public void resetElapsedTime() {
_elapsedTime = 0f;
}
public boolean isRunningSlowly() {
return _running;
}
public float getMilliseconds() {
return _elapsedTime * 1000;
}
public float getElapsedGameTime() {
return _elapsedTime;
}
public float getTotalGameTime() {
return _totalTime;
}
}
| apache-2.0 |
GcsSloop/diycode | diycode-app/src/main/java/com/gcssloop/diycode/fragment/NotificationsFragment.java | 4216 | /*
* Copyright 2017 GcsSloop
*
* 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.
*
* Last modified 2017-04-09 21:20:23
*
* GitHub: https://github.com/GcsSloop
* Website: http://www.gcssloop.com
* Weibo: http://weibo.com/GcsSloop
*/
package com.gcssloop.diycode.fragment;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import com.gcssloop.diycode.fragment.base.SimpleRefreshRecyclerFragment;
import com.gcssloop.diycode.fragment.provider.NotificationsProvider;
import com.gcssloop.diycode_sdk.api.notifications.bean.Notification;
import com.gcssloop.diycode_sdk.api.notifications.event.GetNotificationsListEvent;
import com.gcssloop.recyclerview.adapter.multitype.HeaderFooterAdapter;
import java.util.ArrayList;
import java.util.List;
/**
* 通知列表
*/
public class NotificationsFragment extends SimpleRefreshRecyclerFragment<Notification,
GetNotificationsListEvent> {
private static String TYPE_NodeChanged = "NodeChanged"; // 节点变更
private static String TYPE_TopicReply = "TopicReply"; // Topic 回复
private static String TYPE_NewsReply = "Hacknews"; // News 回复
private static String TYPE_Mention = "Mention"; // 有人提及
private static String MENTION_TYPE_TopicReply = "Reply"; // - Topic 回复中提及
private static String MENTION_TYPE_NewReply = "HacknewsReply"; // - News 回复中提及
private static String MENTION_TYPE_ProjectReply = "ProjectReply"; // - 项目 回复中提及
public static NotificationsFragment newInstance() {
Bundle args = new Bundle();
NotificationsFragment fragment = new NotificationsFragment();
fragment.setArguments(args);
return fragment;
}
@Override public void initData(HeaderFooterAdapter adapter) {
loadMore();
}
@Override
protected void setAdapterRegister(Context context, RecyclerView recyclerView,
HeaderFooterAdapter adapter) {
adapter.register(Notification.class, new NotificationsProvider(getContext()));
}
@NonNull @Override protected String request(int offset, int limit) {
return mDiycode.getNotificationsList(offset, limit);
}
@Override
protected void onRefresh(GetNotificationsListEvent event, HeaderFooterAdapter adapter) {
List<Notification> data = clearData(event.getBean());
adapter.clearDatas();
adapter.addDatas(data);
toast("刷新成功");
}
@Override
protected void onLoadMore(GetNotificationsListEvent event, HeaderFooterAdapter adapter) {
List<Notification> data = clearData(event.getBean());
adapter.addDatas(data);
}
/**
* 清洗数据,主要清洗对象
* 1. HackNew 的回复 type = Hacknews
* 2. HackNew 的提及 type = Mention, mention_type = HacknewsReply
* 3. Project 的提及 type = Mention, mention_type = ProjectReply
* <p>
* 保留数据
* 1. Topic 的回复 type = TopicReply
* 2. Topic 的提及 type = Mention, mention_type = Reply
*/
public List<Notification> clearData(List<Notification> datas) {
List<Notification> clearDatas = new ArrayList<>();
for (Notification data : datas) {
if (data.getType().equals(TYPE_TopicReply) ||
(data.getType().equals(TYPE_Mention) && data.getMention_type().equals
(MENTION_TYPE_TopicReply))) {
clearDatas.add(data);
}
}
return clearDatas;
}
}
| apache-2.0 |
jerkar/jerkar | dev.jeka.core/src/main/java/dev/jeka/core/api/java/JkInternalClassloader.java | 5248 | package dev.jeka.core.api.java;
import dev.jeka.core.api.system.JkLocator;
import dev.jeka.core.api.utils.*;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
/**
* Not part of the public API
*/
public class JkInternalClassloader {
private final ClassLoader classLoader;
private JkInternalClassloader(ClassLoader classLoader) {
this.classLoader = classLoader;
}
public static final Path URL_CACHE_DIR = JkLocator.getJekaUserHomeDir().resolve("cache/url-content");
static {
JkUtilsPath.createDirectories(URL_CACHE_DIR);
}
public static JkInternalClassloader of(ClassLoader classLoader) {
return new JkInternalClassloader(classLoader);
}
public static JkInternalClassloader ofMainEmbeddedLibs() {
return ofMainEmbeddedLibs(Collections.emptyList());
}
public static JkInternalClassloader ofMainEmbeddedLibs(List<Path> extraEntries) {
JkUtilsSystem.disableUnsafeWarning(); // Avoiding unsafe warning due to Ivy.
List<Path> pathList = new LinkedList<>();
URL embeddedNameUrl = JkClassLoader.ofCurrent().get().getResource("META-INF/jeka-embedded-name");
if (embeddedNameUrl != null) {
String jarName = JkUtilsIO.read(embeddedNameUrl);
Path file = getEmbeddedLibAsPath("META-INF/" + jarName);
pathList.add(file);
}
pathList.addAll(extraEntries);
List<URL> urlList = pathList.stream()
.map(JkUtilsPath::toUrl)
.collect(Collectors.toList());
URL[] urls = urlList.toArray(new URL[0]);
ClassLoader classLoader = new URLClassLoader(urls, JkClassLoader.ofCurrent().get());
return of(classLoader);
}
public static Path getEmbeddedLibAsPath(String resourcePath) {
URL url = JkClassLoader.ofCurrent().get().getResource(resourcePath);
final String name = resourcePath.contains("/") ? JkUtilsString.substringBeforeLast(resourcePath, "/")
: resourcePath;
Path result = URL_CACHE_DIR.resolve(name);
if (Files.exists(result)) {
return result;
}
return JkUtilsIO.copyUrlContentToCacheFile(url, null, URL_CACHE_DIR);
}
public JkClassLoader get() {
return JkClassLoader.of(classLoader);
}
/**
* Creates an instance of the specified class in this classloader and
* callable from the current thread classloader.
*/
@SuppressWarnings("unchecked")
public <T> T createCrossClassloaderProxy(Class<T> interfaze, String className,
String staticMethodFactory, Object... args) {
final Object target = invokeStaticMethod(className, staticMethodFactory, args);
ClassLoader from = Thread.currentThread().getContextClassLoader();
return ((T) Proxy.newProxyInstance(from,
new Class[]{interfaze}, new CrossClassloaderInvocationHandler(target, from)));
}
private class CrossClassloaderInvocationHandler implements InvocationHandler {
CrossClassloaderInvocationHandler(Object target, ClassLoader fromClassLoader) {
this.targetObject = target;
this.fromClassLoader = fromClassLoader;
}
private final Object targetObject;
private final ClassLoader fromClassLoader;
@Override
public Object invoke(Object proxy, Method method, Object[] args) {
final Method targetMethod = JkUtilsReflect.methodWithSameNameAndArgType(method,
targetObject.getClass());
return invokeInstanceMethod(fromClassLoader, targetObject, targetMethod, args);
}
}
@SuppressWarnings("unchecked")
private <T> T invokeInstanceMethod(ClassLoader from, Object object, Method method,
Object... args) {
final ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(classLoader);
try {
final Object returned = JkUtilsReflect.invoke(object, method, args);
return (T) returned;
} catch (final IllegalArgumentException e) {
throw new RuntimeException(e);
} finally {
Thread.currentThread().setContextClassLoader(currentClassLoader);
}
}
@SuppressWarnings("unchecked")
private <T> T invokeStaticMethod(String className, String methodName,
Object... args) {
final ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(classLoader);
try {
final Class<?> clazz = get().load(className);
return (T) JkUtilsReflect.invokeStaticMethod(clazz, methodName, args);
} finally {
Thread.currentThread().setContextClassLoader(currentClassLoader);
}
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-iotwireless/src/main/java/com/amazonaws/services/iotwireless/package-info.java | 1658 | /*
* Copyright 2017-2022 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.
*/
/**
* <p>
* AWS IoT Wireless provides bi-directional communication between internet-connected wireless devices and the AWS Cloud.
* To onboard both LoRaWAN and Sidewalk devices to AWS IoT, use the IoT Wireless API. These wireless devices use the Low
* Power Wide Area Networking (LPWAN) communication protocol to communicate with AWS IoT.
* </p>
* <p>
* Using the API, you can perform create, read, update, and delete operations for your wireless devices, gateways,
* destinations, and profiles. After onboarding your devices, you can use the API operations to set log levels and
* monitor your devices with CloudWatch.
* </p>
* <p>
* You can also use the API operations to create multicast groups and schedule a multicast session for sending a
* downlink message to devices in the group. By using Firmware Updates Over-The-Air (FUOTA) API operations, you can
* create a FUOTA task and schedule a session to update the firmware of individual devices or an entire group of devices
* in a multicast group.
* </p>
*/
package com.amazonaws.services.iotwireless;
| apache-2.0 |
forter/storm-python-shellbolt-benchmark | src/main/java/com/forter/ShellBoltBenchmarkApp.java | 2980 | package com.forter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.base.Throwables;
import com.google.common.io.Resources;
import org.msgpack.MessagePack;
import java.io.*;
import java.net.URL;
import java.nio.charset.Charset;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class ShellBoltBenchmarkApp {
public static void main(String[] args) throws IOException, InterruptedException {
URL resource = Resources.getResource("shell_log.json");
List<String> lines = Resources.readLines(resource, Charset.defaultCharset());
final String connect = lines.get(0).trim();
final String tup = lines.get(1).trim();
final String taskIds = lines.get(2).trim();
final FileOutputStream outStream = new FileOutputStream(FileDescriptor.out);
if (args.length == 0 || !args[0].equals("msgpack")) {
floodStream(outStream, new byte[][]{
(connect + "\nend\n").getBytes(),
(tup + "\nend\n").getBytes(),
(taskIds + "\nend\n").getBytes()
});
} else {
MessagePack msgPack = new MessagePack();
ObjectMapper mapper = new ObjectMapper();
ObjectNode node = (ObjectNode) mapper.readTree(tup);
Map tupleMap = mapper.treeToValue(node, Map.class);
floodStream(outStream, new byte[][]{
msgPack.write(getContextMsgpack()),
msgPack.write(tupleMap),
msgPack.write(new int[] { 5 })
});
}
}
private static void floodStream(FileOutputStream stream, byte[][] messages) throws IOException, InterruptedException {
final byte[] connectBytes = messages[0];
final byte[] tupleBytes = messages[1];
final byte[] taskIdBytes = messages[2];
DataOutputStream bufferedStream = new DataOutputStream(new BufferedOutputStream(stream, 1024 * 1024));
try {
bufferedStream.write(connectBytes);
bufferedStream.flush();
while (true) {
bufferedStream.write(tupleBytes);
bufferedStream.flush();
bufferedStream.write(taskIdBytes);
bufferedStream.flush();
}
} catch (IOException e) {
throw Throwables.propagate(e);
}
}
private static Map<String, Object> getContextMsgpack() {
Map<String, Object> setupmsg = new HashMap<String, Object>();
setupmsg.put("conf", new HashMap<String, Object>());
setupmsg.put("pidDir", "/tmp");
Map context_map = new HashMap();
context_map.put("taskid", 1);
context_map.put("task->component", "name");
setupmsg.put("context", context_map);
return setupmsg;
}
}
| apache-2.0 |
zhangleidaniejian/bluemmSite | src/main/java/cn/com/bluemoon/jeesite/modules/act/rest/ActRestApplication.java | 1157 | /**
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package cn.com.bluemoon.jeesite.modules.act.rest;
import org.activiti.rest.common.api.DefaultResource;
import org.activiti.rest.common.application.ActivitiRestApplication;
import org.activiti.rest.common.filter.JsonpFilter;
import org.activiti.rest.diagram.application.DiagramServicesInit;
import org.activiti.rest.editor.application.ModelerServicesInit;
import org.restlet.Restlet;
import org.restlet.routing.Router;
/**
* Activit Rest
* @author ThinkGem
* @version 2013-11-03
*/
public class ActRestApplication extends ActivitiRestApplication {
public ActRestApplication() {
super();
}
/**
* Creates a root Restlet that will receive all incoming calls.
*/
@Override
public synchronized Restlet createInboundRoot() {
Router router = new Router(getContext());
router.attachDefault(DefaultResource.class);
ModelerServicesInit.attachResources(router);
DiagramServicesInit.attachResources(router);
JsonpFilter jsonpFilter = new JsonpFilter(getContext());
jsonpFilter.setNext(router);
return jsonpFilter;
}
}
| apache-2.0 |
consulo/consulo-scala | src/org/jetbrains/plugins/scala/lift/runner/LiftRunConfigurationProducer.java | 5819 | package org.jetbrains.plugins.scala.lift.runner;
import com.intellij.execution.Location;
import com.intellij.execution.RunManagerEx;
import com.intellij.execution.RunnerAndConfigurationSettings;
import com.intellij.execution.actions.ConfigurationContext;
import com.intellij.execution.configurations.ConfigurationTypeUtil;
import com.intellij.execution.impl.RunnerAndConfigurationSettingsImpl;
import com.intellij.execution.junit.RuntimeConfigurationProducer;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ContentEntry;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.roots.SourceFolder;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiElement;
import org.jetbrains.idea.maven.model.MavenArtifact;
import org.jetbrains.idea.maven.project.MavenGeneralSettings;
import org.jetbrains.idea.maven.project.MavenProjectsManager;
import org.jetbrains.idea.maven.project.MavenProject;
import org.jetbrains.idea.maven.execution.MavenRunConfiguration;
import org.jetbrains.idea.maven.execution.MavenRunConfigurationType;
import org.jetbrains.idea.maven.execution.MavenRunnerParameters;
import org.jetbrains.idea.maven.execution.MavenRunnerSettings;
import org.jetbrains.plugins.scala.util.ScalaUtils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* @author ilyas
*/
public class LiftRunConfigurationProducer extends RuntimeConfigurationProducer implements Cloneable {
private PsiElement mySourceElement;
private static final String GROUP_ID_LIFT = "net.liftweb";
private static final String ARTIFACT_ID_LIFT = "lift-webkit";
private static final String JETTY_RUN = "jetty:run";
public LiftRunConfigurationProducer() {
super(ConfigurationTypeUtil.findConfigurationType(MavenRunConfigurationType.class));
}
public PsiElement getSourceElement() {
return mySourceElement;
}
private MavenRunnerParameters createBuildParameters(Location l) {
final PsiElement element = l.getPsiElement();
final Project project = l.getProject();
final Module module = ModuleUtil.findModuleForPsiElement(element);
if (module == null) return null;
final MavenProjectsManager mavenProjectsManager = MavenProjectsManager.getInstance(project);
final MavenProject mavenProject = mavenProjectsManager.findProject(module);
if (mavenProject == null) return null;
//todo: check this code
final List<MavenArtifact> dependencies = mavenProject.getDependencies();
MavenArtifact artifact = null;
for (MavenArtifact dependence : dependencies) {
if (dependence.getArtifactId().equals(GROUP_ID_LIFT)) {
artifact = dependence;
break;
} else if (dependence.getArtifactId().equals(ARTIFACT_ID_LIFT)) {
artifact = dependence;
break;
}
}
//final MavenArtifact artifact = mavenProjectModel.findDependency(GROUP_ID_LIFT, ARTIFACT_ID_LIFT);
if (artifact == null) return null;
mySourceElement = element;
Collection<String> profiles = MavenProjectsManager.getInstance(project).getExplicitProfiles();
List<String> goals = new ArrayList<String>();
goals.add(JETTY_RUN);
final VirtualFile file = module.getModuleFile();
if (file == null) return null;
final VirtualFile parent = file.getParent();
if (parent == null) return null;
return new MavenRunnerParameters(true, parent.getPath(), goals, profiles);
}
private static RunnerAndConfigurationSettings createRunnerAndConfigurationSettings(MavenGeneralSettings generalSettings,
MavenRunnerSettings runnerSettings,
MavenRunnerParameters params,
Project project) {
MavenRunConfigurationType type = ConfigurationTypeUtil.findConfigurationType(MavenRunConfigurationType.class);
final RunnerAndConfigurationSettings settings = RunManagerEx.getInstanceEx(project)
.createConfiguration(MavenRunConfigurationType.generateName(project, params), type.getConfigurationFactories()[0]);
MavenRunConfiguration runConfiguration = (MavenRunConfiguration) settings.getConfiguration();
runConfiguration.setRunnerParameters(params);
if (generalSettings != null) runConfiguration.setGeneralSettings(generalSettings);
if (runnerSettings != null) runConfiguration.setRunnerSettings(runnerSettings);
return settings;
}
protected RunnerAndConfigurationSettings createConfigurationByElement(final Location location, final ConfigurationContext context) {
final Module module = context.getModule();
if (module == null || !ScalaUtils.isSuitableModule(module)) return null;
final MavenRunnerParameters params = createBuildParameters(location);
if (params == null) return null;
return createRunnerAndConfigurationSettings(null, null, params, location.getProject());
}
private static boolean isTestDirectory(final Module module, final PsiElement element) {
final PsiDirectory dir = (PsiDirectory) element;
final ModuleRootManager manager = ModuleRootManager.getInstance(module);
final ContentEntry[] entries = manager.getContentEntries();
for (ContentEntry entry : entries) {
for (SourceFolder folder : entry.getSourceFolders()) {
if (folder.isTestSource() && folder.getFile() == dir.getVirtualFile()) {
return true;
}
}
}
return false;
}
public int compareTo(final Object o) {
return PREFERED;
}
}
| apache-2.0 |
PetrGasparik/midpoint | icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyResource.java | 43596 | /*
* Copyright (c) 2010-2016 Evolveum
*
* 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.evolveum.icf.dummy.resource;
import java.io.FileNotFoundException;
import java.net.ConnectException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.UUID;
import com.evolveum.midpoint.util.exception.SystemException;
import org.apache.commons.lang.StringUtils;
import com.evolveum.midpoint.util.DebugDumpable;
import com.evolveum.midpoint.util.DebugUtil;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
/**
* Resource for use with dummy ICF connector.
*
* This is a simple Java object that pretends to be a resource. It has accounts and
* account schema. It has operations to manipulate accounts, execute scripts and so on
* almost like a real resource. The purpose is to simulate a real resource with a very
* little overhead.
*
* The resource is a singleton, therefore the resource instance can be shared by
* the connector and the test code. The usual story is like this:
*
* 1) test class fetches first instance of the resource (getInstance). This will cause
* loading of the resource class in the test (parent) classloader.
*
* 2) test class configures the connector (e.g. schema) usually by calling the populateWithDefaultSchema() method.
*
* 3) test class initializes IDM. This will cause connector initialization. The connector will fetch
* the instance of dummy resource. As it was loaded by the parent classloader, it will get the same instance
* as the test class.
*
* 4) test class invokes IDM operation. That will invoke connector and change the resource.
*
* 5) test class will access resource directly to see if the operation went OK.
*
* The dummy resource is a separate package (JAR) from the dummy connector. Connector has its own
* classloader. If the resource would be the same package as connector, it will get loaded by the
* connector classloader regardless whether it is already loaded by the parent classloader.
*
* @author Radovan Semancik
*
*/
public class DummyResource implements DebugDumpable {
private static final Trace LOGGER = TraceManager.getTrace(DummyResource.class);
public static final String ATTRIBUTE_CONNECTOR_TO_STRING = "connectorToString";
public static final String ATTRIBUTE_CONNECTOR_STATIC_VAL = "connectorStaticVal";
public static final String ATTRIBUTE_CONNECTOR_CONFIGURATION_TO_STRING = "connectorConfigurationToString";
private String instanceName;
private Map<String,DummyObject> allObjects;
private Map<String,DummyAccount> accounts;
private Map<String,DummyGroup> groups;
private Map<String,DummyPrivilege> privileges;
private Map<String,DummyOrg> orgs;
private List<ScriptHistoryEntry> scriptHistory;
private DummyObjectClass accountObjectClass;
private DummyObjectClass groupObjectClass;
private DummyObjectClass privilegeObjectClass;
private final Map<String,DummyObjectClass> auxiliaryObjectClassMap = new HashMap<>();
private DummySyncStyle syncStyle;
private List<DummyDelta> deltas;
private int latestSyncToken;
private boolean tolerateDuplicateValues = false;
private boolean generateDefaultValues = false;
private boolean enforceUniqueName = true;
private boolean enforceSchema = true;
private boolean caseIgnoreId = false;
private boolean caseIgnoreValues = false;
private int connectionCount = 0;
private int groupMembersReadCount = 0;
private Collection<String> forbiddenNames;
private BreakMode schemaBreakMode = BreakMode.NONE;
private BreakMode getBreakMode = BreakMode.NONE;
private BreakMode addBreakMode = BreakMode.NONE;
private BreakMode modifyBreakMode = BreakMode.NONE;
private BreakMode deleteBreakMode = BreakMode.NONE;
private boolean blockOperations = false;
private boolean generateAccountDescriptionOnCreate = false; // simulates volatile behavior (on create)
private boolean generateAccountDescriptionOnUpdate = false; // simulates volatile behavior (on update)
private boolean disableNameHintChecks = false;
// Following two properties are just copied from the connector
// configuration and can be checked later. They are otherwise
// completely useless.
private String uselessString;
private String uselessGuardedString;
private static Map<String, DummyResource> instances = new HashMap<String, DummyResource>();
DummyResource() {
allObjects = Collections.synchronizedMap(new LinkedHashMap<String,DummyObject>());
accounts = Collections.synchronizedMap(new LinkedHashMap<String, DummyAccount>());
groups = Collections.synchronizedMap(new LinkedHashMap<String, DummyGroup>());
privileges = Collections.synchronizedMap(new LinkedHashMap<String, DummyPrivilege>());
orgs = Collections.synchronizedMap(new LinkedHashMap<String, DummyOrg>());
scriptHistory = new ArrayList<ScriptHistoryEntry>();
accountObjectClass = new DummyObjectClass();
groupObjectClass = new DummyObjectClass();
privilegeObjectClass = new DummyObjectClass();
syncStyle = DummySyncStyle.NONE;
deltas = Collections.synchronizedList(new ArrayList<DummyDelta>());
latestSyncToken = 0;
}
/**
* Clears everything, just like the resouce was just created.
*/
public void reset() {
allObjects.clear();
accounts.clear();
groups.clear();
privileges.clear();
orgs.clear();
scriptHistory.clear();
accountObjectClass = new DummyObjectClass();
groupObjectClass = new DummyObjectClass();
privilegeObjectClass = new DummyObjectClass();
syncStyle = DummySyncStyle.NONE;
deltas.clear();
latestSyncToken = 0;
resetBreakMode();
}
public static DummyResource getInstance() {
return getInstance(null);
}
public static DummyResource getInstance(String instanceName) {
DummyResource instance = instances.get(instanceName);
if (instance == null) {
instance = new DummyResource();
instance.setInstanceName(instanceName);
instances.put(instanceName, instance);
}
return instance;
}
public String getInstanceName() {
return instanceName;
}
public void setInstanceName(String instanceName) {
this.instanceName = instanceName;
}
public boolean isTolerateDuplicateValues() {
return tolerateDuplicateValues;
}
public void setTolerateDuplicateValues(boolean tolerateDuplicateValues) {
this.tolerateDuplicateValues = tolerateDuplicateValues;
}
public boolean isGenerateDefaultValues() {
return generateDefaultValues;
}
public void setGenerateDefaultValues(boolean generateDefaultValues) {
this.generateDefaultValues = generateDefaultValues;
}
public boolean isEnforceUniqueName() {
return enforceUniqueName;
}
public void setEnforceUniqueName(boolean enforceUniqueName) {
this.enforceUniqueName = enforceUniqueName;
}
public boolean isEnforceSchema() {
return enforceSchema;
}
public void setEnforceSchema(boolean enforceSchema) {
this.enforceSchema = enforceSchema;
}
public BreakMode getSchemaBreakMode() {
return schemaBreakMode;
}
public void setSchemaBreakMode(BreakMode schemaBreakMode) {
this.schemaBreakMode = schemaBreakMode;
}
public BreakMode getAddBreakMode() {
return addBreakMode;
}
public void setAddBreakMode(BreakMode addBreakMode) {
this.addBreakMode = addBreakMode;
}
public BreakMode getGetBreakMode() {
return getBreakMode;
}
public void setGetBreakMode(BreakMode getBreakMode) {
this.getBreakMode = getBreakMode;
}
public BreakMode getModifyBreakMode() {
return modifyBreakMode;
}
public void setModifyBreakMode(BreakMode modifyBreakMode) {
this.modifyBreakMode = modifyBreakMode;
}
public BreakMode getDeleteBreakMode() {
return deleteBreakMode;
}
public void setDeleteBreakMode(BreakMode deleteBreakMode) {
this.deleteBreakMode = deleteBreakMode;
}
public void setBreakMode(BreakMode breakMode) {
this.schemaBreakMode = breakMode;
this.addBreakMode = breakMode;
this.getBreakMode = breakMode;
this.modifyBreakMode = breakMode;
this.deleteBreakMode = breakMode;
}
public void resetBreakMode() {
setBreakMode(BreakMode.NONE);
}
public boolean isBlockOperations() {
return blockOperations;
}
public void setBlockOperations(boolean blockOperations) {
this.blockOperations = blockOperations;
}
public String getUselessString() {
return uselessString;
}
public void setUselessString(String uselessString) {
this.uselessString = uselessString;
}
public String getUselessGuardedString() {
return uselessGuardedString;
}
public void setUselessGuardedString(String uselessGuardedString) {
this.uselessGuardedString = uselessGuardedString;
}
public boolean isCaseIgnoreId() {
return caseIgnoreId;
}
public void setCaseIgnoreId(boolean caseIgnoreId) {
this.caseIgnoreId = caseIgnoreId;
}
public boolean isCaseIgnoreValues() {
return caseIgnoreValues;
}
public void setCaseIgnoreValues(boolean caseIgnoreValues) {
this.caseIgnoreValues = caseIgnoreValues;
}
public boolean isGenerateAccountDescriptionOnCreate() {
return generateAccountDescriptionOnCreate;
}
public void setGenerateAccountDescriptionOnCreate(boolean generateAccountDescriptionOnCreate) {
this.generateAccountDescriptionOnCreate = generateAccountDescriptionOnCreate;
}
public boolean isGenerateAccountDescriptionOnUpdate() {
return generateAccountDescriptionOnUpdate;
}
public void setGenerateAccountDescriptionOnUpdate(boolean generateAccountDescriptionOnUpdate) {
this.generateAccountDescriptionOnUpdate = generateAccountDescriptionOnUpdate;
}
public boolean isDisableNameHintChecks() {
return disableNameHintChecks;
}
public void setDisableNameHintChecks(boolean disableNameHintChecks) {
this.disableNameHintChecks = disableNameHintChecks;
}
public Collection<String> getForbiddenNames() {
return forbiddenNames;
}
public void setForbiddenNames(Collection<String> forbiddenNames) {
this.forbiddenNames = forbiddenNames;
}
public int getConnectionCount() {
return connectionCount;
}
public synchronized void connect() {
connectionCount++;
}
public synchronized void disconnect() {
connectionCount--;
}
public void assertNoConnections() {
assert connectionCount == 0 : "Dummy resource: "+connectionCount+" connections still open";
}
public int getGroupMembersReadCount() {
return groupMembersReadCount;
}
public void setGroupMembersReadCount(int groupMembersReadCount) {
this.groupMembersReadCount = groupMembersReadCount;
}
public void recordGroupMembersReadCount() {
groupMembersReadCount++;
traceOperation("groupMembersRead", groupMembersReadCount);
}
public DummyObjectClass getAccountObjectClass() throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException {
if (schemaBreakMode == BreakMode.NONE) {
return accountObjectClass;
} else if (schemaBreakMode == BreakMode.NETWORK) {
throw new ConnectException("The schema is not available (simulated error)");
} else if (schemaBreakMode == BreakMode.IO) {
throw new FileNotFoundException("The schema file not found (simulated error)");
} else if (schemaBreakMode == BreakMode.SCHEMA) {
throw new SchemaViolationException("Schema violation (simulated error)");
} else if (schemaBreakMode == BreakMode.CONFLICT) {
throw new ConflictException("Conflict (simulated error)");
} else if (schemaBreakMode == BreakMode.GENERIC) {
// The connector will react with generic exception
throw new IllegalArgumentException("Generic error fetching schema (simulated error)");
} else if (schemaBreakMode == BreakMode.RUNTIME) {
// The connector will just pass this up
throw new IllegalStateException("Generic error fetching schema (simulated error)");
} else if (schemaBreakMode == BreakMode.UNSUPPORTED) {
throw new UnsupportedOperationException("Schema is not supported (simulated error)");
} else {
// This is a real error. Use this strange thing to make sure it passes up
throw new RuntimeException("Unknown schema break mode "+schemaBreakMode);
}
}
public DummyObjectClass getAccountObjectClassNoExceptions() {
return accountObjectClass;
}
public DummyObjectClass getGroupObjectClass() {
return groupObjectClass;
}
public DummyObjectClass getPrivilegeObjectClass() {
return privilegeObjectClass;
}
public Map<String,DummyObjectClass> getAuxiliaryObjectClassMap() {
return auxiliaryObjectClassMap;
}
public void addAuxiliaryObjectClass(String name, DummyObjectClass objectClass) {
auxiliaryObjectClassMap.put(name, objectClass);
}
public Collection<DummyAccount> listAccounts() throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException {
checkBlockOperations();
if (getBreakMode == BreakMode.NONE) {
return accounts.values();
} else if (schemaBreakMode == BreakMode.NETWORK) {
throw new ConnectException("Network error (simulated error)");
} else if (schemaBreakMode == BreakMode.IO) {
throw new FileNotFoundException("IO error (simulated error)");
} else if (schemaBreakMode == BreakMode.SCHEMA) {
throw new SchemaViolationException("Schema violation (simulated error)");
} else if (schemaBreakMode == BreakMode.CONFLICT) {
throw new ConflictException("Conflict (simulated error)");
} else if (schemaBreakMode == BreakMode.GENERIC) {
// The connector will react with generic exception
throw new IllegalArgumentException("Generic error (simulated error)");
} else if (schemaBreakMode == BreakMode.RUNTIME) {
// The connector will just pass this up
throw new IllegalStateException("Generic error (simulated error)");
} else if (schemaBreakMode == BreakMode.UNSUPPORTED) {
throw new UnsupportedOperationException("Not supported (simulated error)");
} else {
// This is a real error. Use this strange thing to make sure it passes up
throw new RuntimeException("Unknown schema break mode "+schemaBreakMode);
}
}
private <T extends DummyObject> T getObjectByName(Map<String,T> map, String name) throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException {
if (!enforceUniqueName) {
throw new IllegalStateException("Attempt to search object by name while resource is in non-unique name mode");
}
if (getBreakMode == BreakMode.NONE) {
return map.get(normalize(name));
} else if (schemaBreakMode == BreakMode.NETWORK) {
throw new ConnectException("Network error (simulated error)");
} else if (schemaBreakMode == BreakMode.IO) {
throw new FileNotFoundException("IO error (simulated error)");
} else if (schemaBreakMode == BreakMode.SCHEMA) {
throw new SchemaViolationException("Schema violation (simulated error)");
} else if (schemaBreakMode == BreakMode.CONFLICT) {
throw new ConflictException("Conflict (simulated error)");
} else if (schemaBreakMode == BreakMode.GENERIC) {
// The connector will react with generic exception
throw new IllegalArgumentException("Generic error (simulated error)");
} else if (schemaBreakMode == BreakMode.RUNTIME) {
// The connector will just pass this up
throw new IllegalStateException("Generic error (simulated error)");
} else if (schemaBreakMode == BreakMode.UNSUPPORTED) {
throw new UnsupportedOperationException("Not supported (simulated error)");
} else {
// This is a real error. Use this strange thing to make sure it passes up
throw new RuntimeException("Unknown schema break mode "+schemaBreakMode);
}
}
public DummyAccount getAccountByUsername(String username) throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException {
return getObjectByName(accounts, username);
}
public DummyGroup getGroupByName(String name) throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException {
return getObjectByName(groups, name);
}
public DummyPrivilege getPrivilegeByName(String name) throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException {
return getObjectByName(privileges, name);
}
public DummyOrg getOrgByName(String name) throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException {
return getObjectByName(orgs, name);
}
private <T extends DummyObject> T getObjectById(Class<T> expectedClass, String id) throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException {
if (getBreakMode == BreakMode.NONE) {
DummyObject dummyObject = allObjects.get(id);
if (dummyObject == null) {
return null;
}
if (!expectedClass.isInstance(dummyObject)) {
throw new IllegalStateException("Arrrr! Wanted "+expectedClass+" with ID "+id+" but got "+dummyObject+" instead");
}
return (T)dummyObject;
} else if (schemaBreakMode == BreakMode.NETWORK) {
throw new ConnectException("Network error (simulated error)");
} else if (schemaBreakMode == BreakMode.IO) {
throw new FileNotFoundException("IO error (simulated error)");
} else if (schemaBreakMode == BreakMode.SCHEMA) {
throw new SchemaViolationException("Schema violation (simulated error)");
} else if (schemaBreakMode == BreakMode.CONFLICT) {
throw new ConflictException("Conflict (simulated error)");
} else if (schemaBreakMode == BreakMode.GENERIC) {
// The connector will react with generic exception
throw new IllegalArgumentException("Generic error (simulated error)");
} else if (schemaBreakMode == BreakMode.RUNTIME) {
// The connector will just pass this up
throw new IllegalStateException("Generic error (simulated error)");
} else if (schemaBreakMode == BreakMode.UNSUPPORTED) {
throw new UnsupportedOperationException("Not supported (simulated error)");
} else {
// This is a real error. Use this strange thing to make sure it passes up
throw new RuntimeException("Unknown schema break mode "+schemaBreakMode);
}
}
public DummyAccount getAccountById(String id) throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException {
return getObjectById(DummyAccount.class, id);
}
public DummyGroup getGroupById(String id) throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException {
return getObjectById(DummyGroup.class, id);
}
public DummyPrivilege getPrivilegeById(String id) throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException {
return getObjectById(DummyPrivilege.class, id);
}
public DummyOrg getOrgById(String id) throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException {
return getObjectById(DummyOrg.class, id);
}
public Collection<DummyGroup> listGroups() throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException {
checkBlockOperations();
if (getBreakMode == BreakMode.NONE) {
return groups.values();
} else if (schemaBreakMode == BreakMode.NETWORK) {
throw new ConnectException("Network error (simulated error)");
} else if (schemaBreakMode == BreakMode.IO) {
throw new FileNotFoundException("IO error (simulated error)");
} else if (schemaBreakMode == BreakMode.SCHEMA) {
throw new SchemaViolationException("Schema violation (simulated error)");
} else if (schemaBreakMode == BreakMode.CONFLICT) {
throw new ConflictException("Conflict (simulated error)");
} else if (schemaBreakMode == BreakMode.GENERIC) {
// The connector will react with generic exception
throw new IllegalArgumentException("Generic error (simulated error)");
} else if (schemaBreakMode == BreakMode.RUNTIME) {
// The connector will just pass this up
throw new IllegalStateException("Generic error (simulated error)");
} else if (schemaBreakMode == BreakMode.UNSUPPORTED) {
throw new UnsupportedOperationException("Not supported (simulated error)");
} else {
// This is a real error. Use this strange thing to make sure it passes up
throw new RuntimeException("Unknown schema break mode "+schemaBreakMode);
}
}
public Collection<DummyPrivilege> listPrivileges() throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException {
checkBlockOperations();
if (getBreakMode == BreakMode.NONE) {
return privileges.values();
} else if (schemaBreakMode == BreakMode.NETWORK) {
throw new ConnectException("Network error (simulated error)");
} else if (schemaBreakMode == BreakMode.IO) {
throw new FileNotFoundException("IO error (simulated error)");
} else if (schemaBreakMode == BreakMode.SCHEMA) {
throw new SchemaViolationException("Schema violation (simulated error)");
} else if (schemaBreakMode == BreakMode.CONFLICT) {
throw new ConflictException("Conflict (simulated error)");
} else if (schemaBreakMode == BreakMode.GENERIC) {
// The connector will react with generic exception
throw new IllegalArgumentException("Generic error (simulated error)");
} else if (schemaBreakMode == BreakMode.RUNTIME) {
// The connector will just pass this up
throw new IllegalStateException("Generic error (simulated error)");
} else if (schemaBreakMode == BreakMode.UNSUPPORTED) {
throw new UnsupportedOperationException("Not supported (simulated error)");
} else {
// This is a real error. Use this strange thing to make sure it passes up
throw new RuntimeException("Unknown schema break mode "+schemaBreakMode);
}
}
public Collection<DummyOrg> listOrgs() throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException {
checkBlockOperations();
if (getBreakMode == BreakMode.NONE) {
return orgs.values();
} else if (schemaBreakMode == BreakMode.NETWORK) {
throw new ConnectException("Network error (simulated error)");
} else if (schemaBreakMode == BreakMode.IO) {
throw new FileNotFoundException("IO error (simulated error)");
} else if (schemaBreakMode == BreakMode.SCHEMA) {
throw new SchemaViolationException("Schema violation (simulated error)");
} else if (schemaBreakMode == BreakMode.CONFLICT) {
throw new ConflictException("Conflict (simulated error)");
} else if (schemaBreakMode == BreakMode.GENERIC) {
// The connector will react with generic exception
throw new IllegalArgumentException("Generic error (simulated error)");
} else if (schemaBreakMode == BreakMode.RUNTIME) {
// The connector will just pass this up
throw new IllegalStateException("Generic error (simulated error)");
} else if (schemaBreakMode == BreakMode.UNSUPPORTED) {
throw new UnsupportedOperationException("Not supported (simulated error)");
} else {
// This is a real error. Use this strange thing to make sure it passes up
throw new RuntimeException("Unknown schema break mode "+schemaBreakMode);
}
}
private synchronized <T extends DummyObject> String addObject(Map<String,T> map, T newObject) throws ObjectAlreadyExistsException, ConnectException, FileNotFoundException, SchemaViolationException, ConflictException {
checkBlockOperations();
if (addBreakMode == BreakMode.NONE) {
// just go on
} else if (addBreakMode == BreakMode.NETWORK) {
throw new ConnectException("Network error during add (simulated error)");
} else if (addBreakMode == BreakMode.IO) {
throw new FileNotFoundException("IO error during add (simulated error)");
} else if (addBreakMode == BreakMode.SCHEMA) {
throw new SchemaViolationException("Schema violation during add (simulated error)");
} else if (addBreakMode == BreakMode.CONFLICT) {
throw new ConflictException("Conflict during add (simulated error)");
} else if (addBreakMode == BreakMode.GENERIC) {
// The connector will react with generic exception
throw new IllegalArgumentException("Generic error during add (simulated error)");
} else if (addBreakMode == BreakMode.RUNTIME) {
// The connector will just pass this up
throw new IllegalStateException("Generic rutime error during add (simulated error)");
} else if (addBreakMode == BreakMode.UNSUPPORTED) {
throw new UnsupportedOperationException("Unsupported operation: add (simulated error)");
} else {
// This is a real error. Use this strange thing to make sure it passes up
throw new RuntimeException("Unknown break mode "+addBreakMode);
}
Class<? extends DummyObject> type = newObject.getClass();
String normalName = normalize(newObject.getName());
if (normalName != null && forbiddenNames != null && forbiddenNames.contains(normalName)) {
throw new ObjectAlreadyExistsException(normalName + " is forbidden to use as an object name");
}
String newId = UUID.randomUUID().toString();
newObject.setId(newId);
if (allObjects.containsKey(newId)) {
throw new IllegalStateException("The hell is frozen over. The impossible has happened. ID "+newId+" already exists ("+ type.getSimpleName()+" with identifier "+normalName+")");
}
//this is "resource-generated" attribute (used to simulate resource which generate by default attributes which we need to sync)
if (generateDefaultValues){
// int internalId = allObjects.size();
newObject.addAttributeValue(DummyAccount.ATTR_INTERNAL_ID, new Random().nextInt());
}
String mapKey;
if (enforceUniqueName) {
mapKey = normalName;
} else {
mapKey = newId;
}
if (map.containsKey(mapKey)) {
throw new ObjectAlreadyExistsException(type.getSimpleName()+" with name '"+normalName+"' already exists");
}
newObject.setResource(this);
map.put(mapKey, newObject);
allObjects.put(newId, newObject);
if (syncStyle != DummySyncStyle.NONE) {
int syncToken = nextSyncToken();
DummyDelta delta = new DummyDelta(syncToken, type, newId, newObject.getName(), DummyDeltaType.ADD);
deltas.add(delta);
}
return newObject.getName();
}
private synchronized <T extends DummyObject> void deleteObjectByName(Class<T> type, Map<String,T> map, String name) throws ObjectDoesNotExistException, ConnectException, FileNotFoundException, SchemaViolationException, ConflictException {
checkBlockOperations();
if (deleteBreakMode == BreakMode.NONE) {
// go on
} else if (deleteBreakMode == BreakMode.NETWORK) {
throw new ConnectException("Network error (simulated error)");
} else if (deleteBreakMode == BreakMode.IO) {
throw new FileNotFoundException("IO error (simulated error)");
} else if (deleteBreakMode == BreakMode.SCHEMA) {
throw new SchemaViolationException("Schema violation (simulated error)");
} else if (deleteBreakMode == BreakMode.CONFLICT) {
throw new ConflictException("Conflict during (simulated error)");
} else if (deleteBreakMode == BreakMode.GENERIC) {
// The connector will react with generic exception
throw new IllegalArgumentException("Generic error (simulated error)");
} else if (deleteBreakMode == BreakMode.RUNTIME) {
// The connector will just pass this up
throw new IllegalStateException("Generic error (simulated error)");
} else if (deleteBreakMode == BreakMode.UNSUPPORTED) {
throw new UnsupportedOperationException("Not supported (simulated error)");
} else {
// This is a real error. Use this strange thing to make sure it passes up
throw new RuntimeException("Unknown schema break mode "+schemaBreakMode);
}
String normalName = normalize(name);
T existingObject;
if (!enforceUniqueName) {
throw new IllegalStateException("Whoops! got into deleteObjectByName without enforceUniqueName");
}
if (map.containsKey(normalName)) {
existingObject = map.get(normalName);
map.remove(normalName);
allObjects.remove(existingObject.getId());
} else {
throw new ObjectDoesNotExistException(type.getSimpleName()+" with name '"+normalName+"' does not exist");
}
if (syncStyle != DummySyncStyle.NONE) {
int syncToken = nextSyncToken();
DummyDelta delta = new DummyDelta(syncToken, type, existingObject.getId(), name, DummyDeltaType.DELETE);
deltas.add(delta);
}
}
public void deleteAccountById(String id) throws ConnectException, FileNotFoundException, ObjectDoesNotExistException, SchemaViolationException, ConflictException {
deleteObjectById(DummyAccount.class, accounts, id);
}
public void deleteGroupById(String id) throws ConnectException, FileNotFoundException, ObjectDoesNotExistException, SchemaViolationException, ConflictException {
deleteObjectById(DummyGroup.class, groups, id);
}
public void deletePrivilegeById(String id) throws ConnectException, FileNotFoundException, ObjectDoesNotExistException, SchemaViolationException, ConflictException {
deleteObjectById(DummyPrivilege.class, privileges, id);
}
public void deleteOrgById(String id) throws ConnectException, FileNotFoundException, ObjectDoesNotExistException, SchemaViolationException, ConflictException {
deleteObjectById(DummyOrg.class, orgs, id);
}
private synchronized <T extends DummyObject> void deleteObjectById(Class<T> type, Map<String,T> map, String id) throws ObjectDoesNotExistException, ConnectException, FileNotFoundException, SchemaViolationException, ConflictException {
checkBlockOperations();
if (deleteBreakMode == BreakMode.NONE) {
// go on
} else if (deleteBreakMode == BreakMode.NETWORK) {
throw new ConnectException("Network error (simulated error)");
} else if (deleteBreakMode == BreakMode.IO) {
throw new FileNotFoundException("IO error (simulated error)");
} else if (deleteBreakMode == BreakMode.SCHEMA) {
throw new SchemaViolationException("Schema violation (simulated error)");
} else if (deleteBreakMode == BreakMode.CONFLICT) {
throw new ConflictException("Conflict (simulated error)");
} else if (deleteBreakMode == BreakMode.GENERIC) {
// The connector will react with generic exception
throw new IllegalArgumentException("Generic error (simulated error)");
} else if (deleteBreakMode == BreakMode.RUNTIME) {
// The connector will just pass this up
throw new IllegalStateException("Generic error (simulated error)");
} else if (deleteBreakMode == BreakMode.UNSUPPORTED) {
throw new UnsupportedOperationException("Not supported (simulated error)");
} else {
// This is a real error. Use this strange thing to make sure it passes up
throw new RuntimeException("Unknown schema break mode "+schemaBreakMode);
}
DummyObject object = allObjects.get(id);
if (object == null) {
throw new ObjectDoesNotExistException(type.getSimpleName()+" with id '"+id+"' does not exist");
}
if (!type.isInstance(object)) {
throw new IllegalStateException("Arrrr! Wanted "+type+" with ID "+id+" but got "+object+" instead");
}
T existingObject = (T)object;
String normalName = normalize(object.getName());
allObjects.remove(id);
String mapKey;
if (enforceUniqueName) {
mapKey = normalName;
} else {
mapKey = id;
}
if (map.containsKey(mapKey)) {
map.remove(mapKey);
} else {
throw new ObjectDoesNotExistException(type.getSimpleName()+" with name '"+normalName+"' does not exist");
}
if (syncStyle != DummySyncStyle.NONE) {
int syncToken = nextSyncToken();
DummyDelta delta = new DummyDelta(syncToken, type, id, object.getName(), DummyDeltaType.DELETE);
deltas.add(delta);
}
}
private <T extends DummyObject> void renameObject(Class<T> type, Map<String,T> map, String id, String oldName, String newName) throws ObjectDoesNotExistException, ObjectAlreadyExistsException, ConnectException, FileNotFoundException, SchemaViolationException, ConflictException {
checkBlockOperations();
if (modifyBreakMode == BreakMode.NONE) {
// go on
} else if (modifyBreakMode == BreakMode.NETWORK) {
throw new ConnectException("Network error (simulated error)");
} else if (modifyBreakMode == BreakMode.IO) {
throw new FileNotFoundException("IO error (simulated error)");
} else if (modifyBreakMode == BreakMode.SCHEMA) {
throw new SchemaViolationException("Schema violation (simulated error)");
} else if (modifyBreakMode == BreakMode.CONFLICT) {
throw new ConflictException("Conflict (simulated error)");
} else if (modifyBreakMode == BreakMode.GENERIC) {
// The connector will react with generic exception
throw new IllegalArgumentException("Generic error (simulated error)");
} else if (modifyBreakMode == BreakMode.RUNTIME) {
// The connector will just pass this up
throw new IllegalStateException("Generic error (simulated error)");
} else if (modifyBreakMode == BreakMode.UNSUPPORTED) {
throw new UnsupportedOperationException("Not supported (simulated error)");
} else {
// This is a real error. Use this strange thing to make sure it passes up
throw new RuntimeException("Unknown schema break mode "+schemaBreakMode);
}
T existingObject;
if (enforceUniqueName) {
String normalOldName = normalize(oldName);
String normalNewName = normalize(newName);
existingObject = map.get(normalOldName);
if (existingObject == null) {
throw new ObjectDoesNotExistException("Cannot rename, "+type.getSimpleName()+" with username '"+normalOldName+"' does not exist");
}
if (map.containsKey(normalNewName)) {
throw new ObjectAlreadyExistsException("Cannot rename, "+type.getSimpleName()+" with username '"+normalNewName+"' already exists");
}
map.put(normalNewName, existingObject);
map.remove(normalOldName);
} else {
existingObject = (T) allObjects.get(id);
}
existingObject.setName(newName);
if (existingObject instanceof DummyAccount) {
changeDescriptionIfNeeded((DummyAccount) existingObject);
}
}
public String addAccount(DummyAccount newAccount) throws ObjectAlreadyExistsException, ConnectException, FileNotFoundException, SchemaViolationException, ConflictException {
if (generateAccountDescriptionOnCreate && newAccount.getAttributeValue(DummyAccount.ATTR_DESCRIPTION_NAME) == null) {
newAccount.addAttributeValue(DummyAccount.ATTR_DESCRIPTION_NAME, "Description of " + newAccount.getName());
}
return addObject(accounts, newAccount);
}
public void deleteAccountByName(String id) throws ObjectDoesNotExistException, ConnectException, FileNotFoundException, SchemaViolationException, ConflictException {
deleteObjectByName(DummyAccount.class, accounts, id);
}
public void renameAccount(String id, String oldUsername, String newUsername) throws ObjectDoesNotExistException, ObjectAlreadyExistsException, ConnectException, FileNotFoundException, SchemaViolationException, SchemaViolationException, ConflictException {
renameObject(DummyAccount.class, accounts, id, oldUsername, newUsername);
for (DummyGroup group : groups.values()) {
if (group.containsMember(oldUsername)) {
group.removeMember(oldUsername);
group.addMember(newUsername);
}
}
}
public void changeDescriptionIfNeeded(DummyAccount account) throws SchemaViolationException, ConflictException {
if (generateAccountDescriptionOnCreate) {
try {
account.replaceAttributeValue(DummyAccount.ATTR_DESCRIPTION_NAME, "Updated description of " + account.getName());
} catch (SchemaViolationException|ConnectException|FileNotFoundException e) {
throw new SystemException("Couldn't replace the 'description' attribute value", e);
}
}
}
public String addGroup(DummyGroup newGroup) throws ObjectAlreadyExistsException, ConnectException, FileNotFoundException, SchemaViolationException, SchemaViolationException, ConflictException {
return addObject(groups, newGroup);
}
public void deleteGroupByName(String id) throws ObjectDoesNotExistException, ConnectException, FileNotFoundException, SchemaViolationException, ConflictException {
deleteObjectByName(DummyGroup.class, groups, id);
}
public void renameGroup(String id, String oldName, String newName) throws ObjectDoesNotExistException, ObjectAlreadyExistsException, ConnectException, FileNotFoundException, SchemaViolationException, ConflictException {
renameObject(DummyGroup.class, groups, id, oldName, newName);
}
public String addPrivilege(DummyPrivilege newGroup) throws ObjectAlreadyExistsException, ConnectException, FileNotFoundException, SchemaViolationException, SchemaViolationException, ConflictException {
return addObject(privileges, newGroup);
}
public void deletePrivilegeByName(String id) throws ObjectDoesNotExistException, ConnectException, FileNotFoundException, SchemaViolationException, ConflictException {
deleteObjectByName(DummyPrivilege.class, privileges, id);
}
public void renamePrivilege(String id, String oldName, String newName) throws ObjectDoesNotExistException, ObjectAlreadyExistsException, ConnectException, FileNotFoundException, SchemaViolationException, ConflictException {
renameObject(DummyPrivilege.class, privileges, id, oldName, newName);
}
public String addOrg(DummyOrg newGroup) throws ObjectAlreadyExistsException, ConnectException, FileNotFoundException, SchemaViolationException, SchemaViolationException, ConflictException {
return addObject(orgs, newGroup);
}
public void deleteOrgByName(String id) throws ObjectDoesNotExistException, ConnectException, FileNotFoundException, SchemaViolationException, ConflictException {
deleteObjectByName(DummyOrg.class, orgs, id);
}
public void renameOrg(String id, String oldName, String newName) throws ObjectDoesNotExistException, ObjectAlreadyExistsException, ConnectException, FileNotFoundException, SchemaViolationException, ConflictException {
renameObject(DummyOrg.class, orgs, id, oldName, newName);
}
void recordModify(DummyObject dObject) {
if (syncStyle != DummySyncStyle.NONE) {
int syncToken = nextSyncToken();
DummyDelta delta = new DummyDelta(syncToken, dObject.getClass(), dObject.getId(), dObject.getName(), DummyDeltaType.MODIFY);
deltas.add(delta);
}
}
/**
* Returns script history ordered chronologically (oldest first).
* @return script history
*/
public List<ScriptHistoryEntry> getScriptHistory() {
return scriptHistory;
}
/**
* Clears the script history.
*/
public void purgeScriptHistory() {
scriptHistory.clear();
}
/**
* Pretend to run script on the resource.
* The script is actually not executed, it is only recorded in the script history
* and can be fetched by getScriptHistory().
*
* @param scriptCode code of the script
*/
public void runScript(String language, String scriptCode, Map<String, Object> params) {
scriptHistory.add(new ScriptHistoryEntry(language, scriptCode, params));
}
/**
* Populates the resource with some kind of "default" schema. This is a schema that should suit
* majority of basic test cases.
*/
public void populateWithDefaultSchema() {
accountObjectClass.clear();
accountObjectClass.addAttributeDefinition(DummyAccount.ATTR_FULLNAME_NAME, String.class, true, false);
accountObjectClass.addAttributeDefinition(DummyAccount.ATTR_INTERNAL_ID, String.class, false, false);
accountObjectClass.addAttributeDefinition(DummyAccount.ATTR_DESCRIPTION_NAME, String.class, false, false);
accountObjectClass.addAttributeDefinition(DummyAccount.ATTR_INTERESTS_NAME, String.class, false, true);
accountObjectClass.addAttributeDefinition(DummyAccount.ATTR_PRIVILEGES_NAME, String.class, false, true);
groupObjectClass.clear();
groupObjectClass.addAttributeDefinition(DummyGroup.ATTR_MEMBERS_NAME, String.class, false, true);
privilegeObjectClass.clear();
}
public DummySyncStyle getSyncStyle() {
return syncStyle;
}
public void setSyncStyle(DummySyncStyle syncStyle) {
this.syncStyle = syncStyle;
}
private synchronized int nextSyncToken() {
return ++latestSyncToken;
}
public int getLatestSyncToken() {
return latestSyncToken;
}
private String normalize(String id) {
if (caseIgnoreId) {
return StringUtils.lowerCase(id);
} else {
return id;
}
}
public List<DummyDelta> getDeltasSince(int syncToken) {
List<DummyDelta> result = new ArrayList<DummyDelta>();
for (DummyDelta delta: deltas) {
if (delta.getSyncToken() > syncToken) {
result.add(delta);
}
}
return result;
}
private synchronized void checkBlockOperations() {
if (blockOperations) {
try {
LOGGER.info("Thread {} blocked", Thread.currentThread().getName());
this.wait();
LOGGER.info("Thread {} unblocked", Thread.currentThread().getName());
} catch (InterruptedException e) {
LOGGER.debug("Wait interrupted", e);
}
}
}
public synchronized void unblock() {
LOGGER.info("Unblocking");
this.notify();
}
public synchronized void unblockAll() {
LOGGER.info("Unblocking all");
this.notifyAll();
}
private void traceOperation(String opName, long counter) {
LOGGER.info("MONITOR dummy '{}' {} ({})", instanceName, opName, counter);
if (LOGGER.isDebugEnabled()) {
StackTraceElement[] fullStack = Thread.currentThread().getStackTrace();
String immediateClass = null;
String immediateMethod = null;
StringBuilder sb = new StringBuilder();
for (StackTraceElement stackElement: fullStack) {
if (stackElement.getClassName().equals(DummyResource.class.getName()) ||
stackElement.getClassName().equals(Thread.class.getName())) {
// skip our own calls
continue;
}
if (immediateClass == null) {
immediateClass = stackElement.getClassName();
immediateMethod = stackElement.getMethodName();
}
sb.append(stackElement.toString());
sb.append("\n");
}
LOGGER.debug("MONITOR dummy '{}' {} ({}): {} {}", new Object[]{instanceName, opName, counter, immediateClass, immediateMethod});
LOGGER.trace("MONITOR dummy '{}' {} ({}):\n{}", new Object[]{instanceName, opName, counter, sb});
}
}
@Override
public String debugDump() {
return debugDump(0);
}
@Override
public String debugDump(int indent) {
StringBuilder sb = new StringBuilder(toString());
DebugUtil.indentDebugDump(sb, indent);
sb.append("\nAccounts:");
for (Entry<String, DummyAccount> entry: accounts.entrySet()) {
sb.append("\n ");
sb.append(entry.getKey());
sb.append(": ");
sb.append(entry.getValue());
}
sb.append("\nGroups:");
for (Entry<String, DummyGroup> entry: groups.entrySet()) {
sb.append("\n ");
sb.append(entry.getKey());
sb.append(": ");
sb.append(entry.getValue());
}
sb.append("\nPrivileges:");
for (Entry<String, DummyPrivilege> entry: privileges.entrySet()) {
sb.append("\n ");
sb.append(entry.getKey());
sb.append(": ");
sb.append(entry.getValue());
}
sb.append("\nOrgs:");
for (Entry<String, DummyOrg> entry: orgs.entrySet()) {
sb.append("\n ");
sb.append(entry.getKey());
sb.append(": ");
sb.append(entry.getValue());
}
sb.append("\nDeltas:");
for (DummyDelta delta: deltas) {
sb.append("\n ");
sb.append(delta);
}
sb.append("\nLatest token:").append(latestSyncToken);
return sb.toString();
}
@Override
public String toString() {
return "DummyResource("+instanceName+": "+accounts.size()+" accounts, "+groups.size()+" groups, "+privileges.size()+" privileges, "+orgs.size()+" orgs)";
}
} | apache-2.0 |
enekein/nzenkin | chapter_002/src/main/java/ru/job4j/strategy/Triangle.java | 678 | package ru.job4j.strategy;
/**
* @author Nikita Zenkin.
* @version 1.
* @since 08.06.2017.
*/
public class Triangle implements Shape {
/**
* String of triangle.
* @return String.
*/
public String pic() {
StringBuilder s = new StringBuilder();
int h = 10;
for (int i = 0; i < h; i++) {
for (int j = 0; j < (2 * h) - 1; j++) {
if ((j >= h - i - 1) && (j < h + i)) {
s.append("^");
} else {
s.append(" ");
}
}
s.append(System.getProperty("line.separator"));
}
return s.toString();
}
}
| apache-2.0 |
jamesdbloom/mockserver | mockserver-netty/src/test/java/org/mockserver/cli/MainTest.java | 9924 | package org.mockserver.cli;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import org.junit.AfterClass;
import org.junit.Test;
import org.mockserver.client.MockServerClient;
import org.mockserver.client.NettyHttpClient;
import org.mockserver.configuration.ConfigurationProperties;
import org.mockserver.echo.http.EchoServer;
import org.mockserver.logging.MockServerLogger;
import org.mockserver.model.HttpResponse;
import org.mockserver.socket.PortFactory;
import org.slf4j.event.Level;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;
import static io.netty.handler.codec.http.HttpHeaderNames.HOST;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.mockserver.character.Character.NEW_LINE;
import static org.mockserver.model.HttpRequest.request;
import static org.mockserver.model.HttpResponse.response;
import static org.mockserver.stop.Stop.stopQuietly;
/**
* @author jamesdbloom
*/
public class MainTest {
private static EventLoopGroup clientEventLoopGroup = new NioEventLoopGroup();
@AfterClass
public static void stopEventLoopGroup() {
clientEventLoopGroup.shutdownGracefully(0, 0, MILLISECONDS).syncUninterruptibly();
}
@Test
public void shouldStartMockServer() {
// given
final int freePort = PortFactory.findFreePort();
MockServerClient mockServerClient = new MockServerClient("127.0.0.1", freePort);
Level originalLogLevel = ConfigurationProperties.logLevel();
try {
// when
Main.main(
"-serverPort", String.valueOf(freePort),
"-logLevel", "DEBUG"
);
// then
assertThat(mockServerClient.isRunning(), is(true));
assertThat(ConfigurationProperties.logLevel().toString(), is("DEBUG"));
} finally {
ConfigurationProperties.logLevel(originalLogLevel.toString());
stopQuietly(mockServerClient);
}
}
@Test
public void shouldStartMockServerWithRemotePortAndHost() {
// given
final int freePort = PortFactory.findFreePort();
MockServerClient mockServerClient = new MockServerClient("127.0.0.1", freePort);
try {
EchoServer echoServer = new EchoServer(false);
echoServer.withNextResponse(response("port_forwarded_response"));
// when
Main.main(
"-serverPort", String.valueOf(freePort),
"-proxyRemotePort", String.valueOf(echoServer.getPort()),
"-proxyRemoteHost", "127.0.0.1"
);
final HttpResponse response = new NettyHttpClient(new MockServerLogger(), clientEventLoopGroup, null)
.sendRequest(
request()
.withHeader(HOST.toString(), "127.0.0.1:" + freePort),
10,
TimeUnit.SECONDS
);
// then
assertThat(mockServerClient.isRunning(), is(true));
assertThat(response.getBodyAsString(), is("port_forwarded_response"));
} finally {
stopQuietly(mockServerClient);
}
}
@Test
public void shouldStartMockServerWithRemotePort() {
// given
final int freePort = PortFactory.findFreePort();
MockServerClient mockServerClient = new MockServerClient("127.0.0.1", freePort);
try {
EchoServer echoServer = new EchoServer(false);
echoServer.withNextResponse(response("port_forwarded_response"));
// when
Main.main(
"-serverPort", String.valueOf(freePort),
"-proxyRemotePort", String.valueOf(echoServer.getPort())
);
final HttpResponse response = new NettyHttpClient(new MockServerLogger(), clientEventLoopGroup, null)
.sendRequest(
request()
.withHeader(HOST.toString(), "127.0.0.1:" + freePort),
10,
TimeUnit.SECONDS
);
// then
assertThat(mockServerClient.isRunning(), is(true));
assertThat(response.getBodyAsString(), is("port_forwarded_response"));
} finally {
stopQuietly(mockServerClient);
}
}
@Test
public void shouldPrintOutUsageForInvalidServerPort() throws UnsupportedEncodingException {
// given
PrintStream originalPrintStream = Main.systemOut;
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
Main.systemOut = new PrintStream(byteArrayOutputStream, true, StandardCharsets.UTF_8.name());
// when
Main.main("-serverPort", "A");
// then
String actual = new String(byteArrayOutputStream.toByteArray(), StandardCharsets.UTF_8);
String expected = NEW_LINE +
" =====================================================================================================" + NEW_LINE +
" serverPort value \"A\" is invalid, please specify a comma separated list of ports i.e. \"1080,1081,1082\"" + NEW_LINE +
" =====================================================================================================" + NEW_LINE +
NEW_LINE +
Main.USAGE;
assertThat(actual, is(expected));
} finally {
Main.systemOut = originalPrintStream;
}
}
@Test
public void shouldPrintOutUsageForInvalidRemotePort() throws UnsupportedEncodingException {
// given
final int freePort = PortFactory.findFreePort();
PrintStream originalPrintStream = Main.systemOut;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Main.systemOut = new PrintStream(baos, true, StandardCharsets.UTF_8.name());
// when
Main.main("-serverPort", String.valueOf(freePort), "-proxyRemotePort", "A");
// then
String actual = new String(baos.toByteArray(), StandardCharsets.UTF_8);
String expected = NEW_LINE +
" =======================================================================" + NEW_LINE +
" proxyRemotePort value \"A\" is invalid, please specify a port i.e. \"1080\"" + NEW_LINE +
" =======================================================================" + NEW_LINE +
NEW_LINE +
Main.USAGE;
assertThat(actual, is(expected));
} finally {
Main.systemOut = originalPrintStream;
}
}
@Test
public void shouldPrintOutUsageForInvalidRemoteHost() throws UnsupportedEncodingException {
// given
final int freePort = PortFactory.findFreePort();
PrintStream originalPrintStream = Main.systemOut;
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
Main.systemOut = new PrintStream(byteArrayOutputStream, true, StandardCharsets.UTF_8.name());
// when
Main.main("-serverPort", String.valueOf(freePort), "-proxyRemoteHost", "%^&*(");
// then
String actual = new String(byteArrayOutputStream.toByteArray(), StandardCharsets.UTF_8);
String expected = NEW_LINE +
" ====================================================================================================" + NEW_LINE +
" proxyRemoteHost value \"%^&*(\" is invalid, please specify a host name i.e. \"localhost\" or \"127.0.0.1\"" + NEW_LINE +
" ====================================================================================================" + NEW_LINE +
NEW_LINE +
Main.USAGE;
assertThat(actual, is(expected));
} finally {
Main.systemOut = originalPrintStream;
}
}
@Test
public void shouldPrintOutUsageForInvalidLogLevel() throws UnsupportedEncodingException {
// given
final int freePort = PortFactory.findFreePort();
PrintStream originalPrintStream = Main.systemOut;
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
Main.systemOut = new PrintStream(byteArrayOutputStream, true, StandardCharsets.UTF_8.name());
// when
Main.main("-serverPort", String.valueOf(freePort), "-logLevel", "FOO");
// then
String actual = new String(byteArrayOutputStream.toByteArray(), StandardCharsets.UTF_8);
String expected = NEW_LINE +
" ====================================================================================================================================================================================================" + NEW_LINE +
" logLevel value \"FOO\" is invalid, please specify one of SL4J levels: \"TRACE\", \"DEBUG\", \"INFO\", \"WARN\", \"ERROR\", \"OFF\" or the Java Logger levels: \"FINEST\", \"FINE\", \"INFO\", \"WARNING\", \"SEVERE\", \"OFF\"" + NEW_LINE +
" ====================================================================================================================================================================================================" + NEW_LINE +
NEW_LINE +
Main.USAGE;
assertThat(actual, is(expected));
} finally {
Main.systemOut = originalPrintStream;
}
}
}
| apache-2.0 |
phillips1021/uPortal | uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/user/UserInstanceManagerImpl.java | 8949 | /**
* 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:
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apereo.portal.user;
import java.io.Serializable;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apereo.portal.IUserProfile;
import org.apereo.portal.PortalException;
import org.apereo.portal.UserInstance;
import org.apereo.portal.UserPreferencesManager;
import org.apereo.portal.i18n.ILocaleStore;
import org.apereo.portal.i18n.LocaleManager;
import org.apereo.portal.layout.IUserLayoutManager;
import org.apereo.portal.layout.IUserLayoutStore;
import org.apereo.portal.layout.UserLayoutManagerFactory;
import org.apereo.portal.layout.profile.IProfileMapper;
import org.apereo.portal.security.IPerson;
import org.apereo.portal.security.IPersonManager;
import org.apereo.portal.security.PortalSecurityException;
import org.apereo.portal.url.IPortalRequestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/** Determines which user instance object to use for a given user. */
@Service("userInstanceManager")
public class UserInstanceManagerImpl implements IUserInstanceManager {
private static final String KEY = UserInstanceManagerImpl.class.getName() + ".USER_INSTANCE";
protected final Log logger = LogFactory.getLog(UserInstanceManagerImpl.class);
private ILocaleStore localeStore;
private IUserLayoutStore userLayoutStore;
private IPersonManager personManager;
private IPortalRequestUtils portalRequestUtils;
private IProfileMapper profileMapper;
private UserLayoutManagerFactory userLayoutManagerFactory;
@Autowired
public void setUserLayoutManagerFactory(UserLayoutManagerFactory userLayoutManagerFactory) {
this.userLayoutManagerFactory = userLayoutManagerFactory;
}
@Autowired
public void setLocaleStore(ILocaleStore localeStore) {
this.localeStore = localeStore;
}
@Autowired
public void setUserLayoutStore(IUserLayoutStore userLayoutStore) {
this.userLayoutStore = userLayoutStore;
}
@Autowired
public void setPersonManager(IPersonManager personManager) {
this.personManager = personManager;
}
@Autowired
public void setPortalRequestUtils(IPortalRequestUtils portalRequestUtils) {
this.portalRequestUtils = portalRequestUtils;
}
@Autowired
public void setProfileMapper(IProfileMapper profileMapper) {
this.profileMapper = profileMapper;
}
/**
* Returns the UserInstance object that is associated with the given request.
*
* @param request Incoming HttpServletRequest
* @return UserInstance object associated with the given request
*/
@Override
public IUserInstance getUserInstance(HttpServletRequest request) throws PortalException {
try {
request = this.portalRequestUtils.getOriginalPortalRequest(request);
} catch (IllegalArgumentException iae) {
// ignore, just means that this isn't a wrapped request
}
// Use request attributes first for the fastest possible retrieval
IUserInstance userInstance = (IUserInstance) request.getAttribute(KEY);
if (userInstance != null) {
return userInstance;
}
final IPerson person;
try {
// Retrieve the person object that is associated with the request
person = this.personManager.getPerson(request);
} catch (Exception e) {
logger.error("Exception while retrieving IPerson!", e);
throw new PortalSecurityException("Could not retrieve IPerson", e);
}
if (person == null) {
throw new PortalSecurityException(
"PersonManager returned null person for this request. With no user, there's no UserInstance. Is PersonManager misconfigured? RDBMS access misconfigured?");
}
final HttpSession session = request.getSession();
if (session == null) {
throw new IllegalStateException(
"HttpServletRequest.getSession() returned a null session for request: "
+ request);
}
// Return the UserInstance object if it's in the session
UserInstanceHolder userInstanceHolder = getUserInstanceHolder(session);
if (userInstanceHolder != null) {
userInstance = userInstanceHolder.getUserInstance();
if (userInstance != null) {
return userInstance;
}
}
// Create either a UserInstance or a GuestUserInstance
final LocaleManager localeManager = this.getLocaleManager(request, person);
final String userAgent = this.getUserAgent(request);
final IUserProfile userProfile =
this.getUserProfile(request, person, localeManager, userAgent);
// Create the user layout manager and user instance object
IUserLayoutManager userLayoutManager =
userLayoutManagerFactory.getUserLayoutManager(person, userProfile);
final UserPreferencesManager userPreferencesManager =
new UserPreferencesManager(person, userProfile, userLayoutManager);
userInstance = new UserInstance(person, userPreferencesManager, localeManager);
// Ensure the newly created UserInstance is cached in the session
if (userInstanceHolder == null) {
userInstanceHolder = new UserInstanceHolder();
}
userInstanceHolder.setUserInstance(userInstance);
session.setAttribute(KEY, userInstanceHolder);
request.setAttribute(KEY, userInstance);
// Return the new UserInstance
return userInstance;
}
protected IUserProfile getUserProfile(
HttpServletRequest request,
IPerson person,
LocaleManager localeManager,
String userAgent) {
final String profileFname = profileMapper.getProfileFname(person, request);
IUserProfile userProfile = userLayoutStore.getUserProfileByFname(person, profileFname);
if (userProfile == null) {
userProfile = userLayoutStore.getSystemProfileByFname(profileFname);
}
if (localeManager != null && LocaleManager.isLocaleAware()) {
userProfile.setLocaleManager(localeManager);
}
return userProfile;
}
protected LocaleManager getLocaleManager(HttpServletRequest request, IPerson person) {
final String acceptLanguage = request.getHeader("Accept-Language");
final Locale[] userLocales = localeStore.getUserLocales(person);
return new LocaleManager(person, userLocales, acceptLanguage);
}
protected String getUserAgent(HttpServletRequest request) {
String userAgent = request.getHeader("User-Agent");
if (StringUtils.isEmpty(userAgent)) {
userAgent = "null";
}
return userAgent;
}
protected UserInstanceHolder getUserInstanceHolder(final HttpSession session) {
return (UserInstanceHolder) session.getAttribute(KEY);
}
/**
* Serializable wrapper class so the UserInstance object can be indirectly stored in the
* session. The manager can deal with this class returning a null value and its field is
* transient so the session can be serialized successfully with the UserInstance object in it.
*
* <p>Implements HttpSessionBindingListener and delegates those methods to the wrapped
* UserInstance, if present.
*/
private static class UserInstanceHolder implements Serializable {
private static final long serialVersionUID = 1L;
private transient IUserInstance ui = null;
/** @return Returns the userInstance. */
protected IUserInstance getUserInstance() {
return this.ui;
}
/** @param userInstance The userInstance to set. */
protected void setUserInstance(IUserInstance userInstance) {
this.ui = userInstance;
}
}
}
| apache-2.0 |
SignalK/signalk-server-java | src/main/java/nz/co/fortytwo/signalk/processor/RestPathFilterProcessor.java | 3424 | /*
*
* Copyright (C) 2012-2014 R T Huitema. All Rights Reserved.
* Web: www.42.co.nz
* Email: robert@42.co.nz
* Author: R T Huitema
*
* This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
* WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* 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 nz.co.fortytwo.signalk.processor;
import static nz.co.fortytwo.signalk.util.SignalKConstants.LIST;
import javax.servlet.http.HttpServletResponse;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import mjson.Json;
import nz.co.fortytwo.signalk.model.SignalKModel;
import nz.co.fortytwo.signalk.util.JsonSerializer;
import nz.co.fortytwo.signalk.util.Util;
/**
* Trim the path from the json for REST api calls
* @author robert
*
*/
public class RestPathFilterProcessor extends SignalkProcessor implements Processor {
private static Logger logger = LogManager.getLogger(RestPathFilterProcessor.class);
JsonSerializer ser = new JsonSerializer();
public void process(Exchange exchange) throws Exception {
if (exchange.getIn().getBody()==null)
return;
if(logger.isDebugEnabled())logger.debug("Processing, class="+exchange.getIn().getBody().getClass());
//TODO: add more filters here
Json reply = null;
if (exchange.getIn().getBody() instanceof String){
reply = Json.read(exchange.getIn().getBody(String.class));
}else if (exchange.getIn().getBody() instanceof SignalKModel){
SignalKModel model = (SignalKModel)exchange.getIn().getBody();
reply = ser.writeJson(model);
}else if(exchange.getIn().getBody() instanceof Json){
reply = (Json)exchange.getIn().getBody();
}
//trim leading path
String path = exchange.getIn().getHeader(Exchange.HTTP_PATH, String.class);
//not for /list POST PUT
if(!exchange.getIn().getHeader(Exchange.HTTP_METHOD).equals("GET") || path.startsWith("/"+LIST))
return;
path = sanitizePath(path);
if(path.endsWith("*")){
path=path.substring(0, path.lastIndexOf("."));
}
if(logger.isDebugEnabled()){
logger.debug("Trimming:"+exchange.getIn().getHeaders());
logger.debug("Trimming by "+path+" : "+reply);
}
if(StringUtils.isNotBlank(path)&& reply !=null && !reply.toString().equals("{}")){
reply = Util.findNode(reply, path);
}
if(reply==null){
exchange.getIn().setBody("Bad Request");
exchange.getIn().setHeader(Exchange.CONTENT_TYPE, "text/plain");
exchange.getIn().setHeader(Exchange.HTTP_RESPONSE_CODE,
HttpServletResponse.SC_BAD_REQUEST);
return;
}
//all ok
exchange.getIn().setBody(reply.toString());
if(logger.isDebugEnabled()){
logger.debug("Outputting:"+exchange.getIn().getHeaders());
logger.debug("Outputting:"+exchange.getIn());
}
}
}
| apache-2.0 |
JP1998/PicturesWallpaper | app/src/main/java/de/jeanpierrehotz/severalpictureswallpaper/views/WallpaperNameAdapter.java | 2773 | /*
* Copyright 2017 Jean-Pierre Hotz
*
* 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 de.jeanpierrehotz.severalpictureswallpaper.views;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.List;
import de.jeanpierrehotz.severalpictureswallpaper.R;
import de.jeanpierrehotz.severalpictureswallpaper.wallpaper.data.WallpaperSettings;
/**
*
*/
public class WallpaperNameAdapter extends RecyclerView.Adapter<WallpaperNameViewHolder> {
private Context c;
private List<WallpaperSettings> settings;
private int selected;
private OnItemClickListener clickListener;
public WallpaperNameAdapter(Context ctx, List<WallpaperSettings> settings, int selected) {
this.c = ctx;
this.settings = settings;
this.selected = selected;
}
public void notifySelectedChanged(int sel) {
this.notifyItemChanged(this.selected);
this.selected = sel;
this.notifyItemChanged(this.selected);
}
public void setOnItemClickListener(OnItemClickListener listener) {
clickListener = listener;
}
@Override
public WallpaperNameViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.layout_item_wallpaper, parent, false);
final WallpaperNameViewHolder vh = new WallpaperNameViewHolder(v);
v.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (clickListener != null) {
clickListener.onItemClicked(vh, vh.getAdapterPosition());
}
}
});
return vh;
}
@Override
public void onBindViewHolder(WallpaperNameViewHolder holder, int position) {
holder.setCaption(settings.get(position).getCaption());
holder.setSelected(selected, position);
}
@Override
public int getItemCount() {
return settings.size();
}
public interface OnItemClickListener {
void onItemClicked(WallpaperNameViewHolder vh, int pos);
}
} | apache-2.0 |
leafclick/intellij-community | plugins/sh/gen/com/intellij/sh/psi/impl/ShParenthesesConditionImpl.java | 1158 | // This is a generated file. Not intended for manual editing.
package com.intellij.sh.psi.impl;
import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.util.PsiTreeUtil;
import static com.intellij.sh.ShTypes.*;
import com.intellij.sh.psi.*;
public class ShParenthesesConditionImpl extends ShConditionImpl implements ShParenthesesCondition {
public ShParenthesesConditionImpl(ASTNode node) {
super(node);
}
public void accept(@NotNull ShVisitor visitor) {
visitor.visitParenthesesCondition(this);
}
public void accept(@NotNull PsiElementVisitor visitor) {
if (visitor instanceof ShVisitor) accept((ShVisitor)visitor);
else super.accept(visitor);
}
@Override
@Nullable
public ShCondition getCondition() {
return findChildByClass(ShCondition.class);
}
@Override
@NotNull
public PsiElement getLeftParen() {
return findNotNullChildByType(LEFT_PAREN);
}
@Override
@Nullable
public PsiElement getRightParen() {
return findChildByType(RIGHT_PAREN);
}
}
| apache-2.0 |
treasure-data/digdag | digdag-tests/src/test/java/acceptance/TestingCommandExecutorPlugin.java | 3091 | package acceptance;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.inject.Inject;
import io.digdag.spi.CommandContext;
import io.digdag.spi.CommandExecutor;
import io.digdag.spi.CommandExecutorFactory;
import io.digdag.spi.CommandLogger;
import io.digdag.spi.CommandRequest;
import io.digdag.spi.CommandStatus;
import io.digdag.spi.Plugin;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
public class TestingCommandExecutorPlugin
implements Plugin
{
@Override
public <T> Class<? extends T> getServiceProvider(Class<T> type)
{
if (type == CommandExecutorFactory.class) {
return TestingCommandExecutorFactory.class.asSubclass(type);
}
else {
return null;
}
}
static class TestingCommandExecutorFactory
implements CommandExecutorFactory
{
private final CommandLogger clog;
@Inject
public TestingCommandExecutorFactory(CommandLogger clog)
{
this.clog = clog;
}
public String getType()
{
return "testing";
}
@Override
public CommandExecutor newCommandExecutor()
{
return new TestingCommandExecutor(clog);
}
}
static class TestingCommandExecutor
implements CommandExecutor
{
private final CommandLogger clog;
public TestingCommandExecutor(CommandLogger clog)
{
this.clog = clog;
}
@Override
public CommandStatus run(CommandContext context, CommandRequest request)
throws IOException
{
String testStr = "===TestingCommandExecutor====\n";
InputStream is = new ByteArrayInputStream(testStr.getBytes(StandardCharsets.UTF_8));
clog.copy(is, System.out);
return new TestingCommandStatus(0, request.getIoDirectory().toString());
}
@Override
public CommandStatus poll(CommandContext context, ObjectNode previousStatusJson)
throws IOException
{
throw new UnsupportedOperationException("This method should not be called.");
}
}
static class TestingCommandStatus
implements CommandStatus
{
private final int statusCode;
private final String ioDirectory;
TestingCommandStatus(final int statusCode, final String ioDirectory)
{
this.statusCode = statusCode;
this.ioDirectory = ioDirectory;
}
@Override
public boolean isFinished()
{
return true;
}
@Override
public int getStatusCode()
{
return statusCode;
}
@Override
public String getIoDirectory()
{
return ioDirectory;
}
@Override
public ObjectNode toJson()
{
throw new UnsupportedOperationException();
}
}
}
| apache-2.0 |
quarkusio/quarkus | independent-projects/qute/core/src/main/java/io/quarkus/qute/MemberKey.java | 2210 | package io.quarkus.qute;
import java.util.Objects;
/**
*
* @see ReflectionValueResolver
*/
final class MemberKey {
final Class<?> clazz;
final String name;
final int numberOfParams;
final int hashCode;
MemberKey(Class<?> clazz, String name, int numberOfParams) {
this.clazz = clazz;
this.name = name;
this.numberOfParams = numberOfParams;
final int prime = 31;
int result = 1;
result = prime * result + clazz.hashCode();
result = prime * result + name.hashCode();
result = prime * result + numberOfParams;
this.hashCode = result;
}
@Override
public int hashCode() {
return hashCode;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
MemberKey other = (MemberKey) obj;
return Objects.equals(clazz, other.clazz) && Objects.equals(name, other.name) && numberOfParams == other.numberOfParams;
}
@Override
public String toString() {
return String.format("MemberKey [clazz: %s, name: %s, numberOfParams: %s]", clazz, name, numberOfParams);
}
static MemberKey from(EvalContext context) {
Object contextObject = context.getBase();
String name = context.getName();
Class<?> baseClass = contextObject.getClass();
if (contextObject instanceof Class<?>) {
Class<?> clazz = (Class<?>) contextObject;
if (clazz.isEnum() && ("values".equals(name) || isConstantName(clazz, name))) {
// Special handling for enums - allows to access values() and constants
baseClass = clazz;
}
}
return new MemberKey(baseClass, name, context.getParams().size());
}
private static boolean isConstantName(Class<?> enumClazz, String name) {
for (Object constant : enumClazz.getEnumConstants()) {
if (name.equals(constant.toString())) {
return true;
}
}
return false;
}
}
| apache-2.0 |
iritgo/iritgo-aktera | aktera-struts/src/main/java/de/iritgo/aktera/struts/tags/html/WeekdaySelectTag.java | 3017 | /**
* This file is part of the Iritgo/Aktera Framework.
*
* Copyright (C) 2005-2011 Iritgo Technologies.
* Copyright (C) 2003-2005 BueroByte GbR.
*
* Iritgo 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 de.iritgo.aktera.struts.tags.html;
import org.apache.struts.taglib.TagUtils;
import org.apache.struts.util.RequestUtils;
import org.apache.struts.util.ResponseUtils;
import javax.servlet.jsp.JspException;
/**
* Create form elements for weekday editing.
*/
public class WeekdaySelectTag extends SelectTagBase
{
/** */
private static final long serialVersionUID = 1L;
/** Weekday strings. */
static String[] weekdays = new String[]
{
"1.weekday.00", "1.weekday.mon", "1.weekday.tue", "1.weekday.wed", "1.weekday.thu",
"1.weekday.fri", "1.weekday.sat", "1.weekday.sun"
};
/** Weekday values. */
static String[] weekdayValues = new String[]
{
"", "mon", "tue", "wed", "thu", "fri", "sat", "sun"
};
/** Read only. */
protected boolean readOnly = false;
/**
* Set the read only flag.
*
* @param readOnly Read only flag.
*/
public void setReadOnly(boolean readOnly)
{
this.readOnly = readOnly;
}
/**
* Get the read only flag.
*
* @retrun The read only flag.
*/
public boolean getReadOnly()
{
return readOnly;
}
/**
* Render the tag.
*
* @exception JspException if a JSP exception has occurred.
*/
public int doEndTag() throws JspException
{
String selectedValue = getBeanProperty().toString();
StringBuffer results = new StringBuffer();
if (! readOnly)
{
createSelectTag(results);
for (int i = 0; i < weekdays.length; ++i)
{
results.append("<option value=\"");
results.append(weekdayValues[i]);
results.append("\"");
if (weekdayValues[i].equals(selectedValue))
{
results.append(" selected=\"selected\"");
}
results.append(">");
results.append(TagUtils.getInstance().message(pageContext, bundle, locale, weekdays[i]));
results.append("</option>");
}
results.append("</select>\n");
}
else
{
for (int i = 0; i < weekdays.length; ++i)
{
if (weekdayValues[i].equals(selectedValue))
{
results.append(TagUtils.getInstance().message(pageContext, bundle, locale, weekdays[i]));
}
}
}
TagUtils.getInstance().write(pageContext, results.toString());
return EVAL_PAGE;
}
/**
* Reset all tag attributes to their default values.
*/
public void release()
{
super.release();
readOnly = false;
}
}
| apache-2.0 |
EMResearch/EMB | jdk_8_maven/cs/rest/original/languagetool/languagetool-language-modules/br/src/test/java/org/languagetool/rules/br/MorfologikBretonSpellerRuleTest.java | 3756 | /* LanguageTool, a natural language style checker
* Copyright (C) 2012 Marcin Miłkowski
*
* 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 St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.languagetool.rules.br;
import org.junit.Test;
import org.languagetool.JLanguageTool;
import org.languagetool.TestTools;
import org.languagetool.language.Breton;
import org.languagetool.rules.RuleMatch;
import java.io.IOException;
import java.util.Collections;
import static org.junit.Assert.assertEquals;
public class MorfologikBretonSpellerRuleTest {
@Test
public void testMorfologikSpeller() throws IOException {
final MorfologikBretonSpellerRule rule =
new MorfologikBretonSpellerRule (TestTools.getMessages("br"), new Breton(), null, Collections.emptyList());
RuleMatch[] matches;
final JLanguageTool langTool = new JLanguageTool(new Breton());
// correct sentences:
assertEquals(0, rule.match(langTool.getAnalyzedSentence("Penaos emañ kont ganit?")).length);
assertEquals(0, rule.match(langTool.getAnalyzedSentence("C'hwerc'h merc'h gwerc'h war c'hwerc'h marc'h kalloc'h")).length);
assertEquals(0, rule.match(langTool.getAnalyzedSentence("C’hwerc’h merc’h gwerc‘h war c‘hwerc‘h marc'h kalloc‘h")).length);
//words with hyphens are tokenized internally...
assertEquals(0, rule.match(langTool.getAnalyzedSentence("Evel-just")).length);
assertEquals(0, rule.match(langTool.getAnalyzedSentence("Barrek-tre eo LanguageTool")).length);
assertEquals(0, rule.match(langTool.getAnalyzedSentence("C'hwerc'h merc'h gwerc'h war c'hwerc'h marc'h kalloc'h")).length);
assertEquals(0, rule.match(langTool.getAnalyzedSentence("C’hwerc’h merc’h gwerc‘h war c‘hwerc‘h marc'h kalloc‘h")).length);
assertEquals(0, rule.match(langTool.getAnalyzedSentence("Evel-just")).length);
assertEquals(1, rule.match(langTool.getAnalyzedSentence("Evel-juste")).length);
assertEquals(0, rule.match(langTool.getAnalyzedSentence("Barrek-tre eo LanguageTool")).length);
//test for "LanguageTool":
assertEquals(0, rule.match(langTool.getAnalyzedSentence("LanguageTool!")).length);
assertEquals(0, rule.match(langTool.getAnalyzedSentence(",")).length);
assertEquals(0, rule.match(langTool.getAnalyzedSentence("123454")).length);
//incorrect sentences:
assertEquals(1, rule.match(langTool.getAnalyzedSentence("Evel-juste")).length);
matches = rule.match(langTool.getAnalyzedSentence("Evel-juste"));
// check match positions:
assertEquals(1, matches.length);
assertEquals(5, matches[0].getFromPos());
assertEquals(10, matches[0].getToPos());
matches = rule.match(langTool.getAnalyzedSentence("C’hreizhig-don"));
assertEquals(1, matches.length);
// check match positions:
assertEquals(1, matches.length);
assertEquals(0, matches[0].getFromPos());
assertEquals(10, matches[0].getToPos());
assertEquals(1, rule.match(langTool.getAnalyzedSentence("aõh")).length);
assertEquals(0, rule.match(langTool.getAnalyzedSentence("a")).length);
}
}
| apache-2.0 |
googleads/googleads-java-lib | modules/dfp_axis/src/main/java/com/google/api/ads/admanager/axis/v202111/AdCategoryDto.java | 7305 | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* AdCategoryDto.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
*/
package com.google.api.ads.admanager.axis.v202111;
/**
* A canonical ad category.
*/
public class AdCategoryDto implements java.io.Serializable {
/* Canonical ID of the ad category. */
private java.lang.Long id;
/* Localized name of the category. */
private java.lang.String displayName;
/* ID of the category's parent, or 0 if it has no parent. */
private java.lang.Long parentId;
public AdCategoryDto() {
}
public AdCategoryDto(
java.lang.Long id,
java.lang.String displayName,
java.lang.Long parentId) {
this.id = id;
this.displayName = displayName;
this.parentId = parentId;
}
@Override
public String toString() {
return com.google.common.base.MoreObjects.toStringHelper(this.getClass())
.omitNullValues()
.add("displayName", getDisplayName())
.add("id", getId())
.add("parentId", getParentId())
.toString();
}
/**
* Gets the id value for this AdCategoryDto.
*
* @return id * Canonical ID of the ad category.
*/
public java.lang.Long getId() {
return id;
}
/**
* Sets the id value for this AdCategoryDto.
*
* @param id * Canonical ID of the ad category.
*/
public void setId(java.lang.Long id) {
this.id = id;
}
/**
* Gets the displayName value for this AdCategoryDto.
*
* @return displayName * Localized name of the category.
*/
public java.lang.String getDisplayName() {
return displayName;
}
/**
* Sets the displayName value for this AdCategoryDto.
*
* @param displayName * Localized name of the category.
*/
public void setDisplayName(java.lang.String displayName) {
this.displayName = displayName;
}
/**
* Gets the parentId value for this AdCategoryDto.
*
* @return parentId * ID of the category's parent, or 0 if it has no parent.
*/
public java.lang.Long getParentId() {
return parentId;
}
/**
* Sets the parentId value for this AdCategoryDto.
*
* @param parentId * ID of the category's parent, or 0 if it has no parent.
*/
public void setParentId(java.lang.Long parentId) {
this.parentId = parentId;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof AdCategoryDto)) return false;
AdCategoryDto other = (AdCategoryDto) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true &&
((this.id==null && other.getId()==null) ||
(this.id!=null &&
this.id.equals(other.getId()))) &&
((this.displayName==null && other.getDisplayName()==null) ||
(this.displayName!=null &&
this.displayName.equals(other.getDisplayName()))) &&
((this.parentId==null && other.getParentId()==null) ||
(this.parentId!=null &&
this.parentId.equals(other.getParentId())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = 1;
if (getId() != null) {
_hashCode += getId().hashCode();
}
if (getDisplayName() != null) {
_hashCode += getDisplayName().hashCode();
}
if (getParentId() != null) {
_hashCode += getParentId().hashCode();
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(AdCategoryDto.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202111", "AdCategoryDto"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("id");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202111", "id"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("displayName");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202111", "displayName"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("parentId");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202111", "parentId"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
| apache-2.0 |
rapeflower/Android-Animation | BootPageAnimation/app/src/main/java/com/lily/animation/guideview/PointEvaluator.java | 753 | package com.lily.animation.guideview;
import android.animation.TypeEvaluator;
import com.lily.animation.model.Point;
/**
* @author rape flower
* @Date 2017-06-22 14:18
* @descripe 坐标点估值器
*/
public class PointEvaluator implements TypeEvaluator {
@Override
public Object evaluate(float fraction, Object startValue, Object endValue) {
android.util.Log.w("PointEvaluator", "fraction = " + fraction);
Point startPoint = (Point) startValue;
Point endPoint = (Point) endValue;
float x = startPoint.getX();//startPoint.getX() = endPoint.getX()
float y = startPoint.getY() - fraction * (startPoint.getY() - endPoint.getY());
Point point = new Point(x, y);
return point;
}
}
| apache-2.0 |
Ariah-Group/Finance | af_webapp/src/main/java/org/kuali/kfs/module/bc/document/validation/DeleteMonthlySpreadRule.java | 1049 | /*
* Copyright 2008 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.kfs.module.bc.document.validation;
import org.kuali.kfs.module.bc.BCConstants.MonthSpreadDeleteType;
import org.kuali.kfs.module.bc.document.BudgetConstructionDocument;
/**
* This class...
*/
public interface DeleteMonthlySpreadRule<D extends BudgetConstructionDocument> {
public boolean processDeleteMonthlySpreadRules(D budgetConstructionDocument, MonthSpreadDeleteType monthSpreadDeleteType);
}
| apache-2.0 |