lang
stringclasses 2
values | license
stringclasses 13
values | stderr
stringlengths 0
343
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 6
87.7k
| new_contents
stringlengths 0
6.23M
| new_file
stringlengths 3
311
| old_contents
stringlengths 0
6.23M
| message
stringlengths 6
9.1k
| old_file
stringlengths 3
311
| subject
stringlengths 0
4k
| git_diff
stringlengths 0
6.31M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
Java | epl-1.0 | b86059c2b4fb55d7004aa59ac4c1bf786aa5d843 | 0 | snxamdf/SimpleControl,snxamdf/SimpleControl | package com.yhy.test.action;
import javax.servlet.http.HttpServletRequest;
import sc.yhy.annotation.annot.Autowired;
import sc.yhy.annotation.annot.Value;
import sc.yhy.annotation.request.Action;
import sc.yhy.annotation.request.RequestMapping;
import com.yhy.test.service.TestService;
import com.yhy.test.service.TranService;
@Action
@RequestMapping(value = "/tran")
public class TransactionAction {
@Autowired
private TranService tranService;
@Autowired
private TestService testService;
private static int index = 0;
@Value("${sc.annot.init}")
private String testinit;
@Value("${sc.annot.init.3}")
private String scannotinit3;
@Value("${sc.annot.init.3}")
private String scannotinit1;
@RequestMapping(value = "/test.action")
public String testTran(HttpServletRequest request) {
try {
tranService.saveTest();
if (request.getParameter("index") != null) {
index = 0;
}
index = index + 1;
request.setAttribute("index", index);
} catch (Exception e) {
e.printStackTrace();
}
return "/tran.jsp";
}
}
| SC/src/com/yhy/test/action/TransactionAction.java | package com.yhy.test.action;
import javax.servlet.http.HttpServletRequest;
import sc.yhy.annotation.annot.Autowired;
import sc.yhy.annotation.annot.Value;
import sc.yhy.annotation.request.Action;
import sc.yhy.annotation.request.RequestMapping;
import com.yhy.test.service.TestService;
import com.yhy.test.service.TranService;
@Action
@RequestMapping(value = "/tran")
public class TransactionAction {
@Autowired
private TranService tranService;
@Autowired
private TestService testService;
private static int index = 0;
@Value("${sc.annot.init}")
private String testinit;
@Value("${sc.annot.init.3}")
private String scannotinit3;
@RequestMapping(value = "/test.action")
public String testTran(HttpServletRequest request) {
try {
tranService.saveTest();
if (request.getParameter("index") != null) {
index = 0;
}
index = index + 1;
request.setAttribute("index", index);
} catch (Exception e) {
e.printStackTrace();
}
return "/tran.jsp";
}
}
| YHY 测试@value注解 | SC/src/com/yhy/test/action/TransactionAction.java | YHY 测试@value注解 | <ide><path>C/src/com/yhy/test/action/TransactionAction.java
<ide>
<ide> @Value("${sc.annot.init}")
<ide> private String testinit;
<del>
<add>
<ide> @Value("${sc.annot.init.3}")
<ide> private String scannotinit3;
<add> @Value("${sc.annot.init.3}")
<add> private String scannotinit1;
<ide>
<ide> @RequestMapping(value = "/test.action")
<ide> public String testTran(HttpServletRequest request) { |
|
Java | apache-2.0 | 01cb1a90d68ca149488deebf2e2b8b61a852bccb | 0 | oplinkoms/onos,LorenzReinhart/ONOSnew,maheshraju-Huawei/actn,gkatsikas/onos,sonu283304/onos,zsh2938/onos,chinghanyu/onos,kuujo/onos,oplinkoms/onos,maheshraju-Huawei/actn,lsinfo3/onos,gkatsikas/onos,zsh2938/onos,CNlukai/onos-gerrit-test,oeeagle/onos,packet-tracker/onos,chenxiuyang/onos,jmiserez/onos,kkkane/ONOS,opennetworkinglab/onos,osinstom/onos,kkkane/ONOS,jmiserez/onos,VinodKumarS-Huawei/ietf96yang,sdnwiselab/onos,y-higuchi/onos,oplinkoms/onos,sdnwiselab/onos,Shashikanth-Huawei/bmp,donNewtonAlpha/onos,packet-tracker/onos,sdnwiselab/onos,y-higuchi/onos,chinghanyu/onos,sdnwiselab/onos,jmiserez/onos,VinodKumarS-Huawei/ietf96yang,mengmoya/onos,oeeagle/onos,rvhub/onos,opennetworkinglab/onos,planoAccess/clonedONOS,lsinfo3/onos,donNewtonAlpha/onos,castroflavio/onos,kuujo/onos,mengmoya/onos,lsinfo3/onos,kkkane/ONOS,kuujo/onos,donNewtonAlpha/onos,sonu283304/onos,sdnwiselab/onos,rvhub/onos,castroflavio/onos,planoAccess/clonedONOS,packet-tracker/onos,oplinkoms/onos,Shashikanth-Huawei/bmp,jinlongliu/onos,rvhub/onos,opennetworkinglab/onos,rvhub/onos,y-higuchi/onos,gkatsikas/onos,kuujo/onos,kkkane/ONOS,VinodKumarS-Huawei/ietf96yang,LorenzReinhart/ONOSnew,maheshraju-Huawei/actn,osinstom/onos,maheshraju-Huawei/actn,donNewtonAlpha/onos,opennetworkinglab/onos,gkatsikas/onos,gkatsikas/onos,lsinfo3/onos,oeeagle/onos,osinstom/onos,zsh2938/onos,chenxiuyang/onos,y-higuchi/onos,opennetworkinglab/onos,jinlongliu/onos,VinodKumarS-Huawei/ietf96yang,Shashikanth-Huawei/bmp,osinstom/onos,oplinkoms/onos,Shashikanth-Huawei/bmp,donNewtonAlpha/onos,chenxiuyang/onos,LorenzReinhart/ONOSnew,jinlongliu/onos,mengmoya/onos,chinghanyu/onos,chinghanyu/onos,planoAccess/clonedONOS,maheshraju-Huawei/actn,opennetworkinglab/onos,castroflavio/onos,sdnwiselab/onos,CNlukai/onos-gerrit-test,sonu283304/onos,kuujo/onos,packet-tracker/onos,mengmoya/onos,VinodKumarS-Huawei/ietf96yang,kuujo/onos,planoAccess/clonedONOS,y-higuchi/onos,oplinkoms/onos,kuujo/onos,gkatsikas/onos,sonu283304/onos,Shashikanth-Huawei/bmp,jinlongliu/onos,oplinkoms/onos,CNlukai/onos-gerrit-test,jmiserez/onos,CNlukai/onos-gerrit-test,chenxiuyang/onos,castroflavio/onos,osinstom/onos,oeeagle/onos,LorenzReinhart/ONOSnew,LorenzReinhart/ONOSnew,mengmoya/onos,zsh2938/onos | /*
* Copyright 2014-2015 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.store.serializers;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import org.onlab.packet.ChassisId;
import org.onlab.packet.Ip4Address;
import org.onlab.packet.Ip4Prefix;
import org.onlab.packet.Ip6Address;
import org.onlab.packet.Ip6Prefix;
import org.onlab.packet.IpAddress;
import org.onlab.packet.IpPrefix;
import org.onlab.packet.MacAddress;
import org.onlab.packet.VlanId;
import org.onlab.util.Bandwidth;
import org.onlab.util.Frequency;
import org.onlab.util.KryoNamespace;
import org.onosproject.app.ApplicationState;
import org.onosproject.cluster.ControllerNode;
import org.onosproject.cluster.DefaultControllerNode;
import org.onosproject.cluster.Leadership;
import org.onosproject.cluster.LeadershipEvent;
import org.onosproject.cluster.NodeId;
import org.onosproject.cluster.RoleInfo;
import org.onosproject.core.DefaultApplication;
import org.onosproject.core.DefaultApplicationId;
import org.onosproject.core.DefaultGroupId;
import org.onosproject.core.Version;
import org.onosproject.mastership.MastershipTerm;
import org.onosproject.net.Annotations;
import org.onosproject.net.ChannelSpacing;
import org.onosproject.net.ConnectPoint;
import org.onosproject.net.DefaultAnnotations;
import org.onosproject.net.DefaultDevice;
import org.onosproject.net.DefaultEdgeLink;
import org.onosproject.net.DefaultLink;
import org.onosproject.net.DefaultPath;
import org.onosproject.net.DefaultPort;
import org.onosproject.net.Device;
import org.onosproject.net.DeviceId;
import org.onosproject.net.Element;
import org.onosproject.net.GridType;
import org.onosproject.net.HostId;
import org.onosproject.net.HostLocation;
import org.onosproject.net.IndexedLambda;
import org.onosproject.net.Link;
import org.onosproject.net.LinkKey;
import org.onosproject.net.OchPort;
import org.onosproject.net.OchSignal;
import org.onosproject.net.OduCltPort;
import org.onosproject.net.OduSignalType;
import org.onosproject.net.OmsPort;
import org.onosproject.net.Port;
import org.onosproject.net.PortNumber;
import org.onosproject.net.device.DefaultDeviceDescription;
import org.onosproject.net.device.DefaultPortDescription;
import org.onosproject.net.device.OchPortDescription;
import org.onosproject.net.device.OduCltPortDescription;
import org.onosproject.net.device.OmsPortDescription;
import org.onosproject.net.flow.CompletedBatchOperation;
import org.onosproject.net.flow.DefaultFlowEntry;
import org.onosproject.net.flow.DefaultFlowRule;
import org.onosproject.net.flow.DefaultTrafficSelector;
import org.onosproject.net.flow.DefaultTrafficTreatment;
import org.onosproject.net.flow.FlowEntry;
import org.onosproject.net.flow.FlowId;
import org.onosproject.net.flow.FlowRule;
import org.onosproject.net.flow.FlowRuleBatchEntry;
import org.onosproject.net.flow.FlowRuleBatchEvent;
import org.onosproject.net.flow.FlowRuleBatchOperation;
import org.onosproject.net.flow.FlowRuleBatchRequest;
import org.onosproject.net.flow.FlowRuleExtPayLoad;
import org.onosproject.net.flow.StoredFlowEntry;
import org.onosproject.net.flow.criteria.Criterion;
import org.onosproject.net.flow.criteria.EthCriterion;
import org.onosproject.net.flow.criteria.EthTypeCriterion;
import org.onosproject.net.flow.criteria.IPCriterion;
import org.onosproject.net.flow.criteria.IPDscpCriterion;
import org.onosproject.net.flow.criteria.IPEcnCriterion;
import org.onosproject.net.flow.criteria.IPProtocolCriterion;
import org.onosproject.net.flow.criteria.IPv6ExthdrFlagsCriterion;
import org.onosproject.net.flow.criteria.IPv6FlowLabelCriterion;
import org.onosproject.net.flow.criteria.IPv6NDLinkLayerAddressCriterion;
import org.onosproject.net.flow.criteria.IPv6NDTargetAddressCriterion;
import org.onosproject.net.flow.criteria.IcmpCodeCriterion;
import org.onosproject.net.flow.criteria.IcmpTypeCriterion;
import org.onosproject.net.flow.criteria.Icmpv6CodeCriterion;
import org.onosproject.net.flow.criteria.Icmpv6TypeCriterion;
import org.onosproject.net.flow.criteria.IndexedLambdaCriterion;
import org.onosproject.net.flow.criteria.LambdaCriterion;
import org.onosproject.net.flow.criteria.MetadataCriterion;
import org.onosproject.net.flow.criteria.MplsCriterion;
import org.onosproject.net.flow.criteria.OchSignalCriterion;
import org.onosproject.net.flow.criteria.OchSignalTypeCriterion;
import org.onosproject.net.flow.criteria.OpticalSignalTypeCriterion;
import org.onosproject.net.flow.criteria.PortCriterion;
import org.onosproject.net.flow.criteria.SctpPortCriterion;
import org.onosproject.net.flow.criteria.TcpPortCriterion;
import org.onosproject.net.flow.criteria.UdpPortCriterion;
import org.onosproject.net.flow.criteria.VlanIdCriterion;
import org.onosproject.net.flow.criteria.VlanPcpCriterion;
import org.onosproject.net.flow.instructions.Instructions;
import org.onosproject.net.flow.instructions.L0ModificationInstruction;
import org.onosproject.net.flow.instructions.L2ModificationInstruction;
import org.onosproject.net.flow.instructions.L3ModificationInstruction;
import org.onosproject.net.host.DefaultHostDescription;
import org.onosproject.net.host.HostDescription;
import org.onosproject.net.intent.ConnectivityIntent;
import org.onosproject.net.intent.FlowRuleIntent;
import org.onosproject.net.intent.HostToHostIntent;
import org.onosproject.net.intent.Intent;
import org.onosproject.net.intent.IntentId;
import org.onosproject.net.intent.IntentOperation;
import org.onosproject.net.intent.IntentState;
import org.onosproject.net.intent.Key;
import org.onosproject.net.intent.LinkCollectionIntent;
import org.onosproject.net.intent.MplsIntent;
import org.onosproject.net.intent.MplsPathIntent;
import org.onosproject.net.intent.MultiPointToSinglePointIntent;
import org.onosproject.net.intent.OpticalConnectivityIntent;
import org.onosproject.net.intent.OpticalPathIntent;
import org.onosproject.net.intent.PathIntent;
import org.onosproject.net.intent.PointToPointIntent;
import org.onosproject.net.intent.SinglePointToMultiPointIntent;
import org.onosproject.net.intent.constraint.AnnotationConstraint;
import org.onosproject.net.intent.constraint.BandwidthConstraint;
import org.onosproject.net.intent.constraint.BooleanConstraint;
import org.onosproject.net.intent.constraint.LambdaConstraint;
import org.onosproject.net.intent.constraint.LatencyConstraint;
import org.onosproject.net.intent.constraint.LinkTypeConstraint;
import org.onosproject.net.intent.constraint.ObstacleConstraint;
import org.onosproject.net.intent.constraint.WaypointConstraint;
import org.onosproject.net.link.DefaultLinkDescription;
import org.onosproject.net.packet.DefaultOutboundPacket;
import org.onosproject.net.packet.DefaultPacketRequest;
import org.onosproject.net.packet.PacketPriority;
import org.onosproject.net.provider.ProviderId;
import org.onosproject.net.resource.BandwidthResource;
import org.onosproject.net.resource.BandwidthResourceAllocation;
import org.onosproject.net.resource.BandwidthResourceRequest;
import org.onosproject.net.resource.DefaultLinkResourceAllocations;
import org.onosproject.net.resource.DefaultLinkResourceRequest;
import org.onosproject.net.resource.LambdaResource;
import org.onosproject.net.resource.LambdaResourceAllocation;
import org.onosproject.net.resource.LambdaResourceRequest;
import org.onosproject.net.resource.LinkResourceRequest;
import org.onosproject.net.resource.MplsLabel;
import org.onosproject.net.resource.MplsLabelResourceAllocation;
import org.onosproject.net.resource.MplsLabelResourceRequest;
import org.onosproject.store.Timestamp;
import org.onosproject.store.service.Versioned;
import java.net.URI;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
public final class KryoNamespaces {
public static final KryoNamespace BASIC = KryoNamespace.newBuilder()
.nextId(KryoNamespace.FLOATING_ID)
.register(byte[].class)
.register(new ImmutableListSerializer(),
ImmutableList.class,
ImmutableList.of(1).getClass(),
ImmutableList.of(1, 2).getClass())
.register(new ImmutableSetSerializer(),
ImmutableSet.class,
ImmutableSet.of().getClass(),
ImmutableSet.of(1).getClass(),
ImmutableSet.of(1, 2).getClass())
.register(new ImmutableMapSerializer(),
ImmutableMap.class,
ImmutableMap.of().getClass(),
ImmutableMap.of("a", 1).getClass(),
ImmutableMap.of("R", 2, "D", 2).getClass())
.register(HashMap.class)
.register(ConcurrentHashMap.class)
.register(CopyOnWriteArraySet.class)
.register(ArrayList.class,
LinkedList.class,
HashSet.class
)
.register(new ArraysAsListSerializer(), Arrays.asList().getClass())
.register(Collections.singletonList(1).getClass())
.register(Duration.class)
.register(Collections.emptySet().getClass())
.register(Optional.class)
.register(Collections.emptyList().getClass())
.register(Collections.unmodifiableSet(Collections.emptySet()).getClass())
.build();
/**
* KryoNamespace which can serialize ON.lab misc classes.
*/
public static final KryoNamespace MISC = KryoNamespace.newBuilder()
.nextId(KryoNamespace.FLOATING_ID)
.register(new IpPrefixSerializer(), IpPrefix.class)
.register(new Ip4PrefixSerializer(), Ip4Prefix.class)
.register(new Ip6PrefixSerializer(), Ip6Prefix.class)
.register(new IpAddressSerializer(), IpAddress.class)
.register(new Ip4AddressSerializer(), Ip4Address.class)
.register(new Ip6AddressSerializer(), Ip6Address.class)
.register(new MacAddressSerializer(), MacAddress.class)
.register(VlanId.class)
.register(Frequency.class)
.register(Bandwidth.class)
.build();
/**
* Kryo registration Id for user custom registration.
*/
public static final int BEGIN_USER_CUSTOM_ID = 300;
// TODO: Populate other classes
/**
* KryoNamespace which can serialize API bundle classes.
*/
public static final KryoNamespace API = KryoNamespace.newBuilder()
.nextId(KryoNamespace.INITIAL_ID)
.register(BASIC)
.nextId(KryoNamespace.INITIAL_ID + 30)
.register(MISC)
.nextId(KryoNamespace.INITIAL_ID + 30 + 10)
.register(
Version.class,
ControllerNode.State.class,
ApplicationState.class,
DefaultApplication.class,
Device.Type.class,
Port.Type.class,
ChassisId.class,
DefaultAnnotations.class,
DefaultControllerNode.class,
DefaultDevice.class,
DefaultDeviceDescription.class,
DefaultLinkDescription.class,
Port.class,
DefaultPortDescription.class,
Element.class,
Link.Type.class,
Link.State.class,
Timestamp.class,
Leadership.class,
LeadershipEvent.class,
LeadershipEvent.Type.class,
HostId.class,
HostDescription.class,
DefaultHostDescription.class,
DefaultFlowEntry.class,
StoredFlowEntry.class,
FlowRule.Type.class,
DefaultFlowRule.class,
DefaultFlowEntry.class,
DefaultPacketRequest.class,
PacketPriority.class,
FlowEntry.FlowEntryState.class,
FlowId.class,
DefaultTrafficSelector.class,
PortCriterion.class,
MetadataCriterion.class,
EthCriterion.class,
EthTypeCriterion.class,
VlanIdCriterion.class,
VlanPcpCriterion.class,
IPDscpCriterion.class,
IPEcnCriterion.class,
IPProtocolCriterion.class,
IPCriterion.class,
TcpPortCriterion.class,
UdpPortCriterion.class,
SctpPortCriterion.class,
IcmpTypeCriterion.class,
IcmpCodeCriterion.class,
IPv6FlowLabelCriterion.class,
Icmpv6TypeCriterion.class,
Icmpv6CodeCriterion.class,
IPv6NDTargetAddressCriterion.class,
IPv6NDLinkLayerAddressCriterion.class,
MplsCriterion.class,
IPv6ExthdrFlagsCriterion.class,
LambdaCriterion.class,
IndexedLambdaCriterion.class,
OchSignalCriterion.class,
OchSignalTypeCriterion.class,
OpticalSignalTypeCriterion.class,
Criterion.class,
Criterion.Type.class,
DefaultTrafficTreatment.class,
Instructions.DropInstruction.class,
Instructions.OutputInstruction.class,
Instructions.GroupInstruction.class,
L0ModificationInstruction.class,
L0ModificationInstruction.L0SubType.class,
L0ModificationInstruction.ModLambdaInstruction.class,
L0ModificationInstruction.ModOchSignalInstruction.class,
L2ModificationInstruction.class,
L2ModificationInstruction.L2SubType.class,
L2ModificationInstruction.ModEtherInstruction.class,
L2ModificationInstruction.PushHeaderInstructions.class,
L2ModificationInstruction.ModVlanIdInstruction.class,
L2ModificationInstruction.ModVlanPcpInstruction.class,
L2ModificationInstruction.ModMplsLabelInstruction.class,
L2ModificationInstruction.ModMplsTtlInstruction.class,
L3ModificationInstruction.class,
L3ModificationInstruction.L3SubType.class,
L3ModificationInstruction.ModIPInstruction.class,
L3ModificationInstruction.ModIPv6FlowLabelInstruction.class,
L3ModificationInstruction.ModTtlInstruction.class,
RoleInfo.class,
FlowRuleBatchEvent.class,
FlowRuleBatchEvent.Type.class,
FlowRuleBatchRequest.class,
FlowRuleBatchOperation.class,
CompletedBatchOperation.class,
FlowRuleBatchEntry.class,
FlowRuleBatchEntry.FlowRuleOperation.class,
IntentId.class,
IntentState.class,
//Key.class, is abstract
Key.of(1L, new DefaultApplicationId(0, "bar")).getClass(), //LongKey.class
Key.of("foo", new DefaultApplicationId(0, "bar")).getClass(), //StringKey.class
Intent.class,
ConnectivityIntent.class,
PathIntent.class,
DefaultPath.class,
DefaultEdgeLink.class,
HostToHostIntent.class,
PointToPointIntent.class,
MultiPointToSinglePointIntent.class,
SinglePointToMultiPointIntent.class,
FlowRuleIntent.class,
LinkCollectionIntent.class,
OpticalConnectivityIntent.class,
OpticalPathIntent.class,
LinkResourceRequest.class,
DefaultLinkResourceRequest.class,
BandwidthResourceRequest.class,
LambdaResourceRequest.class,
LambdaResource.class,
BandwidthResource.class,
DefaultLinkResourceAllocations.class,
BandwidthResourceAllocation.class,
LambdaResourceAllocation.class,
// Constraints
LambdaConstraint.class,
BandwidthConstraint.class,
LinkTypeConstraint.class,
LatencyConstraint.class,
WaypointConstraint.class,
ObstacleConstraint.class,
AnnotationConstraint.class,
BooleanConstraint.class,
IntentOperation.class,
FlowRuleExtPayLoad.class,
Frequency.class,
DefaultAnnotations.class
)
.register(new DefaultApplicationIdSerializer(), DefaultApplicationId.class)
.register(new URISerializer(), URI.class)
.register(new NodeIdSerializer(), NodeId.class)
.register(new ProviderIdSerializer(), ProviderId.class)
.register(new DeviceIdSerializer(), DeviceId.class)
.register(new PortNumberSerializer(), PortNumber.class)
.register(new DefaultPortSerializer(), DefaultPort.class)
.register(new LinkKeySerializer(), LinkKey.class)
.register(new ConnectPointSerializer(), ConnectPoint.class)
.register(new DefaultLinkSerializer(), DefaultLink.class)
.register(new MastershipTermSerializer(), MastershipTerm.class)
.register(new HostLocationSerializer(), HostLocation.class)
.register(new DefaultOutboundPacketSerializer(), DefaultOutboundPacket.class)
.register(Versioned.class)
.register(DefaultGroupId.class)
.register(Annotations.class)
.register(OmsPort.class)
.register(OchPort.class)
.register(OduSignalType.class)
.register(GridType.class)
.register(ChannelSpacing.class)
.register(OduCltPort.class)
.register(OduCltPort.SignalType.class)
.register(IndexedLambda.class)
.register(OchSignal.class)
.register(OduCltPortDescription.class)
.register(OchPortDescription.class)
.register(OmsPortDescription.class)
.register(
MplsIntent.class,
MplsPathIntent.class,
MplsLabelResourceAllocation.class,
MplsLabelResourceRequest.class,
MplsLabel.class,
org.onlab.packet.MplsLabel.class,
org.onlab.packet.MPLS.class
)
.build();
// not to be instantiated
private KryoNamespaces() {}
}
| core/store/serializers/src/main/java/org/onosproject/store/serializers/KryoNamespaces.java | /*
* Copyright 2014-2015 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.store.serializers;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import org.onlab.packet.ChassisId;
import org.onlab.packet.Ip4Address;
import org.onlab.packet.Ip4Prefix;
import org.onlab.packet.Ip6Address;
import org.onlab.packet.Ip6Prefix;
import org.onlab.packet.IpAddress;
import org.onlab.packet.IpPrefix;
import org.onlab.packet.MacAddress;
import org.onlab.packet.VlanId;
import org.onlab.util.Bandwidth;
import org.onlab.util.Frequency;
import org.onlab.util.KryoNamespace;
import org.onosproject.app.ApplicationState;
import org.onosproject.cluster.ControllerNode;
import org.onosproject.cluster.DefaultControllerNode;
import org.onosproject.cluster.Leadership;
import org.onosproject.cluster.LeadershipEvent;
import org.onosproject.cluster.NodeId;
import org.onosproject.cluster.RoleInfo;
import org.onosproject.core.DefaultApplication;
import org.onosproject.core.DefaultApplicationId;
import org.onosproject.core.DefaultGroupId;
import org.onosproject.core.Version;
import org.onosproject.mastership.MastershipTerm;
import org.onosproject.net.Annotations;
import org.onosproject.net.ChannelSpacing;
import org.onosproject.net.ConnectPoint;
import org.onosproject.net.DefaultAnnotations;
import org.onosproject.net.DefaultDevice;
import org.onosproject.net.DefaultEdgeLink;
import org.onosproject.net.DefaultLink;
import org.onosproject.net.DefaultPath;
import org.onosproject.net.DefaultPort;
import org.onosproject.net.Device;
import org.onosproject.net.DeviceId;
import org.onosproject.net.Element;
import org.onosproject.net.GridType;
import org.onosproject.net.HostId;
import org.onosproject.net.HostLocation;
import org.onosproject.net.IndexedLambda;
import org.onosproject.net.Link;
import org.onosproject.net.LinkKey;
import org.onosproject.net.OchPort;
import org.onosproject.net.OchSignal;
import org.onosproject.net.OduCltPort;
import org.onosproject.net.OduSignalType;
import org.onosproject.net.OmsPort;
import org.onosproject.net.Port;
import org.onosproject.net.PortNumber;
import org.onosproject.net.device.DefaultDeviceDescription;
import org.onosproject.net.device.DefaultPortDescription;
import org.onosproject.net.flow.CompletedBatchOperation;
import org.onosproject.net.flow.DefaultFlowEntry;
import org.onosproject.net.flow.DefaultFlowRule;
import org.onosproject.net.flow.DefaultTrafficSelector;
import org.onosproject.net.flow.DefaultTrafficTreatment;
import org.onosproject.net.flow.FlowEntry;
import org.onosproject.net.flow.FlowId;
import org.onosproject.net.flow.FlowRule;
import org.onosproject.net.flow.FlowRuleBatchEntry;
import org.onosproject.net.flow.FlowRuleBatchEvent;
import org.onosproject.net.flow.FlowRuleBatchOperation;
import org.onosproject.net.flow.FlowRuleBatchRequest;
import org.onosproject.net.flow.FlowRuleExtPayLoad;
import org.onosproject.net.flow.StoredFlowEntry;
import org.onosproject.net.flow.criteria.Criterion;
import org.onosproject.net.flow.criteria.EthCriterion;
import org.onosproject.net.flow.criteria.EthTypeCriterion;
import org.onosproject.net.flow.criteria.IPCriterion;
import org.onosproject.net.flow.criteria.IPDscpCriterion;
import org.onosproject.net.flow.criteria.IPEcnCriterion;
import org.onosproject.net.flow.criteria.IPProtocolCriterion;
import org.onosproject.net.flow.criteria.IPv6ExthdrFlagsCriterion;
import org.onosproject.net.flow.criteria.IPv6FlowLabelCriterion;
import org.onosproject.net.flow.criteria.IPv6NDLinkLayerAddressCriterion;
import org.onosproject.net.flow.criteria.IPv6NDTargetAddressCriterion;
import org.onosproject.net.flow.criteria.IcmpCodeCriterion;
import org.onosproject.net.flow.criteria.IcmpTypeCriterion;
import org.onosproject.net.flow.criteria.Icmpv6CodeCriterion;
import org.onosproject.net.flow.criteria.Icmpv6TypeCriterion;
import org.onosproject.net.flow.criteria.IndexedLambdaCriterion;
import org.onosproject.net.flow.criteria.LambdaCriterion;
import org.onosproject.net.flow.criteria.MetadataCriterion;
import org.onosproject.net.flow.criteria.MplsCriterion;
import org.onosproject.net.flow.criteria.OchSignalCriterion;
import org.onosproject.net.flow.criteria.OchSignalTypeCriterion;
import org.onosproject.net.flow.criteria.OpticalSignalTypeCriterion;
import org.onosproject.net.flow.criteria.PortCriterion;
import org.onosproject.net.flow.criteria.SctpPortCriterion;
import org.onosproject.net.flow.criteria.TcpPortCriterion;
import org.onosproject.net.flow.criteria.UdpPortCriterion;
import org.onosproject.net.flow.criteria.VlanIdCriterion;
import org.onosproject.net.flow.criteria.VlanPcpCriterion;
import org.onosproject.net.flow.instructions.Instructions;
import org.onosproject.net.flow.instructions.L0ModificationInstruction;
import org.onosproject.net.flow.instructions.L2ModificationInstruction;
import org.onosproject.net.flow.instructions.L3ModificationInstruction;
import org.onosproject.net.host.DefaultHostDescription;
import org.onosproject.net.host.HostDescription;
import org.onosproject.net.intent.ConnectivityIntent;
import org.onosproject.net.intent.FlowRuleIntent;
import org.onosproject.net.intent.HostToHostIntent;
import org.onosproject.net.intent.Intent;
import org.onosproject.net.intent.IntentId;
import org.onosproject.net.intent.IntentOperation;
import org.onosproject.net.intent.IntentState;
import org.onosproject.net.intent.Key;
import org.onosproject.net.intent.LinkCollectionIntent;
import org.onosproject.net.intent.MplsIntent;
import org.onosproject.net.intent.MplsPathIntent;
import org.onosproject.net.intent.MultiPointToSinglePointIntent;
import org.onosproject.net.intent.OpticalConnectivityIntent;
import org.onosproject.net.intent.OpticalPathIntent;
import org.onosproject.net.intent.PathIntent;
import org.onosproject.net.intent.PointToPointIntent;
import org.onosproject.net.intent.SinglePointToMultiPointIntent;
import org.onosproject.net.intent.constraint.AnnotationConstraint;
import org.onosproject.net.intent.constraint.BandwidthConstraint;
import org.onosproject.net.intent.constraint.BooleanConstraint;
import org.onosproject.net.intent.constraint.LambdaConstraint;
import org.onosproject.net.intent.constraint.LatencyConstraint;
import org.onosproject.net.intent.constraint.LinkTypeConstraint;
import org.onosproject.net.intent.constraint.ObstacleConstraint;
import org.onosproject.net.intent.constraint.WaypointConstraint;
import org.onosproject.net.link.DefaultLinkDescription;
import org.onosproject.net.packet.DefaultOutboundPacket;
import org.onosproject.net.packet.DefaultPacketRequest;
import org.onosproject.net.packet.PacketPriority;
import org.onosproject.net.provider.ProviderId;
import org.onosproject.net.resource.BandwidthResource;
import org.onosproject.net.resource.BandwidthResourceAllocation;
import org.onosproject.net.resource.BandwidthResourceRequest;
import org.onosproject.net.resource.DefaultLinkResourceAllocations;
import org.onosproject.net.resource.DefaultLinkResourceRequest;
import org.onosproject.net.resource.LambdaResource;
import org.onosproject.net.resource.LambdaResourceAllocation;
import org.onosproject.net.resource.LambdaResourceRequest;
import org.onosproject.net.resource.LinkResourceRequest;
import org.onosproject.net.resource.MplsLabel;
import org.onosproject.net.resource.MplsLabelResourceAllocation;
import org.onosproject.net.resource.MplsLabelResourceRequest;
import org.onosproject.store.Timestamp;
import org.onosproject.store.service.Versioned;
import java.net.URI;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
public final class KryoNamespaces {
public static final KryoNamespace BASIC = KryoNamespace.newBuilder()
.nextId(KryoNamespace.FLOATING_ID)
.register(byte[].class)
.register(new ImmutableListSerializer(),
ImmutableList.class,
ImmutableList.of(1).getClass(),
ImmutableList.of(1, 2).getClass())
.register(new ImmutableSetSerializer(),
ImmutableSet.class,
ImmutableSet.of().getClass(),
ImmutableSet.of(1).getClass(),
ImmutableSet.of(1, 2).getClass())
.register(new ImmutableMapSerializer(),
ImmutableMap.class,
ImmutableMap.of().getClass(),
ImmutableMap.of("a", 1).getClass(),
ImmutableMap.of("R", 2, "D", 2).getClass())
.register(HashMap.class)
.register(ConcurrentHashMap.class)
.register(CopyOnWriteArraySet.class)
.register(ArrayList.class,
LinkedList.class,
HashSet.class
)
.register(new ArraysAsListSerializer(), Arrays.asList().getClass())
.register(Collections.singletonList(1).getClass())
.register(Duration.class)
.register(Collections.emptySet().getClass())
.register(Optional.class)
.register(Collections.emptyList().getClass())
.register(Collections.unmodifiableSet(Collections.emptySet()).getClass())
.build();
/**
* KryoNamespace which can serialize ON.lab misc classes.
*/
public static final KryoNamespace MISC = KryoNamespace.newBuilder()
.nextId(KryoNamespace.FLOATING_ID)
.register(new IpPrefixSerializer(), IpPrefix.class)
.register(new Ip4PrefixSerializer(), Ip4Prefix.class)
.register(new Ip6PrefixSerializer(), Ip6Prefix.class)
.register(new IpAddressSerializer(), IpAddress.class)
.register(new Ip4AddressSerializer(), Ip4Address.class)
.register(new Ip6AddressSerializer(), Ip6Address.class)
.register(new MacAddressSerializer(), MacAddress.class)
.register(VlanId.class)
.register(Frequency.class)
.register(Bandwidth.class)
.build();
/**
* Kryo registration Id for user custom registration.
*/
public static final int BEGIN_USER_CUSTOM_ID = 300;
// TODO: Populate other classes
/**
* KryoNamespace which can serialize API bundle classes.
*/
public static final KryoNamespace API = KryoNamespace.newBuilder()
.nextId(KryoNamespace.INITIAL_ID)
.register(BASIC)
.nextId(KryoNamespace.INITIAL_ID + 30)
.register(MISC)
.nextId(KryoNamespace.INITIAL_ID + 30 + 10)
.register(
Version.class,
ControllerNode.State.class,
ApplicationState.class,
DefaultApplication.class,
Device.Type.class,
Port.Type.class,
ChassisId.class,
DefaultAnnotations.class,
DefaultControllerNode.class,
DefaultDevice.class,
DefaultDeviceDescription.class,
DefaultLinkDescription.class,
Port.class,
DefaultPortDescription.class,
Element.class,
Link.Type.class,
Link.State.class,
Timestamp.class,
Leadership.class,
LeadershipEvent.class,
LeadershipEvent.Type.class,
HostId.class,
HostDescription.class,
DefaultHostDescription.class,
DefaultFlowEntry.class,
StoredFlowEntry.class,
FlowRule.Type.class,
DefaultFlowRule.class,
DefaultFlowEntry.class,
DefaultPacketRequest.class,
PacketPriority.class,
FlowEntry.FlowEntryState.class,
FlowId.class,
DefaultTrafficSelector.class,
PortCriterion.class,
MetadataCriterion.class,
EthCriterion.class,
EthTypeCriterion.class,
VlanIdCriterion.class,
VlanPcpCriterion.class,
IPDscpCriterion.class,
IPEcnCriterion.class,
IPProtocolCriterion.class,
IPCriterion.class,
TcpPortCriterion.class,
UdpPortCriterion.class,
SctpPortCriterion.class,
IcmpTypeCriterion.class,
IcmpCodeCriterion.class,
IPv6FlowLabelCriterion.class,
Icmpv6TypeCriterion.class,
Icmpv6CodeCriterion.class,
IPv6NDTargetAddressCriterion.class,
IPv6NDLinkLayerAddressCriterion.class,
MplsCriterion.class,
IPv6ExthdrFlagsCriterion.class,
LambdaCriterion.class,
IndexedLambdaCriterion.class,
OchSignalCriterion.class,
OchSignalTypeCriterion.class,
OpticalSignalTypeCriterion.class,
Criterion.class,
Criterion.Type.class,
DefaultTrafficTreatment.class,
Instructions.DropInstruction.class,
Instructions.OutputInstruction.class,
Instructions.GroupInstruction.class,
L0ModificationInstruction.class,
L0ModificationInstruction.L0SubType.class,
L0ModificationInstruction.ModLambdaInstruction.class,
L0ModificationInstruction.ModOchSignalInstruction.class,
L2ModificationInstruction.class,
L2ModificationInstruction.L2SubType.class,
L2ModificationInstruction.ModEtherInstruction.class,
L2ModificationInstruction.PushHeaderInstructions.class,
L2ModificationInstruction.ModVlanIdInstruction.class,
L2ModificationInstruction.ModVlanPcpInstruction.class,
L2ModificationInstruction.ModMplsLabelInstruction.class,
L2ModificationInstruction.ModMplsTtlInstruction.class,
L3ModificationInstruction.class,
L3ModificationInstruction.L3SubType.class,
L3ModificationInstruction.ModIPInstruction.class,
L3ModificationInstruction.ModIPv6FlowLabelInstruction.class,
L3ModificationInstruction.ModTtlInstruction.class,
RoleInfo.class,
FlowRuleBatchEvent.class,
FlowRuleBatchEvent.Type.class,
FlowRuleBatchRequest.class,
FlowRuleBatchOperation.class,
CompletedBatchOperation.class,
FlowRuleBatchEntry.class,
FlowRuleBatchEntry.FlowRuleOperation.class,
IntentId.class,
IntentState.class,
//Key.class, is abstract
Key.of(1L, new DefaultApplicationId(0, "bar")).getClass(), //LongKey.class
Key.of("foo", new DefaultApplicationId(0, "bar")).getClass(), //StringKey.class
Intent.class,
ConnectivityIntent.class,
PathIntent.class,
DefaultPath.class,
DefaultEdgeLink.class,
HostToHostIntent.class,
PointToPointIntent.class,
MultiPointToSinglePointIntent.class,
SinglePointToMultiPointIntent.class,
FlowRuleIntent.class,
LinkCollectionIntent.class,
OpticalConnectivityIntent.class,
OpticalPathIntent.class,
LinkResourceRequest.class,
DefaultLinkResourceRequest.class,
BandwidthResourceRequest.class,
LambdaResourceRequest.class,
LambdaResource.class,
BandwidthResource.class,
DefaultLinkResourceAllocations.class,
BandwidthResourceAllocation.class,
LambdaResourceAllocation.class,
// Constraints
LambdaConstraint.class,
BandwidthConstraint.class,
LinkTypeConstraint.class,
LatencyConstraint.class,
WaypointConstraint.class,
ObstacleConstraint.class,
AnnotationConstraint.class,
BooleanConstraint.class,
IntentOperation.class,
FlowRuleExtPayLoad.class,
Frequency.class,
DefaultAnnotations.class
)
.register(new DefaultApplicationIdSerializer(), DefaultApplicationId.class)
.register(new URISerializer(), URI.class)
.register(new NodeIdSerializer(), NodeId.class)
.register(new ProviderIdSerializer(), ProviderId.class)
.register(new DeviceIdSerializer(), DeviceId.class)
.register(new PortNumberSerializer(), PortNumber.class)
.register(new DefaultPortSerializer(), DefaultPort.class)
.register(new LinkKeySerializer(), LinkKey.class)
.register(new ConnectPointSerializer(), ConnectPoint.class)
.register(new DefaultLinkSerializer(), DefaultLink.class)
.register(new MastershipTermSerializer(), MastershipTerm.class)
.register(new HostLocationSerializer(), HostLocation.class)
.register(new DefaultOutboundPacketSerializer(), DefaultOutboundPacket.class)
.register(Versioned.class)
.register(DefaultGroupId.class)
.register(Annotations.class)
.register(OmsPort.class)
.register(OchPort.class)
.register(OduSignalType.class)
.register(GridType.class)
.register(ChannelSpacing.class)
.register(OduCltPort.class)
.register(OduCltPort.SignalType.class)
.register(IndexedLambda.class)
.register(OchSignal.class)
.register(
MplsIntent.class,
MplsPathIntent.class,
MplsLabelResourceAllocation.class,
MplsLabelResourceRequest.class,
MplsLabel.class,
org.onlab.packet.MplsLabel.class,
org.onlab.packet.MPLS.class
)
.build();
// not to be instantiated
private KryoNamespaces() {}
}
| Fix exception for optical port descriptions (ONOS-1908)
Change-Id: I8868bf3c9c36bb731171cd64623d0f86a56f1299
| core/store/serializers/src/main/java/org/onosproject/store/serializers/KryoNamespaces.java | Fix exception for optical port descriptions (ONOS-1908) | <ide><path>ore/store/serializers/src/main/java/org/onosproject/store/serializers/KryoNamespaces.java
<ide> import org.onosproject.net.PortNumber;
<ide> import org.onosproject.net.device.DefaultDeviceDescription;
<ide> import org.onosproject.net.device.DefaultPortDescription;
<add>import org.onosproject.net.device.OchPortDescription;
<add>import org.onosproject.net.device.OduCltPortDescription;
<add>import org.onosproject.net.device.OmsPortDescription;
<ide> import org.onosproject.net.flow.CompletedBatchOperation;
<ide> import org.onosproject.net.flow.DefaultFlowEntry;
<ide> import org.onosproject.net.flow.DefaultFlowRule;
<ide> .register(OduCltPort.SignalType.class)
<ide> .register(IndexedLambda.class)
<ide> .register(OchSignal.class)
<add> .register(OduCltPortDescription.class)
<add> .register(OchPortDescription.class)
<add> .register(OmsPortDescription.class)
<ide> .register(
<ide> MplsIntent.class,
<ide> MplsPathIntent.class, |
|
Java | apache-2.0 | b6993341ac565638fcd6d29865ab68fed617f4f2 | 0 | shaoshao613/mixpanel-android,Flutterbee/mixpanel-android,danmcknight/mixpanel-android,shaoshao613/mixpanel-android,mixpanel/mixpanel-android,engvik/mixpanel-android,zumper/mixpanel-android,erpragatisingh/mixpanel-android,LLin233/mixpanel-android,danmcknight/mixpanel-android,omadahealth/mixpanel-android,engvik/mixpanel-android,omadahealth/mixpanel-android,danmcknight/mixpanel-android,zumper/mixpanel-android,Aloomaio/androidsdk,zumper/mixpanel-android,mixpanel/mixpanel-android,palaniyappanBala/mixpanel-android,kevinmost/mixpanel-android,pLucky-Inc/logbk-android,LLin233/mixpanel-android,dreamseekerkun/mixpanel-android,dreamseekerkun/mixpanel-android,shaoshao613/mixpanel-android,pLucky-Inc/logbk-android,erpragatisingh/mixpanel-android,kevinmost/mixpanel-android,Sellegit/mixpanel-android,palaniyappanBala/mixpanel-android,engvik/mixpanel-android,matteoburgassi/mixpanel-fork,kevinmost/mixpanel-android,LLin233/mixpanel-android,palaniyappanBala/mixpanel-android,mixpanel/mixpanel-android,Sellegit/mixpanel-android,erpragatisingh/mixpanel-android,omadahealth/mixpanel-android,dreamseekerkun/mixpanel-android | package com.mixpanel.android.mpmetrics;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Application;
import android.app.FragmentTransaction;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Build;
import android.util.Log;
import com.mixpanel.android.R;
import com.mixpanel.android.surveys.SurveyActivity;
import com.mixpanel.android.util.ActivityImageUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.locks.ReentrantLock;
/**
* Core class for interacting with Mixpanel Analytics.
*
* <p>Call {@link #getInstance(Context, String)} with
* your main application activity and your Mixpanel API token as arguments
* an to get an instance you can use to report how users are using your
* application.
*
* <p>Once you have an instance, you can send events to Mixpanel
* using {@link #track(String, JSONObject)}, and update People Analytics
* records with {@link #getPeople()}
*
* <p>The Mixpanel library will periodically send information to
* Mixpanel servers, so your application will need to have
* <tt>android.permission.INTERNET</tt>. In addition, to preserve
* battery life, messages to Mixpanel servers may not be sent immediately
* when you call <tt>track</tt> or {@link People#set(String, Object)}.
* The library will send messages periodically throughout the lifetime
* of your application, but you will need to call {@link #flush()}
* before your application is completely shutdown to ensure all of your
* events are sent.
*
* <p>A typical use-case for the library might look like this:
*
* <pre>
* {@code
* public class MainActivity extends Activity {
* MixpanelAPI mMixpanel;
*
* public void onCreate(Bundle saved) {
* mMixpanel = MixpanelAPI.getInstance(this, "YOUR MIXPANEL API TOKEN");
* ...
* }
*
* public void whenSomethingInterestingHappens(int flavor) {
* JSONObject properties = new JSONObject();
* properties.put("flavor", flavor);
* mMixpanel.track("Something Interesting Happened", properties);
* ...
* }
*
* public void onDestroy() {
* mMixpanel.flush();
* super.onDestroy();
* }
* }
* }
* </pre>
*
* <p>In addition to this documentation, you may wish to take a look at
* <a href="https://github.com/mixpanel/sample-android-mixpanel-integration">the Mixpanel sample Android application</a>.
* It demonstrates a variety of techniques, including
* updating People Analytics records with {@link People} and registering for
* and receiving push notifications with {@link People#initPushHandling(String)}.
*
* <p>There are also <a href="https://mixpanel.com/docs/">step-by-step getting started documents</a>
* available at mixpanel.com
*
* @see <a href="https://mixpanel.com/docs/integration-libraries/android">getting started documentation for tracking events</a>
* @see <a href="https://mixpanel.com/docs/people-analytics/android">getting started documentation for People Analytics</a>
* @see <a href="https://mixpanel.com/docs/people-analytics/android-push">getting started with push notifications for Android</a>
* @see <a href="https://github.com/mixpanel/sample-android-mixpanel-integration">The Mixpanel Android sample application</a>
*/
public class MixpanelAPI {
/**
* String version of the library.
*/
public static final String VERSION = MPConfig.VERSION;
/**
* You shouldn't instantiate MixpanelAPI objects directly.
* Use MixpanelAPI.getInstance to get an instance.
*/
MixpanelAPI(Context context, Future<SharedPreferences> referrerPreferences, String token) {
mContext = context;
mToken = token;
mPeople = new PeopleImpl();
mMessages = getAnalyticsMessages();
mConfig = getConfig();
mPersistentIdentity = getPersistentIdentity(context, referrerPreferences, token);
mUpdatesListener = new UpdatesListener();
mDecideUpdates = null;
// TODO this immediately forces the lazy load of the preferences, and defeats the
// purpose of PersistentIdentity's laziness.
final String peopleId = mPersistentIdentity.getPeopleDistinctId();
if (null != peopleId) {
mDecideUpdates = constructDecideUpdates(token, peopleId, mUpdatesListener);
}
registerMixpanelActivityLifecycleCallbacks();
if (null != mDecideUpdates) {
mMessages.installDecideCheck(mDecideUpdates);
}
}
/**
* Get the instance of MixpanelAPI associated with your Mixpanel project token.
*
* <p>Use getInstance to get a reference to a shared
* instance of MixpanelAPI you can use to send events
* and People Analytics updates to Mixpanel.</p>
* <p>getInstance is thread safe, but the returned instance is not,
* and may be shared with other callers of getInstance.
* The best practice is to call getInstance, and use the returned MixpanelAPI,
* object from a single thread (probably the main UI thread of your application).</p>
* <p>If you do choose to track events from multiple threads in your application,
* you should synchronize your calls on the instance itself, like so:</p>
* <pre>
* {@code
* MixpanelAPI instance = MixpanelAPI.getInstance(context, token);
* synchronized(instance) { // Only necessary if the instance will be used in multiple threads.
* instance.track(...)
* }
* }
* </pre>
*
* @param context The application context you are tracking
* @param token Your Mixpanel project token. You can get your project token on the Mixpanel web site,
* in the settings dialog.
* @return an instance of MixpanelAPI associated with your project
*/
public static MixpanelAPI getInstance(Context context, String token) {
if (null == token || null == context) {
return null;
}
synchronized (sInstanceMap) {
final Context appContext = context.getApplicationContext();
if (null == sReferrerPrefs) {
sReferrerPrefs = sPrefsLoader.loadPreferences(context, MPConfig.REFERRER_PREFS_NAME, null);
}
Map <Context, MixpanelAPI> instances = sInstanceMap.get(token);
if (null == instances) {
instances = new HashMap<Context, MixpanelAPI>();
sInstanceMap.put(token, instances);
}
MixpanelAPI instance = instances.get(appContext);
if (null == instance) {
instance = new MixpanelAPI(appContext, sReferrerPrefs, token);
instances.put(appContext, instance);
}
return instance;
}
}
/**
* Sets the target frequency of messages to Mixpanel servers.
* If no calls to {@link #flush()} are made, the Mixpanel
* library attempts to send tracking information in batches at a rate
* that provides a reasonable compromise between battery life and liveness of data.
* Callers can override this value, for the whole application, by calling
* <tt>setFlushInterval</tt>.
*
* If milliseconds is negative, Mixpanel will never flush the data automatically,
* and require callers to call {@link #flush()} to send data. This can have
* implications for storage and is not appropriate for most situations.
*
* @param context the execution context associated with this application, probably
* the main application activity.
* @param milliseconds the target number of milliseconds between automatic flushes.
* this value is advisory, actual flushes may be more or less frequent
* @deprecated in 4.0.0, use com.mixpanel.android.MPConfig.FlushInterval application metadata instead
*/
@Deprecated
public static void setFlushInterval(Context context, long milliseconds) {
Log.i(
LOGTAG,
"MixpanelAPI.setFlushInterval is deprecated.\n" +
" To set a custom Mixpanel flush interval for your application, add\n" +
" <meta-data android:name=\"com.mixpanel.android.MPConfig.FlushInterval\" android:value=\"YOUR_INTERVAL\" />\n" +
" to the <application> section of your AndroidManifest.xml."
);
final AnalyticsMessages msgs = AnalyticsMessages.getInstance(context);
msgs.setFlushInterval(milliseconds);
}
/**
* By default, if the MixpanelAPI cannot contact the API server over HTTPS,
* it will attempt to contact the server via regular HTTP. To disable this
* behavior, call enableFallbackServer(context, false)
*
* @param context the execution context associated with this context.
* @param enableIfTrue if true, the library will fall back to using http
* when https is unavailable.
* @deprecated in 4.0.0, use com.mixpanel.android.MPConfig.EventsFallbackEndpoint, com.mixpanel.android.MPConfig.PeopleFallbackEndpoint, or com.mixpanel.android.MPConfig.DecideFallbackEndpoint instead
*/
@Deprecated
public static void enableFallbackServer(Context context, boolean enableIfTrue) {
Log.i(
LOGTAG,
"MixpanelAPI.enableFallbackServer is deprecated.\n" +
" To enable fallback in your application, add\n" +
" <meta-data android:name=\"com.mixpanel.android.MPConfig.DisableFallback\" android:value=\"false\" />\n" +
" to the <application> section of your AndroidManifest.xml."
);
final AnalyticsMessages msgs = AnalyticsMessages.getInstance(context);
msgs.setDisableFallback(! enableIfTrue);
}
/**
* This function creates a distinct_id alias from alias to original. If original is null, then it will create an alias
* to the current events distinct_id, which may be the distinct_id randomly generated by the Mixpanel library
* before {@link #identify(String)} is called.
*
* <p>This call does not identify the user after. You must still call both {@link #identify(String)} and
* {@link People#identify(String)} if you wish the new alias to be used for Events and People.
*
* @param alias the new distinct_id that should represent original.
* @param original the old distinct_id that alias will be mapped to.
*/
public void alias(String alias, String original) {
if (original == null) {
original = getDistinctId();
}
if (alias.equals(original)) {
Log.w(LOGTAG, "Attempted to alias identical distinct_ids " + alias + ", returning.");
return;
}
try {
JSONObject j = new JSONObject();
j.put("alias", alias);
j.put("original", original);
track("$create_alias", j);
} catch (JSONException e) {
Log.e(LOGTAG, "Failed to alias", e);
}
flush();
}
/**
* Associate all future calls to {@link #track(String, JSONObject)} with the user identified by
* the given distinct id.
*
* <p>This call does not identify the user for People Analytics;
* to do that, see {@link People#identify(String)}. Mixpanel recommends using
* the same distinct_id for both calls, and using a distinct_id that is easy
* to associate with the given user, for example, a server-side account identifier.
*
* <p>Calls to {@link #track(String, JSONObject)} made before corresponding calls to
* identify will use an internally generated distinct id, which means it is best
* to call identify early to ensure that your Mixpanel funnels and retention
* analytics can continue to track the user throughout their lifetime. We recommend
* calling identify as early as you can.
*
* <p>Once identify is called, the given distinct id persists across restarts of your
* application.
*
* @param distinctId a string uniquely identifying this user. Events sent to
* Mixpanel using the same disinct_id will be considered associated with the
* same visitor/customer for retention and funnel reporting, so be sure that the given
* value is globally unique for each individual user you intend to track.
*
* @see People#identify(String)
*/
public void identify(String distinctId) {
mPersistentIdentity.setEventsDistinctId(distinctId);
}
/**
* Track an event.
*
* <p>Every call to track eventually results in a data point sent to Mixpanel. These data points
* are what are measured, counted, and broken down to create your Mixpanel reports. Events
* have a string name, and an optional set of name/value pairs that describe the properties of
* that event.
*
* @param eventName The name of the event to send
* @param properties A JSONObject containing the key value pairs of the properties to include in this event.
* Pass null if no extra properties exist.
*/
// DO NOT DOCUMENT, but track() must be thread safe since it is used to track events in
// notifications from the UI thread, which might not be our MixpanelAPI "home" thread.
// This MAY CHANGE IN FUTURE RELEASES, so minimize code that assumes thread safety
// (and perhaps document that code here).
public void track(String eventName, JSONObject properties) {
try {
final JSONObject messageProps = new JSONObject();
final Map<String, String> referrerProperties = mPersistentIdentity.getReferrerProperties();
for (final Map.Entry<String, String> entry:referrerProperties.entrySet()) {
final String key = entry.getKey();
final String value = entry.getValue();
messageProps.put(key, value);
}
final JSONObject superProperties = mPersistentIdentity.getSuperProperties();
final Iterator<?> superIter = superProperties.keys();
while (superIter.hasNext()) {
final String key = (String) superIter.next();
messageProps.put(key, superProperties.get(key));
}
// Don't allow super properties or referral properties to override these fields,
// but DO allow the caller to override them in their given properties.
final long time = System.currentTimeMillis() / 1000;
messageProps.put("time", time);
messageProps.put("distinct_id", getDistinctId());
if (null != properties) {
final Iterator<?> propIter = properties.keys();
while (propIter.hasNext()) {
final String key = (String) propIter.next();
messageProps.put(key, properties.get(key));
}
}
final AnalyticsMessages.EventDescription eventDescription =
new AnalyticsMessages.EventDescription(eventName, messageProps, mToken);
mMessages.eventsMessage(eventDescription);
} catch (final JSONException e) {
Log.e(LOGTAG, "Exception tracking event " + eventName, e);
}
}
/**
* Push all queued Mixpanel events and People Analytics changes to Mixpanel servers.
*
* <p>Events and People messages are pushed gradually throughout
* the lifetime of your application. This means that to ensure that all messages
* are sent to Mixpanel when your application is shut down, you will
* need to call flush() to let the Mixpanel library know it should
* send all remaining messages to the server. We strongly recommend
* placing a call to flush() in the onDestroy() method of
* your main application activity.
*/
public void flush() {
mMessages.postToServer();
}
/**
* Returns the string id currently being used to uniquely identify the user associated
* with events sent using {@link #track(String, JSONObject)}. Before any calls to
* {@link #identify(String)}, this will be an id automatically generated by the library.
*
* <p>The id returned by getDistinctId is independent of the distinct id used to identify
* any People Analytics properties in Mixpanel. To read and write that identifier,
* use {@link People#identify(String)} and {@link People#getDistinctId()}.
*
* @return The distinct id associated with event tracking
*
* @see #identify(String)
* @see People#getDistinctId()
*/
public String getDistinctId() {
return mPersistentIdentity.getEventsDistinctId();
}
/**
* Register properties that will be sent with every subsequent call to {@link #track(String, JSONObject)}.
*
* <p>SuperProperties are a collection of properties that will be sent with every event to Mixpanel,
* and persist beyond the lifetime of your application.
*
* <p>Setting a superProperty with registerSuperProperties will store a new superProperty,
* possibly overwriting any existing superProperty with the same name (to set a
* superProperty only if it is currently unset, use {@link #registerSuperPropertiesOnce(JSONObject)})
*
* <p>SuperProperties will persist even if your application is taken completely out of memory.
* to remove a superProperty, call {@link #unregisterSuperProperty(String)} or {@link #clearSuperProperties()}
*
* @param superProperties A JSONObject containing super properties to register
* @see #registerSuperPropertiesOnce(JSONObject)
* @see #unregisterSuperProperty(String)
* @see #clearSuperProperties()
*/
public void registerSuperProperties(JSONObject superProperties) {
mPersistentIdentity.registerSuperProperties(superProperties);
}
/**
* Remove a single superProperty, so that it will not be sent with future calls to {@link #track(String, JSONObject)}.
*
* <p>If there is a superProperty registered with the given name, it will be permanently
* removed from the existing superProperties.
* To clear all superProperties, use {@link #clearSuperProperties()}
*
* @param superPropertyName name of the property to unregister
* @see #registerSuperProperties(JSONObject)
*/
public void unregisterSuperProperty(String superPropertyName) {
mPersistentIdentity.unregisterSuperProperty(superPropertyName);
}
/**
* Register super properties for events, only if no other super property with the
* same names has already been registered.
*
* <p>Calling registerSuperPropertiesOnce will never overwrite existing properties.
*
* @param superProperties A JSONObject containing the super properties to register.
* @see #registerSuperProperties(JSONObject)
*/
public void registerSuperPropertiesOnce(JSONObject superProperties) {
mPersistentIdentity.registerSuperPropertiesOnce(superProperties);
}
/**
* Erase all currently registered superProperties.
*
* <p>Future tracking calls to Mixpanel (even those already queued up but not
* yet sent to Mixpanel servers) will not be associated with the superProperties registered
* before this call was made.
*
* <p>To remove a single superProperty, use {@link #unregisterSuperProperty(String)}
*
* @see #registerSuperProperties(JSONObject)
*/
public void clearSuperProperties() {
mPersistentIdentity.clearSuperProperties();
}
/**
* Returns a Mixpanel.People object that can be used to set and increment
* People Analytics properties.
*
* @return an instance of {@link People} that you can use to update
* records in Mixpanel People Analytics and manage Mixpanel Google Cloud Messaging notifications.
*/
public People getPeople() {
return mPeople;
}
/**
* Core interface for using Mixpanel People Analytics features.
* You can get an instance by calling {@link MixpanelAPI#getPeople()}
*
* <p>The People object is used to update properties in a user's People Analytics record,
* and to manage the receipt of push notifications sent via Mixpanel Engage.
* For this reason, it's important to call {@link #identify(String)} on the People
* object before you work with it. Once you call identify, the user identity will
* persist across stops and starts of your application, until you make another
* call to identify using a different id.
*
* A typical use case for the People object might look like this:
*
* <pre>
* {@code
*
* public class MainActivity extends Activity {
* MixpanelAPI mMixpanel;
*
* public void onCreate(Bundle saved) {
* mMixpanel = MixpanelAPI.getInstance(this, "YOUR MIXPANEL API TOKEN");
* mMixpanel.getPeople().identify("A UNIQUE ID FOR THIS USER");
* mMixpanel.getPeople().initPushHandling("YOUR 12 DIGIT GOOGLE SENDER API");
* ...
* }
*
* public void userUpdatedJobTitle(String newTitle) {
* mMixpanel.getPeople().set("Job Title", newTitle);
* ...
* }
*
* public void onDestroy() {
* mMixpanel.flush();
* super.onDestroy();
* }
* }
*
* }
* </pre>
*
* @see MixpanelAPI
*/
public interface People {
/**
* Associate future calls to {@link #set(JSONObject)}, {@link #increment(Map)},
* and {@link #initPushHandling(String)} with a particular People Analytics user.
*
* <p>All future calls to the People object will rely on this value to assign
* and increment properties. The user identification will persist across
* restarts of your application. We recommend calling
* People.identify as soon as you know the distinct id of the user.
*
* @param distinctId a String that uniquely identifies the user. Users identified with
* the same distinct id will be considered to be the same user in Mixpanel,
* across all platforms and devices. We recommend choosing a distinct id
* that is meaningful to your other systems (for example, a server-side account
* identifier), and using the same distinct id for both calls to People.identify
* and {@link MixpanelAPI#identify(String)}
*
* @see MixpanelAPI#identify(String)
*/
public void identify(String distinctId);
/**
* Sets a single property with the given name and value for this user.
* The given name and value will be assigned to the user in Mixpanel People Analytics,
* possibly overwriting an existing property with the same name.
*
* @param propertyName The name of the Mixpanel property. This must be a String, for example "Zip Code"
* @param value The value of the Mixpanel property. For "Zip Code", this value might be the String "90210"
*/
public void set(String propertyName, Object value);
/**
* Set a collection of properties on the identified user all at once.
*
* @param properties a JSONObject containing the collection of properties you wish to apply
* to the identified user. Each key in the JSONObject will be associated with
* a property name, and the value of that key will be assigned to the property.
*/
public void set(JSONObject properties);
/**
* Works just like {@link People#set(String, Object)}, except it will not overwrite existing property values. This is useful for properties like "First login date".
*
* @param propertyName The name of the Mixpanel property. This must be a String, for example "Zip Code"
* @param value The value of the Mixpanel property. For "Zip Code", this value might be the String "90210"
*/
public void setOnce(String propertyName, Object value);
/**
* Like {@link People#set(String, Object)}, but will not set properties that already exist on a record.
*
* @param properties a JSONObject containing the collection of properties you wish to apply
* to the identified user. Each key in the JSONObject will be associated with
* a property name, and the value of that key will be assigned to the property.
*/
public void setOnce(JSONObject properties);
/**
* Add the given amount to an existing property on the identified user. If the user does not already
* have the associated property, the amount will be added to zero. To reduce a property,
* provide a negative number for the value.
*
* @param name the People Analytics property that should have its value changed
* @param increment the amount to be added to the current value of the named property
*
* @see #increment(Map)
*/
public void increment(String name, double increment);
/**
* Change the existing values of multiple People Analytics properties at once.
*
* <p>If the user does not already have the associated property, the amount will
* be added to zero. To reduce a property, provide a negative number for the value.
*
* @param properties A map of String properties names to Long amounts. Each
* property associated with a name in the map will have its value changed by the given amount
*
* @see #increment(String, double)
*/
public void increment(Map<String, ? extends Number> properties);
/**
* Appends a value to a list-valued property. If the property does not currently exist,
* it will be created as a list of one element. If the property does exist and doesn't
* currently have a list value, the append will be ignored.
* @param name the People Analytics property that should have it's value appended to
* @param value the new value that will appear at the end of the property's list
*/
public void append(String name, Object value);
/**
* Adds values to a list-valued property only if they are not already present in the list.
* If the property does not currently exist, it will be created with the given list as it's value.
* If the property exists and is not list-valued, the union will be ignored.
*
* @param name name of the list-valued property to set or modify
* @param value an array of values to add to the property value if not already present
*/
void union(String name, JSONArray value);
/**
* permanently removes the property with the given name from the user's profile
* @param name name of a property to unset
*/
void unset(String name);
/**
* Track a revenue transaction for the identified people profile.
*
* @param amount the amount of money exchanged. Positive amounts represent purchases or income from the customer, negative amounts represent refunds or payments to the customer.
* @param properties an optional collection of properties to associate with this transaction.
*/
public void trackCharge(double amount, JSONObject properties);
/**
* Permanently clear the whole transaction history for the identified people profile.
*/
public void clearCharges();
/**
* Permanently deletes the identified user's record from People Analytics.
*
* <p>Calling deleteUser deletes an entire record completely. Any future calls
* to People Analytics using the same distinct id will create and store new values.
*/
public void deleteUser();
/**
* Enable end-to-end Google Cloud Messaging (GCM) from Mixpanel.
*
* <p>Calling this method will allow the Mixpanel libraries to handle GCM user
* registration, and enable Mixpanel to show alerts when GCM messages arrive.
*
* <p>To use {@link People#initPushHandling}, you will need to add the following to your application manifest:
*
* <pre>
* {@code
* <receiver android:name="com.mixpanel.android.mpmetrics.GCMReceiver"
* android:permission="com.google.android.c2dm.permission.SEND" >
* <intent-filter>
* <action android:name="com.google.android.c2dm.intent.RECEIVE" />
* <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
* <category android:name="YOUR_PACKAGE_NAME" />
* </intent-filter>
* </receiver>
* }
* </pre>
*
* Be sure to replace "YOUR_PACKAGE_NAME" with the name of your package. For
* more information and a list of necessary permissions, see {@link GCMReceiver}.
*
* <p>If you're planning to use end-to-end support for Messaging, we recommend you
* call this method immediately after calling {@link People#identify(String)}, likely
* early in your application's life cycle. (for example, in the onCreate method of your
* main application activity.)
*
* <p>Calls to {@link People#initPushHandling} should not be mixed with calls to
* {@link #setPushRegistrationId(String)} and {@link #clearPushRegistrationId()}
* in the same application. Application authors should choose one or the other
* method for handling Mixpanel GCM messages.
*
* @param senderID of the Google API Project that registered for Google Cloud Messaging
* You can find your ID by looking at the URL of in your Google API Console
* at https://code.google.com/apis/console/; it is the twelve digit number after
* after "#project:" in the URL address bar on console pages.
*
* @see com.mixpanel.android.mpmetrics.GCMReceiver
* @see <a href="https://mixpanel.com/docs/people-analytics/android-push">Getting Started with Android Push Notifications</a>
*/
public void initPushHandling(String senderID);
/**
* Manually send a Google Cloud Messaging registration id to Mixpanel.
*
* <p>If you are handling Google Cloud Messages in your own application, but would like to
* allow Mixpanel to handle messages originating from Mixpanel campaigns, you should
* call setPushRegistrationId with the "registration_id" property of the
* com.google.android.c2dm.intent.REGISTRATION intent when it is received.
*
* <p>setPushRegistrationId should only be called after {@link #identify(String)} has been called.
*
* <p>Calls to {@link People#setPushRegistrationId} should not be mixed with calls to {@link #initPushHandling(String)}
* in the same application. In addition, applications that call setPushRegistrationId
* should also call {@link #clearPushRegistrationId()} when they receive an intent to unregister
* (a com.google.android.c2dm.intent.REGISTRATION intent with getStringExtra("unregistered") != null)
*
* @param registrationId the result of calling intent.getStringExtra("registration_id")
* on a com.google.android.c2dm.intent.REGISTRATION intent
*
* @see #initPushHandling(String)
* @see #clearPushRegistrationId()
*/
public void setPushRegistrationId(String registrationId);
/**
* Manually clear a current Google Cloud Messaging registration id from Mixpanel.
*
* <p>If you are handling Google Cloud Messages in your own application, you should
* call this method when your application receives a com.google.android.c2dm.intent.REGISTRATION
* with getStringExtra("unregistered") != null
*
* <p>{@link People#clearPushRegistrationId} should only be called after {@link #identify(String)} has been called.
*
* <p>In general, all applications that call {@link #setPushRegistrationId(String)} should include a call to
* removePushRegistrationId, and no applications that call {@link #initPushHandling(String)} should
* call removePushRegistrationId
*/
public void clearPushRegistrationId();
/**
* Returns the string id currently being used to uniquely identify the user associated
* with events sent using {@link People#set(String, Object)} and {@link People#increment(String, double)}.
* If no calls to {@link People#identify(String)} have been made, this method will return null.
*
* <p>The id returned by getDistinctId is independent of the distinct id used to identify
* any events sent with {@link MixpanelAPI#track(String, JSONObject)}. To read and write that identifier,
* use {@link MixpanelAPI#identify(String)} and {@link MixpanelAPI#getDistinctId()}.
*
* @return The distinct id associated with updates to People Analytics
*
* @see People#identify(String)
* @see MixpanelAPI#getDistinctId()
*/
public String getDistinctId();
/**
* If a survey is currently available, this method will launch an activity that shows a
* survey to the user and then send the responses to Mixpanel.
*
* <p>The survey activity will use the root of the given view to take a screenshot
* for its background.
*
* <p>It is safe to call this method any time you want to potentially display an in app notification.
* This method will be a no-op if there is already a survey or in app notification being displayed.
* Thus, if you have both surveys and in app notification campaigns built in Mixpanel, you may call
* both this and {@link People#showNotificationIfAvailable(Activity)} right after each other, and
* only one of them will be displayed.
*
* <p>This method is a no-op in environments with
* Android API before Ice Cream Sandwich/API level 14.
*
* @param parent the Activity that this Survey will be displayed on top of. A snapshot will be
* taken of parent to be used as a blurred background.
*/
public void showSurveyIfAvailable(Activity parent);
/**
* Shows an in app not3ification to the user if one is available. If the notification
* is a mini notification, this method will attach and remove a Fragment to parent.
* The lifecycle of the Fragment will be handled entirely by the Mixpanel library.
*
* <p>If the notification is a takeover notification, a SurveyActivity will be launched to
* display the Takeover notification.
*
* <p>It is safe to call this method any time you want to potentially display an in app notification.
* This method will be a no-op if there is already a survey or in app notification being displayed.
* Thus, if you have both surveys and in app notification campaigns built in Mixpanel, you may call
* both this and {@link People#showSurveyIfAvailable(Activity)} right after each other, and
* only one of them will be displayed.
*
* <p>This method is a no-op in environments with
* Android API before Ice Cream Sandwich/API level 14.
*
* @param parent the Activity that the mini notification will be displayed in, or the Activity
* that will be used to launch SurveyActivity for the takeover notification.
*/
public void showNotificationIfAvailable(Activity parent);
/**
* Returns a survey object if one is available and being held by the library, or null if
* no survey is currently available. Callers who want to display surveys with their own UI
* should call this method to get the Survey data. A given survey will be returned only once
* from this method, so callers should be ready to consume any non-null return value.
*
* <p>This function will always return quickly, and will not cause any communication with
* Mixpanel's servers, so it is safe to call this from the UI thread.
*
* @return a Survey object if one is available, null otherwise.
*/
public Survey getSurveyIfAvailable();
/**
* Returns an InAppNotification object if one is available and being held by the library, or null if
* no survey is currently available. Callers who want to display in app notifications should call this
* method periodically. A given InAppNotification will be returned only once from this method, so callers
* should be ready to consume any non-null return value.
*
* <p>This function will return quickly, and will not cause any communication with
* Mixpanel's servers, so it is safe to call this from the UI thread.
*
* @return an InAppNotification object if one is available, null otherwise.
*/
public InAppNotification getNotificationIfAvailable();
/**
* Return an instance of Mixpanel people with a temporary distinct id.
* This is used by Mixpanel Surveys but is likely not needed in your code.
*/
public People withIdentity(String distinctId);
/**
* Adds a new listener that will receive a callback when new updates from Mixpanel
* (like surveys or in app notifications) are discovered.
*
* <p>The given listener will be called when a new batch of updates is detected. Handlers
* should be prepared to handle the callback on an arbitrary thread.
*
* <p>Once this listener is called, you may call {@link People#getSurveyIfAvailable()}
* or {@link People#getNotificationIfAvailable()}
* to retrieve a Survey or InAppNotification object. However, if you have multiple
* listeners registered, one listener may have consumed the available Survey or
* InAppNotification, and so the other listeners may obtain null when calling
* {@link People#getSurveyIfAvailable()} or {@link People#getNotificationIfAvailable()}.
*
* @param listener the listener to add
*/
public void addOnMixpanelUpdatesReceivedListener(OnMixpanelUpdatesReceivedListener listener);
/**
* Removes a listener previously registered with addOnMixpanelUpdatesReceivedListener.
*
* @param listener the listener to add
*/
public void removeOnMixpanelUpdatesReceivedListener(OnMixpanelUpdatesReceivedListener listener);
/**
* @deprecated Use showSurveyIfAvailable() instead.
*/
@Deprecated
public void showSurvey(Survey s, Activity parent);
/**
* @deprecated Use getSurveyIfAvailable() instead.
*/
@Deprecated
public void checkForSurvey(SurveyCallbacks callbacks);
/**
* @deprecated Use getSurveyIfAvailable() instead.
*/
@Deprecated
public void checkForSurvey(SurveyCallbacks callbacks, Activity parent);
}
/**
* Manage verbose logging about messages sent to Mixpanel.
*
* <p>Under ordinary circumstances, the Mixpanel library will only send messages
* to the log when errors occur. However, after logPosts is called, Mixpanel will
* send messages describing it's communication with the Mixpanel servers to
* the system log.
*
* <p>Mixpanel will log its verbose messages tag "MixpanelAPI" with priority I("Information")
*/
@Deprecated
public void logPosts() {
Log.i(
LOGTAG,
"MixpanelAPI.logPosts() is deprecated.\n" +
" To get verbose debug level logging, add\n" +
" <meta-data android:name=\"com.mixpanel.android.MPConfig.EnableDebugLogging\" />\n" +
" to the <application> section of your AndroidManifest.xml."
);
}
/**
* Attempt to register MixpanelActivityLifecycleCallbacks to the application's event lifecycle.
* Once registered, we can automatically check for and show surveys and in app notifications
* when any Activity is opened.
*
* This is only available if the android version is >= 14. You can disable this by setting
* com.mixpanel.android.MPConfig.AutoShowMixpanelUpdates to false in your AndroidManifest.xml
*
* This function is automatically called when the library is initialized unless you explicitly
* set com.mixpanel.android.MPConfig.AutoShowMixpanelUpdates to false in your AndroidManifest.xml
*/
/* package */
@TargetApi(14)
void registerMixpanelActivityLifecycleCallbacks() {
if (android.os.Build.VERSION.SDK_INT >= 14 && mConfig.getAutoShowMixpanelUpdates()) {
if (mContext.getApplicationContext() instanceof Application) {
final Application app = (Application) mContext.getApplicationContext();
app.registerActivityLifecycleCallbacks((new MixpanelActivityLifecycleCallbacks(this)));
} else {
if (MPConfig.DEBUG) Log.d(LOGTAG, "Context is NOT instanceof Application, AutoShowMixpanelUpdates will be disabled.");
}
}
}
// Package-level access. Used (at least) by GCMReceiver
// when OS-level events occur.
/* package */ interface InstanceProcessor {
public void process(MixpanelAPI m);
}
/* package */ static void allInstances(InstanceProcessor processor) {
synchronized (sInstanceMap) {
for (final Map<Context, MixpanelAPI> contextInstances:sInstanceMap.values()) {
for (final MixpanelAPI instance:contextInstances.values()) {
processor.process(instance);
}
}
}
}
////////////////////////////////////////////////////////////////////
// Conveniences for testing. These methods should not be called by
// non-test client code.
/* package */ AnalyticsMessages getAnalyticsMessages() {
return AnalyticsMessages.getInstance(mContext);
}
/* package */ MPConfig getConfig() {
return MPConfig.getInstance(mContext);
}
/* package */ PersistentIdentity getPersistentIdentity(final Context context, Future<SharedPreferences> referrerPreferences, final String token) {
final SharedPreferencesLoader.OnPrefsLoadedListener listener = new SharedPreferencesLoader.OnPrefsLoadedListener() {
@Override
public void onPrefsLoaded(SharedPreferences preferences) {
final JSONArray records = PersistentIdentity.waitingPeopleRecordsForSending(preferences);
if (null != records) {
sendAllPeopleRecords(records);
}
}
};
final String prefsName = "com.mixpanel.android.mpmetrics.MixpanelAPI_" + token;
final Future<SharedPreferences> storedPreferences = sPrefsLoader.loadPreferences(context, prefsName, listener);
return new PersistentIdentity(referrerPreferences, storedPreferences);
}
/* package */ DecideUpdates constructDecideUpdates(final String token, final String peopleId, final DecideUpdates.OnNewResultsListener listener) {
return new DecideUpdates(token, peopleId, listener);
}
/* package */ void clearPreferences() {
// Will clear distinct_ids, superProperties,
// and waiting People Analytics properties. Will have no effect
// on messages already queued to send with AnalyticsMessages.
mPersistentIdentity.clearPreferences();
}
///////////////////////
private class PeopleImpl implements People {
@Override
public void identify(String distinctId) {
mPersistentIdentity.setPeopleDistinctId(distinctId);
if (null != mDecideUpdates && !mDecideUpdates.getDistinctId().equals(distinctId)) {
mDecideUpdates.destroy();
mDecideUpdates = null;
}
if (null == mDecideUpdates) {
mDecideUpdates = constructDecideUpdates(mToken, distinctId, mUpdatesListener);
mMessages.installDecideCheck(mDecideUpdates);
}
pushWaitingPeopleRecord();
}
@Override
public void set(JSONObject properties) {
try {
final JSONObject sendProperties = new JSONObject();
sendProperties.put("$android_lib_version", MPConfig.VERSION);
sendProperties.put("$android_os", "Android");
sendProperties.put("$android_os_version", Build.VERSION.RELEASE == null ? "UNKNOWN" : Build.VERSION.RELEASE);
try {
PackageManager manager = mContext.getPackageManager();
PackageInfo info = manager.getPackageInfo(mContext.getPackageName(), 0);
sendProperties.put("$android_app_version", info.versionName);
} catch (PackageManager.NameNotFoundException e) {
Log.e(LOGTAG, "Exception getting app version name", e);
}
sendProperties.put("$android_manufacturer", Build.MANUFACTURER == null ? "UNKNOWN" : Build.MANUFACTURER);
sendProperties.put("$android_brand", Build.BRAND == null ? "UNKNOWN" : Build.BRAND);
sendProperties.put("$android_model", Build.MODEL == null ? "UNKNOWN" : Build.MODEL);
for (final Iterator<?> iter = properties.keys(); iter.hasNext();) {
final String key = (String) iter.next();
sendProperties.put(key, properties.get(key));
}
final JSONObject message = stdPeopleMessage("$set", sendProperties);
recordPeopleMessage(message);
} catch (final JSONException e) {
Log.e(LOGTAG, "Exception setting people properties", e);
}
}
@Override
public void set(String property, Object value) {
try {
set(new JSONObject().put(property, value));
} catch (final JSONException e) {
Log.e(LOGTAG, "set", e);
}
}
@Override
public void setOnce(JSONObject properties) {
try {
final JSONObject message = stdPeopleMessage("$set_once", properties);
recordPeopleMessage(message);
} catch (final JSONException e) {
Log.e(LOGTAG, "Exception setting people properties");
}
}
@Override
public void setOnce(String property, Object value) {
try {
setOnce(new JSONObject().put(property, value));
} catch (final JSONException e) {
Log.e(LOGTAG, "set", e);
}
}
@Override
public void increment(Map<String, ? extends Number> properties) {
final JSONObject json = new JSONObject(properties);
try {
final JSONObject message = stdPeopleMessage("$add", json);
recordPeopleMessage(message);
} catch (final JSONException e) {
Log.e(LOGTAG, "Exception incrementing properties", e);
}
}
@Override
public void increment(String property, double value) {
final Map<String, Double> map = new HashMap<String, Double>();
map.put(property, value);
increment(map);
}
@Override
public void append(String name, Object value) {
try {
final JSONObject properties = new JSONObject();
properties.put(name, value);
final JSONObject message = stdPeopleMessage("$append", properties);
recordPeopleMessage(message);
} catch (final JSONException e) {
Log.e(LOGTAG, "Exception appending a property", e);
}
}
@Override
public void union(String name, JSONArray value) {
try {
final JSONObject properties = new JSONObject();
properties.put(name, value);
final JSONObject message = stdPeopleMessage("$union", properties);
recordPeopleMessage(message);
} catch (final JSONException e) {
Log.e(LOGTAG, "Exception unioning a property");
}
}
@Override
public void unset(String name) {
try {
final JSONArray names = new JSONArray();
names.put(name);
final JSONObject message = stdPeopleMessage("$unset", names);
recordPeopleMessage(message);
} catch (final JSONException e) {
Log.e(LOGTAG, "Exception unsetting a property", e);
}
}
@Override
@Deprecated
public void checkForSurvey(final SurveyCallbacks callbacks) {
if (null == callbacks) {
Log.i(LOGTAG, "Skipping survey check because callback is null.");
return;
}
final Survey found = getSurveyIfAvailable();
callbacks.foundSurvey(found);
}
@Override
@Deprecated
public void checkForSurvey(final SurveyCallbacks callbacks, final Activity parentActivity) {
// Originally this call pre-computed UI chrome while it was waiting for the check to run.
// Since modern checks run asynchronously, it's useless nowdays.
checkForSurvey(callbacks);
}
@Override
public InAppNotification getNotificationIfAvailable() {
if (null == getDistinctId()) {
return null;
}
return mDecideUpdates.getNotification(mConfig.getTestMode());
}
@Override
public Survey getSurveyIfAvailable() {
if (null == getDistinctId()) {
return null;
}
return mDecideUpdates.getSurvey(mConfig.getTestMode());
}
@Override
@Deprecated
public void showSurvey(final Survey survey, final Activity parent) {
showGivenOrAvailableSurvey(survey, parent);
}
@Override
public void showSurveyIfAvailable(final Activity parent) {
if (Build.VERSION.SDK_INT < 14) {
return;
}
showGivenOrAvailableSurvey(null, parent);
}
@Override
public void showNotificationIfAvailable(final Activity parent) {
if (Build.VERSION.SDK_INT < 14) {
return;
}
parent.runOnUiThread(new Runnable() {
@Override
@TargetApi(14)
public void run() {
final ReentrantLock lock = UpdateDisplayState.getLockObject();
lock.lock();
try {
if (UpdateDisplayState.hasCurrentProposal()) {
return; // Already being used.
}
InAppNotification notif = getNotificationIfAvailable();
if (null == notif) {
return; // Nothing to show
}
final InAppNotification.Type inAppType = notif.getType();
if (inAppType == InAppNotification.Type.TAKEOVER && ! ConfigurationChecker.checkSurveyActivityAvailable(parent.getApplicationContext())) {
return; // Can't show due to config.
}
final int highlightColor = ActivityImageUtils.getHighlightColorFromBackground(parent);
final UpdateDisplayState.DisplayState.InAppNotificationState proposal =
new UpdateDisplayState.DisplayState.InAppNotificationState(notif, highlightColor);
final int intentId = UpdateDisplayState.proposeDisplay(proposal, getDistinctId(), mToken);
assert intentId > 0; // Since we're holding the lock and !hasCurrentProposal
switch (inAppType) {
case MINI: {
final UpdateDisplayState claimed = UpdateDisplayState.claimDisplayState(intentId);
InAppFragment inapp = new InAppFragment();
inapp.setDisplayState(intentId, (UpdateDisplayState.DisplayState.InAppNotificationState) claimed.getDisplayState());
inapp.setRetainInstance(true);
FragmentTransaction transaction = parent.getFragmentManager().beginTransaction();
transaction.setCustomAnimations(0, R.anim.com_mixpanel_android_slide_down);
transaction.add(android.R.id.content, inapp);
transaction.commit();
}
break;
case TAKEOVER: {
final Intent intent = new Intent(parent.getApplicationContext(), SurveyActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
intent.putExtra(SurveyActivity.INTENT_ID_KEY, intentId);
parent.startActivity(intent);
}
break;
default:
Log.e(LOGTAG, "Unrecognized notification type " + inAppType + " can't be shown");
}
if (!mConfig.getTestMode()) {
trackNotificationSeen(notif);
}
} finally {
lock.unlock();
}
} // run()
private void trackNotificationSeen(InAppNotification notif) {
track("$campaign_delivery", notif.getCampaignProperties());
final MixpanelAPI.People people = getPeople().withIdentity(getDistinctId());
final DateFormat dateFormat = new SimpleDateFormat(ENGAGE_DATE_FORMAT_STRING);
final JSONObject notifProperties = notif.getCampaignProperties();
try {
notifProperties.put("$time", dateFormat.format(new Date()));
} catch (JSONException e) {
Log.e(LOGTAG, "Exception trying to track an in app notification seen", e);
}
people.append("$campaigns", notif.getId());
people.append("$notifications", notifProperties);
}
});
}
@Override
public void trackCharge(double amount, JSONObject properties) {
final Date now = new Date();
final DateFormat dateFormat = new SimpleDateFormat(ENGAGE_DATE_FORMAT_STRING);
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
final JSONObject transactionValue = new JSONObject();
transactionValue.put("$amount", amount);
transactionValue.put("$time", dateFormat.format(now));
if (null != properties) {
for (final Iterator<?> iter = properties.keys(); iter.hasNext();) {
final String key = (String) iter.next();
transactionValue.put(key, properties.get(key));
}
}
this.append("$transactions", transactionValue);
} catch (final JSONException e) {
Log.e(LOGTAG, "Exception creating new charge", e);
}
}
/**
* Permanently clear the whole transaction history for the identified people profile.
*/
@Override
public void clearCharges() {
this.unset("$transactions");
}
@Override
public void deleteUser() {
try {
final JSONObject message = stdPeopleMessage("$delete", JSONObject.NULL);
recordPeopleMessage(message);
} catch (final JSONException e) {
Log.e(LOGTAG, "Exception deleting a user");
}
}
@Override
public void setPushRegistrationId(String registrationId) {
if (getDistinctId() == null) {
return;
}
mPersistentIdentity.storePushId(registrationId);
try {
union("$android_devices", new JSONArray("[" + registrationId + "]"));
} catch (final JSONException e) {
Log.e(LOGTAG, "set push registration id error", e);
}
}
@Override
public void clearPushRegistrationId() {
mPersistentIdentity.clearPushId();
set("$android_devices", new JSONArray());
}
@Override
public void initPushHandling(String senderID) {
if (! ConfigurationChecker.checkPushConfiguration(mContext) ) {
Log.i(LOGTAG, "Can't start push notification service. Push notifications will not work.");
Log.i(LOGTAG, "See log tagged " + ConfigurationChecker.LOGTAG + " above for details.");
}
else { // Configuration is good for push notifications
final String pushId = mPersistentIdentity.getPushId();
if (pushId == null) {
if (MPConfig.DEBUG) Log.d(LOGTAG, "Registering a new push id");
try {
final Intent registrationIntent = new Intent("com.google.android.c2dm.intent.REGISTER");
registrationIntent.putExtra("app", PendingIntent.getBroadcast(mContext, 0, new Intent(), 0)); // boilerplate
registrationIntent.putExtra("sender", senderID);
mContext.startService(registrationIntent);
} catch (final SecurityException e) {
Log.w(LOGTAG, e);
}
} else {
MixpanelAPI.allInstances(new InstanceProcessor() {
@Override
public void process(MixpanelAPI api) {
if (MPConfig.DEBUG) Log.d(LOGTAG, "Using existing pushId " + pushId);
api.getPeople().setPushRegistrationId(pushId);
}
});
}
}// endelse
}
@Override
public String getDistinctId() {
return mPersistentIdentity.getPeopleDistinctId();
}
@Override
public People withIdentity(final String distinctId) {
if (null == distinctId) {
return null;
}
return new PeopleImpl() {
@Override
public String getDistinctId() {
return distinctId;
}
@Override
public void identify(String distinctId) {
throw new RuntimeException("This MixpanelPeople object has a fixed, constant distinctId");
}
};
}
@Override
public void addOnMixpanelUpdatesReceivedListener(final OnMixpanelUpdatesReceivedListener listener) {
mUpdatesListener.addOnMixpanelUpdatesReceivedListener(listener);
}
@Override
public void removeOnMixpanelUpdatesReceivedListener(final OnMixpanelUpdatesReceivedListener listener) {
mUpdatesListener.removeOnMixpanelUpdatesReceivedListener(listener);
}
public JSONObject stdPeopleMessage(String actionType, Object properties)
throws JSONException {
final JSONObject dataObj = new JSONObject();
final String distinctId = getDistinctId();
dataObj.put(actionType, properties);
dataObj.put("$token", mToken);
dataObj.put("$time", System.currentTimeMillis());
if (null != distinctId) {
dataObj.put("$distinct_id", getDistinctId());
}
return dataObj;
}
private void showGivenOrAvailableSurvey(final Survey surveyOrNull, final Activity parent) {
// Showing surveys is not supported before Ice Cream Sandwich
if (Build.VERSION.SDK_INT < 14) {
return;
}
if (! ConfigurationChecker.checkSurveyActivityAvailable(parent.getApplicationContext())) {
return;
}
BackgroundCapture.OnBackgroundCapturedListener listener = null;
final ReentrantLock lock = UpdateDisplayState.getLockObject();
lock.lock();
try {
if (UpdateDisplayState.hasCurrentProposal()) {
return; // Already being used.
}
Survey toShow = surveyOrNull;
if (null == toShow) {
toShow = getSurveyIfAvailable();
}
if (null == toShow) {
return; // Nothing to show
}
final UpdateDisplayState.DisplayState.SurveyState surveyDisplay =
new UpdateDisplayState.DisplayState.SurveyState(toShow);
final int intentId = UpdateDisplayState.proposeDisplay(surveyDisplay, getDistinctId(), mToken);
assert intentId > 0; // Since we hold the lock, and !hasCurrentProposal
listener = new BackgroundCapture.OnBackgroundCapturedListener() {
@Override
public void onBackgroundCaptured(Bitmap bitmapCaptured, int highlightColorCaptured) {
surveyDisplay.setBackground(bitmapCaptured);
surveyDisplay.setHighlightColor(highlightColorCaptured);
final Intent surveyIntent = new Intent(parent.getApplicationContext(), SurveyActivity.class);
surveyIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
surveyIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
surveyIntent.putExtra(SurveyActivity.INTENT_ID_KEY, intentId);
parent.startActivity(surveyIntent);
}
};
} finally {
lock.unlock();
}
assert listener != null;
BackgroundCapture.captureBackground(parent, listener);
}
}// PeopleImpl
private class UpdatesListener implements DecideUpdates.OnNewResultsListener, Runnable {
@Override
public void onNewResults(final String distinctId) {
mExecutor.execute(this);
}
public synchronized void addOnMixpanelUpdatesReceivedListener(OnMixpanelUpdatesReceivedListener listener) {
// Workaround for a race between checking for updates using getSurveyIfAvailable() and getNotificationIfAvailable()
// and registering a listener.
synchronized (mDecideUpdates) {
if (mDecideUpdates.hasUpdatesAvailable()) {
onNewResults(mDecideUpdates.getDistinctId());
}
}
mListeners.add(listener);
}
public synchronized void removeOnMixpanelUpdatesReceivedListener(OnMixpanelUpdatesReceivedListener listener) {
mListeners.remove(listener);
}
public synchronized void run() {
// It's possible that by the time this has run the updates we detected are no longer
// present, which is ok.
Log.e(LOGTAG, "UPDATE RECIEVED, INFORMING " + mListeners.size() + " LISTENERS");
for (OnMixpanelUpdatesReceivedListener listener: mListeners) {
listener.onMixpanelUpdatesReceived();
}
}
private final Set<OnMixpanelUpdatesReceivedListener> mListeners = new HashSet<OnMixpanelUpdatesReceivedListener>();
private final Executor mExecutor = Executors.newSingleThreadExecutor();
}
////////////////////////////////////////////////////
private void recordPeopleMessage(JSONObject message) {
if (message.has("$distinct_id")) {
mMessages.peopleMessage(message);
} else {
mPersistentIdentity.storeWaitingPeopleRecord(message);
}
}
private void pushWaitingPeopleRecord() {
final JSONArray records = mPersistentIdentity.waitingPeopleRecordsForSending();
if (null != records) {
sendAllPeopleRecords(records);
}
}
// MUST BE THREAD SAFE. Called from crazy places. mPersistentIdentity may not exist
// when this is called (from its crazy thread)
private void sendAllPeopleRecords(JSONArray records) {
for (int i = 0; i < records.length(); i++) {
try {
final JSONObject message = records.getJSONObject(i);
mMessages.peopleMessage(message);
} catch (final JSONException e) {
Log.e(LOGTAG, "Malformed people record stored pending identity, will not send it.", e);
}
}
}
private static final String LOGTAG = "MixpanelAPI";
private static final String ENGAGE_DATE_FORMAT_STRING = "yyyy-MM-dd'T'HH:mm:ss";
private final Context mContext;
private final AnalyticsMessages mMessages;
private final MPConfig mConfig;
private final String mToken;
private final PeopleImpl mPeople;
private final PersistentIdentity mPersistentIdentity;
private final UpdatesListener mUpdatesListener;
private DecideUpdates mDecideUpdates;
// Maps each token to a singleton MixpanelAPI instance
private static final Map<String, Map<Context, MixpanelAPI>> sInstanceMap = new HashMap<String, Map<Context, MixpanelAPI>>();
private static final SharedPreferencesLoader sPrefsLoader = new SharedPreferencesLoader();
private static Future<SharedPreferences> sReferrerPrefs;
}
| src/main/java/com/mixpanel/android/mpmetrics/MixpanelAPI.java | package com.mixpanel.android.mpmetrics;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Application;
import android.app.FragmentTransaction;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Build;
import android.util.Log;
import com.mixpanel.android.R;
import com.mixpanel.android.surveys.SurveyActivity;
import com.mixpanel.android.util.ActivityImageUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.locks.ReentrantLock;
/**
* Core class for interacting with Mixpanel Analytics.
*
* <p>Call {@link #getInstance(Context, String)} with
* your main application activity and your Mixpanel API token as arguments
* an to get an instance you can use to report how users are using your
* application.
*
* <p>Once you have an instance, you can send events to Mixpanel
* using {@link #track(String, JSONObject)}, and update People Analytics
* records with {@link #getPeople()}
*
* <p>The Mixpanel library will periodically send information to
* Mixpanel servers, so your application will need to have
* <tt>android.permission.INTERNET</tt>. In addition, to preserve
* battery life, messages to Mixpanel servers may not be sent immediately
* when you call <tt>track</tt> or {@link People#set(String, Object)}.
* The library will send messages periodically throughout the lifetime
* of your application, but you will need to call {@link #flush()}
* before your application is completely shutdown to ensure all of your
* events are sent.
*
* <p>A typical use-case for the library might look like this:
*
* <pre>
* {@code
* public class MainActivity extends Activity {
* MixpanelAPI mMixpanel;
*
* public void onCreate(Bundle saved) {
* mMixpanel = MixpanelAPI.getInstance(this, "YOUR MIXPANEL API TOKEN");
* ...
* }
*
* public void whenSomethingInterestingHappens(int flavor) {
* JSONObject properties = new JSONObject();
* properties.put("flavor", flavor);
* mMixpanel.track("Something Interesting Happened", properties);
* ...
* }
*
* public void onDestroy() {
* mMixpanel.flush();
* super.onDestroy();
* }
* }
* }
* </pre>
*
* <p>In addition to this documentation, you may wish to take a look at
* <a href="https://github.com/mixpanel/sample-android-mixpanel-integration">the Mixpanel sample Android application</a>.
* It demonstrates a variety of techniques, including
* updating People Analytics records with {@link People} and registering for
* and receiving push notifications with {@link People#initPushHandling(String)}.
*
* <p>There are also <a href="https://mixpanel.com/docs/">step-by-step getting started documents</a>
* available at mixpanel.com
*
* @see <a href="https://mixpanel.com/docs/integration-libraries/android">getting started documentation for tracking events</a>
* @see <a href="https://mixpanel.com/docs/people-analytics/android">getting started documentation for People Analytics</a>
* @see <a href="https://mixpanel.com/docs/people-analytics/android-push">getting started with push notifications for Android</a>
* @see <a href="https://github.com/mixpanel/sample-android-mixpanel-integration">The Mixpanel Android sample application</a>
*/
public class MixpanelAPI {
/**
* String version of the library.
*/
public static final String VERSION = MPConfig.VERSION;
/**
* You shouldn't instantiate MixpanelAPI objects directly.
* Use MixpanelAPI.getInstance to get an instance.
*/
MixpanelAPI(Context context, Future<SharedPreferences> referrerPreferences, String token) {
mContext = context;
mToken = token;
mPeople = new PeopleImpl();
mMessages = getAnalyticsMessages();
mConfig = getConfig();
mPersistentIdentity = getPersistentIdentity(context, referrerPreferences, token);
mUpdatesListener = new UpdatesListener();
mDecideUpdates = null;
// TODO this immediately forces the lazy load of the preferences, and defeats the
// purpose of PersistentIdentity's laziness.
final String peopleId = mPersistentIdentity.getPeopleDistinctId();
if (null != peopleId) {
mDecideUpdates = constructDecideUpdates(token, peopleId, mUpdatesListener);
}
registerMixpanelActivityLifecycleCallbacks();
if (null != mDecideUpdates) {
mMessages.installDecideCheck(mDecideUpdates);
}
}
/**
* Get the instance of MixpanelAPI associated with your Mixpanel project token.
*
* <p>Use getInstance to get a reference to a shared
* instance of MixpanelAPI you can use to send events
* and People Analytics updates to Mixpanel.</p>
* <p>getInstance is thread safe, but the returned instance is not,
* and may be shared with other callers of getInstance.
* The best practice is to call getInstance, and use the returned MixpanelAPI,
* object from a single thread (probably the main UI thread of your application).</p>
* <p>If you do choose to track events from multiple threads in your application,
* you should synchronize your calls on the instance itself, like so:</p>
* <pre>
* {@code
* MixpanelAPI instance = MixpanelAPI.getInstance(context, token);
* synchronized(instance) { // Only necessary if the instance will be used in multiple threads.
* instance.track(...)
* }
* }
* </pre>
*
* @param context The application context you are tracking
* @param token Your Mixpanel project token. You can get your project token on the Mixpanel web site,
* in the settings dialog.
* @return an instance of MixpanelAPI associated with your project
*/
public static MixpanelAPI getInstance(Context context, String token) {
if (null == token || null == context) {
return null;
}
synchronized (sInstanceMap) {
final Context appContext = context.getApplicationContext();
if (null == sReferrerPrefs) {
sReferrerPrefs = sPrefsLoader.loadPreferences(context, MPConfig.REFERRER_PREFS_NAME, null);
}
Map <Context, MixpanelAPI> instances = sInstanceMap.get(token);
if (null == instances) {
instances = new HashMap<Context, MixpanelAPI>();
sInstanceMap.put(token, instances);
}
MixpanelAPI instance = instances.get(appContext);
if (null == instance) {
instance = new MixpanelAPI(appContext, sReferrerPrefs, token);
instances.put(appContext, instance);
}
return instance;
}
}
/**
* Sets the target frequency of messages to Mixpanel servers.
* If no calls to {@link #flush()} are made, the Mixpanel
* library attempts to send tracking information in batches at a rate
* that provides a reasonable compromise between battery life and liveness of data.
* Callers can override this value, for the whole application, by calling
* <tt>setFlushInterval</tt>.
*
* If milliseconds is negative, Mixpanel will never flush the data automatically,
* and require callers to call {@link #flush()} to send data. This can have
* implications for storage and is not appropriate for most situations.
*
* @param context the execution context associated with this application, probably
* the main application activity.
* @param milliseconds the target number of milliseconds between automatic flushes.
* this value is advisory, actual flushes may be more or less frequent
* @deprecated in 4.0.0, use com.mixpanel.android.MPConfig.FlushInterval application metadata instead
*/
@Deprecated
public static void setFlushInterval(Context context, long milliseconds) {
Log.i(
LOGTAG,
"MixpanelAPI.setFlushInterval is deprecated.\n" +
" To set a custom Mixpanel flush interval for your application, add\n" +
" <meta-data android:name=\"com.mixpanel.android.MPConfig.FlushInterval\" android:value=\"YOUR_INTERVAL\" />\n" +
" to the <application> section of your AndroidManifest.xml."
);
final AnalyticsMessages msgs = AnalyticsMessages.getInstance(context);
msgs.setFlushInterval(milliseconds);
}
/**
* By default, if the MixpanelAPI cannot contact the API server over HTTPS,
* it will attempt to contact the server via regular HTTP. To disable this
* behavior, call enableFallbackServer(context, false)
*
* @param context the execution context associated with this context.
* @param enableIfTrue if true, the library will fall back to using http
* when https is unavailable.
* @deprecated in 4.0.0, use com.mixpanel.android.MPConfig.EventsFallbackEndpoint, com.mixpanel.android.MPConfig.PeopleFallbackEndpoint, or com.mixpanel.android.MPConfig.DecideFallbackEndpoint instead
*/
@Deprecated
public static void enableFallbackServer(Context context, boolean enableIfTrue) {
Log.i(
LOGTAG,
"MixpanelAPI.enableFallbackServer is deprecated.\n" +
" To enable fallback in your application, add\n" +
" <meta-data android:name=\"com.mixpanel.android.MPConfig.DisableFallback\" android:value=\"false\" />\n" +
" to the <application> section of your AndroidManifest.xml."
);
final AnalyticsMessages msgs = AnalyticsMessages.getInstance(context);
msgs.setDisableFallback(! enableIfTrue);
}
/**
* This function creates a distinct_id alias from alias to original. If original is null, then it will create an alias
* to the current events distinct_id, which may be the distinct_id randomly generated by the Mixpanel library
* before {@link #identify(String)} is called.
*
* <p>This call does not identify the user after. You must still call both {@link #identify(String)} and
* {@link People#identify(String)} if you wish the new alias to be used for Events and People.
*
* @param alias the new distinct_id that should represent original.
* @param original the old distinct_id that alias will be mapped to.
*/
public void alias(String alias, String original) {
if (original == null) {
original = getDistinctId();
}
if (alias.equals(original)) {
Log.w(LOGTAG, "Attempted to alias identical distinct_ids " + alias + ", returning.");
return;
}
try {
JSONObject j = new JSONObject();
j.put("alias", alias);
j.put("original", original);
track("$create_alias", j);
} catch (JSONException e) {
Log.e(LOGTAG, "Failed to alias", e);
}
flush();
}
/**
* Associate all future calls to {@link #track(String, JSONObject)} with the user identified by
* the given distinct id.
*
* <p>This call does not identify the user for People Analytics;
* to do that, see {@link People#identify(String)}. Mixpanel recommends using
* the same distinct_id for both calls, and using a distinct_id that is easy
* to associate with the given user, for example, a server-side account identifier.
*
* <p>Calls to {@link #track(String, JSONObject)} made before corresponding calls to
* identify will use an internally generated distinct id, which means it is best
* to call identify early to ensure that your Mixpanel funnels and retention
* analytics can continue to track the user throughout their lifetime. We recommend
* calling identify as early as you can.
*
* <p>Once identify is called, the given distinct id persists across restarts of your
* application.
*
* @param distinctId a string uniquely identifying this user. Events sent to
* Mixpanel using the same disinct_id will be considered associated with the
* same visitor/customer for retention and funnel reporting, so be sure that the given
* value is globally unique for each individual user you intend to track.
*
* @see People#identify(String)
*/
public void identify(String distinctId) {
mPersistentIdentity.setEventsDistinctId(distinctId);
}
/**
* Track an event.
*
* <p>Every call to track eventually results in a data point sent to Mixpanel. These data points
* are what are measured, counted, and broken down to create your Mixpanel reports. Events
* have a string name, and an optional set of name/value pairs that describe the properties of
* that event.
*
* @param eventName The name of the event to send
* @param properties A JSONObject containing the key value pairs of the properties to include in this event.
* Pass null if no extra properties exist.
*/
// DO NOT DOCUMENT, but track() must be thread safe since it is used to track events in
// notifications from the UI thread, which might not be our MixpanelAPI "home" thread.
// This MAY CHANGE IN FUTURE RELEASES, so minimize code that assumes thread safety
// (and perhaps document that code here).
public void track(String eventName, JSONObject properties) {
try {
final JSONObject messageProps = new JSONObject();
final Map<String, String> referrerProperties = mPersistentIdentity.getReferrerProperties();
for (final Map.Entry<String, String> entry:referrerProperties.entrySet()) {
final String key = entry.getKey();
final String value = entry.getValue();
messageProps.put(key, value);
}
final JSONObject superProperties = mPersistentIdentity.getSuperProperties();
final Iterator<?> superIter = superProperties.keys();
while (superIter.hasNext()) {
final String key = (String) superIter.next();
messageProps.put(key, superProperties.get(key));
}
// Don't allow super properties or referral properties to override these fields,
// but DO allow the caller to override them in their given properties.
final long time = System.currentTimeMillis() / 1000;
messageProps.put("time", time);
messageProps.put("distinct_id", getDistinctId());
if (null != properties) {
final Iterator<?> propIter = properties.keys();
while (propIter.hasNext()) {
final String key = (String) propIter.next();
messageProps.put(key, properties.get(key));
}
}
final AnalyticsMessages.EventDescription eventDescription =
new AnalyticsMessages.EventDescription(eventName, messageProps, mToken);
mMessages.eventsMessage(eventDescription);
} catch (final JSONException e) {
Log.e(LOGTAG, "Exception tracking event " + eventName, e);
}
}
/**
* Push all queued Mixpanel events and People Analytics changes to Mixpanel servers.
*
* <p>Events and People messages are pushed gradually throughout
* the lifetime of your application. This means that to ensure that all messages
* are sent to Mixpanel when your application is shut down, you will
* need to call flush() to let the Mixpanel library know it should
* send all remaining messages to the server. We strongly recommend
* placing a call to flush() in the onDestroy() method of
* your main application activity.
*/
public void flush() {
mMessages.postToServer();
}
/**
* Returns the string id currently being used to uniquely identify the user associated
* with events sent using {@link #track(String, JSONObject)}. Before any calls to
* {@link #identify(String)}, this will be an id automatically generated by the library.
*
* <p>The id returned by getDistinctId is independent of the distinct id used to identify
* any People Analytics properties in Mixpanel. To read and write that identifier,
* use {@link People#identify(String)} and {@link People#getDistinctId()}.
*
* @return The distinct id associated with event tracking
*
* @see #identify(String)
* @see People#getDistinctId()
*/
public String getDistinctId() {
return mPersistentIdentity.getEventsDistinctId();
}
/**
* Register properties that will be sent with every subsequent call to {@link #track(String, JSONObject)}.
*
* <p>SuperProperties are a collection of properties that will be sent with every event to Mixpanel,
* and persist beyond the lifetime of your application.
*
* <p>Setting a superProperty with registerSuperProperties will store a new superProperty,
* possibly overwriting any existing superProperty with the same name (to set a
* superProperty only if it is currently unset, use {@link #registerSuperPropertiesOnce(JSONObject)})
*
* <p>SuperProperties will persist even if your application is taken completely out of memory.
* to remove a superProperty, call {@link #unregisterSuperProperty(String)} or {@link #clearSuperProperties()}
*
* @param superProperties A JSONObject containing super properties to register
* @see #registerSuperPropertiesOnce(JSONObject)
* @see #unregisterSuperProperty(String)
* @see #clearSuperProperties()
*/
public void registerSuperProperties(JSONObject superProperties) {
mPersistentIdentity.registerSuperProperties(superProperties);
}
/**
* Remove a single superProperty, so that it will not be sent with future calls to {@link #track(String, JSONObject)}.
*
* <p>If there is a superProperty registered with the given name, it will be permanently
* removed from the existing superProperties.
* To clear all superProperties, use {@link #clearSuperProperties()}
*
* @param superPropertyName name of the property to unregister
* @see #registerSuperProperties(JSONObject)
*/
public void unregisterSuperProperty(String superPropertyName) {
mPersistentIdentity.unregisterSuperProperty(superPropertyName);
}
/**
* Register super properties for events, only if no other super property with the
* same names has already been registered.
*
* <p>Calling registerSuperPropertiesOnce will never overwrite existing properties.
*
* @param superProperties A JSONObject containing the super properties to register.
* @see #registerSuperProperties(JSONObject)
*/
public void registerSuperPropertiesOnce(JSONObject superProperties) {
mPersistentIdentity.registerSuperPropertiesOnce(superProperties);
}
/**
* Erase all currently registered superProperties.
*
* <p>Future tracking calls to Mixpanel (even those already queued up but not
* yet sent to Mixpanel servers) will not be associated with the superProperties registered
* before this call was made.
*
* <p>To remove a single superProperty, use {@link #unregisterSuperProperty(String)}
*
* @see #registerSuperProperties(JSONObject)
*/
public void clearSuperProperties() {
mPersistentIdentity.clearSuperProperties();
}
/**
* Returns a Mixpanel.People object that can be used to set and increment
* People Analytics properties.
*
* @return an instance of {@link People} that you can use to update
* records in Mixpanel People Analytics and manage Mixpanel Google Cloud Messaging notifications.
*/
public People getPeople() {
return mPeople;
}
/**
* Core interface for using Mixpanel People Analytics features.
* You can get an instance by calling {@link MixpanelAPI#getPeople()}
*
* <p>The People object is used to update properties in a user's People Analytics record,
* and to manage the receipt of push notifications sent via Mixpanel Engage.
* For this reason, it's important to call {@link #identify(String)} on the People
* object before you work with it. Once you call identify, the user identity will
* persist across stops and starts of your application, until you make another
* call to identify using a different id.
*
* A typical use case for the People object might look like this:
*
* <pre>
* {@code
*
* public class MainActivity extends Activity {
* MixpanelAPI mMixpanel;
*
* public void onCreate(Bundle saved) {
* mMixpanel = MixpanelAPI.getInstance(this, "YOUR MIXPANEL API TOKEN");
* mMixpanel.getPeople().identify("A UNIQUE ID FOR THIS USER");
* mMixpanel.getPeople().initPushHandling("YOUR 12 DIGIT GOOGLE SENDER API");
* ...
* }
*
* public void userUpdatedJobTitle(String newTitle) {
* mMixpanel.getPeople().set("Job Title", newTitle);
* ...
* }
*
* public void onDestroy() {
* mMixpanel.flush();
* super.onDestroy();
* }
* }
*
* }
* </pre>
*
* @see MixpanelAPI
*/
public interface People {
/**
* Associate future calls to {@link #set(JSONObject)}, {@link #increment(Map)},
* and {@link #initPushHandling(String)} with a particular People Analytics user.
*
* <p>All future calls to the People object will rely on this value to assign
* and increment properties. The user identification will persist across
* restarts of your application. We recommend calling
* People.identify as soon as you know the distinct id of the user.
*
* @param distinctId a String that uniquely identifies the user. Users identified with
* the same distinct id will be considered to be the same user in Mixpanel,
* across all platforms and devices. We recommend choosing a distinct id
* that is meaningful to your other systems (for example, a server-side account
* identifier), and using the same distinct id for both calls to People.identify
* and {@link MixpanelAPI#identify(String)}
*
* @see MixpanelAPI#identify(String)
*/
public void identify(String distinctId);
/**
* Sets a single property with the given name and value for this user.
* The given name and value will be assigned to the user in Mixpanel People Analytics,
* possibly overwriting an existing property with the same name.
*
* @param propertyName The name of the Mixpanel property. This must be a String, for example "Zip Code"
* @param value The value of the Mixpanel property. For "Zip Code", this value might be the String "90210"
*/
public void set(String propertyName, Object value);
/**
* Set a collection of properties on the identified user all at once.
*
* @param properties a JSONObject containing the collection of properties you wish to apply
* to the identified user. Each key in the JSONObject will be associated with
* a property name, and the value of that key will be assigned to the property.
*/
public void set(JSONObject properties);
/**
* Works just like {@link People#set(String, Object)}, except it will not overwrite existing property values. This is useful for properties like "First login date".
*
* @param propertyName The name of the Mixpanel property. This must be a String, for example "Zip Code"
* @param value The value of the Mixpanel property. For "Zip Code", this value might be the String "90210"
*/
public void setOnce(String propertyName, Object value);
/**
* Like {@link People#set(String, Object)}, but will not set properties that already exist on a record.
*
* @param properties a JSONObject containing the collection of properties you wish to apply
* to the identified user. Each key in the JSONObject will be associated with
* a property name, and the value of that key will be assigned to the property.
*/
public void setOnce(JSONObject properties);
/**
* Add the given amount to an existing property on the identified user. If the user does not already
* have the associated property, the amount will be added to zero. To reduce a property,
* provide a negative number for the value.
*
* @param name the People Analytics property that should have its value changed
* @param increment the amount to be added to the current value of the named property
*
* @see #increment(Map)
*/
public void increment(String name, double increment);
/**
* Change the existing values of multiple People Analytics properties at once.
*
* <p>If the user does not already have the associated property, the amount will
* be added to zero. To reduce a property, provide a negative number for the value.
*
* @param properties A map of String properties names to Long amounts. Each
* property associated with a name in the map will have its value changed by the given amount
*
* @see #increment(String, double)
*/
public void increment(Map<String, ? extends Number> properties);
/**
* Appends a value to a list-valued property. If the property does not currently exist,
* it will be created as a list of one element. If the property does exist and doesn't
* currently have a list value, the append will be ignored.
* @param name the People Analytics property that should have it's value appended to
* @param value the new value that will appear at the end of the property's list
*/
public void append(String name, Object value);
/**
* Adds values to a list-valued property only if they are not already present in the list.
* If the property does not currently exist, it will be created with the given list as it's value.
* If the property exists and is not list-valued, the union will be ignored.
*
* @param name name of the list-valued property to set or modify
* @param value an array of values to add to the property value if not already present
*/
void union(String name, JSONArray value);
/**
* permanently removes the property with the given name from the user's profile
* @param name name of a property to unset
*/
void unset(String name);
/**
* Track a revenue transaction for the identified people profile.
*
* @param amount the amount of money exchanged. Positive amounts represent purchases or income from the customer, negative amounts represent refunds or payments to the customer.
* @param properties an optional collection of properties to associate with this transaction.
*/
public void trackCharge(double amount, JSONObject properties);
/**
* Permanently clear the whole transaction history for the identified people profile.
*/
public void clearCharges();
/**
* Permanently deletes the identified user's record from People Analytics.
*
* <p>Calling deleteUser deletes an entire record completely. Any future calls
* to People Analytics using the same distinct id will create and store new values.
*/
public void deleteUser();
/**
* Enable end-to-end Google Cloud Messaging (GCM) from Mixpanel.
*
* <p>Calling this method will allow the Mixpanel libraries to handle GCM user
* registration, and enable Mixpanel to show alerts when GCM messages arrive.
*
* <p>To use {@link People#initPushHandling}, you will need to add the following to your application manifest:
*
* <pre>
* {@code
* <receiver android:name="com.mixpanel.android.mpmetrics.GCMReceiver"
* android:permission="com.google.android.c2dm.permission.SEND" >
* <intent-filter>
* <action android:name="com.google.android.c2dm.intent.RECEIVE" />
* <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
* <category android:name="YOUR_PACKAGE_NAME" />
* </intent-filter>
* </receiver>
* }
* </pre>
*
* Be sure to replace "YOUR_PACKAGE_NAME" with the name of your package. For
* more information and a list of necessary permissions, see {@link GCMReceiver}.
*
* <p>If you're planning to use end-to-end support for Messaging, we recommend you
* call this method immediately after calling {@link People#identify(String)}, likely
* early in your application's life cycle. (for example, in the onCreate method of your
* main application activity.)
*
* <p>Calls to {@link People#initPushHandling} should not be mixed with calls to
* {@link #setPushRegistrationId(String)} and {@link #clearPushRegistrationId()}
* in the same application. Application authors should choose one or the other
* method for handling Mixpanel GCM messages.
*
* @param senderID of the Google API Project that registered for Google Cloud Messaging
* You can find your ID by looking at the URL of in your Google API Console
* at https://code.google.com/apis/console/; it is the twelve digit number after
* after "#project:" in the URL address bar on console pages.
*
* @see com.mixpanel.android.mpmetrics.GCMReceiver
* @see <a href="https://mixpanel.com/docs/people-analytics/android-push">Getting Started with Android Push Notifications</a>
*/
public void initPushHandling(String senderID);
/**
* Manually send a Google Cloud Messaging registration id to Mixpanel.
*
* <p>If you are handling Google Cloud Messages in your own application, but would like to
* allow Mixpanel to handle messages originating from Mixpanel campaigns, you should
* call setPushRegistrationId with the "registration_id" property of the
* com.google.android.c2dm.intent.REGISTRATION intent when it is received.
*
* <p>setPushRegistrationId should only be called after {@link #identify(String)} has been called.
*
* <p>Calls to {@link People#setPushRegistrationId} should not be mixed with calls to {@link #initPushHandling(String)}
* in the same application. In addition, applications that call setPushRegistrationId
* should also call {@link #clearPushRegistrationId()} when they receive an intent to unregister
* (a com.google.android.c2dm.intent.REGISTRATION intent with getStringExtra("unregistered") != null)
*
* @param registrationId the result of calling intent.getStringExtra("registration_id")
* on a com.google.android.c2dm.intent.REGISTRATION intent
*
* @see #initPushHandling(String)
* @see #clearPushRegistrationId()
*/
public void setPushRegistrationId(String registrationId);
/**
* Manually clear a current Google Cloud Messaging registration id from Mixpanel.
*
* <p>If you are handling Google Cloud Messages in your own application, you should
* call this method when your application receives a com.google.android.c2dm.intent.REGISTRATION
* with getStringExtra("unregistered") != null
*
* <p>{@link People#clearPushRegistrationId} should only be called after {@link #identify(String)} has been called.
*
* <p>In general, all applications that call {@link #setPushRegistrationId(String)} should include a call to
* removePushRegistrationId, and no applications that call {@link #initPushHandling(String)} should
* call removePushRegistrationId
*/
public void clearPushRegistrationId();
/**
* Returns the string id currently being used to uniquely identify the user associated
* with events sent using {@link People#set(String, Object)} and {@link People#increment(String, double)}.
* If no calls to {@link People#identify(String)} have been made, this method will return null.
*
* <p>The id returned by getDistinctId is independent of the distinct id used to identify
* any events sent with {@link MixpanelAPI#track(String, JSONObject)}. To read and write that identifier,
* use {@link MixpanelAPI#identify(String)} and {@link MixpanelAPI#getDistinctId()}.
*
* @return The distinct id associated with updates to People Analytics
*
* @see People#identify(String)
* @see MixpanelAPI#getDistinctId()
*/
public String getDistinctId();
/**
* If a survey is currently available, this method will launch an activity that shows a
* survey to the user and then send the responses to Mixpanel.
*
* <p>The survey activity will use the root of the given view to take a screenshot
* for its background.
*
* <p>It is safe to call this method any time you want to potentially display an in app notification.
* This method will be a no-op if there is already a survey or in app notification being displayed.
* Thus, if you have both surveys and in app notification campaigns built in Mixpanel, you may call
* both this and {@link People#showNotificationIfAvailable(Activity)} right after each other, and
* only one of them will be displayed.
*
* <p>This method is a no-op in environments with
* Android API before Ice Cream Sandwich/API level 14.
*
* @param parent the Activity that this Survey will be displayed on top of. A snapshot will be
* taken of parent to be used as a blurred background.
*/
public void showSurveyIfAvailable(Activity parent);
/**
* Shows an in app not3ification to the user if one is available. If the notification
* is a mini notification, this method will attach and remove a Fragment to parent.
* The lifecycle of the Fragment will be handled entirely by the Mixpanel library.
*
* <p>If the notification is a takeover notification, a SurveyActivity will be launched to
* display the Takeover notification.
*
* <p>It is safe to call this method any time you want to potentially display an in app notification.
* This method will be a no-op if there is already a survey or in app notification being displayed.
* Thus, if you have both surveys and in app notification campaigns built in Mixpanel, you may call
* both this and {@link People#showSurveyIfAvailable(Activity)} right after each other, and
* only one of them will be displayed.
*
* <p>This method is a no-op in environments with
* Android API before Ice Cream Sandwich/API level 14.
*
* @param parent the Activity that the mini notification will be displayed in, or the Activity
* that will be used to launch SurveyActivity for the takeover notification.
*/
public void showNotificationIfAvailable(Activity parent);
/**
* Returns a survey object if one is available and being held by the library, or null if
* no survey is currently available. Callers who want to display surveys with their own UI
* should call this method to get the Survey data. A given survey will be returned only once
* from this method, so callers should be ready to consume any non-null return value.
*
* <p>This function will always return quickly, and will not cause any communication with
* Mixpanel's servers, so it is safe to call this from the UI thread.
*
* @return a Survey object if one is available, null otherwise.
*/
public Survey getSurveyIfAvailable();
/**
* Returns an InAppNotification object if one is available and being held by the library, or null if
* no survey is currently available. Callers who want to display in app notifications should call this
* method periodically. A given InAppNotification will be returned only once from this method, so callers
* should be ready to consume any non-null return value.
*
* <p>This function will return quickly, and will not cause any communication with
* Mixpanel's servers, so it is safe to call this from the UI thread.
*
* @return an InAppNotification object if one is available, null otherwise.
*/
public InAppNotification getNotificationIfAvailable();
/**
* Return an instance of Mixpanel people with a temporary distinct id.
* This is used by Mixpanel Surveys but is likely not needed in your code.
*/
public People withIdentity(String distinctId);
/**
* Adds a new listener that will receive a callback when new updates from Mixpanel
* (like surveys or in app notifications) are discovered.
*
* <p>The given listener will be called when a new batch of updates is detected. Handlers
* should be prepared to handle the callback on an arbitrary thread.
*
* <p>Once this listener is called, you may call {@link People#getSurveyIfAvailable()}
* or {@link People#getNotificationIfAvailable()}
* to retrieve a Survey or InAppNotification object. However, if you have multiple
* listeners registered, one listener may have consumed the available Survey or
* InAppNotification, and so the other listeners may obtain null when calling
* {@link People#getSurveyIfAvailable()} or {@link People#getNotificationIfAvailable()}.
*
* @param listener the listener to add
*/
public void addOnMixpanelUpdatesReceivedListener(OnMixpanelUpdatesReceivedListener listener);
/**
* Removes a listener previously registered with addOnMixpanelUpdatesReceivedListener.
*
* @param listener the listener to add
*/
public void removeOnMixpanelUpdatesReceivedListener(OnMixpanelUpdatesReceivedListener listener);
/**
* @deprecated Use showSurveyIfAvailable() instead.
*/
@Deprecated
public void showSurvey(Survey s, Activity parent);
/**
* @deprecated Use getSurveyIfAvailable() instead.
*/
@Deprecated
public void checkForSurvey(SurveyCallbacks callbacks);
/**
* @deprecated Use getSurveyIfAvailable() instead.
*/
@Deprecated
public void checkForSurvey(SurveyCallbacks callbacks, Activity parent);
}
/**
* Manage verbose logging about messages sent to Mixpanel.
*
* <p>Under ordinary circumstances, the Mixpanel library will only send messages
* to the log when errors occur. However, after logPosts is called, Mixpanel will
* send messages describing it's communication with the Mixpanel servers to
* the system log.
*
* <p>Mixpanel will log its verbose messages tag "MixpanelAPI" with priority I("Information")
*/
@Deprecated
public void logPosts() {
Log.i(
LOGTAG,
"MixpanelAPI.logPosts() is deprecated.\n" +
" To get verbose debug level logging, add\n" +
" <meta-data android:name=\"com.mixpanel.android.MPConfig.EnableDebugLogging\" />\n" +
" to the <application> section of your AndroidManifest.xml."
);
}
/**
* Attempt to register MixpanelActivityLifecycleCallbacks to the application's event lifecycle.
* Once registered, we can automatically check for and show surveys and in app notifications
* when any Activity is opened.
*
* This is only available if the android version is >= 14. You can disable this by setting
* com.mixpanel.android.MPConfig.AutoShowMixpanelUpdates to false in your AndroidManifest.xml
*
* This function is automatically called when the library is initialized unless you explicitly
* set com.mixpanel.android.MPConfig.AutoShowMixpanelUpdates to false in your AndroidManifest.xml
*/
/* package */
@TargetApi(14)
void registerMixpanelActivityLifecycleCallbacks() {
if (android.os.Build.VERSION.SDK_INT >= 14 && mConfig.getAutoShowMixpanelUpdates()) {
if (mContext.getApplicationContext() instanceof Application) {
final Application app = (Application) mContext.getApplicationContext();
app.registerActivityLifecycleCallbacks((new MixpanelActivityLifecycleCallbacks(this)));
} else {
if (MPConfig.DEBUG) Log.d(LOGTAG, "Context is NOT instanceof Application, AutoShowMixpanelUpdates will be disabled.");
}
}
}
// Package-level access. Used (at least) by GCMReceiver
// when OS-level events occur.
/* package */ interface InstanceProcessor {
public void process(MixpanelAPI m);
}
/* package */ static void allInstances(InstanceProcessor processor) {
synchronized (sInstanceMap) {
for (final Map<Context, MixpanelAPI> contextInstances:sInstanceMap.values()) {
for (final MixpanelAPI instance:contextInstances.values()) {
processor.process(instance);
}
}
}
}
////////////////////////////////////////////////////////////////////
// Conveniences for testing. These methods should not be called by
// non-test client code.
/* package */ AnalyticsMessages getAnalyticsMessages() {
return AnalyticsMessages.getInstance(mContext);
}
/* package */ MPConfig getConfig() {
return MPConfig.getInstance(mContext);
}
/* package */ PersistentIdentity getPersistentIdentity(final Context context, Future<SharedPreferences> referrerPreferences, final String token) {
final SharedPreferencesLoader.OnPrefsLoadedListener listener = new SharedPreferencesLoader.OnPrefsLoadedListener() {
@Override
public void onPrefsLoaded(SharedPreferences preferences) {
final JSONArray records = PersistentIdentity.waitingPeopleRecordsForSending(preferences);
if (null != records) {
sendAllPeopleRecords(records);
}
}
};
final String prefsName = "com.mixpanel.android.mpmetrics.MixpanelAPI_" + token;
final Future<SharedPreferences> storedPreferences = sPrefsLoader.loadPreferences(context, prefsName, listener);
return new PersistentIdentity(referrerPreferences, storedPreferences);
}
/* package */ DecideUpdates constructDecideUpdates(final String token, final String peopleId, final DecideUpdates.OnNewResultsListener listener) {
return new DecideUpdates(token, peopleId, listener);
}
/* package */ void clearPreferences() {
// Will clear distinct_ids, superProperties,
// and waiting People Analytics properties. Will have no effect
// on messages already queued to send with AnalyticsMessages.
mPersistentIdentity.clearPreferences();
}
///////////////////////
private class PeopleImpl implements People {
@Override
public void identify(String distinctId) {
mPersistentIdentity.setPeopleDistinctId(distinctId);
if (null != mDecideUpdates && !mDecideUpdates.getDistinctId().equals(distinctId)) {
mDecideUpdates.destroy();
mDecideUpdates = null;
}
if (null == mDecideUpdates) {
mDecideUpdates = constructDecideUpdates(mToken, distinctId, mUpdatesListener);
mMessages.installDecideCheck(mDecideUpdates);
}
pushWaitingPeopleRecord();
}
@Override
public void set(JSONObject properties) {
try {
final JSONObject sendProperties = new JSONObject();
sendProperties.put("$android_lib_version", MPConfig.VERSION);
sendProperties.put("$android_os", "Android");
sendProperties.put("$android_os_version", Build.VERSION.RELEASE == null ? "UNKNOWN" : Build.VERSION.RELEASE);
sendProperties.put("$android_manufacturer", Build.MANUFACTURER == null ? "UNKNOWN" : Build.MANUFACTURER);
sendProperties.put("$android_brand", Build.BRAND == null ? "UNKNOWN" : Build.BRAND);
sendProperties.put("$android_model", Build.MODEL == null ? "UNKNOWN" : Build.MODEL);
for (final Iterator<?> iter = properties.keys(); iter.hasNext();) {
final String key = (String) iter.next();
sendProperties.put(key, properties.get(key));
}
final JSONObject message = stdPeopleMessage("$set", sendProperties);
recordPeopleMessage(message);
} catch (final JSONException e) {
Log.e(LOGTAG, "Exception setting people properties", e);
}
}
@Override
public void set(String property, Object value) {
try {
set(new JSONObject().put(property, value));
} catch (final JSONException e) {
Log.e(LOGTAG, "set", e);
}
}
@Override
public void setOnce(JSONObject properties) {
try {
final JSONObject message = stdPeopleMessage("$set_once", properties);
recordPeopleMessage(message);
} catch (final JSONException e) {
Log.e(LOGTAG, "Exception setting people properties");
}
}
@Override
public void setOnce(String property, Object value) {
try {
setOnce(new JSONObject().put(property, value));
} catch (final JSONException e) {
Log.e(LOGTAG, "set", e);
}
}
@Override
public void increment(Map<String, ? extends Number> properties) {
final JSONObject json = new JSONObject(properties);
try {
final JSONObject message = stdPeopleMessage("$add", json);
recordPeopleMessage(message);
} catch (final JSONException e) {
Log.e(LOGTAG, "Exception incrementing properties", e);
}
}
@Override
public void increment(String property, double value) {
final Map<String, Double> map = new HashMap<String, Double>();
map.put(property, value);
increment(map);
}
@Override
public void append(String name, Object value) {
try {
final JSONObject properties = new JSONObject();
properties.put(name, value);
final JSONObject message = stdPeopleMessage("$append", properties);
recordPeopleMessage(message);
} catch (final JSONException e) {
Log.e(LOGTAG, "Exception appending a property", e);
}
}
@Override
public void union(String name, JSONArray value) {
try {
final JSONObject properties = new JSONObject();
properties.put(name, value);
final JSONObject message = stdPeopleMessage("$union", properties);
recordPeopleMessage(message);
} catch (final JSONException e) {
Log.e(LOGTAG, "Exception unioning a property");
}
}
@Override
public void unset(String name) {
try {
final JSONArray names = new JSONArray();
names.put(name);
final JSONObject message = stdPeopleMessage("$unset", names);
recordPeopleMessage(message);
} catch (final JSONException e) {
Log.e(LOGTAG, "Exception unsetting a property", e);
}
}
@Override
@Deprecated
public void checkForSurvey(final SurveyCallbacks callbacks) {
if (null == callbacks) {
Log.i(LOGTAG, "Skipping survey check because callback is null.");
return;
}
final Survey found = getSurveyIfAvailable();
callbacks.foundSurvey(found);
}
@Override
@Deprecated
public void checkForSurvey(final SurveyCallbacks callbacks, final Activity parentActivity) {
// Originally this call pre-computed UI chrome while it was waiting for the check to run.
// Since modern checks run asynchronously, it's useless nowdays.
checkForSurvey(callbacks);
}
@Override
public InAppNotification getNotificationIfAvailable() {
if (null == getDistinctId()) {
return null;
}
return mDecideUpdates.getNotification(mConfig.getTestMode());
}
@Override
public Survey getSurveyIfAvailable() {
if (null == getDistinctId()) {
return null;
}
return mDecideUpdates.getSurvey(mConfig.getTestMode());
}
@Override
@Deprecated
public void showSurvey(final Survey survey, final Activity parent) {
showGivenOrAvailableSurvey(survey, parent);
}
@Override
public void showSurveyIfAvailable(final Activity parent) {
if (Build.VERSION.SDK_INT < 14) {
return;
}
showGivenOrAvailableSurvey(null, parent);
}
@Override
public void showNotificationIfAvailable(final Activity parent) {
if (Build.VERSION.SDK_INT < 14) {
return;
}
parent.runOnUiThread(new Runnable() {
@Override
@TargetApi(14)
public void run() {
final ReentrantLock lock = UpdateDisplayState.getLockObject();
lock.lock();
try {
if (UpdateDisplayState.hasCurrentProposal()) {
return; // Already being used.
}
InAppNotification notif = getNotificationIfAvailable();
if (null == notif) {
return; // Nothing to show
}
final InAppNotification.Type inAppType = notif.getType();
if (inAppType == InAppNotification.Type.TAKEOVER && ! ConfigurationChecker.checkSurveyActivityAvailable(parent.getApplicationContext())) {
return; // Can't show due to config.
}
final int highlightColor = ActivityImageUtils.getHighlightColorFromBackground(parent);
final UpdateDisplayState.DisplayState.InAppNotificationState proposal =
new UpdateDisplayState.DisplayState.InAppNotificationState(notif, highlightColor);
final int intentId = UpdateDisplayState.proposeDisplay(proposal, getDistinctId(), mToken);
assert intentId > 0; // Since we're holding the lock and !hasCurrentProposal
switch (inAppType) {
case MINI: {
final UpdateDisplayState claimed = UpdateDisplayState.claimDisplayState(intentId);
InAppFragment inapp = new InAppFragment();
inapp.setDisplayState(intentId, (UpdateDisplayState.DisplayState.InAppNotificationState) claimed.getDisplayState());
inapp.setRetainInstance(true);
FragmentTransaction transaction = parent.getFragmentManager().beginTransaction();
transaction.setCustomAnimations(0, R.anim.com_mixpanel_android_slide_down);
transaction.add(android.R.id.content, inapp);
transaction.commit();
}
break;
case TAKEOVER: {
final Intent intent = new Intent(parent.getApplicationContext(), SurveyActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
intent.putExtra(SurveyActivity.INTENT_ID_KEY, intentId);
parent.startActivity(intent);
}
break;
default:
Log.e(LOGTAG, "Unrecognized notification type " + inAppType + " can't be shown");
}
if (!mConfig.getTestMode()) {
trackNotificationSeen(notif);
}
} finally {
lock.unlock();
}
} // run()
private void trackNotificationSeen(InAppNotification notif) {
track("$campaign_delivery", notif.getCampaignProperties());
final MixpanelAPI.People people = getPeople().withIdentity(getDistinctId());
final DateFormat dateFormat = new SimpleDateFormat(ENGAGE_DATE_FORMAT_STRING);
final JSONObject notifProperties = notif.getCampaignProperties();
try {
notifProperties.put("$time", dateFormat.format(new Date()));
} catch (JSONException e) {
Log.e(LOGTAG, "Exception trying to track an in app notification seen", e);
}
people.append("$campaigns", notif.getId());
people.append("$notifications", notifProperties);
}
});
}
@Override
public void trackCharge(double amount, JSONObject properties) {
final Date now = new Date();
final DateFormat dateFormat = new SimpleDateFormat(ENGAGE_DATE_FORMAT_STRING);
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
final JSONObject transactionValue = new JSONObject();
transactionValue.put("$amount", amount);
transactionValue.put("$time", dateFormat.format(now));
if (null != properties) {
for (final Iterator<?> iter = properties.keys(); iter.hasNext();) {
final String key = (String) iter.next();
transactionValue.put(key, properties.get(key));
}
}
this.append("$transactions", transactionValue);
} catch (final JSONException e) {
Log.e(LOGTAG, "Exception creating new charge", e);
}
}
/**
* Permanently clear the whole transaction history for the identified people profile.
*/
@Override
public void clearCharges() {
this.unset("$transactions");
}
@Override
public void deleteUser() {
try {
final JSONObject message = stdPeopleMessage("$delete", JSONObject.NULL);
recordPeopleMessage(message);
} catch (final JSONException e) {
Log.e(LOGTAG, "Exception deleting a user");
}
}
@Override
public void setPushRegistrationId(String registrationId) {
if (getDistinctId() == null) {
return;
}
mPersistentIdentity.storePushId(registrationId);
try {
union("$android_devices", new JSONArray("[" + registrationId + "]"));
} catch (final JSONException e) {
Log.e(LOGTAG, "set push registration id error", e);
}
}
@Override
public void clearPushRegistrationId() {
mPersistentIdentity.clearPushId();
set("$android_devices", new JSONArray());
}
@Override
public void initPushHandling(String senderID) {
if (! ConfigurationChecker.checkPushConfiguration(mContext) ) {
Log.i(LOGTAG, "Can't start push notification service. Push notifications will not work.");
Log.i(LOGTAG, "See log tagged " + ConfigurationChecker.LOGTAG + " above for details.");
}
else { // Configuration is good for push notifications
final String pushId = mPersistentIdentity.getPushId();
if (pushId == null) {
if (MPConfig.DEBUG) Log.d(LOGTAG, "Registering a new push id");
try {
final Intent registrationIntent = new Intent("com.google.android.c2dm.intent.REGISTER");
registrationIntent.putExtra("app", PendingIntent.getBroadcast(mContext, 0, new Intent(), 0)); // boilerplate
registrationIntent.putExtra("sender", senderID);
mContext.startService(registrationIntent);
} catch (final SecurityException e) {
Log.w(LOGTAG, e);
}
} else {
MixpanelAPI.allInstances(new InstanceProcessor() {
@Override
public void process(MixpanelAPI api) {
if (MPConfig.DEBUG) Log.d(LOGTAG, "Using existing pushId " + pushId);
api.getPeople().setPushRegistrationId(pushId);
}
});
}
}// endelse
}
@Override
public String getDistinctId() {
return mPersistentIdentity.getPeopleDistinctId();
}
@Override
public People withIdentity(final String distinctId) {
if (null == distinctId) {
return null;
}
return new PeopleImpl() {
@Override
public String getDistinctId() {
return distinctId;
}
@Override
public void identify(String distinctId) {
throw new RuntimeException("This MixpanelPeople object has a fixed, constant distinctId");
}
};
}
@Override
public void addOnMixpanelUpdatesReceivedListener(final OnMixpanelUpdatesReceivedListener listener) {
mUpdatesListener.addOnMixpanelUpdatesReceivedListener(listener);
}
@Override
public void removeOnMixpanelUpdatesReceivedListener(final OnMixpanelUpdatesReceivedListener listener) {
mUpdatesListener.removeOnMixpanelUpdatesReceivedListener(listener);
}
public JSONObject stdPeopleMessage(String actionType, Object properties)
throws JSONException {
final JSONObject dataObj = new JSONObject();
final String distinctId = getDistinctId();
dataObj.put(actionType, properties);
dataObj.put("$token", mToken);
dataObj.put("$time", System.currentTimeMillis());
if (null != distinctId) {
dataObj.put("$distinct_id", getDistinctId());
}
return dataObj;
}
private void showGivenOrAvailableSurvey(final Survey surveyOrNull, final Activity parent) {
// Showing surveys is not supported before Ice Cream Sandwich
if (Build.VERSION.SDK_INT < 14) {
return;
}
if (! ConfigurationChecker.checkSurveyActivityAvailable(parent.getApplicationContext())) {
return;
}
BackgroundCapture.OnBackgroundCapturedListener listener = null;
final ReentrantLock lock = UpdateDisplayState.getLockObject();
lock.lock();
try {
if (UpdateDisplayState.hasCurrentProposal()) {
return; // Already being used.
}
Survey toShow = surveyOrNull;
if (null == toShow) {
toShow = getSurveyIfAvailable();
}
if (null == toShow) {
return; // Nothing to show
}
final UpdateDisplayState.DisplayState.SurveyState surveyDisplay =
new UpdateDisplayState.DisplayState.SurveyState(toShow);
final int intentId = UpdateDisplayState.proposeDisplay(surveyDisplay, getDistinctId(), mToken);
assert intentId > 0; // Since we hold the lock, and !hasCurrentProposal
listener = new BackgroundCapture.OnBackgroundCapturedListener() {
@Override
public void onBackgroundCaptured(Bitmap bitmapCaptured, int highlightColorCaptured) {
surveyDisplay.setBackground(bitmapCaptured);
surveyDisplay.setHighlightColor(highlightColorCaptured);
final Intent surveyIntent = new Intent(parent.getApplicationContext(), SurveyActivity.class);
surveyIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
surveyIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
surveyIntent.putExtra(SurveyActivity.INTENT_ID_KEY, intentId);
parent.startActivity(surveyIntent);
}
};
} finally {
lock.unlock();
}
assert listener != null;
BackgroundCapture.captureBackground(parent, listener);
}
}// PeopleImpl
private class UpdatesListener implements DecideUpdates.OnNewResultsListener, Runnable {
@Override
public void onNewResults(final String distinctId) {
mExecutor.execute(this);
}
public synchronized void addOnMixpanelUpdatesReceivedListener(OnMixpanelUpdatesReceivedListener listener) {
// Workaround for a race between checking for updates using getSurveyIfAvailable() and getNotificationIfAvailable()
// and registering a listener.
synchronized (mDecideUpdates) {
if (mDecideUpdates.hasUpdatesAvailable()) {
onNewResults(mDecideUpdates.getDistinctId());
}
}
mListeners.add(listener);
}
public synchronized void removeOnMixpanelUpdatesReceivedListener(OnMixpanelUpdatesReceivedListener listener) {
mListeners.remove(listener);
}
public synchronized void run() {
// It's possible that by the time this has run the updates we detected are no longer
// present, which is ok.
Log.e(LOGTAG, "UPDATE RECIEVED, INFORMING " + mListeners.size() + " LISTENERS");
for (OnMixpanelUpdatesReceivedListener listener: mListeners) {
listener.onMixpanelUpdatesReceived();
}
}
private final Set<OnMixpanelUpdatesReceivedListener> mListeners = new HashSet<OnMixpanelUpdatesReceivedListener>();
private final Executor mExecutor = Executors.newSingleThreadExecutor();
}
////////////////////////////////////////////////////
private void recordPeopleMessage(JSONObject message) {
if (message.has("$distinct_id")) {
mMessages.peopleMessage(message);
} else {
mPersistentIdentity.storeWaitingPeopleRecord(message);
}
}
private void pushWaitingPeopleRecord() {
final JSONArray records = mPersistentIdentity.waitingPeopleRecordsForSending();
if (null != records) {
sendAllPeopleRecords(records);
}
}
// MUST BE THREAD SAFE. Called from crazy places. mPersistentIdentity may not exist
// when this is called (from its crazy thread)
private void sendAllPeopleRecords(JSONArray records) {
for (int i = 0; i < records.length(); i++) {
try {
final JSONObject message = records.getJSONObject(i);
mMessages.peopleMessage(message);
} catch (final JSONException e) {
Log.e(LOGTAG, "Malformed people record stored pending identity, will not send it.", e);
}
}
}
private static final String LOGTAG = "MixpanelAPI";
private static final String ENGAGE_DATE_FORMAT_STRING = "yyyy-MM-dd'T'HH:mm:ss";
private final Context mContext;
private final AnalyticsMessages mMessages;
private final MPConfig mConfig;
private final String mToken;
private final PeopleImpl mPeople;
private final PersistentIdentity mPersistentIdentity;
private final UpdatesListener mUpdatesListener;
private DecideUpdates mDecideUpdates;
// Maps each token to a singleton MixpanelAPI instance
private static final Map<String, Map<Context, MixpanelAPI>> sInstanceMap = new HashMap<String, Map<Context, MixpanelAPI>>();
private static final SharedPreferencesLoader sPrefsLoader = new SharedPreferencesLoader();
private static Future<SharedPreferences> sReferrerPrefs;
}
| Android App Version as property
| src/main/java/com/mixpanel/android/mpmetrics/MixpanelAPI.java | Android App Version as property | <ide><path>rc/main/java/com/mixpanel/android/mpmetrics/MixpanelAPI.java
<ide> import android.content.Context;
<ide> import android.content.Intent;
<ide> import android.content.SharedPreferences;
<add>import android.content.pm.PackageInfo;
<add>import android.content.pm.PackageManager;
<ide> import android.graphics.Bitmap;
<ide> import android.os.Build;
<ide> import android.util.Log;
<ide> sendProperties.put("$android_lib_version", MPConfig.VERSION);
<ide> sendProperties.put("$android_os", "Android");
<ide> sendProperties.put("$android_os_version", Build.VERSION.RELEASE == null ? "UNKNOWN" : Build.VERSION.RELEASE);
<add> try {
<add> PackageManager manager = mContext.getPackageManager();
<add> PackageInfo info = manager.getPackageInfo(mContext.getPackageName(), 0);
<add> sendProperties.put("$android_app_version", info.versionName);
<add> } catch (PackageManager.NameNotFoundException e) {
<add> Log.e(LOGTAG, "Exception getting app version name", e);
<add> }
<ide> sendProperties.put("$android_manufacturer", Build.MANUFACTURER == null ? "UNKNOWN" : Build.MANUFACTURER);
<ide> sendProperties.put("$android_brand", Build.BRAND == null ? "UNKNOWN" : Build.BRAND);
<ide> sendProperties.put("$android_model", Build.MODEL == null ? "UNKNOWN" : Build.MODEL); |
|
Java | apache-2.0 | 2460d2d00f9c73ab4d9b4f668452f89a66fa7d08 | 0 | ol-loginov/intellij-community,ryano144/intellij-community,ahb0327/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,semonte/intellij-community,izonder/intellij-community,slisson/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,holmes/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,asedunov/intellij-community,hurricup/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,samthor/intellij-community,asedunov/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,allotria/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,hurricup/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,da1z/intellij-community,fitermay/intellij-community,caot/intellij-community,izonder/intellij-community,apixandru/intellij-community,FHannes/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,slisson/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,TangHao1987/intellij-community,consulo/consulo,semonte/intellij-community,fnouama/intellij-community,robovm/robovm-studio,amith01994/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,vladmm/intellij-community,FHannes/intellij-community,samthor/intellij-community,FHannes/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,asedunov/intellij-community,robovm/robovm-studio,youdonghai/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,salguarnieri/intellij-community,ernestp/consulo,asedunov/intellij-community,robovm/robovm-studio,supersven/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,diorcety/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,clumsy/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,Lekanich/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,amith01994/intellij-community,petteyg/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,clumsy/intellij-community,izonder/intellij-community,dslomov/intellij-community,ryano144/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,hurricup/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,izonder/intellij-community,kdwink/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,pwoodworth/intellij-community,suncycheng/intellij-community,kool79/intellij-community,samthor/intellij-community,slisson/intellij-community,caot/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,asedunov/intellij-community,fitermay/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,supersven/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,da1z/intellij-community,nicolargo/intellij-community,tmpgit/intellij-community,supersven/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,kool79/intellij-community,signed/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,ryano144/intellij-community,kool79/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,caot/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,samthor/intellij-community,blademainer/intellij-community,petteyg/intellij-community,caot/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,da1z/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,holmes/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,tmpgit/intellij-community,caot/intellij-community,kool79/intellij-community,robovm/robovm-studio,xfournet/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,apixandru/intellij-community,hurricup/intellij-community,holmes/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,supersven/intellij-community,izonder/intellij-community,asedunov/intellij-community,samthor/intellij-community,fnouama/intellij-community,fitermay/intellij-community,blademainer/intellij-community,consulo/consulo,mglukhikh/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,ryano144/intellij-community,kdwink/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,tmpgit/intellij-community,signed/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,ernestp/consulo,TangHao1987/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,alphafoobar/intellij-community,caot/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,nicolargo/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,robovm/robovm-studio,youdonghai/intellij-community,vladmm/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,jagguli/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,consulo/consulo,signed/intellij-community,supersven/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,blademainer/intellij-community,consulo/consulo,Lekanich/intellij-community,holmes/intellij-community,amith01994/intellij-community,blademainer/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,kdwink/intellij-community,samthor/intellij-community,akosyakov/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,fitermay/intellij-community,retomerz/intellij-community,signed/intellij-community,retomerz/intellij-community,robovm/robovm-studio,caot/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,holmes/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,signed/intellij-community,akosyakov/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,slisson/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,fnouama/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,ernestp/consulo,holmes/intellij-community,fitermay/intellij-community,allotria/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,adedayo/intellij-community,retomerz/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,petteyg/intellij-community,allotria/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,signed/intellij-community,clumsy/intellij-community,adedayo/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,amith01994/intellij-community,izonder/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,consulo/consulo,Lekanich/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,apixandru/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,jagguli/intellij-community,signed/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,kool79/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,adedayo/intellij-community,clumsy/intellij-community,pwoodworth/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,ernestp/consulo,vvv1559/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,orekyuu/intellij-community,da1z/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,semonte/intellij-community,ryano144/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,da1z/intellij-community,fitermay/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,izonder/intellij-community,asedunov/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,da1z/intellij-community,petteyg/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,blademainer/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,muntasirsyed/intellij-community,adedayo/intellij-community,apixandru/intellij-community,jagguli/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,samthor/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,xfournet/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,fnouama/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,ernestp/consulo,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,diorcety/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,ryano144/intellij-community,holmes/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,izonder/intellij-community,nicolargo/intellij-community,ernestp/consulo,MER-GROUP/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,fnouama/intellij-community,retomerz/intellij-community,semonte/intellij-community,wreckJ/intellij-community,samthor/intellij-community,allotria/intellij-community,allotria/intellij-community,slisson/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,asedunov/intellij-community,vladmm/intellij-community,semonte/intellij-community,signed/intellij-community,robovm/robovm-studio,signed/intellij-community,pwoodworth/intellij-community,caot/intellij-community,Lekanich/intellij-community,samthor/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,signed/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,consulo/consulo,ibinti/intellij-community,apixandru/intellij-community,kdwink/intellij-community,petteyg/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,supersven/intellij-community,semonte/intellij-community,youdonghai/intellij-community,kool79/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,FHannes/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,hurricup/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,petteyg/intellij-community,supersven/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,kool79/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,kdwink/intellij-community,dslomov/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,caot/intellij-community,vladmm/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,Lekanich/intellij-community | /*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.util;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.util.io.URLUtil;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import sun.reflect.Reflection;
import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@Deprecated
public class ImageLoader implements Serializable {
private static final Component ourComponent = new Component() {
};
private static final Logger LOG = Logger.getInstance("#com.intellij.util.ImageLoader");
private static boolean waitForImage(Image image) {
if (image == null) return false;
if (image.getWidth(null) > 0) return true;
MediaTracker mediatracker = new MediaTracker(ourComponent);
mediatracker.addImage(image, 1);
try {
mediatracker.waitForID(1, 5000);
}
catch (InterruptedException ex) {
LOG.info(ex);
}
return !mediatracker.isErrorID(1);
}
@Nullable
public static Image loadFromUrl(URL url) {
for (Pair<String, Integer> each : getFileNames(url.toString())) {
try {
return loadFromStream(URLUtil.openStream(new URL(each.first)), each.second);
}
catch (IOException ignore) {
}
}
return null;
}
@Nullable
public static Image loadFromResource(@NonNls String s) {
int stackFrameCount = 2;
Class callerClass = Reflection.getCallerClass(stackFrameCount);
while (callerClass != null && callerClass.getClassLoader() == null) { // looks like a system class
callerClass = Reflection.getCallerClass(++stackFrameCount);
}
if (callerClass == null) {
callerClass = Reflection.getCallerClass(1);
}
return loadFromResource(s, callerClass);
}
@Nullable
public static Image loadFromResource(String path, Class aClass) {
for (Pair<String, Integer> each : getFileNames(path)) {
InputStream stream = aClass.getResourceAsStream(each.first);
if (stream == null) continue;
Image image = loadFromStream(stream, each.second);
if (image != null) return image;
}
return null;
}
public static List<Pair<String, Integer>> getFileNames(@NotNull String file) {
final boolean dark = UIUtil.isUnderDarcula();
final boolean retina = UIUtil.isRetina();
if (retina || dark) {
List<Pair<String, Integer>> answer = new ArrayList<Pair<String, Integer>>(4);
final String name = FileUtil.getNameWithoutExtension(file);
final String ext = FileUtil.getExtension(file);
if (dark && retina) {
answer.add(Pair.create(name + "@2x_dark." + ext, 2));
}
if (dark) {
answer.add(Pair.create(name + "_dark." + ext, 1));
}
if (retina) {
answer.add(Pair.create(name + "@2x." + ext, 2));
}
answer.add(Pair.create(file, 1));
return answer;
}
return Collections.singletonList(Pair.create(file, 1));
}
public static Image loadFromStream(@NotNull final InputStream inputStream) {
return loadFromStream(inputStream, 1);
}
public static Image loadFromStream(@NotNull final InputStream inputStream, final int scale) {
if (scale <= 0) throw new IllegalArgumentException("Scale must 1 or more");
try {
BufferExposingByteArrayOutputStream outputStream = new BufferExposingByteArrayOutputStream();
try {
byte[] buffer = new byte[1024];
while (true) {
final int n = inputStream.read(buffer);
if (n < 0) break;
outputStream.write(buffer, 0, n);
}
}
finally {
inputStream.close();
}
Image image = Toolkit.getDefaultToolkit().createImage(outputStream.getInternalBuffer(), 0, outputStream.size());
waitForImage(image);
if (UIUtil.isRetina() && scale > 1) {
image = RetinaImage.createFrom(image, scale, ourComponent);
}
return image;
}
catch (Exception ex) {
LOG.error(ex);
}
return null;
}
public static boolean isGoodSize(final Icon icon) {
return IconLoader.isGoodSize(icon);
}
}
| platform/util/src/com/intellij/util/ImageLoader.java | /*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.util;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.util.io.URLUtil;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import sun.reflect.Reflection;
import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.URL;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
@Deprecated
public class ImageLoader implements Serializable {
private static final Component ourComponent = new Component() {
};
private static final Logger LOG = Logger.getInstance("#com.intellij.util.ImageLoader");
private static boolean waitForImage(Image image) {
if (image == null) return false;
if (image.getWidth(null) > 0) return true;
MediaTracker mediatracker = new MediaTracker(ourComponent);
mediatracker.addImage(image, 1);
try {
mediatracker.waitForID(1, 5000);
}
catch (InterruptedException ex) {
LOG.info(ex);
}
return !mediatracker.isErrorID(1);
}
@Nullable
public static Image loadFromUrl(URL url) {
for (Pair<String, Integer> each : getFileNames(url.toString())) {
try {
return loadFromStream(URLUtil.openStream(new URL(each.first)), each.second);
}
catch (IOException ignore) {
}
}
return null;
}
@Nullable
public static Image loadFromResource(@NonNls String s) {
int stackFrameCount = 2;
Class callerClass = Reflection.getCallerClass(stackFrameCount);
while (callerClass != null && callerClass.getClassLoader() == null) { // looks like a system class
callerClass = Reflection.getCallerClass(++stackFrameCount);
}
if (callerClass == null) {
callerClass = Reflection.getCallerClass(1);
}
return loadFromResource(s, callerClass);
}
@Nullable
public static Image loadFromResource(String path, Class aClass) {
for (Pair<String, Integer> each : getFileNames(path)) {
InputStream stream = aClass.getResourceAsStream(each.first);
if (stream == null) continue;
Image image = loadFromStream(stream, each.second);
if (image != null) return image;
}
return null;
}
public static List<Pair<String, Integer>> getFileNames(@NotNull String file) {
final boolean dark = UIUtil.isUnderDarcula();
final boolean retina = UIUtil.isRetina();
if (retina || dark) {
String suffix = "";
if (retina) suffix += "@2x";
if (dark) suffix += "_dark";
suffix += ".";
return Arrays.asList(Pair.create(FileUtil.getNameWithoutExtension(file) + suffix + FileUtil.getExtension(file), retina ? 2 : 1),
Pair.create(file, 1));
}
return Collections.singletonList(Pair.create(file, 1));
}
public static Image loadFromStream(@NotNull final InputStream inputStream) {
return loadFromStream(inputStream, 1);
}
public static Image loadFromStream(@NotNull final InputStream inputStream, final int scale) {
if (scale <= 0) throw new IllegalArgumentException("Scale must 1 or more");
try {
BufferExposingByteArrayOutputStream outputStream = new BufferExposingByteArrayOutputStream();
try {
byte[] buffer = new byte[1024];
while (true) {
final int n = inputStream.read(buffer);
if (n < 0) break;
outputStream.write(buffer, 0, n);
}
}
finally {
inputStream.close();
}
Image image = Toolkit.getDefaultToolkit().createImage(outputStream.getInternalBuffer(), 0, outputStream.size());
waitForImage(image);
if (UIUtil.isRetina() && scale > 1) {
image = RetinaImage.createFrom(image, scale, ourComponent);
}
return image;
}
catch (Exception ex) {
LOG.error(ex);
}
return null;
}
public static boolean isGoodSize(final Icon icon) {
return IconLoader.isGoodSize(icon);
}
}
| Fix retina images under Darcula
| platform/util/src/com/intellij/util/ImageLoader.java | Fix retina images under Darcula | <ide><path>latform/util/src/com/intellij/util/ImageLoader.java
<ide> import java.io.InputStream;
<ide> import java.io.Serializable;
<ide> import java.net.URL;
<del>import java.util.Arrays;
<add>import java.util.ArrayList;
<ide> import java.util.Collections;
<ide> import java.util.List;
<ide>
<ide> final boolean dark = UIUtil.isUnderDarcula();
<ide> final boolean retina = UIUtil.isRetina();
<ide> if (retina || dark) {
<del> String suffix = "";
<del> if (retina) suffix += "@2x";
<del> if (dark) suffix += "_dark";
<del> suffix += ".";
<del> return Arrays.asList(Pair.create(FileUtil.getNameWithoutExtension(file) + suffix + FileUtil.getExtension(file), retina ? 2 : 1),
<del> Pair.create(file, 1));
<add> List<Pair<String, Integer>> answer = new ArrayList<Pair<String, Integer>>(4);
<add>
<add> final String name = FileUtil.getNameWithoutExtension(file);
<add> final String ext = FileUtil.getExtension(file);
<add> if (dark && retina) {
<add> answer.add(Pair.create(name + "@2x_dark." + ext, 2));
<add> }
<add>
<add> if (dark) {
<add> answer.add(Pair.create(name + "_dark." + ext, 1));
<add> }
<add>
<add> if (retina) {
<add> answer.add(Pair.create(name + "@2x." + ext, 2));
<add> }
<add>
<add> answer.add(Pair.create(file, 1));
<add>
<add> return answer;
<ide> }
<add>
<ide> return Collections.singletonList(Pair.create(file, 1));
<ide> }
<ide> |
|
Java | mit | error: pathspec 'src/edacc/configurator/aac/course/StratifiedClusterCourse.java' did not match any file(s) known to git
| 2a1ed9b79e1501d2c280a98eb38fed4d25bd9a1d | 1 | EDACC/edacc_aac,EDACC/edacc_aac,EDACC/edacc_aac,EDACC/edacc_aac,EDACC/edacc_aac,EDACC/edacc_aac | package edacc.configurator.aac.course;
import java.util.List;
import edacc.model.Instance;
import edacc.configurator.aac.InstanceIdSeed;
public class StratifiedClusterCourse {
List<InstanceIdSeed> course;
public StratifiedClusterCourse(List<Instance> instances, float maxExpansionFactor) {
if (instances.size() == 0) throw new RuntimeException("Course has to consists of at least one instance.");
if (maxExpansionFactor <= 0) throw new RuntimeException("maxExpansionFactor has to be > 0.");
}
}
| src/edacc/configurator/aac/course/StratifiedClusterCourse.java | skeleton
| src/edacc/configurator/aac/course/StratifiedClusterCourse.java | skeleton | <ide><path>rc/edacc/configurator/aac/course/StratifiedClusterCourse.java
<add>package edacc.configurator.aac.course;
<add>
<add>import java.util.List;
<add>
<add>import edacc.model.Instance;
<add>import edacc.configurator.aac.InstanceIdSeed;
<add>
<add>public class StratifiedClusterCourse {
<add> List<InstanceIdSeed> course;
<add>
<add> public StratifiedClusterCourse(List<Instance> instances, float maxExpansionFactor) {
<add> if (instances.size() == 0) throw new RuntimeException("Course has to consists of at least one instance.");
<add> if (maxExpansionFactor <= 0) throw new RuntimeException("maxExpansionFactor has to be > 0.");
<add>
<add>
<add> }
<add>} |
|
Java | apache-2.0 | 196b36ec5b64af00bceaab81b10584df79239fd5 | 0 | krichter722/jfreesane,sjamesr/jfreesane,sjamesr/jfreesane | package au.com.southsky.jfreesane;
import com.google.common.base.MoreObjects;
import com.google.common.primitives.UnsignedInteger;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Represents a stream for reading image {@link Frame frames}.
*/
class FrameInputStream extends InputStream {
private static final Logger log = Logger.getLogger(FrameInputStream.class.getName());
private final SaneParameters parameters;
private final InputStream underlyingStream;
private final boolean bigEndian;
public FrameInputStream(
SaneParameters parameters, InputStream underlyingStream, boolean bigEndian) {
this.parameters = parameters;
this.underlyingStream = underlyingStream;
this.bigEndian = bigEndian;
}
@Override
public int read() throws IOException {
return underlyingStream.read();
}
public Frame readFrame() throws IOException, SaneException {
log.log(Level.FINE, "Reading frame: {0}", this);
ByteArrayOutputStream bigArray;
int imageSize = parameters.getBytesPerLine() * parameters.getLineCount();
if (parameters.getLineCount() > 0) {
bigArray = new ByteArrayOutputStream(imageSize);
} else {
bigArray = new ByteArrayOutputStream(256);
}
while (readRecord(bigArray) >= 0);
if (imageSize > 0 && imageSize != bigArray.size()) {
throw new IOException("truncated read (expected " + bigArray.size() + ", got " + imageSize);
}
// Now, if necessary, put the bytes in the correct order according
// to the stream's endianness
byte[] outputArray = bigArray.toByteArray();
if (parameters.getDepthPerPixel() == 16 && !bigEndian) {
if (outputArray.length % 2 != 0) {
throw new IOException("expected a multiple of 2 frame length");
}
for (int i = 0; i < outputArray.length; i += 2) {
byte swap = outputArray[i];
outputArray[i] = outputArray[i + 1];
outputArray[i + 1] = swap;
}
}
if (parameters.getLineCount() <= 0) {
// register the real height
parameters.setLineCount(outputArray.length / parameters.getBytesPerLine());
log.log(Level.FINE, "Detected new frame line count: {0}", parameters.getLineCount());
}
return new Frame(parameters, outputArray);
}
private int readRecord(ByteArrayOutputStream destination) throws IOException, SaneException {
DataInputStream inputStream = new DataInputStream(this);
int length = inputStream.readInt();
if (length == 0xffffffff) {
log.fine("Reached end of records");
// Hack: saned may actually write a status record here, even
// though the sane specification says that no more bytes should
// be read in an end-of-records situation
int status = read();
if (status != -1) {
SaneStatus saneStatus = SaneStatus.fromWireValue(status);
// An EOF condition is expected: that is what SANE told us!
if (saneStatus != null && saneStatus != SaneStatus.STATUS_EOF) {
throw new SaneException(saneStatus);
}
}
return -1;
}
if (UnsignedInteger.fromIntBits(length).longValue() > Integer.MAX_VALUE) {
throw new IllegalStateException("TODO: support massive records");
}
byte[] buffer = new byte[length];
int result = read(buffer, 0, length);
if (result != length) {
throw new IllegalStateException(
"read too few bytes (" + result + "), was expecting " + length);
}
destination.write(buffer, 0, length);
log.fine("Read a record of " + result + " bytes");
return result;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(FrameInputStream.class).add("isBigEndian", bigEndian)
.add("parameters", parameters).toString();
}
} | src/main/java/au/com/southsky/jfreesane/FrameInputStream.java | package au.com.southsky.jfreesane;
import com.google.common.primitives.UnsignedInteger;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Logger;
/**
* Represents a stream for reading image {@link Frame frames}.
*/
class FrameInputStream extends InputStream {
private static final Logger log = Logger.getLogger(FrameInputStream.class.getName());
private final SaneParameters parameters;
private final InputStream underlyingStream;
private final boolean bigEndian;
public FrameInputStream(
SaneParameters parameters, InputStream underlyingStream, boolean bigEndian) {
this.parameters = parameters;
this.underlyingStream = underlyingStream;
this.bigEndian = bigEndian;
}
@Override
public int read() throws IOException {
return underlyingStream.read();
}
public Frame readFrame() throws IOException, SaneException {
ByteArrayOutputStream bigArray;
int imageSize = parameters.getBytesPerLine() * parameters.getLineCount();
if (parameters.getLineCount() > 0) {
bigArray = new ByteArrayOutputStream(imageSize);
} else {
bigArray = new ByteArrayOutputStream(256);
}
while (readRecord(bigArray) >= 0);
if (imageSize > 0 && imageSize != bigArray.size()) {
throw new IOException("truncated read");
}
// Now, if necessary, put the bytes in the correct order according
// to the stream's endianness
byte[] outputArray = bigArray.toByteArray();
if (parameters.getDepthPerPixel() == 16 && !bigEndian) {
if (outputArray.length % 2 != 0) {
throw new IOException("expected a multiple of 2 frame length");
}
for (int i = 0; i < outputArray.length; i += 2) {
byte swap = outputArray[i];
outputArray[i] = outputArray[i + 1];
outputArray[i + 1] = swap;
}
}
if (parameters.getLineCount() <= 0) {
// register the real height
parameters.setLineCount(outputArray.length / parameters.getBytesPerLine());
}
return new Frame(parameters,outputArray);
}
private int readRecord(ByteArrayOutputStream destination) throws IOException, SaneException {
DataInputStream inputStream = new DataInputStream(this);
int length = inputStream.readInt();
if (length == 0xffffffff) {
log.fine("Reached end of records");
// Hack: saned may actually write a status record here, even
// though the sane specification says that no more bytes should
// be read in an end-of-records situation
int status = read();
if (status != -1) {
SaneStatus saneStatus = SaneStatus.fromWireValue(status);
// An EOF condition is expected: that is what SANE told us!
if (saneStatus != null && saneStatus != SaneStatus.STATUS_EOF) {
throw new SaneException(saneStatus);
}
}
return -1;
}
if (UnsignedInteger.fromIntBits(length).longValue() > Integer.MAX_VALUE) {
throw new IllegalStateException("TODO: support massive records");
}
byte[] buffer = new byte[length];
int result = read(buffer, 0, length);
if (result != length) {
throw new IllegalStateException(
"read too few bytes (" + result + "), was expecting " + length);
}
destination.write(buffer, 0, length);
log.fine("Read a record of " + result + " bytes");
return result;
}
} | Improve error message in the case of a truncated read, add more logging.
| src/main/java/au/com/southsky/jfreesane/FrameInputStream.java | Improve error message in the case of a truncated read, add more logging. | <ide><path>rc/main/java/au/com/southsky/jfreesane/FrameInputStream.java
<ide> package au.com.southsky.jfreesane;
<ide>
<add>import com.google.common.base.MoreObjects;
<ide> import com.google.common.primitives.UnsignedInteger;
<ide>
<ide> import java.io.ByteArrayOutputStream;
<ide> import java.io.DataInputStream;
<ide> import java.io.IOException;
<ide> import java.io.InputStream;
<add>import java.util.logging.Level;
<ide> import java.util.logging.Logger;
<ide>
<ide> /**
<ide> }
<ide>
<ide> public Frame readFrame() throws IOException, SaneException {
<add> log.log(Level.FINE, "Reading frame: {0}", this);
<ide> ByteArrayOutputStream bigArray;
<ide> int imageSize = parameters.getBytesPerLine() * parameters.getLineCount();
<ide>
<ide> while (readRecord(bigArray) >= 0);
<ide>
<ide> if (imageSize > 0 && imageSize != bigArray.size()) {
<del> throw new IOException("truncated read");
<add> throw new IOException("truncated read (expected " + bigArray.size() + ", got " + imageSize);
<ide> }
<ide>
<ide> // Now, if necessary, put the bytes in the correct order according
<ide> if (parameters.getLineCount() <= 0) {
<ide> // register the real height
<ide> parameters.setLineCount(outputArray.length / parameters.getBytesPerLine());
<add> log.log(Level.FINE, "Detected new frame line count: {0}", parameters.getLineCount());
<ide> }
<ide>
<del> return new Frame(parameters,outputArray);
<add> return new Frame(parameters, outputArray);
<ide> }
<ide>
<ide> private int readRecord(ByteArrayOutputStream destination) throws IOException, SaneException {
<ide> log.fine("Read a record of " + result + " bytes");
<ide> return result;
<ide> }
<add>
<add> @Override
<add> public String toString() {
<add> return MoreObjects.toStringHelper(FrameInputStream.class).add("isBigEndian", bigEndian)
<add> .add("parameters", parameters).toString();
<add> }
<ide> } |
|
Java | apache-2.0 | d551d98b2bf1c12e6b25c9af34f0ee0d09e803d8 | 0 | vanta/commons-lang,hollycroxton/commons-lang,apache/commons-lang,chaoyi66/commons-lang,byMan/naya279,xiwc/commons-lang,jacktan1991/commons-lang,byMan/naya279,jankill/commons-lang,MuShiiii/commons-lang,britter/commons-lang,MuShiiii/commons-lang,Ajeet-Ganga/commons-lang,jankill/commons-lang,suntengteng/commons-lang,byMan/naya279,mohanaraosv/commons-lang,xiwc/commons-lang,hollycroxton/commons-lang,jacktan1991/commons-lang,longestname1/commonslang,xiwc/commons-lang,PascalSchumacher/commons-lang,xuerenlv/commons-lang,suntengteng/commons-lang,arbasha/commons-lang,britter/commons-lang,arbasha/commons-lang,arbasha/commons-lang,vanta/commons-lang,longestname1/commonslang,xuerenlv/commons-lang,MarkDacek/commons-lang,mohanaraosv/commons-lang,MuShiiii/commons-lang,weston100721/commons-lang,lovecindy/commons-lang,lovecindy/commons-lang,suntengteng/commons-lang,chaoyi66/commons-lang,chaoyi66/commons-lang,weston100721/commons-lang,mohanaraosv/commons-lang,britter/commons-lang,MarkDacek/commons-lang,vanta/commons-lang,Ajeet-Ganga/commons-lang,apache/commons-lang,MarkDacek/commons-lang,jankill/commons-lang,Ajeet-Ganga/commons-lang,jacktan1991/commons-lang,hollycroxton/commons-lang,weston100721/commons-lang,PascalSchumacher/commons-lang,longestname1/commonslang,lovecindy/commons-lang,PascalSchumacher/commons-lang,apache/commons-lang,xuerenlv/commons-lang | /*
* 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.commons.lang3.builder;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.SystemUtils;
import org.junit.After;
import org.junit.Test;
/**
* Unit tests for {@link org.apache.commons.lang3.builder.ToStringBuilder}.
*
* @version $Id$
*/
public class ToStringBuilderTest {
private final Integer base = Integer.valueOf(5);
private final String baseStr = base.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(base));
/*
* All tests should leave the registry empty.
*/
@After
public void after(){
validateNullToStringStyleRegistry();
}
//-----------------------------------------------------------------------
@Test
public void testConstructorEx1() {
assertEquals("<null>", new ToStringBuilder(null).toString());
}
@Test
public void testConstructorEx2() {
assertEquals("<null>", new ToStringBuilder(null, null).toString());
new ToStringBuilder(this.base, null).toString();
}
@Test
public void testConstructorEx3() {
assertEquals("<null>", new ToStringBuilder(null, null, null).toString());
new ToStringBuilder(this.base, null, null).toString();
new ToStringBuilder(this.base, ToStringStyle.DEFAULT_STYLE, null).toString();
}
@Test
public void testGetSetDefault() {
try {
ToStringBuilder.setDefaultStyle(ToStringStyle.NO_FIELD_NAMES_STYLE);
assertSame(ToStringStyle.NO_FIELD_NAMES_STYLE, ToStringBuilder.getDefaultStyle());
} finally {
// reset for other tests
ToStringBuilder.setDefaultStyle(ToStringStyle.DEFAULT_STYLE);
}
}
@Test
public void testSetDefaultEx() {
try {
ToStringBuilder.setDefaultStyle(null);
} catch (IllegalArgumentException ex) {
return;
}
fail();
}
@Test
public void testBlank() {
assertEquals(baseStr + "[]", new ToStringBuilder(base).toString());
}
/**
* Test wrapper for int primitive.
*/
@Test
public void testReflectionInteger() {
assertEquals(baseStr + "[value=5]", ToStringBuilder.reflectionToString(base));
}
/**
* Test wrapper for char primitive.
*/
@Test
public void testReflectionCharacter() {
Character c = new Character('A');
assertEquals(this.toBaseString(c) + "[value=A]", ToStringBuilder.reflectionToString(c));
}
/**
* Test wrapper for char boolean.
*/
@Test
public void testReflectionBoolean() {
Boolean b;
b = Boolean.TRUE;
assertEquals(this.toBaseString(b) + "[value=true]", ToStringBuilder.reflectionToString(b));
b = Boolean.FALSE;
assertEquals(this.toBaseString(b) + "[value=false]", ToStringBuilder.reflectionToString(b));
}
/**
* Create the same toString() as Object.toString().
* @param o the object to create the string for.
* @return a String in the Object.toString format.
*/
private String toBaseString(Object o) {
return o.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(o));
}
// Reflection Array tests
//
// Note on the following line of code repeated in the reflection array tests.
//
// assertReflectionArray("<null>", array);
//
// The expected value is not baseStr + "[<null>]" since array==null and is typed as Object.
// The null array does not carry array type information.
// If we added a primitive array type constructor and pile of associated methods,
// then type declaring type information could be carried forward. IMHO, null is null.
//
// Gary Gregory - 2003-03-12 - [email protected]
//
public void assertReflectionArray(String expected, Object actual) {
if (actual == null) {
// Until ToStringBuilder supports null objects.
return;
}
assertEquals(expected, ToStringBuilder.reflectionToString(actual));
assertEquals(expected, ToStringBuilder.reflectionToString(actual, null));
assertEquals(expected, ToStringBuilder.reflectionToString(actual, null, true));
assertEquals(expected, ToStringBuilder.reflectionToString(actual, null, false));
}
@Test
public void testReflectionObjectArray() {
Object[] array = new Object[] { null, base, new int[] { 3, 6 } };
String baseStr = this.toBaseString(array);
assertEquals(baseStr + "[{<null>,5,{3,6}}]", ToStringBuilder.reflectionToString(array));
array = null;
assertReflectionArray("<null>", array);
}
@Test
public void testReflectionLongArray() {
long[] array = new long[] { 1, 2, -3, 4 };
String baseStr = this.toBaseString(array);
assertEquals(baseStr + "[{1,2,-3,4}]", ToStringBuilder.reflectionToString(array));
array = null;
assertReflectionArray("<null>", array);
}
@Test
public void testReflectionIntArray() {
int[] array = new int[] { 1, 2, -3, 4 };
String baseStr = this.toBaseString(array);
assertEquals(baseStr + "[{1,2,-3,4}]", ToStringBuilder.reflectionToString(array));
array = null;
assertReflectionArray("<null>", array);
}
@Test
public void testReflectionShortArray() {
short[] array = new short[] { 1, 2, -3, 4 };
String baseStr = this.toBaseString(array);
assertEquals(baseStr + "[{1,2,-3,4}]", ToStringBuilder.reflectionToString(array));
array = null;
assertReflectionArray("<null>", array);
}
@Test
public void testReflectionyteArray() {
byte[] array = new byte[] { 1, 2, -3, 4 };
String baseStr = this.toBaseString(array);
assertEquals(baseStr + "[{1,2,-3,4}]", ToStringBuilder.reflectionToString(array));
array = null;
assertReflectionArray("<null>", array);
}
@Test
public void testReflectionCharArray() {
char[] array = new char[] { 'A', '2', '_', 'D' };
String baseStr = this.toBaseString(array);
assertEquals(baseStr + "[{A,2,_,D}]", ToStringBuilder.reflectionToString(array));
array = null;
assertReflectionArray("<null>", array);
}
@Test
public void testReflectionDoubleArray() {
double[] array = new double[] { 1.0, 2.9876, -3.00001, 4.3 };
String baseStr = this.toBaseString(array);
assertEquals(baseStr + "[{1.0,2.9876,-3.00001,4.3}]", ToStringBuilder.reflectionToString(array));
array = null;
assertReflectionArray("<null>", array);
}
@Test
public void testReflectionFloatArray() {
float[] array = new float[] { 1.0f, 2.9876f, -3.00001f, 4.3f };
String baseStr = this.toBaseString(array);
assertEquals(baseStr + "[{1.0,2.9876,-3.00001,4.3}]", ToStringBuilder.reflectionToString(array));
array = null;
assertReflectionArray("<null>", array);
}
@Test
public void testReflectionBooleanArray() {
boolean[] array = new boolean[] { true, false, false };
String baseStr = this.toBaseString(array);
assertEquals(baseStr + "[{true,false,false}]", ToStringBuilder.reflectionToString(array));
array = null;
assertReflectionArray("<null>", array);
}
// Reflection Array Array tests
@Test
public void testReflectionFloatArrayArray() {
float[][] array = new float[][] { { 1.0f, 2.29686f }, null, { Float.NaN } };
String baseStr = this.toBaseString(array);
assertEquals(baseStr + "[{{1.0,2.29686},<null>,{NaN}}]", ToStringBuilder.reflectionToString(array));
array = null;
assertReflectionArray("<null>", array);
}
@Test
public void testReflectionLongArrayArray() {
long[][] array = new long[][] { { 1, 2 }, null, { 5 } };
String baseStr = this.toBaseString(array);
assertEquals(baseStr + "[{{1,2},<null>,{5}}]", ToStringBuilder.reflectionToString(array));
array = null;
assertReflectionArray("<null>", array);
}
@Test
public void testReflectionIntArrayArray() {
int[][] array = new int[][] { { 1, 2 }, null, { 5 } };
String baseStr = this.toBaseString(array);
assertEquals(baseStr + "[{{1,2},<null>,{5}}]", ToStringBuilder.reflectionToString(array));
array = null;
assertReflectionArray("<null>", array);
}
@Test
public void testReflectionhortArrayArray() {
short[][] array = new short[][] { { 1, 2 }, null, { 5 } };
String baseStr = this.toBaseString(array);
assertEquals(baseStr + "[{{1,2},<null>,{5}}]", ToStringBuilder.reflectionToString(array));
array = null;
assertReflectionArray("<null>", array);
}
@Test
public void testReflectionByteArrayArray() {
byte[][] array = new byte[][] { { 1, 2 }, null, { 5 } };
String baseStr = this.toBaseString(array);
assertEquals(baseStr + "[{{1,2},<null>,{5}}]", ToStringBuilder.reflectionToString(array));
array = null;
assertReflectionArray("<null>", array);
}
@Test
public void testReflectionCharArrayArray() {
char[][] array = new char[][] { { 'A', 'B' }, null, { 'p' } };
String baseStr = this.toBaseString(array);
assertEquals(baseStr + "[{{A,B},<null>,{p}}]", ToStringBuilder.reflectionToString(array));
array = null;
assertReflectionArray("<null>", array);
}
@Test
public void testReflectionDoubleArrayArray() {
double[][] array = new double[][] { { 1.0, 2.29686 }, null, { Double.NaN } };
String baseStr = this.toBaseString(array);
assertEquals(baseStr + "[{{1.0,2.29686},<null>,{NaN}}]", ToStringBuilder.reflectionToString(array));
array = null;
assertReflectionArray("<null>", array);
}
@Test
public void testReflectionBooleanArrayArray() {
boolean[][] array = new boolean[][] { { true, false }, null, { false } };
String baseStr = this.toBaseString(array);
assertEquals(baseStr + "[{{true,false},<null>,{false}}]", ToStringBuilder.reflectionToString(array));
assertEquals(baseStr + "[{{true,false},<null>,{false}}]", ToStringBuilder.reflectionToString(array));
array = null;
assertReflectionArray("<null>", array);
}
// Reflection hierarchy tests
@Test
public void testReflectionHierarchyArrayList() {
List<Object> base = new ArrayList<Object>();
String baseStr = this.toBaseString(base);
// note, the test data depends on the internal representation of the ArrayList, which may differ between JDK versions and vendors
String expectedWithTransients = baseStr + "[elementData={<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>},size=0,modCount=0]";
String toStringWithTransients = ToStringBuilder.reflectionToString(base, null, true);
if (!expectedWithTransients.equals(toStringWithTransients)) {
// representation different for IBM JDK 1.6.0, LANG-727
if (!("IBM Corporation".equals(SystemUtils.JAVA_VENDOR) && "1.6".equals(SystemUtils.JAVA_SPECIFICATION_VERSION))) {
assertEquals(expectedWithTransients, toStringWithTransients);
}
}
String expectedWithoutTransients = baseStr + "[size=0]";
String toStringWithoutTransients = ToStringBuilder.reflectionToString(base, null, false);
if (!expectedWithoutTransients.equals(toStringWithoutTransients)) {
// representation different for IBM JDK 1.6.0, LANG-727
if (!("IBM Corporation".equals(SystemUtils.JAVA_VENDOR) && "1.6".equals(SystemUtils.JAVA_SPECIFICATION_VERSION))) {
assertEquals(expectedWithoutTransients, toStringWithoutTransients);
}
}
}
@Test
public void testReflectionHierarchy() {
ReflectionTestFixtureA baseA = new ReflectionTestFixtureA();
String baseStr = this.toBaseString(baseA);
assertEquals(baseStr + "[a=a]", ToStringBuilder.reflectionToString(baseA));
assertEquals(baseStr + "[a=a]", ToStringBuilder.reflectionToString(baseA, null));
assertEquals(baseStr + "[a=a]", ToStringBuilder.reflectionToString(baseA, null, false));
assertEquals(baseStr + "[a=a,transientA=t]", ToStringBuilder.reflectionToString(baseA, null, true));
assertEquals(baseStr + "[a=a]", ToStringBuilder.reflectionToString(baseA, null, false, null));
assertEquals(baseStr + "[a=a]", ToStringBuilder.reflectionToString(baseA, null, false, Object.class));
assertEquals(baseStr + "[a=a]", ToStringBuilder.reflectionToString(baseA, null, false, ReflectionTestFixtureA.class));
ReflectionTestFixtureB baseB = new ReflectionTestFixtureB();
baseStr = this.toBaseString(baseB);
assertEquals(baseStr + "[b=b,a=a]", ToStringBuilder.reflectionToString(baseB));
assertEquals(baseStr + "[b=b,a=a]", ToStringBuilder.reflectionToString(baseB));
assertEquals(baseStr + "[b=b,a=a]", ToStringBuilder.reflectionToString(baseB, null));
assertEquals(baseStr + "[b=b,a=a]", ToStringBuilder.reflectionToString(baseB, null, false));
assertEquals(baseStr + "[b=b,transientB=t,a=a,transientA=t]", ToStringBuilder.reflectionToString(baseB, null, true));
assertEquals(baseStr + "[b=b,a=a]", ToStringBuilder.reflectionToString(baseB, null, false, null));
assertEquals(baseStr + "[b=b,a=a]", ToStringBuilder.reflectionToString(baseB, null, false, Object.class));
assertEquals(baseStr + "[b=b,a=a]", ToStringBuilder.reflectionToString(baseB, null, false, ReflectionTestFixtureA.class));
assertEquals(baseStr + "[b=b]", ToStringBuilder.reflectionToString(baseB, null, false, ReflectionTestFixtureB.class));
}
static class ReflectionTestFixtureA {
@SuppressWarnings("unused")
private char a='a';
@SuppressWarnings("unused")
private transient char transientA='t';
}
static class ReflectionTestFixtureB extends ReflectionTestFixtureA {
@SuppressWarnings("unused")
private char b='b';
@SuppressWarnings("unused")
private transient char transientB='t';
}
@Test
public void testInnerClassReflection() {
Outer outer = new Outer();
assertEquals(toBaseString(outer) + "[inner=" + toBaseString(outer.inner) + "[]]", outer.toString());
}
static class Outer {
Inner inner = new Inner();
class Inner {
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
// Reflection cycle tests
/**
* Test an array element pointing to its container.
*/
@Test
public void testReflectionArrayCycle() throws Exception {
Object[] objects = new Object[1];
objects[0] = objects;
assertEquals(
this.toBaseString(objects) + "[{" + this.toBaseString(objects) + "}]",
ToStringBuilder.reflectionToString(objects));
}
/**
* Test an array element pointing to its container.
*/
@Test
public void testReflectionArrayCycleLevel2() throws Exception {
Object[] objects = new Object[1];
Object[] objectsLevel2 = new Object[1];
objects[0] = objectsLevel2;
objectsLevel2[0] = objects;
assertEquals(
this.toBaseString(objects) + "[{{" + this.toBaseString(objects) + "}}]",
ToStringBuilder.reflectionToString(objects));
assertEquals(
this.toBaseString(objectsLevel2) + "[{{" + this.toBaseString(objectsLevel2) + "}}]",
ToStringBuilder.reflectionToString(objectsLevel2));
}
@Test
public void testReflectionArrayArrayCycle() throws Exception {
Object[][] objects = new Object[2][2];
objects[0][0] = objects;
objects[0][1] = objects;
objects[1][0] = objects;
objects[1][1] = objects;
String basicToString = this.toBaseString(objects);
assertEquals(
basicToString
+ "[{{"
+ basicToString
+ ","
+ basicToString
+ "},{"
+ basicToString
+ ","
+ basicToString
+ "}}]",
ToStringBuilder.reflectionToString(objects));
}
/**
* A reflection test fixture.
*/
static class ReflectionTestCycleA {
ReflectionTestCycleB b;
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
/**
* A reflection test fixture.
*/
static class ReflectionTestCycleB {
ReflectionTestCycleA a;
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
/**
* A reflection test fixture.
*/
static class SimpleReflectionTestFixture {
Object o;
public SimpleReflectionTestFixture() {
}
public SimpleReflectionTestFixture(Object o) {
this.o = o;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
private static class SelfInstanceVarReflectionTestFixture {
@SuppressWarnings("unused")
private SelfInstanceVarReflectionTestFixture typeIsSelf;
public SelfInstanceVarReflectionTestFixture() {
this.typeIsSelf = this;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
private static class SelfInstanceTwoVarsReflectionTestFixture {
@SuppressWarnings("unused")
private SelfInstanceTwoVarsReflectionTestFixture typeIsSelf;
private String otherType = "The Other Type";
public SelfInstanceTwoVarsReflectionTestFixture() {
this.typeIsSelf = this;
}
public String getOtherType(){
return this.otherType;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
/**
* Test an Object pointing to itself, the simplest test.
*
* @throws Exception
*/
@Test
public void testSimpleReflectionObjectCycle() throws Exception {
SimpleReflectionTestFixture simple = new SimpleReflectionTestFixture();
simple.o = simple;
assertEquals(this.toBaseString(simple) + "[o=" + this.toBaseString(simple) + "]", simple.toString());
}
/**
* Test a class that defines an ivar pointing to itself.
*
* @throws Exception
*/
@Test
public void testSelfInstanceVarReflectionObjectCycle() throws Exception {
SelfInstanceVarReflectionTestFixture test = new SelfInstanceVarReflectionTestFixture();
assertEquals(this.toBaseString(test) + "[typeIsSelf=" + this.toBaseString(test) + "]", test.toString());
}
/**
* Test a class that defines an ivar pointing to itself. This test was
* created to show that handling cyclical object resulted in a missing endFieldSeparator call.
*
* @throws Exception
*/
@Test
public void testSelfInstanceTwoVarsReflectionObjectCycle() throws Exception {
SelfInstanceTwoVarsReflectionTestFixture test = new SelfInstanceTwoVarsReflectionTestFixture();
assertEquals(this.toBaseString(test) + "[typeIsSelf=" + this.toBaseString(test) + ",otherType=" + test.getOtherType().toString() + "]", test.toString());
}
/**
* Test Objects pointing to each other.
*
* @throws Exception
*/
@Test
public void testReflectionObjectCycle() throws Exception {
ReflectionTestCycleA a = new ReflectionTestCycleA();
ReflectionTestCycleB b = new ReflectionTestCycleB();
a.b = b;
b.a = a;
assertEquals(
this.toBaseString(a) + "[b=" + this.toBaseString(b) + "[a=" + this.toBaseString(a) + "]]",
a.toString());
}
/**
* Test a nasty combination of arrays and Objects pointing to each other.
* objects[0] -> SimpleReflectionTestFixture[ o -> objects ]
*
* @throws Exception
*/
@Test
public void testReflectionArrayAndObjectCycle() throws Exception {
Object[] objects = new Object[1];
SimpleReflectionTestFixture simple = new SimpleReflectionTestFixture(objects);
objects[0] = simple;
assertEquals(
this.toBaseString(objects)
+ "[{"
+ this.toBaseString(simple)
+ "[o="
+ this.toBaseString(objects)
+ "]"
+ "}]",
ToStringBuilder.reflectionToString(objects));
assertEquals(
this.toBaseString(simple)
+ "[o={"
+ this.toBaseString(simple)
+ "}]",
ToStringBuilder.reflectionToString(simple));
}
void validateNullToStringStyleRegistry() {
final Map<Object, Object> registry = ToStringStyle.getRegistry();
assertNull("Expected null, actual: "+registry, registry);
}
// End: Reflection cycle tests
@Test
public void testAppendSuper() {
assertEquals(baseStr + "[]", new ToStringBuilder(base).appendSuper("Integer@8888[]").toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).appendSuper("Integer@8888[<null>]").toString());
assertEquals(baseStr + "[a=hello]", new ToStringBuilder(base).appendSuper("Integer@8888[]").append("a", "hello").toString());
assertEquals(baseStr + "[<null>,a=hello]", new ToStringBuilder(base).appendSuper("Integer@8888[<null>]").append("a", "hello").toString());
assertEquals(baseStr + "[a=hello]", new ToStringBuilder(base).appendSuper(null).append("a", "hello").toString());
}
@Test
public void testAppendToString() {
assertEquals(baseStr + "[]", new ToStringBuilder(base).appendToString("Integer@8888[]").toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).appendToString("Integer@8888[<null>]").toString());
assertEquals(baseStr + "[a=hello]", new ToStringBuilder(base).appendToString("Integer@8888[]").append("a", "hello").toString());
assertEquals(baseStr + "[<null>,a=hello]", new ToStringBuilder(base).appendToString("Integer@8888[<null>]").append("a", "hello").toString());
assertEquals(baseStr + "[a=hello]", new ToStringBuilder(base).appendToString(null).append("a", "hello").toString());
}
@Test
public void testObject() {
Integer i3 = Integer.valueOf(3);
Integer i4 = Integer.valueOf(4);
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) null).toString());
assertEquals(baseStr + "[3]", new ToStringBuilder(base).append(i3).toString());
assertEquals(baseStr + "[a=<null>]", new ToStringBuilder(base).append("a", (Object) null).toString());
assertEquals(baseStr + "[a=3]", new ToStringBuilder(base).append("a", i3).toString());
assertEquals(baseStr + "[a=3,b=4]", new ToStringBuilder(base).append("a", i3).append("b", i4).toString());
assertEquals(baseStr + "[a=<Integer>]", new ToStringBuilder(base).append("a", i3, false).toString());
assertEquals(baseStr + "[a=<size=0>]", new ToStringBuilder(base).append("a", new ArrayList<Object>(), false).toString());
assertEquals(baseStr + "[a=[]]", new ToStringBuilder(base).append("a", new ArrayList<Object>(), true).toString());
assertEquals(baseStr + "[a=<size=0>]", new ToStringBuilder(base).append("a", new HashMap<Object, Object>(), false).toString());
assertEquals(baseStr + "[a={}]", new ToStringBuilder(base).append("a", new HashMap<Object, Object>(), true).toString());
assertEquals(baseStr + "[a=<size=0>]", new ToStringBuilder(base).append("a", (Object) new String[0], false).toString());
assertEquals(baseStr + "[a={}]", new ToStringBuilder(base).append("a", (Object) new String[0], true).toString());
}
@Test
public void testObjectBuild() {
Integer i3 = Integer.valueOf(3);
Integer i4 = Integer.valueOf(4);
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) null).build());
assertEquals(baseStr + "[3]", new ToStringBuilder(base).append(i3).build());
assertEquals(baseStr + "[a=<null>]", new ToStringBuilder(base).append("a", (Object) null).build());
assertEquals(baseStr + "[a=3]", new ToStringBuilder(base).append("a", i3).build());
assertEquals(baseStr + "[a=3,b=4]", new ToStringBuilder(base).append("a", i3).append("b", i4).build());
assertEquals(baseStr + "[a=<Integer>]", new ToStringBuilder(base).append("a", i3, false).build());
assertEquals(baseStr + "[a=<size=0>]", new ToStringBuilder(base).append("a", new ArrayList<Object>(), false).build());
assertEquals(baseStr + "[a=[]]", new ToStringBuilder(base).append("a", new ArrayList<Object>(), true).build());
assertEquals(baseStr + "[a=<size=0>]", new ToStringBuilder(base).append("a", new HashMap<Object, Object>(), false).build());
assertEquals(baseStr + "[a={}]", new ToStringBuilder(base).append("a", new HashMap<Object, Object>(), true).build());
assertEquals(baseStr + "[a=<size=0>]", new ToStringBuilder(base).append("a", (Object) new String[0], false).build());
assertEquals(baseStr + "[a={}]", new ToStringBuilder(base).append("a", (Object) new String[0], true).build());
}
@Test
public void testLong() {
assertEquals(baseStr + "[3]", new ToStringBuilder(base).append(3L).toString());
assertEquals(baseStr + "[a=3]", new ToStringBuilder(base).append("a", 3L).toString());
assertEquals(baseStr + "[a=3,b=4]", new ToStringBuilder(base).append("a", 3L).append("b", 4L).toString());
}
@SuppressWarnings("cast") // cast is not really needed, keep for consistency
@Test
public void testInt() {
assertEquals(baseStr + "[3]", new ToStringBuilder(base).append((int) 3).toString());
assertEquals(baseStr + "[a=3]", new ToStringBuilder(base).append("a", (int) 3).toString());
assertEquals(baseStr + "[a=3,b=4]", new ToStringBuilder(base).append("a", (int) 3).append("b", (int) 4).toString());
}
@Test
public void testShort() {
assertEquals(baseStr + "[3]", new ToStringBuilder(base).append((short) 3).toString());
assertEquals(baseStr + "[a=3]", new ToStringBuilder(base).append("a", (short) 3).toString());
assertEquals(baseStr + "[a=3,b=4]", new ToStringBuilder(base).append("a", (short) 3).append("b", (short) 4).toString());
}
@Test
public void testChar() {
assertEquals(baseStr + "[A]", new ToStringBuilder(base).append((char) 65).toString());
assertEquals(baseStr + "[a=A]", new ToStringBuilder(base).append("a", (char) 65).toString());
assertEquals(baseStr + "[a=A,b=B]", new ToStringBuilder(base).append("a", (char) 65).append("b", (char) 66).toString());
}
@Test
public void testByte() {
assertEquals(baseStr + "[3]", new ToStringBuilder(base).append((byte) 3).toString());
assertEquals(baseStr + "[a=3]", new ToStringBuilder(base).append("a", (byte) 3).toString());
assertEquals(baseStr + "[a=3,b=4]", new ToStringBuilder(base).append("a", (byte) 3).append("b", (byte) 4).toString());
}
@SuppressWarnings("cast")
@Test
public void testDouble() {
assertEquals(baseStr + "[3.2]", new ToStringBuilder(base).append((double) 3.2).toString());
assertEquals(baseStr + "[a=3.2]", new ToStringBuilder(base).append("a", (double) 3.2).toString());
assertEquals(baseStr + "[a=3.2,b=4.3]", new ToStringBuilder(base).append("a", (double) 3.2).append("b", (double) 4.3).toString());
}
@Test
public void testFloat() {
assertEquals(baseStr + "[3.2]", new ToStringBuilder(base).append((float) 3.2).toString());
assertEquals(baseStr + "[a=3.2]", new ToStringBuilder(base).append("a", (float) 3.2).toString());
assertEquals(baseStr + "[a=3.2,b=4.3]", new ToStringBuilder(base).append("a", (float) 3.2).append("b", (float) 4.3).toString());
}
@Test
public void testBoolean() {
assertEquals(baseStr + "[true]", new ToStringBuilder(base).append(true).toString());
assertEquals(baseStr + "[a=true]", new ToStringBuilder(base).append("a", true).toString());
assertEquals(baseStr + "[a=true,b=false]", new ToStringBuilder(base).append("a", true).append("b", false).toString());
}
@Test
public void testObjectArray() {
Object[] array = new Object[] {null, base, new int[] {3, 6}};
assertEquals(baseStr + "[{<null>,5,{3,6}}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{<null>,5,{3,6}}]", new ToStringBuilder(base).append((Object) array).toString());
array = null;
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString());
}
@Test
public void testLongArray() {
long[] array = new long[] {1, 2, -3, 4};
assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append((Object) array).toString());
array = null;
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString());
}
@Test
public void testIntArray() {
int[] array = new int[] {1, 2, -3, 4};
assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append((Object) array).toString());
array = null;
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString());
}
@Test
public void testShortArray() {
short[] array = new short[] {1, 2, -3, 4};
assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append((Object) array).toString());
array = null;
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString());
}
@Test
public void testByteArray() {
byte[] array = new byte[] {1, 2, -3, 4};
assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append((Object) array).toString());
array = null;
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString());
}
@Test
public void testCharArray() {
char[] array = new char[] {'A', '2', '_', 'D'};
assertEquals(baseStr + "[{A,2,_,D}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{A,2,_,D}]", new ToStringBuilder(base).append((Object) array).toString());
array = null;
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString());
}
@Test
public void testDoubleArray() {
double[] array = new double[] {1.0, 2.9876, -3.00001, 4.3};
assertEquals(baseStr + "[{1.0,2.9876,-3.00001,4.3}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{1.0,2.9876,-3.00001,4.3}]", new ToStringBuilder(base).append((Object) array).toString());
array = null;
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString());
}
@Test
public void testFloatArray() {
float[] array = new float[] {1.0f, 2.9876f, -3.00001f, 4.3f};
assertEquals(baseStr + "[{1.0,2.9876,-3.00001,4.3}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{1.0,2.9876,-3.00001,4.3}]", new ToStringBuilder(base).append((Object) array).toString());
array = null;
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString());
}
@Test
public void testBooleanArray() {
boolean[] array = new boolean[] {true, false, false};
assertEquals(baseStr + "[{true,false,false}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{true,false,false}]", new ToStringBuilder(base).append((Object) array).toString());
array = null;
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString());
}
@Test
public void testLongArrayArray() {
long[][] array = new long[][] {{1, 2}, null, {5}};
assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append((Object) array).toString());
array = null;
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString());
}
@Test
public void testIntArrayArray() {
int[][] array = new int[][] {{1, 2}, null, {5}};
assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append((Object) array).toString());
array = null;
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString());
}
@Test
public void testShortArrayArray() {
short[][] array = new short[][] {{1, 2}, null, {5}};
assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append((Object) array).toString());
array = null;
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString());
}
@Test
public void testByteArrayArray() {
byte[][] array = new byte[][] {{1, 2}, null, {5}};
assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append((Object) array).toString());
array = null;
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString());
}
@Test
public void testCharArrayArray() {
char[][] array = new char[][] {{'A', 'B'}, null, {'p'}};
assertEquals(baseStr + "[{{A,B},<null>,{p}}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{{A,B},<null>,{p}}]", new ToStringBuilder(base).append((Object) array).toString());
array = null;
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString());
}
@Test
public void testDoubleArrayArray() {
double[][] array = new double[][] {{1.0, 2.29686}, null, {Double.NaN}};
assertEquals(baseStr + "[{{1.0,2.29686},<null>,{NaN}}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{{1.0,2.29686},<null>,{NaN}}]", new ToStringBuilder(base).append((Object) array).toString());
array = null;
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString());
}
@Test
public void testFloatArrayArray() {
float[][] array = new float[][] {{1.0f, 2.29686f}, null, {Float.NaN}};
assertEquals(baseStr + "[{{1.0,2.29686},<null>,{NaN}}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{{1.0,2.29686},<null>,{NaN}}]", new ToStringBuilder(base).append((Object) array).toString());
array = null;
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString());
}
@Test
public void testBooleanArrayArray() {
boolean[][] array = new boolean[][] {{true, false}, null, {false}};
assertEquals(baseStr + "[{{true,false},<null>,{false}}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{{true,false},<null>,{false}}]", new ToStringBuilder(base).append((Object) array).toString());
array = null;
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString());
}
@Test
public void testObjectCycle() {
ObjectCycle a = new ObjectCycle();
ObjectCycle b = new ObjectCycle();
a.obj = b;
b.obj = a;
String expected = toBaseString(a) + "[" + toBaseString(b) + "[" + toBaseString(a) + "]]";
assertEquals(expected, a.toString());
}
static class ObjectCycle {
Object obj;
@Override
public String toString() {
return new ToStringBuilder(this).append(obj).toString();
}
}
@Test
public void testSimpleReflectionStatics() {
SimpleReflectionStaticFieldsFixture instance1 = new SimpleReflectionStaticFieldsFixture();
assertEquals(
this.toBaseString(instance1) + "[staticString=staticString,staticInt=12345]",
ReflectionToStringBuilder.toString(instance1, null, false, true, SimpleReflectionStaticFieldsFixture.class));
assertEquals(
this.toBaseString(instance1) + "[staticString=staticString,staticInt=12345]",
ReflectionToStringBuilder.toString(instance1, null, true, true, SimpleReflectionStaticFieldsFixture.class));
assertEquals(
this.toBaseString(instance1) + "[staticString=staticString,staticInt=12345]",
this.toStringWithStatics(instance1, null, SimpleReflectionStaticFieldsFixture.class));
assertEquals(
this.toBaseString(instance1) + "[staticString=staticString,staticInt=12345]",
this.toStringWithStatics(instance1, null, SimpleReflectionStaticFieldsFixture.class));
}
/**
* Tests ReflectionToStringBuilder.toString() for statics.
*/
@Test
public void testReflectionStatics() {
ReflectionStaticFieldsFixture instance1 = new ReflectionStaticFieldsFixture();
assertEquals(
this.toBaseString(instance1) + "[staticString=staticString,staticInt=12345,instanceString=instanceString,instanceInt=67890]",
ReflectionToStringBuilder.toString(instance1, null, false, true, ReflectionStaticFieldsFixture.class));
assertEquals(
this.toBaseString(instance1) + "[staticString=staticString,staticInt=12345,staticTransientString=staticTransientString,staticTransientInt=54321,instanceString=instanceString,instanceInt=67890,transientString=transientString,transientInt=98765]",
ReflectionToStringBuilder.toString(instance1, null, true, true, ReflectionStaticFieldsFixture.class));
assertEquals(
this.toBaseString(instance1) + "[staticString=staticString,staticInt=12345,instanceString=instanceString,instanceInt=67890]",
this.toStringWithStatics(instance1, null, ReflectionStaticFieldsFixture.class));
assertEquals(
this.toBaseString(instance1) + "[staticString=staticString,staticInt=12345,instanceString=instanceString,instanceInt=67890]",
this.toStringWithStatics(instance1, null, ReflectionStaticFieldsFixture.class));
}
/**
* Tests ReflectionToStringBuilder.toString() for statics.
*/
@Test
public void testInheritedReflectionStatics() {
InheritedReflectionStaticFieldsFixture instance1 = new InheritedReflectionStaticFieldsFixture();
assertEquals(
this.toBaseString(instance1) + "[staticString2=staticString2,staticInt2=67890]",
ReflectionToStringBuilder.toString(instance1, null, false, true, InheritedReflectionStaticFieldsFixture.class));
assertEquals(
this.toBaseString(instance1) + "[staticString2=staticString2,staticInt2=67890,staticString=staticString,staticInt=12345]",
ReflectionToStringBuilder.toString(instance1, null, false, true, SimpleReflectionStaticFieldsFixture.class));
assertEquals(
this.toBaseString(instance1) + "[staticString2=staticString2,staticInt2=67890,staticString=staticString,staticInt=12345]",
this.toStringWithStatics(instance1, null, SimpleReflectionStaticFieldsFixture.class));
assertEquals(
this.toBaseString(instance1) + "[staticString2=staticString2,staticInt2=67890,staticString=staticString,staticInt=12345]",
this.toStringWithStatics(instance1, null, SimpleReflectionStaticFieldsFixture.class));
}
/**
* <p>This method uses reflection to build a suitable
* <code>toString</code> value which includes static fields.</p>
*
* <p>It uses <code>AccessibleObject.setAccessible</code> to gain access to private
* fields. This means that it will throw a security exception if run
* under a security manager, if the permissions are not set up correctly.
* It is also not as efficient as testing explicitly. </p>
*
* <p>Transient fields are not output.</p>
*
* <p>Superclass fields will be appended up to and including the specified superclass.
* A null superclass is treated as <code>java.lang.Object</code>.</p>
*
* <p>If the style is <code>null</code>, the default
* <code>ToStringStyle</code> is used.</p>
*
* @param object the Object to be output
* @param style the style of the <code>toString</code> to create,
* may be <code>null</code>
* @param reflectUpToClass the superclass to reflect up to (inclusive),
* may be <code>null</code>
* @return the String result
* @throws IllegalArgumentException if the Object is <code>null</code>
*/
public <T> String toStringWithStatics(T object, ToStringStyle style, Class<? super T> reflectUpToClass) {
return ReflectionToStringBuilder.toString(object, style, false, true, reflectUpToClass);
}
/**
* Tests ReflectionToStringBuilder setUpToClass().
*/
@Test
public void test_setUpToClass_valid() {
Integer val = Integer.valueOf(5);
ReflectionToStringBuilder test = new ReflectionToStringBuilder(val);
test.setUpToClass(Number.class);
test.toString();
}
/**
* Tests ReflectionToStringBuilder setUpToClass().
*/
@Test
public void test_setUpToClass_invalid() {
Integer val = Integer.valueOf(5);
ReflectionToStringBuilder test = new ReflectionToStringBuilder(val);
try {
test.setUpToClass(String.class);
fail();
} catch (IllegalArgumentException ex) {
// expected
} finally {
test.toString();
}
}
/**
* Tests ReflectionToStringBuilder.toString() for statics.
*/
class ReflectionStaticFieldsFixture {
static final String staticString = "staticString";
static final int staticInt = 12345;
static final transient String staticTransientString = "staticTransientString";
static final transient int staticTransientInt = 54321;
String instanceString = "instanceString";
int instanceInt = 67890;
transient String transientString = "transientString";
transient int transientInt = 98765;
}
/**
* Test fixture for ReflectionToStringBuilder.toString() for statics.
*/
class SimpleReflectionStaticFieldsFixture {
static final String staticString = "staticString";
static final int staticInt = 12345;
}
/**
* Test fixture for ReflectionToStringBuilder.toString() for statics.
*/
class InheritedReflectionStaticFieldsFixture extends SimpleReflectionStaticFieldsFixture {
static final String staticString2 = "staticString2";
static final int staticInt2 = 67890;
}
@Test
public void testReflectionNull() {
assertEquals("<null>", ReflectionToStringBuilder.toString(null));
}
/**
* Points out failure to print anything from appendToString methods using MULTI_LINE_STYLE.
* See issue LANG-372.
*/
class MultiLineTestObject {
Integer i = Integer.valueOf(31337);
@Override
public String toString() {
return new ToStringBuilder(this).append("testInt", i).toString();
}
}
@Test
public void testAppendToStringUsingMultiLineStyle() {
MultiLineTestObject obj = new MultiLineTestObject();
ToStringBuilder testBuilder = new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
.appendToString(obj.toString());
assertEquals(testBuilder.toString().indexOf("testInt=31337"), -1);
}
}
| src/test/java/org/apache/commons/lang3/builder/ToStringBuilderTest.java | /*
* 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.commons.lang3.builder;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.After;
import org.junit.Test;
import org.apache.commons.lang3.SystemUtils;
/**
* Unit tests for {@link org.apache.commons.lang3.builder.ToStringBuilder}.
*
* @version $Id$
*/
public class ToStringBuilderTest {
private final Integer base = Integer.valueOf(5);
private final String baseStr = base.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(base));
/*
* All tests should leave the registry empty.
*/
@After
public void after(){
validateNullToStringStyleRegistry();
}
//-----------------------------------------------------------------------
@Test
public void testConstructorEx1() {
assertEquals("<null>", new ToStringBuilder(null).toString());
}
@Test
public void testConstructorEx2() {
assertEquals("<null>", new ToStringBuilder(null, null).toString());
new ToStringBuilder(this.base, null).toString();
}
@Test
public void testConstructorEx3() {
assertEquals("<null>", new ToStringBuilder(null, null, null).toString());
new ToStringBuilder(this.base, null, null).toString();
new ToStringBuilder(this.base, ToStringStyle.DEFAULT_STYLE, null).toString();
}
@Test
public void testGetSetDefault() {
try {
ToStringBuilder.setDefaultStyle(ToStringStyle.NO_FIELD_NAMES_STYLE);
assertSame(ToStringStyle.NO_FIELD_NAMES_STYLE, ToStringBuilder.getDefaultStyle());
} finally {
// reset for other tests
ToStringBuilder.setDefaultStyle(ToStringStyle.DEFAULT_STYLE);
}
}
@Test
public void testSetDefaultEx() {
try {
ToStringBuilder.setDefaultStyle(null);
} catch (IllegalArgumentException ex) {
return;
}
fail();
}
@Test
public void testBlank() {
assertEquals(baseStr + "[]", new ToStringBuilder(base).toString());
}
/**
* Test wrapper for int primitive.
*/
@Test
public void testReflectionInteger() {
assertEquals(baseStr + "[value=5]", ToStringBuilder.reflectionToString(base));
}
/**
* Test wrapper for char primitive.
*/
@Test
public void testReflectionCharacter() {
Character c = new Character('A');
assertEquals(this.toBaseString(c) + "[value=A]", ToStringBuilder.reflectionToString(c));
}
/**
* Test wrapper for char boolean.
*/
@Test
public void testReflectionBoolean() {
Boolean b;
b = Boolean.TRUE;
assertEquals(this.toBaseString(b) + "[value=true]", ToStringBuilder.reflectionToString(b));
b = Boolean.FALSE;
assertEquals(this.toBaseString(b) + "[value=false]", ToStringBuilder.reflectionToString(b));
}
/**
* Create the same toString() as Object.toString().
* @param o the object to create the string for.
* @return a String in the Object.toString format.
*/
private String toBaseString(Object o) {
return o.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(o));
}
// Reflection Array tests
//
// Note on the following line of code repeated in the reflection array tests.
//
// assertReflectionArray("<null>", array);
//
// The expected value is not baseStr + "[<null>]" since array==null and is typed as Object.
// The null array does not carry array type information.
// If we added a primitive array type constructor and pile of associated methods,
// then type declaring type information could be carried forward. IMHO, null is null.
//
// Gary Gregory - 2003-03-12 - [email protected]
//
public void assertReflectionArray(String expected, Object actual) {
if (actual == null) {
// Until ToStringBuilder supports null objects.
return;
}
assertEquals(expected, ToStringBuilder.reflectionToString(actual));
assertEquals(expected, ToStringBuilder.reflectionToString(actual, null));
assertEquals(expected, ToStringBuilder.reflectionToString(actual, null, true));
assertEquals(expected, ToStringBuilder.reflectionToString(actual, null, false));
}
@Test
public void testReflectionObjectArray() {
Object[] array = new Object[] { null, base, new int[] { 3, 6 } };
String baseStr = this.toBaseString(array);
assertEquals(baseStr + "[{<null>,5,{3,6}}]", ToStringBuilder.reflectionToString(array));
array = null;
assertReflectionArray("<null>", array);
}
@Test
public void testReflectionLongArray() {
long[] array = new long[] { 1, 2, -3, 4 };
String baseStr = this.toBaseString(array);
assertEquals(baseStr + "[{1,2,-3,4}]", ToStringBuilder.reflectionToString(array));
array = null;
assertReflectionArray("<null>", array);
}
@Test
public void testReflectionIntArray() {
int[] array = new int[] { 1, 2, -3, 4 };
String baseStr = this.toBaseString(array);
assertEquals(baseStr + "[{1,2,-3,4}]", ToStringBuilder.reflectionToString(array));
array = null;
assertReflectionArray("<null>", array);
}
@Test
public void testReflectionShortArray() {
short[] array = new short[] { 1, 2, -3, 4 };
String baseStr = this.toBaseString(array);
assertEquals(baseStr + "[{1,2,-3,4}]", ToStringBuilder.reflectionToString(array));
array = null;
assertReflectionArray("<null>", array);
}
@Test
public void testReflectionyteArray() {
byte[] array = new byte[] { 1, 2, -3, 4 };
String baseStr = this.toBaseString(array);
assertEquals(baseStr + "[{1,2,-3,4}]", ToStringBuilder.reflectionToString(array));
array = null;
assertReflectionArray("<null>", array);
}
@Test
public void testReflectionCharArray() {
char[] array = new char[] { 'A', '2', '_', 'D' };
String baseStr = this.toBaseString(array);
assertEquals(baseStr + "[{A,2,_,D}]", ToStringBuilder.reflectionToString(array));
array = null;
assertReflectionArray("<null>", array);
}
@Test
public void testReflectionDoubleArray() {
double[] array = new double[] { 1.0, 2.9876, -3.00001, 4.3 };
String baseStr = this.toBaseString(array);
assertEquals(baseStr + "[{1.0,2.9876,-3.00001,4.3}]", ToStringBuilder.reflectionToString(array));
array = null;
assertReflectionArray("<null>", array);
}
@Test
public void testReflectionFloatArray() {
float[] array = new float[] { 1.0f, 2.9876f, -3.00001f, 4.3f };
String baseStr = this.toBaseString(array);
assertEquals(baseStr + "[{1.0,2.9876,-3.00001,4.3}]", ToStringBuilder.reflectionToString(array));
array = null;
assertReflectionArray("<null>", array);
}
@Test
public void testReflectionBooleanArray() {
boolean[] array = new boolean[] { true, false, false };
String baseStr = this.toBaseString(array);
assertEquals(baseStr + "[{true,false,false}]", ToStringBuilder.reflectionToString(array));
array = null;
assertReflectionArray("<null>", array);
}
// Reflection Array Array tests
@Test
public void testReflectionFloatArrayArray() {
float[][] array = new float[][] { { 1.0f, 2.29686f }, null, { Float.NaN } };
String baseStr = this.toBaseString(array);
assertEquals(baseStr + "[{{1.0,2.29686},<null>,{NaN}}]", ToStringBuilder.reflectionToString(array));
array = null;
assertReflectionArray("<null>", array);
}
@Test
public void testReflectionLongArrayArray() {
long[][] array = new long[][] { { 1, 2 }, null, { 5 } };
String baseStr = this.toBaseString(array);
assertEquals(baseStr + "[{{1,2},<null>,{5}}]", ToStringBuilder.reflectionToString(array));
array = null;
assertReflectionArray("<null>", array);
}
@Test
public void testReflectionIntArrayArray() {
int[][] array = new int[][] { { 1, 2 }, null, { 5 } };
String baseStr = this.toBaseString(array);
assertEquals(baseStr + "[{{1,2},<null>,{5}}]", ToStringBuilder.reflectionToString(array));
array = null;
assertReflectionArray("<null>", array);
}
@Test
public void testReflectionhortArrayArray() {
short[][] array = new short[][] { { 1, 2 }, null, { 5 } };
String baseStr = this.toBaseString(array);
assertEquals(baseStr + "[{{1,2},<null>,{5}}]", ToStringBuilder.reflectionToString(array));
array = null;
assertReflectionArray("<null>", array);
}
@Test
public void testReflectionByteArrayArray() {
byte[][] array = new byte[][] { { 1, 2 }, null, { 5 } };
String baseStr = this.toBaseString(array);
assertEquals(baseStr + "[{{1,2},<null>,{5}}]", ToStringBuilder.reflectionToString(array));
array = null;
assertReflectionArray("<null>", array);
}
@Test
public void testReflectionCharArrayArray() {
char[][] array = new char[][] { { 'A', 'B' }, null, { 'p' } };
String baseStr = this.toBaseString(array);
assertEquals(baseStr + "[{{A,B},<null>,{p}}]", ToStringBuilder.reflectionToString(array));
array = null;
assertReflectionArray("<null>", array);
}
@Test
public void testReflectionDoubleArrayArray() {
double[][] array = new double[][] { { 1.0, 2.29686 }, null, { Double.NaN } };
String baseStr = this.toBaseString(array);
assertEquals(baseStr + "[{{1.0,2.29686},<null>,{NaN}}]", ToStringBuilder.reflectionToString(array));
array = null;
assertReflectionArray("<null>", array);
}
@Test
public void testReflectionBooleanArrayArray() {
boolean[][] array = new boolean[][] { { true, false }, null, { false } };
String baseStr = this.toBaseString(array);
assertEquals(baseStr + "[{{true,false},<null>,{false}}]", ToStringBuilder.reflectionToString(array));
assertEquals(baseStr + "[{{true,false},<null>,{false}}]", ToStringBuilder.reflectionToString(array));
array = null;
assertReflectionArray("<null>", array);
}
// Reflection hierarchy tests
@Test
public void testReflectionHierarchyArrayList() {
List<Object> base = new ArrayList<Object>();
String baseStr = this.toBaseString(base);
// note, the test data depends on the internal representation of the ArrayList, which may differ between JDK versions and vendors
String expectedWithTransients = baseStr + "[elementData={<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>},size=0,modCount=0]";
String toStringWithTransients = ToStringBuilder.reflectionToString(base, null, true);
if (!expectedWithTransients.equals(toStringWithTransients)) {
// representation different for IBM JDK 1.6.0, LANG-727
if (!("IBM Corporation".equals(SystemUtils.JAVA_VENDOR) && "1.6".equals(SystemUtils.JAVA_SPECIFICATION_VERSION))) {
assertEquals(expectedWithTransients, toStringWithTransients);
}
}
String expectedWithoutTransients = baseStr + "[size=0]";
String toStringWithoutTransients = ToStringBuilder.reflectionToString(base, null, false);
if (!expectedWithoutTransients.equals(toStringWithoutTransients)) {
// representation different for IBM JDK 1.6.0, LANG-727
if (!("IBM Corporation".equals(SystemUtils.JAVA_VENDOR) && "1.6".equals(SystemUtils.JAVA_SPECIFICATION_VERSION))) {
assertEquals(expectedWithoutTransients, toStringWithoutTransients);
}
}
}
@Test
public void testReflectionHierarchy() {
ReflectionTestFixtureA baseA = new ReflectionTestFixtureA();
String baseStr = this.toBaseString(baseA);
assertEquals(baseStr + "[a=a]", ToStringBuilder.reflectionToString(baseA));
assertEquals(baseStr + "[a=a]", ToStringBuilder.reflectionToString(baseA, null));
assertEquals(baseStr + "[a=a]", ToStringBuilder.reflectionToString(baseA, null, false));
assertEquals(baseStr + "[a=a,transientA=t]", ToStringBuilder.reflectionToString(baseA, null, true));
assertEquals(baseStr + "[a=a]", ToStringBuilder.reflectionToString(baseA, null, false, null));
assertEquals(baseStr + "[a=a]", ToStringBuilder.reflectionToString(baseA, null, false, Object.class));
assertEquals(baseStr + "[a=a]", ToStringBuilder.reflectionToString(baseA, null, false, ReflectionTestFixtureA.class));
ReflectionTestFixtureB baseB = new ReflectionTestFixtureB();
baseStr = this.toBaseString(baseB);
assertEquals(baseStr + "[b=b,a=a]", ToStringBuilder.reflectionToString(baseB));
assertEquals(baseStr + "[b=b,a=a]", ToStringBuilder.reflectionToString(baseB));
assertEquals(baseStr + "[b=b,a=a]", ToStringBuilder.reflectionToString(baseB, null));
assertEquals(baseStr + "[b=b,a=a]", ToStringBuilder.reflectionToString(baseB, null, false));
assertEquals(baseStr + "[b=b,transientB=t,a=a,transientA=t]", ToStringBuilder.reflectionToString(baseB, null, true));
assertEquals(baseStr + "[b=b,a=a]", ToStringBuilder.reflectionToString(baseB, null, false, null));
assertEquals(baseStr + "[b=b,a=a]", ToStringBuilder.reflectionToString(baseB, null, false, Object.class));
assertEquals(baseStr + "[b=b,a=a]", ToStringBuilder.reflectionToString(baseB, null, false, ReflectionTestFixtureA.class));
assertEquals(baseStr + "[b=b]", ToStringBuilder.reflectionToString(baseB, null, false, ReflectionTestFixtureB.class));
}
static class ReflectionTestFixtureA {
@SuppressWarnings("unused")
private char a='a';
@SuppressWarnings("unused")
private transient char transientA='t';
}
static class ReflectionTestFixtureB extends ReflectionTestFixtureA {
@SuppressWarnings("unused")
private char b='b';
@SuppressWarnings("unused")
private transient char transientB='t';
}
@Test
public void testInnerClassReflection() {
Outer outer = new Outer();
assertEquals(toBaseString(outer) + "[inner=" + toBaseString(outer.inner) + "[]]", outer.toString());
}
static class Outer {
Inner inner = new Inner();
class Inner {
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
// Reflection cycle tests
/**
* Test an array element pointing to its container.
*/
@Test
public void testReflectionArrayCycle() throws Exception {
Object[] objects = new Object[1];
objects[0] = objects;
assertEquals(
this.toBaseString(objects) + "[{" + this.toBaseString(objects) + "}]",
ToStringBuilder.reflectionToString(objects));
}
/**
* Test an array element pointing to its container.
*/
@Test
public void testReflectionArrayCycleLevel2() throws Exception {
Object[] objects = new Object[1];
Object[] objectsLevel2 = new Object[1];
objects[0] = objectsLevel2;
objectsLevel2[0] = objects;
assertEquals(
this.toBaseString(objects) + "[{{" + this.toBaseString(objects) + "}}]",
ToStringBuilder.reflectionToString(objects));
assertEquals(
this.toBaseString(objectsLevel2) + "[{{" + this.toBaseString(objectsLevel2) + "}}]",
ToStringBuilder.reflectionToString(objectsLevel2));
}
@Test
public void testReflectionArrayArrayCycle() throws Exception {
Object[][] objects = new Object[2][2];
objects[0][0] = objects;
objects[0][1] = objects;
objects[1][0] = objects;
objects[1][1] = objects;
String basicToString = this.toBaseString(objects);
assertEquals(
basicToString
+ "[{{"
+ basicToString
+ ","
+ basicToString
+ "},{"
+ basicToString
+ ","
+ basicToString
+ "}}]",
ToStringBuilder.reflectionToString(objects));
}
/**
* A reflection test fixture.
*/
static class ReflectionTestCycleA {
ReflectionTestCycleB b;
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
/**
* A reflection test fixture.
*/
static class ReflectionTestCycleB {
ReflectionTestCycleA a;
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
/**
* A reflection test fixture.
*/
static class SimpleReflectionTestFixture {
Object o;
public SimpleReflectionTestFixture() {
}
public SimpleReflectionTestFixture(Object o) {
this.o = o;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
private static class SelfInstanceVarReflectionTestFixture {
@SuppressWarnings("unused")
private SelfInstanceVarReflectionTestFixture typeIsSelf;
public SelfInstanceVarReflectionTestFixture() {
this.typeIsSelf = this;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
private static class SelfInstanceTwoVarsReflectionTestFixture {
@SuppressWarnings("unused")
private SelfInstanceTwoVarsReflectionTestFixture typeIsSelf;
private String otherType = "The Other Type";
public SelfInstanceTwoVarsReflectionTestFixture() {
this.typeIsSelf = this;
}
public String getOtherType(){
return this.otherType;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
/**
* Test an Object pointing to itself, the simplest test.
*
* @throws Exception
*/
@Test
public void testSimpleReflectionObjectCycle() throws Exception {
SimpleReflectionTestFixture simple = new SimpleReflectionTestFixture();
simple.o = simple;
assertEquals(this.toBaseString(simple) + "[o=" + this.toBaseString(simple) + "]", simple.toString());
}
/**
* Test a class that defines an ivar pointing to itself.
*
* @throws Exception
*/
@Test
public void testSelfInstanceVarReflectionObjectCycle() throws Exception {
SelfInstanceVarReflectionTestFixture test = new SelfInstanceVarReflectionTestFixture();
assertEquals(this.toBaseString(test) + "[typeIsSelf=" + this.toBaseString(test) + "]", test.toString());
}
/**
* Test a class that defines an ivar pointing to itself. This test was
* created to show that handling cyclical object resulted in a missing endFieldSeparator call.
*
* @throws Exception
*/
@Test
public void testSelfInstanceTwoVarsReflectionObjectCycle() throws Exception {
SelfInstanceTwoVarsReflectionTestFixture test = new SelfInstanceTwoVarsReflectionTestFixture();
assertEquals(this.toBaseString(test) + "[typeIsSelf=" + this.toBaseString(test) + ",otherType=" + test.getOtherType().toString() + "]", test.toString());
}
/**
* Test Objects pointing to each other.
*
* @throws Exception
*/
@Test
public void testReflectionObjectCycle() throws Exception {
ReflectionTestCycleA a = new ReflectionTestCycleA();
ReflectionTestCycleB b = new ReflectionTestCycleB();
a.b = b;
b.a = a;
assertEquals(
this.toBaseString(a) + "[b=" + this.toBaseString(b) + "[a=" + this.toBaseString(a) + "]]",
a.toString());
}
/**
* Test a nasty combination of arrays and Objects pointing to each other.
* objects[0] -> SimpleReflectionTestFixture[ o -> objects ]
*
* @throws Exception
*/
@Test
public void testReflectionArrayAndObjectCycle() throws Exception {
Object[] objects = new Object[1];
SimpleReflectionTestFixture simple = new SimpleReflectionTestFixture(objects);
objects[0] = simple;
assertEquals(
this.toBaseString(objects)
+ "[{"
+ this.toBaseString(simple)
+ "[o="
+ this.toBaseString(objects)
+ "]"
+ "}]",
ToStringBuilder.reflectionToString(objects));
assertEquals(
this.toBaseString(simple)
+ "[o={"
+ this.toBaseString(simple)
+ "}]",
ToStringBuilder.reflectionToString(simple));
}
void validateNullToStringStyleRegistry() {
final Map<Object, Object> registry = ToStringStyle.getRegistry();
assertNull("Expected null, actual: "+registry, registry);
}
// End: Reflection cycle tests
@Test
public void testAppendSuper() {
assertEquals(baseStr + "[]", new ToStringBuilder(base).appendSuper("Integer@8888[]").toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).appendSuper("Integer@8888[<null>]").toString());
assertEquals(baseStr + "[a=hello]", new ToStringBuilder(base).appendSuper("Integer@8888[]").append("a", "hello").toString());
assertEquals(baseStr + "[<null>,a=hello]", new ToStringBuilder(base).appendSuper("Integer@8888[<null>]").append("a", "hello").toString());
assertEquals(baseStr + "[a=hello]", new ToStringBuilder(base).appendSuper(null).append("a", "hello").toString());
}
@Test
public void testAppendToString() {
assertEquals(baseStr + "[]", new ToStringBuilder(base).appendToString("Integer@8888[]").toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).appendToString("Integer@8888[<null>]").toString());
assertEquals(baseStr + "[a=hello]", new ToStringBuilder(base).appendToString("Integer@8888[]").append("a", "hello").toString());
assertEquals(baseStr + "[<null>,a=hello]", new ToStringBuilder(base).appendToString("Integer@8888[<null>]").append("a", "hello").toString());
assertEquals(baseStr + "[a=hello]", new ToStringBuilder(base).appendToString(null).append("a", "hello").toString());
}
@Test
public void testObject() {
Integer i3 = Integer.valueOf(3);
Integer i4 = Integer.valueOf(4);
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) null).toString());
assertEquals(baseStr + "[3]", new ToStringBuilder(base).append(i3).toString());
assertEquals(baseStr + "[a=<null>]", new ToStringBuilder(base).append("a", (Object) null).toString());
assertEquals(baseStr + "[a=3]", new ToStringBuilder(base).append("a", i3).toString());
assertEquals(baseStr + "[a=3,b=4]", new ToStringBuilder(base).append("a", i3).append("b", i4).toString());
assertEquals(baseStr + "[a=<Integer>]", new ToStringBuilder(base).append("a", i3, false).toString());
assertEquals(baseStr + "[a=<size=0>]", new ToStringBuilder(base).append("a", new ArrayList<Object>(), false).toString());
assertEquals(baseStr + "[a=[]]", new ToStringBuilder(base).append("a", new ArrayList<Object>(), true).toString());
assertEquals(baseStr + "[a=<size=0>]", new ToStringBuilder(base).append("a", new HashMap<Object, Object>(), false).toString());
assertEquals(baseStr + "[a={}]", new ToStringBuilder(base).append("a", new HashMap<Object, Object>(), true).toString());
assertEquals(baseStr + "[a=<size=0>]", new ToStringBuilder(base).append("a", (Object) new String[0], false).toString());
assertEquals(baseStr + "[a={}]", new ToStringBuilder(base).append("a", (Object) new String[0], true).toString());
}
@Test
public void testObjectBuild() {
Integer i3 = Integer.valueOf(3);
Integer i4 = Integer.valueOf(4);
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) null).build());
assertEquals(baseStr + "[3]", new ToStringBuilder(base).append(i3).build());
assertEquals(baseStr + "[a=<null>]", new ToStringBuilder(base).append("a", (Object) null).build());
assertEquals(baseStr + "[a=3]", new ToStringBuilder(base).append("a", i3).build());
assertEquals(baseStr + "[a=3,b=4]", new ToStringBuilder(base).append("a", i3).append("b", i4).build());
assertEquals(baseStr + "[a=<Integer>]", new ToStringBuilder(base).append("a", i3, false).build());
assertEquals(baseStr + "[a=<size=0>]", new ToStringBuilder(base).append("a", new ArrayList<Object>(), false).build());
assertEquals(baseStr + "[a=[]]", new ToStringBuilder(base).append("a", new ArrayList<Object>(), true).build());
assertEquals(baseStr + "[a=<size=0>]", new ToStringBuilder(base).append("a", new HashMap<Object, Object>(), false).build());
assertEquals(baseStr + "[a={}]", new ToStringBuilder(base).append("a", new HashMap<Object, Object>(), true).build());
assertEquals(baseStr + "[a=<size=0>]", new ToStringBuilder(base).append("a", (Object) new String[0], false).build());
assertEquals(baseStr + "[a={}]", new ToStringBuilder(base).append("a", (Object) new String[0], true).build());
}
@Test
public void testLong() {
assertEquals(baseStr + "[3]", new ToStringBuilder(base).append(3L).toString());
assertEquals(baseStr + "[a=3]", new ToStringBuilder(base).append("a", 3L).toString());
assertEquals(baseStr + "[a=3,b=4]", new ToStringBuilder(base).append("a", 3L).append("b", 4L).toString());
}
@SuppressWarnings("cast") // cast is not really needed, keep for consistency
@Test
public void testInt() {
assertEquals(baseStr + "[3]", new ToStringBuilder(base).append((int) 3).toString());
assertEquals(baseStr + "[a=3]", new ToStringBuilder(base).append("a", (int) 3).toString());
assertEquals(baseStr + "[a=3,b=4]", new ToStringBuilder(base).append("a", (int) 3).append("b", (int) 4).toString());
}
@Test
public void testShort() {
assertEquals(baseStr + "[3]", new ToStringBuilder(base).append((short) 3).toString());
assertEquals(baseStr + "[a=3]", new ToStringBuilder(base).append("a", (short) 3).toString());
assertEquals(baseStr + "[a=3,b=4]", new ToStringBuilder(base).append("a", (short) 3).append("b", (short) 4).toString());
}
@Test
public void testChar() {
assertEquals(baseStr + "[A]", new ToStringBuilder(base).append((char) 65).toString());
assertEquals(baseStr + "[a=A]", new ToStringBuilder(base).append("a", (char) 65).toString());
assertEquals(baseStr + "[a=A,b=B]", new ToStringBuilder(base).append("a", (char) 65).append("b", (char) 66).toString());
}
@Test
public void testByte() {
assertEquals(baseStr + "[3]", new ToStringBuilder(base).append((byte) 3).toString());
assertEquals(baseStr + "[a=3]", new ToStringBuilder(base).append("a", (byte) 3).toString());
assertEquals(baseStr + "[a=3,b=4]", new ToStringBuilder(base).append("a", (byte) 3).append("b", (byte) 4).toString());
}
@SuppressWarnings("cast")
@Test
public void testDouble() {
assertEquals(baseStr + "[3.2]", new ToStringBuilder(base).append((double) 3.2).toString());
assertEquals(baseStr + "[a=3.2]", new ToStringBuilder(base).append("a", (double) 3.2).toString());
assertEquals(baseStr + "[a=3.2,b=4.3]", new ToStringBuilder(base).append("a", (double) 3.2).append("b", (double) 4.3).toString());
}
@Test
public void testFloat() {
assertEquals(baseStr + "[3.2]", new ToStringBuilder(base).append((float) 3.2).toString());
assertEquals(baseStr + "[a=3.2]", new ToStringBuilder(base).append("a", (float) 3.2).toString());
assertEquals(baseStr + "[a=3.2,b=4.3]", new ToStringBuilder(base).append("a", (float) 3.2).append("b", (float) 4.3).toString());
}
@Test
public void testBoolean() {
assertEquals(baseStr + "[true]", new ToStringBuilder(base).append(true).toString());
assertEquals(baseStr + "[a=true]", new ToStringBuilder(base).append("a", true).toString());
assertEquals(baseStr + "[a=true,b=false]", new ToStringBuilder(base).append("a", true).append("b", false).toString());
}
@Test
public void testObjectArray() {
Object[] array = new Object[] {null, base, new int[] {3, 6}};
assertEquals(baseStr + "[{<null>,5,{3,6}}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{<null>,5,{3,6}}]", new ToStringBuilder(base).append((Object) array).toString());
array = null;
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString());
}
@Test
public void testLongArray() {
long[] array = new long[] {1, 2, -3, 4};
assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append((Object) array).toString());
array = null;
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString());
}
@Test
public void testIntArray() {
int[] array = new int[] {1, 2, -3, 4};
assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append((Object) array).toString());
array = null;
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString());
}
@Test
public void testShortArray() {
short[] array = new short[] {1, 2, -3, 4};
assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append((Object) array).toString());
array = null;
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString());
}
@Test
public void testByteArray() {
byte[] array = new byte[] {1, 2, -3, 4};
assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append((Object) array).toString());
array = null;
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString());
}
@Test
public void testCharArray() {
char[] array = new char[] {'A', '2', '_', 'D'};
assertEquals(baseStr + "[{A,2,_,D}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{A,2,_,D}]", new ToStringBuilder(base).append((Object) array).toString());
array = null;
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString());
}
@Test
public void testDoubleArray() {
double[] array = new double[] {1.0, 2.9876, -3.00001, 4.3};
assertEquals(baseStr + "[{1.0,2.9876,-3.00001,4.3}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{1.0,2.9876,-3.00001,4.3}]", new ToStringBuilder(base).append((Object) array).toString());
array = null;
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString());
}
@Test
public void testFloatArray() {
float[] array = new float[] {1.0f, 2.9876f, -3.00001f, 4.3f};
assertEquals(baseStr + "[{1.0,2.9876,-3.00001,4.3}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{1.0,2.9876,-3.00001,4.3}]", new ToStringBuilder(base).append((Object) array).toString());
array = null;
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString());
}
@Test
public void testBooleanArray() {
boolean[] array = new boolean[] {true, false, false};
assertEquals(baseStr + "[{true,false,false}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{true,false,false}]", new ToStringBuilder(base).append((Object) array).toString());
array = null;
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString());
}
@Test
public void testLongArrayArray() {
long[][] array = new long[][] {{1, 2}, null, {5}};
assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append((Object) array).toString());
array = null;
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString());
}
@Test
public void testIntArrayArray() {
int[][] array = new int[][] {{1, 2}, null, {5}};
assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append((Object) array).toString());
array = null;
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString());
}
@Test
public void testShortArrayArray() {
short[][] array = new short[][] {{1, 2}, null, {5}};
assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append((Object) array).toString());
array = null;
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString());
}
@Test
public void testByteArrayArray() {
byte[][] array = new byte[][] {{1, 2}, null, {5}};
assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append((Object) array).toString());
array = null;
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString());
}
@Test
public void testCharArrayArray() {
char[][] array = new char[][] {{'A', 'B'}, null, {'p'}};
assertEquals(baseStr + "[{{A,B},<null>,{p}}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{{A,B},<null>,{p}}]", new ToStringBuilder(base).append((Object) array).toString());
array = null;
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString());
}
@Test
public void testDoubleArrayArray() {
double[][] array = new double[][] {{1.0, 2.29686}, null, {Double.NaN}};
assertEquals(baseStr + "[{{1.0,2.29686},<null>,{NaN}}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{{1.0,2.29686},<null>,{NaN}}]", new ToStringBuilder(base).append((Object) array).toString());
array = null;
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString());
}
@Test
public void testFloatArrayArray() {
float[][] array = new float[][] {{1.0f, 2.29686f}, null, {Float.NaN}};
assertEquals(baseStr + "[{{1.0,2.29686},<null>,{NaN}}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{{1.0,2.29686},<null>,{NaN}}]", new ToStringBuilder(base).append((Object) array).toString());
array = null;
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString());
}
@Test
public void testBooleanArrayArray() {
boolean[][] array = new boolean[][] {{true, false}, null, {false}};
assertEquals(baseStr + "[{{true,false},<null>,{false}}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{{true,false},<null>,{false}}]", new ToStringBuilder(base).append((Object) array).toString());
array = null;
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString());
}
@Test
public void testObjectCycle() {
ObjectCycle a = new ObjectCycle();
ObjectCycle b = new ObjectCycle();
a.obj = b;
b.obj = a;
String expected = toBaseString(a) + "[" + toBaseString(b) + "[" + toBaseString(a) + "]]";
assertEquals(expected, a.toString());
}
static class ObjectCycle {
Object obj;
@Override
public String toString() {
return new ToStringBuilder(this).append(obj).toString();
}
}
@Test
public void testSimpleReflectionStatics() {
SimpleReflectionStaticFieldsFixture instance1 = new SimpleReflectionStaticFieldsFixture();
assertEquals(
this.toBaseString(instance1) + "[staticString=staticString,staticInt=12345]",
ReflectionToStringBuilder.toString(instance1, null, false, true, SimpleReflectionStaticFieldsFixture.class));
assertEquals(
this.toBaseString(instance1) + "[staticString=staticString,staticInt=12345]",
ReflectionToStringBuilder.toString(instance1, null, true, true, SimpleReflectionStaticFieldsFixture.class));
assertEquals(
this.toBaseString(instance1) + "[staticString=staticString,staticInt=12345]",
this.toStringWithStatics(instance1, null, SimpleReflectionStaticFieldsFixture.class));
assertEquals(
this.toBaseString(instance1) + "[staticString=staticString,staticInt=12345]",
this.toStringWithStatics(instance1, null, SimpleReflectionStaticFieldsFixture.class));
}
/**
* Tests ReflectionToStringBuilder.toString() for statics.
*/
@Test
public void testReflectionStatics() {
ReflectionStaticFieldsFixture instance1 = new ReflectionStaticFieldsFixture();
assertEquals(
this.toBaseString(instance1) + "[staticString=staticString,staticInt=12345,instanceString=instanceString,instanceInt=67890]",
ReflectionToStringBuilder.toString(instance1, null, false, true, ReflectionStaticFieldsFixture.class));
assertEquals(
this.toBaseString(instance1) + "[staticString=staticString,staticInt=12345,staticTransientString=staticTransientString,staticTransientInt=54321,instanceString=instanceString,instanceInt=67890,transientString=transientString,transientInt=98765]",
ReflectionToStringBuilder.toString(instance1, null, true, true, ReflectionStaticFieldsFixture.class));
assertEquals(
this.toBaseString(instance1) + "[staticString=staticString,staticInt=12345,instanceString=instanceString,instanceInt=67890]",
this.toStringWithStatics(instance1, null, ReflectionStaticFieldsFixture.class));
assertEquals(
this.toBaseString(instance1) + "[staticString=staticString,staticInt=12345,instanceString=instanceString,instanceInt=67890]",
this.toStringWithStatics(instance1, null, ReflectionStaticFieldsFixture.class));
}
/**
* Tests ReflectionToStringBuilder.toString() for statics.
*/
@Test
public void testInheritedReflectionStatics() {
InheritedReflectionStaticFieldsFixture instance1 = new InheritedReflectionStaticFieldsFixture();
assertEquals(
this.toBaseString(instance1) + "[staticString2=staticString2,staticInt2=67890]",
ReflectionToStringBuilder.toString(instance1, null, false, true, InheritedReflectionStaticFieldsFixture.class));
assertEquals(
this.toBaseString(instance1) + "[staticString2=staticString2,staticInt2=67890,staticString=staticString,staticInt=12345]",
ReflectionToStringBuilder.toString(instance1, null, false, true, SimpleReflectionStaticFieldsFixture.class));
assertEquals(
this.toBaseString(instance1) + "[staticString2=staticString2,staticInt2=67890,staticString=staticString,staticInt=12345]",
this.toStringWithStatics(instance1, null, SimpleReflectionStaticFieldsFixture.class));
assertEquals(
this.toBaseString(instance1) + "[staticString2=staticString2,staticInt2=67890,staticString=staticString,staticInt=12345]",
this.toStringWithStatics(instance1, null, SimpleReflectionStaticFieldsFixture.class));
}
/**
* <p>This method uses reflection to build a suitable
* <code>toString</code> value which includes static fields.</p>
*
* <p>It uses <code>AccessibleObject.setAccessible</code> to gain access to private
* fields. This means that it will throw a security exception if run
* under a security manager, if the permissions are not set up correctly.
* It is also not as efficient as testing explicitly. </p>
*
* <p>Transient fields are not output.</p>
*
* <p>Superclass fields will be appended up to and including the specified superclass.
* A null superclass is treated as <code>java.lang.Object</code>.</p>
*
* <p>If the style is <code>null</code>, the default
* <code>ToStringStyle</code> is used.</p>
*
* @param object the Object to be output
* @param style the style of the <code>toString</code> to create,
* may be <code>null</code>
* @param reflectUpToClass the superclass to reflect up to (inclusive),
* may be <code>null</code>
* @return the String result
* @throws IllegalArgumentException if the Object is <code>null</code>
*/
public <T> String toStringWithStatics(T object, ToStringStyle style, Class<? super T> reflectUpToClass) {
return ReflectionToStringBuilder.toString(object, style, false, true, reflectUpToClass);
}
/**
* Tests ReflectionToStringBuilder setUpToClass().
*/
@Test
public void test_setUpToClass_valid() {
Integer val = Integer.valueOf(5);
ReflectionToStringBuilder test = new ReflectionToStringBuilder(val);
test.setUpToClass(Number.class);
test.toString();
}
/**
* Tests ReflectionToStringBuilder setUpToClass().
*/
@Test
public void test_setUpToClass_invalid() {
Integer val = Integer.valueOf(5);
ReflectionToStringBuilder test = new ReflectionToStringBuilder(val);
try {
test.setUpToClass(String.class);
fail();
} catch (IllegalArgumentException ex) {
// expected
} finally {
test.toString();
}
}
/**
* Tests ReflectionToStringBuilder.toString() for statics.
*/
class ReflectionStaticFieldsFixture {
static final String staticString = "staticString";
static final int staticInt = 12345;
static final transient String staticTransientString = "staticTransientString";
static final transient int staticTransientInt = 54321;
String instanceString = "instanceString";
int instanceInt = 67890;
transient String transientString = "transientString";
transient int transientInt = 98765;
}
/**
* Test fixture for ReflectionToStringBuilder.toString() for statics.
*/
class SimpleReflectionStaticFieldsFixture {
static final String staticString = "staticString";
static final int staticInt = 12345;
}
/**
* Test fixture for ReflectionToStringBuilder.toString() for statics.
*/
class InheritedReflectionStaticFieldsFixture extends SimpleReflectionStaticFieldsFixture {
static final String staticString2 = "staticString2";
static final int staticInt2 = 67890;
}
@Test
public void testReflectionNull() {
assertEquals("<null>", ReflectionToStringBuilder.toString(null));
}
/**
* Points out failure to print anything from appendToString methods using MULTI_LINE_STYLE.
* See issue LANG-372.
*/
class MultiLineTestObject {
Integer i = Integer.valueOf(31337);
@Override
public String toString() {
return new ToStringBuilder(this).append("testInt", i).toString();
}
}
@Test
public void testAppendToStringUsingMultiLineStyle() {
MultiLineTestObject obj = new MultiLineTestObject();
ToStringBuilder testBuilder = new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
.appendToString(obj.toString());
assertEquals(testBuilder.toString().indexOf("testInt=31337"), -1);
}
}
| Do not import *
git-svn-id: bab3daebc4e66440cbcc4aded890e63215874748@1309911 13f79535-47bb-0310-9956-ffa450edef68
| src/test/java/org/apache/commons/lang3/builder/ToStringBuilderTest.java | Do not import * | <ide><path>rc/test/java/org/apache/commons/lang3/builder/ToStringBuilderTest.java
<ide> */
<ide> package org.apache.commons.lang3.builder;
<ide>
<del>import static org.junit.Assert.*;
<add>import static org.junit.Assert.assertEquals;
<add>import static org.junit.Assert.assertNull;
<add>import static org.junit.Assert.assertSame;
<add>import static org.junit.Assert.fail;
<ide>
<ide> import java.util.ArrayList;
<ide> import java.util.HashMap;
<ide> import java.util.List;
<ide> import java.util.Map;
<ide>
<add>import org.apache.commons.lang3.SystemUtils;
<ide> import org.junit.After;
<ide> import org.junit.Test;
<del>
<del>import org.apache.commons.lang3.SystemUtils;
<ide>
<ide> /**
<ide> * Unit tests for {@link org.apache.commons.lang3.builder.ToStringBuilder}. |
|
Java | apache-2.0 | 67cb6ea94ca957e31acfa0385b8a21502b3716fb | 0 | pentaho-labs/pentaho-cpython-plugin,pentaho-labs/pentaho-cpython-plugin | /*! ******************************************************************************
*
* Pentaho Data Science
*
* Copyright (C) 2002-2015 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.python;
import org.apache.commons.io.IOUtils;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.logging.LogChannelInterface;
import org.pentaho.di.core.row.RowMeta;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.row.value.ValueMetaFactory;
import org.pentaho.di.i18n.BaseMessages;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Class implementing a session for interacting with Python
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
*/
public class PythonSession {
public static enum PythonVariableType {
DataFrame, Image, String, Unknown;
}
/**
* Simple container for row meta data and rows
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
*/
public static class RowMetaAndRows {
public Object[][] m_rows;
public RowMetaInterface m_rowMeta;
}
/**
* The command used to start python
*/
private String m_pythonCommand;
/**
* The session singleton
*/
private static PythonSession s_sessionSingleton;
/**
* the current session holder
*/
private static Object s_sessionHolder;
/**
* The results of the python check script
*/
private static String s_pythonEnvCheckResults = "";
/**
* For locking
*/
protected SessionMutex m_mutex = new SessionMutex();
/**
* Server socket
*/
protected ServerSocket m_serverSocket;
/**
* Local socket for comms with the python server
*/
protected Socket m_localSocket;
/**
* The process executing the server
*/
protected Process m_serverProcess;
/**
* True when the server has been shutdown
*/
protected boolean m_shutdown;
/**
* A shutdown hook for stopping the server
*/
protected Thread m_shutdownHook;
/**
* PID of the running python server
*/
protected int m_pythonPID = -1;
/**
* The log to use
*/
protected LogChannelInterface m_log;
// TODO fix this
protected String m_kettlePluginDir = "./";
protected String m_osTmpDir = "";
/**
* Acquire the session for the requester
*
* @param requester the object requesting the session
* @return the session singleton
* @throws SessionException if python is not available
*/
public static PythonSession acquireSession( Object requester ) throws SessionException {
return s_sessionSingleton.getSession( requester );
}
/**
* Release the session so that other clients can obtain it. This method does
* nothing if the requester is not the current session holder
*
* @param requester the session holder
*/
public static void releaseSession( Object requester ) {
s_sessionSingleton.dropSession( requester );
}
/**
* Returns true if the python environment/server is available
*
* @return true if the python environment/server is available
*/
public static boolean pythonAvailable() {
return s_sessionSingleton != null;
}
protected static File installPyScriptsToTmp() throws IOException {
ClassLoader loader = PythonSession.class.getClassLoader();
InputStream in = loader.getResourceAsStream( "py/pyCheck.py" );
if ( in == null ) {
throw new IOException( "Unable to read the pyCheck.py script as a resource" );
}
String tmpDir = System.getProperty( "java.io.tmpdir" );
File tempDir = new File( tmpDir );
String pyCheckDest = tmpDir + File.separator + "pyCheck.py";
String pyServerDest = tmpDir + File.separator + "pyServer.py";
PrintWriter outW = null;
BufferedReader inR = null;
try {
outW = new PrintWriter( new BufferedWriter( new FileWriter( pyCheckDest ) ) );
inR = new BufferedReader( new InputStreamReader( in ) );
String line;
while ( ( line = inR.readLine() ) != null ) {
outW.println( line );
}
outW.flush();
outW.close();
inR.close();
in = loader.getResourceAsStream( "py/pyServer.py" );
outW = new PrintWriter( new BufferedWriter( new FileWriter( pyServerDest ) ) );
inR = new BufferedReader( new InputStreamReader( in ) );
while ( ( line = inR.readLine() ) != null ) {
outW.println( line );
}
} finally {
if ( outW != null ) {
outW.flush();
outW.close();
}
if ( inR != null ) {
inR.close();
}
}
return tempDir;
}
/**
* Private constructor
*
* @param pythonCommand the command used to start python
* @throws IOException if a problem occurs
*/
private PythonSession( String pythonCommand ) throws IOException {
m_pythonCommand = pythonCommand;
s_sessionSingleton = null;
s_pythonEnvCheckResults = "";
// Read scripts from classpath and write them to tmp.
/* String
tester =
m_kettlePluginDir + File.separator + File.separator + "resources" + File.separator + "py" + File.separator
+ "pyCheck.py"; */
File tmpDir = installPyScriptsToTmp();
m_osTmpDir = tmpDir.toString();
String tester = m_osTmpDir + File.separator + "pyCheck.py";
ProcessBuilder builder = new ProcessBuilder( pythonCommand, tester );
Process pyProcess = builder.start();
StringWriter writer = new StringWriter();
IOUtils.copy( pyProcess.getInputStream(), writer );
s_pythonEnvCheckResults = writer.toString();
s_sessionSingleton = this;
m_shutdown = false;
// launch the server socket and python server
if ( s_pythonEnvCheckResults.length() < 5 ) {
launchServer( true );
}
}
/**
* Gets the access to python for a requester. Handles locking.
*
* @param requester the requesting object
* @return the session
* @throws SessionException if python is not available
*/
private synchronized PythonSession getSession( Object requester ) throws SessionException {
if ( s_sessionSingleton == null ) {
throw new SessionException( "Python not available!" );
}
if ( s_sessionHolder == requester ) {
return this;
}
m_mutex.safeLock();
s_sessionHolder = requester;
return this;
}
/**
* Release the session for a requester
*
* @param requester the requesting object
*/
private void dropSession( Object requester ) {
if ( requester == s_sessionHolder ) {
s_sessionHolder = null;
m_mutex.unlock();
}
}
/**
* Launches the python server. Performs some basic requirements checks for the
* python environment - e.g. python needs to have numpy, pandas and sklearn
* installed.
*
* @param startPython true if the server is to actually be started. False is
* really just for debugging/development where the server can be
* manually started in a separate terminal
* @throws IOException if a problem occurs
*/
private void launchServer( boolean startPython ) throws IOException {
if ( m_log != null ) {
m_log.logDebug( "Launching server socket..." );
}
m_serverSocket = new ServerSocket( 0 );
m_serverSocket.setSoTimeout( 10000 );
int localPort = m_serverSocket.getLocalPort();
if ( m_log != null ) {
m_log.logDebug( "Local port: " + localPort );
} else {
System.err.println( "Local port: " + localPort );
}
Thread acceptThread = new Thread() {
@Override public void run() {
try {
m_localSocket = m_serverSocket.accept();
} catch ( IOException e ) {
m_localSocket = null;
}
}
};
acceptThread.start();
if ( startPython ) {
/*String
serverScript =
m_kettlePluginDir + File.separator + "resources" + File.separator + "py" + File.separator + "pyServer.py"; */
String serverScript = m_osTmpDir + File.separator + "pyServer.py";
boolean debug = m_log != null && m_log.isDebug();
ProcessBuilder
processBuilder =
new ProcessBuilder( m_pythonCommand, serverScript, "" + localPort, debug ? "debug" : "" );
m_serverProcess = processBuilder.start();
}
try {
acceptThread.join();
} catch ( InterruptedException e ) {
}
if ( m_localSocket == null ) {
shutdown();
throw new IOException( "Was unable to start python server" );
} else {
m_pythonPID = ServerUtils.receiveServerPIDAck( m_localSocket.getInputStream() );
m_shutdownHook = new Thread() {
@Override public void run() {
shutdown();
}
};
Runtime.getRuntime().addShutdownHook( m_shutdownHook );
}
}
public void setLog( LogChannelInterface log ) {
m_log = log;
}
/**
* Initialize the session. This needs to be called exactly once in order to
* run checks and launch the server. Creates a session singleton.
*
* @param pythonCommand the python command
* @return true if the server launched successfully
* @throws KettleException if there was a problem - missing packages in python,
* or python could not be started for some reason
*/
public static synchronized boolean initSession( String pythonCommand ) throws KettleException {
if ( s_sessionSingleton != null ) {
return true;
// throw new KettleException( BaseMessages.getString( ServerUtils.PKG, "PythonSession.Error.EnvAlreadyAvailable" ) );
}
try {
new PythonSession( pythonCommand );
} catch ( IOException ex ) {
throw new KettleException( ex );
}
return s_pythonEnvCheckResults.length() < 5;
}
/**
* Gets the result of running the checks in python
*
* @return a string containing the possible errors
*/
public static String getPythonEnvCheckResults() {
return s_pythonEnvCheckResults;
}
/**
* Transfer Kettle rows into python as a named pandas data frame
*
* @param rowMeta the metadata of the rows
* @param rows the rows to transfer
* @param pythonFrameName the name of the data frame to use in python
* @throws KettleException if a problem occurs
*/
public void rowsToPythonDataFrame( RowMetaInterface rowMeta, List<Object[]> rows, String pythonFrameName )
throws KettleException {
try {
ServerUtils.sendRowsToPandasDataFrame( m_log, rowMeta, rows, pythonFrameName, m_localSocket.getOutputStream(),
m_localSocket.getInputStream() );
} catch ( IOException ex ) {
throw new KettleException( ex );
}
}
/**
* Transfer a pandas data frame from python and convert into Kettle rows and metadata
*
* @param frameName the name of the pandas data frame to get
* @param includeRowIndex true to include the pandas data frame row index as a field
* @return rows and row metadata encapsulated in a RowMetaAndRows object
* @throws KettleException if a problem occurs
*/
public RowMetaAndRows rowsFromPythonDataFrame( String frameName, boolean includeRowIndex ) throws KettleException {
try {
return ServerUtils
.receiveRowsFromPandasDataFrame( m_log, frameName, includeRowIndex, m_localSocket.getOutputStream(),
m_localSocket.getInputStream() );
} catch ( IOException ex ) {
throw new KettleException( ex );
}
}
/**
* Check if a named variable is set in pythong
*
* @param pyVarName the name of the python variable to check for
* @return true if the named variable exists in the python environment
* @throws KettleException if a problem occurs
*/
public boolean checkIfPythonVariableIsSet( String pyVarName ) throws KettleException {
try {
return ServerUtils.checkIfPythonVariableIsSet( m_log, pyVarName, m_localSocket.getInputStream(),
m_localSocket.getOutputStream() );
} catch ( IOException ex ) {
throw new KettleException( ex );
}
}
/**
* Grab the contents of the debug buffer from the python server. The server
* redirects both sys out and sys err to StringIO objects. If debug has been
* specified, then server debugging output will have been collected in these
* buffers. Note that the buffers will potentially also contain output from
* the execution of arbitrary scripts too. Calling this method also resets the
* buffers.
*
* @return the contents of the sys out and sys err streams. Element 0 in the
* list contains sys out and element 1 contains sys err
* @throws KettleException if a problem occurs
*/
public List<String> getPythonDebugBuffer() throws KettleException {
try {
return ServerUtils.receiveDebugBuffer( m_localSocket.getOutputStream(), m_localSocket.getInputStream(), m_log );
} catch ( IOException ex ) {
throw new KettleException( ex );
}
}
/**
* Get the type of a variable (according to pre-defined types that we can do something with) in python
*
* @param varName the name of the variable to get the type of
* @return whether the variable is a DataFrame, Image, String or Unknown. DataFrames will be converted to rows; Images
* (png form) and Strings are output as a single row with fields for each variable value. Unknown types will be
* returned in their string form.
* @throws KettleException if a problem occurs
*/
public PythonVariableType getPythonVariableType( String varName ) throws KettleException {
try {
return ServerUtils
.getPythonVariableType( varName, m_localSocket.getOutputStream(), m_localSocket.getInputStream(), m_log );
} catch ( IOException ex ) {
throw new KettleException( ex );
}
}
/**
* Execute a python script.
*
* @param pyScript the script to execute
* @return a List of strings - index 0 contains std out from the script and
* index 1 contains std err
* @throws KettleException if a problem occurs
*/
public List<String> executeScript( String pyScript ) throws KettleException {
try {
return ServerUtils
.executeUserScript( pyScript, m_localSocket.getOutputStream(), m_localSocket.getInputStream(), m_log );
} catch ( IOException ex ) {
throw new KettleException( ex );
}
}
/**
* Get an image from python. Assumes that the image is a matplotlib.figure.Figure object. Retrieves this as png
* data and returns a BufferedImage
*
* @param varName the name of the variable containing the image in python
* @return the image as a BufferedImage
* @throws KettleException if a problem occurs
*/
public BufferedImage getImageFromPython( String varName ) throws KettleException {
try {
return ServerUtils
.getPNGImageFromPython( varName, m_localSocket.getOutputStream(), m_localSocket.getInputStream(), m_log );
} catch ( IOException ex ) {
throw new KettleException( ex );
}
}
/**
* Get the value of a variable from python in plain text form
*
* @param varName the name of the variable to get
* @return the value of the variable
* @throws KettleException if a problem occurs
*/
public String getVariableValueFromPythonAsPlainString( String varName ) throws KettleException {
try {
return ServerUtils
.receivePickledVariableValue( varName, m_localSocket.getOutputStream(), m_localSocket.getInputStream(), true,
m_log );
} catch ( IOException ex ) {
throw new KettleException( ex );
}
}
/**
* Shutdown the python server
*/
private void shutdown() {
if ( !m_shutdown ) {
try {
m_shutdown = true;
if ( m_localSocket != null ) {
if ( m_log == null ) {
System.err.println( "Sending shutdown command..." );
} else if ( m_log.isDebug() ) {
m_log.logDebug( "Sending shutdown command..." );
}
if ( m_log == null || m_log.isDebug() ) {
List<String>
outAndErr =
ServerUtils
.receiveDebugBuffer( m_localSocket.getOutputStream(), m_localSocket.getInputStream(), m_log );
if ( outAndErr.get( 0 ).length() > 0 ) {
if ( m_log == null ) {
System.err.println( "Python debug std out:\n" + outAndErr.get( 0 ) + "\n" );
} else {
m_log.logDebug( "Python debug std out:\n" + outAndErr.get( 0 ) + "\n" );
}
}
if ( outAndErr.get( 1 ).length() > 0 ) {
if ( m_log == null ) {
System.err.println( "Python debug std err:\n" + outAndErr.get( 1 ) + "\n" );
} else {
m_log.logDebug( "Python debug std err:\n" + outAndErr.get( 1 ) + "\n" );
}
}
}
ServerUtils.sendServerShutdown( m_localSocket.getOutputStream() );
m_localSocket.close();
if ( m_serverProcess != null ) {
m_serverProcess.destroy();
m_serverProcess = null;
}
}
if ( m_serverSocket != null ) {
m_serverSocket.close();
}
s_sessionSingleton = null;
} catch ( Exception ex ) {
ex.printStackTrace();
if ( m_pythonPID > 0 ) {
// try to kill process, just in case
ProcessBuilder killer;
if ( System.getProperty( "os.name" ).toLowerCase().contains( "win" ) ) {
killer = new ProcessBuilder( "taskkill", "/F", "/PID", "" + m_pythonPID );
} else {
killer = new ProcessBuilder( "kill", "-9", "" + m_pythonPID );
}
try {
killer.start();
} catch ( IOException e ) {
e.printStackTrace();
}
}
} finally {
if ( m_serverProcess != null ) {
m_serverProcess.destroy();
}
}
}
}
public static void main( String[] args ) {
try {
/* File tmp = PythonSession.installPyScriptsToTmp();
System.err.println( tmp ); */
if ( !PythonSession.initSession( "python" ) ) {
System.err.print( "Initialization failed!" );
System.exit( 1 );
}
String temp = "";
PythonSession session = PythonSession.acquireSession( temp );
Object[] rowData = { 22, 300.22, "Hello bob", false, new Date(), new Timestamp( new Date().getTime() ), null };
RowMetaInterface rowMeta = new RowMeta();
//rowMeta.addValueMeta( new ValueMeta( "Field1", ValueMetaInterface.TYPE_INTEGER ) );
rowMeta.addValueMeta( ValueMetaFactory.createValueMeta( "Field1", ValueMetaInterface.TYPE_INTEGER ) );
//rowMeta.addValueMeta( new ValueMeta( "Field2", ValueMetaInterface.TYPE_NUMBER ) );
rowMeta.addValueMeta( ValueMetaFactory.createValueMeta( "Field2", ValueMetaInterface.TYPE_NUMBER ) );
// rowMeta.addValueMeta( new ValueMeta( "Field3", ValueMetaInterface.TYPE_STRING ) );
rowMeta.addValueMeta( ValueMetaFactory.createValueMeta( "Field3", ValueMetaInterface.TYPE_STRING ));
// rowMeta.addValueMeta( new ValueMeta( "Field4", ValueMetaInterface.TYPE_BOOLEAN ) );
rowMeta.addValueMeta( ValueMetaFactory.createValueMeta( "Field4", ValueMetaInterface.TYPE_BOOLEAN ));
// rowMeta.addValueMeta( new ValueMeta( "Field5", ValueMetaInterface.TYPE_DATE ) );
rowMeta.addValueMeta( ValueMetaFactory.createValueMeta( "Field5", ValueMetaInterface.TYPE_DATE ) );
// rowMeta.addValueMeta( new ValueMeta( "Field6", ValueMetaInterface.TYPE_TIMESTAMP ) );
rowMeta.addValueMeta( ValueMetaFactory.createValueMeta( "Field6", ValueMetaInterface.TYPE_TIMESTAMP ) );
// rowMeta.addValueMeta( new ValueMeta( "NullField", ValueMetaInterface.TYPE_STRING ) );
rowMeta.addValueMeta( ValueMetaFactory.createValueMeta( "NullField", ValueMetaInterface.TYPE_STRING ));
List<Object[]> data = new ArrayList<Object[]>();
data.add( rowData );
session.rowsToPythonDataFrame( rowMeta, data, "test" );
if ( session.checkIfPythonVariableIsSet( "test" ) ) {
RowMetaAndRows fromPy = session.rowsFromPythonDataFrame( "test", false );
System.err.println( "Nubmer of field metas returned: " + fromPy.m_rowMeta.size() );
System.err.println( "Number of rows returned: " + fromPy.m_rows.length );
for ( ValueMetaInterface v : fromPy.m_rowMeta.getValueMetaList() ) {
System.err.println( "Col: " + v.getName() + " Type: " + v.getType() );
}
} else {
System.err.println( "Variable 'test' does not seem to be set in python!!!!" );
}
session.executeScript( "x = 100\n" );
if ( session.checkIfPythonVariableIsSet( "x" ) ) {
System.err.println( "Var x is set!" );
}
PythonVariableType t = session.getPythonVariableType( "x" );
System.err.println( "X is of type " + t.toString() );
} catch ( Exception ex ) {
ex.printStackTrace();
}
}
}
| src/org/pentaho/python/PythonSession.java | /*! ******************************************************************************
*
* Pentaho Data Science
*
* Copyright (C) 2002-2015 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.python;
import org.apache.commons.io.IOUtils;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.logging.LogChannelInterface;
import org.pentaho.di.core.row.RowMeta;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.row.value.ValueMetaFactory;
import org.pentaho.di.i18n.BaseMessages;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Class implementing a session for interacting with Python
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
*/
public class PythonSession {
public static enum PythonVariableType {
DataFrame, Image, String, Unknown;
}
/**
* Simple container for row meta data and rows
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
*/
public static class RowMetaAndRows {
public Object[][] m_rows;
public RowMetaInterface m_rowMeta;
}
/**
* The command used to start python
*/
private String m_pythonCommand;
/**
* The session singleton
*/
private static PythonSession s_sessionSingleton;
/**
* the current session holder
*/
private static Object s_sessionHolder;
/**
* The results of the python check script
*/
private static String s_pythonEnvCheckResults = "";
/**
* For locking
*/
protected SessionMutex m_mutex = new SessionMutex();
/**
* Server socket
*/
protected ServerSocket m_serverSocket;
/**
* Local socket for comms with the python server
*/
protected Socket m_localSocket;
/**
* The process executing the server
*/
protected Process m_serverProcess;
/**
* True when the server has been shutdown
*/
protected boolean m_shutdown;
/**
* A shutdown hook for stopping the server
*/
protected Thread m_shutdownHook;
/**
* PID of the running python server
*/
protected int m_pythonPID = -1;
/**
* The log to use
*/
protected LogChannelInterface m_log;
// TODO fix this
protected String m_kettlePluginDir = "./";
protected String m_osTmpDir = "";
/**
* Acquire the session for the requester
*
* @param requester the object requesting the session
* @return the session singleton
* @throws SessionException if python is not available
*/
public static PythonSession acquireSession( Object requester ) throws SessionException {
return s_sessionSingleton.getSession( requester );
}
/**
* Release the session so that other clients can obtain it. This method does
* nothing if the requester is not the current session holder
*
* @param requester the session holder
*/
public static void releaseSession( Object requester ) {
s_sessionSingleton.dropSession( requester );
}
/**
* Returns true if the python environment/server is available
*
* @return true if the python environment/server is available
*/
public static boolean pythonAvailable() {
return s_sessionSingleton != null;
}
protected static File installPyScriptsToTmp() throws IOException {
ClassLoader loader = PythonSession.class.getClassLoader();
InputStream in = loader.getResourceAsStream( "py/pyCheck.py" );
if ( in == null ) {
throw new IOException( "Unable to read the pyCheck.py script as a resource" );
}
String tmpDir = System.getProperty( "java.io.tmpdir" );
File tempDir = new File( tmpDir );
String pyCheckDest = tmpDir + File.separator + "pyCheck.py";
String pyServerDest = tmpDir + File.separator + "pyServer.py";
PrintWriter outW = null;
BufferedReader inR = null;
try {
outW = new PrintWriter( new BufferedWriter( new FileWriter( pyCheckDest ) ) );
inR = new BufferedReader( new InputStreamReader( in ) );
String line;
while ( ( line = inR.readLine() ) != null ) {
outW.println( line );
}
outW.flush();
outW.close();
inR.close();
in = loader.getResourceAsStream( "py/pyServer.py" );
outW = new PrintWriter( new BufferedWriter( new FileWriter( pyServerDest ) ) );
inR = new BufferedReader( new InputStreamReader( in ) );
while ( ( line = inR.readLine() ) != null ) {
outW.println( line );
}
} finally {
if ( outW != null ) {
outW.flush();
outW.close();
}
if ( inR != null ) {
inR.close();
}
}
return tempDir;
}
/**
* Private constructor
*
* @param pythonCommand the command used to start python
* @throws IOException if a problem occurs
*/
private PythonSession( String pythonCommand ) throws IOException {
m_pythonCommand = pythonCommand;
s_sessionSingleton = null;
s_pythonEnvCheckResults = "";
// Read scripts from classpath and write them to tmp.
/* String
tester =
m_kettlePluginDir + File.separator + File.separator + "resources" + File.separator + "py" + File.separator
+ "pyCheck.py"; */
File tmpDir = installPyScriptsToTmp();
m_osTmpDir = tmpDir.toString();
String tester = m_osTmpDir + File.separator + "pyCheck.py";
ProcessBuilder builder = new ProcessBuilder( pythonCommand, tester );
Process pyProcess = builder.start();
StringWriter writer = new StringWriter();
IOUtils.copy( pyProcess.getInputStream(), writer );
s_pythonEnvCheckResults = writer.toString();
s_sessionSingleton = this;
m_shutdown = false;
// launch the server socket and python server
if ( s_pythonEnvCheckResults.length() < 5 ) {
launchServer( true );
}
}
/**
* Gets the access to python for a requester. Handles locking.
*
* @param requester the requesting object
* @return the session
* @throws SessionException if python is not available
*/
private synchronized PythonSession getSession( Object requester ) throws SessionException {
if ( s_sessionSingleton == null ) {
throw new SessionException( "Python not available!" );
}
if ( s_sessionHolder == requester ) {
return this;
}
m_mutex.safeLock();
s_sessionHolder = requester;
return this;
}
/**
* Release the session for a requester
*
* @param requester the requesting object
*/
private void dropSession( Object requester ) {
if ( requester == s_sessionHolder ) {
s_sessionHolder = null;
m_mutex.unlock();
}
}
/**
* Launches the python server. Performs some basic requirements checks for the
* python environment - e.g. python needs to have numpy, pandas and sklearn
* installed.
*
* @param startPython true if the server is to actually be started. False is
* really just for debugging/development where the server can be
* manually started in a separate terminal
* @throws IOException if a problem occurs
*/
private void launchServer( boolean startPython ) throws IOException {
if ( m_log != null ) {
m_log.logDebug( "Launching server socket..." );
}
m_serverSocket = new ServerSocket( 0 );
m_serverSocket.setSoTimeout( 10000 );
int localPort = m_serverSocket.getLocalPort();
if ( m_log != null ) {
m_log.logDebug( "Local port: " + localPort );
} else {
System.err.println( "Local port: " + localPort );
}
Thread acceptThread = new Thread() {
@Override public void run() {
try {
m_localSocket = m_serverSocket.accept();
} catch ( IOException e ) {
m_localSocket = null;
}
}
};
acceptThread.start();
if ( startPython ) {
/*String
serverScript =
m_kettlePluginDir + File.separator + "resources" + File.separator + "py" + File.separator + "pyServer.py"; */
String serverScript = m_osTmpDir + File.separator + "pyServer.py";
boolean debug = m_log != null && m_log.isDebug();
ProcessBuilder
processBuilder =
new ProcessBuilder( m_pythonCommand, serverScript, "" + localPort, debug ? "debug" : "" );
m_serverProcess = processBuilder.start();
}
try {
acceptThread.join();
} catch ( InterruptedException e ) {
}
if ( m_localSocket == null ) {
shutdown();
throw new IOException( "Was unable to start python server" );
} else {
m_pythonPID = ServerUtils.receiveServerPIDAck( m_localSocket.getInputStream() );
m_shutdownHook = new Thread() {
@Override public void run() {
shutdown();
}
};
Runtime.getRuntime().addShutdownHook( m_shutdownHook );
}
}
public void setLog( LogChannelInterface log ) {
m_log = log;
}
/**
* Initialize the session. This needs to be called exactly once in order to
* run checks and launch the server. Creates a session singleton.
*
* @param pythonCommand the python command
* @return true if the server launched successfully
* @throws KettleException if there was a problem - missing packages in python,
* or python could not be started for some reason
*/
public static synchronized boolean initSession( String pythonCommand ) throws KettleException {
if ( s_sessionSingleton != null ) {
return true;
// throw new KettleException( BaseMessages.getString( ServerUtils.PKG, "PythonSession.Error.EnvAlreadyAvailable" ) );
}
try {
new PythonSession( pythonCommand );
} catch ( IOException ex ) {
throw new KettleException( ex );
}
return s_pythonEnvCheckResults.length() < 5;
}
/**
* Gets the result of running the checks in python
*
* @return a string containing the possible errors
*/
public static String getPythonEnvCheckResults() {
return s_pythonEnvCheckResults;
}
/**
* Transfer Kettle rows into python as a named pandas data frame
*
* @param rowMeta the metadata of the rows
* @param rows the rows to transfer
* @param pythonFrameName the name of the data frame to use in python
* @throws KettleException if a problem occurs
*/
public void rowsToPythonDataFrame( RowMetaInterface rowMeta, List<Object[]> rows, String pythonFrameName )
throws KettleException {
try {
ServerUtils.sendRowsToPandasDataFrame( m_log, rowMeta, rows, pythonFrameName, m_localSocket.getOutputStream(),
m_localSocket.getInputStream() );
} catch ( IOException ex ) {
throw new KettleException( ex );
}
}
/**
* Transfer a pandas data frame from python and convert into Kettle rows and metadata
*
* @param frameName the name of the pandas data frame to get
* @param includeRowIndex true to include the pandas data frame row index as a field
* @return rows and row metadata encapsulated in a RowMetaAndRows object
* @throws KettleException if a problem occurs
*/
public RowMetaAndRows rowsFromPythonDataFrame( String frameName, boolean includeRowIndex ) throws KettleException {
try {
return ServerUtils
.receiveRowsFromPandasDataFrame( m_log, frameName, includeRowIndex, m_localSocket.getOutputStream(),
m_localSocket.getInputStream() );
} catch ( IOException ex ) {
throw new KettleException( ex );
}
}
/**
* Check if a named variable is set in pythong
*
* @param pyVarName the name of the python variable to check for
* @return true if the named variable exists in the python environment
* @throws KettleException if a problem occurs
*/
public boolean checkIfPythonVariableIsSet( String pyVarName ) throws KettleException {
try {
return ServerUtils.checkIfPythonVariableIsSet( m_log, pyVarName, m_localSocket.getInputStream(),
m_localSocket.getOutputStream() );
} catch ( IOException ex ) {
throw new KettleException( ex );
}
}
/**
* Grab the contents of the debug buffer from the python server. The server
* redirects both sys out and sys err to StringIO objects. If debug has been
* specified, then server debugging output will have been collected in these
* buffers. Note that the buffers will potentially also contain output from
* the execution of arbitrary scripts too. Calling this method also resets the
* buffers.
*
* @return the contents of the sys out and sys err streams. Element 0 in the
* list contains sys out and element 1 contains sys err
* @throws KettleException if a problem occurs
*/
public List<String> getPythonDebugBuffer() throws KettleException {
try {
return ServerUtils.receiveDebugBuffer( m_localSocket.getOutputStream(), m_localSocket.getInputStream(), m_log );
} catch ( IOException ex ) {
throw new KettleException( ex );
}
}
/**
* Get the type of a variable (according to pre-defined types that we can do something with) in python
*
* @param varName the name of the variable to get the type of
* @return whether the variable is a DataFrame, Image, String or Unknown. DataFrames will be converted to rows; Images
* (png form) and Strings are output as a single row with fields for each variable value. Unknown types will be
* returned in their string form.
* @throws KettleException if a problem occurs
*/
public PythonVariableType getPythonVariableType( String varName ) throws KettleException {
try {
return ServerUtils
.getPythonVariableType( varName, m_localSocket.getOutputStream(), m_localSocket.getInputStream(), m_log );
} catch ( IOException ex ) {
throw new KettleException( ex );
}
}
/**
* Execute a python script.
*
* @param pyScript the script to execute
* @return a List of strings - index 0 contains std out from the script and
* index 1 contains std err
* @throws KettleException if a problem occurs
*/
public List<String> executeScript( String pyScript ) throws KettleException {
try {
return ServerUtils
.executeUserScript( pyScript, m_localSocket.getOutputStream(), m_localSocket.getInputStream(), m_log );
} catch ( IOException ex ) {
throw new KettleException( ex );
}
}
/**
* Get an image from python. Assumes that the image is a matplotlib.figure.Figure object. Retrieves this as png
* data and returns a BufferedImage
*
* @param varName the name of the variable containing the image in python
* @return the image as a BufferedImage
* @throws KettleException if a problem occurs
*/
public BufferedImage getImageFromPython( String varName ) throws KettleException {
try {
return ServerUtils
.getPNGImageFromPython( varName, m_localSocket.getOutputStream(), m_localSocket.getInputStream(), m_log );
} catch ( IOException ex ) {
throw new KettleException( ex );
}
}
/**
* Get the value of a variable from python in plain text form
*
* @param varName the name of the variable to get
* @return the value of the variable
* @throws KettleException if a problem occurs
*/
public String getVariableValueFromPythonAsPlainString( String varName ) throws KettleException {
try {
return ServerUtils
.receivePickledVariableValue( varName, m_localSocket.getOutputStream(), m_localSocket.getInputStream(), true,
m_log );
} catch ( IOException ex ) {
throw new KettleException( ex );
}
}
/**
* Shutdown the python server
*/
private void shutdown() {
if ( !m_shutdown ) {
try {
m_shutdown = true;
if ( m_localSocket != null ) {
if ( m_log == null ) {
System.err.println( "Sending shutdown command..." );
} else if ( m_log.isDebug() ) {
m_log.logDebug( "Sending shutdown command..." );
}
if ( m_log == null || m_log.isDebug() ) {
List<String>
outAndErr =
ServerUtils
.receiveDebugBuffer( m_localSocket.getOutputStream(), m_localSocket.getInputStream(), m_log );
if ( outAndErr.get( 0 ).length() > 0 ) {
if ( m_log == null ) {
System.err.println( "Python debug std out:\n" + outAndErr.get( 0 ) + "\n" );
} else {
m_log.logDebug( "Python debug std out:\n" + outAndErr.get( 0 ) + "\n" );
}
}
if ( outAndErr.get( 1 ).length() > 0 ) {
if ( m_log == null ) {
System.err.println( "Python debug std err:\n" + outAndErr.get( 1 ) + "\n" );
} else {
m_log.logDebug( "Python debug std err:\n" + outAndErr.get( 1 ) + "\n" );
}
}
}
ServerUtils.sendServerShutdown( m_localSocket.getOutputStream() );
m_localSocket.close();
if ( m_serverProcess != null ) {
m_serverProcess.destroy();
m_serverProcess = null;
}
}
if ( m_serverSocket != null ) {
m_serverSocket.close();
}
s_sessionSingleton = null;
} catch ( Exception ex ) {
ex.printStackTrace();
if ( m_pythonPID > 0 ) {
// try to kill process, just in case
ProcessBuilder killer;
if ( System.getProperty( "os.name" ).toLowerCase().contains( "win" ) ) {
killer = new ProcessBuilder( "takskill", "/F", "/PID", "" + m_pythonPID );
} else {
killer = new ProcessBuilder( "kill", "-9", "" + m_pythonPID );
}
try {
killer.start();
} catch ( IOException e ) {
e.printStackTrace();
}
}
} finally {
if ( m_serverProcess != null ) {
m_serverProcess.destroy();
}
}
}
}
public static void main( String[] args ) {
try {
/* File tmp = PythonSession.installPyScriptsToTmp();
System.err.println( tmp ); */
if ( !PythonSession.initSession( "python" ) ) {
System.err.print( "Initialization failed!" );
System.exit( 1 );
}
String temp = "";
PythonSession session = PythonSession.acquireSession( temp );
Object[] rowData = { 22, 300.22, "Hello bob", false, new Date(), new Timestamp( new Date().getTime() ), null };
RowMetaInterface rowMeta = new RowMeta();
//rowMeta.addValueMeta( new ValueMeta( "Field1", ValueMetaInterface.TYPE_INTEGER ) );
rowMeta.addValueMeta( ValueMetaFactory.createValueMeta( "Field1", ValueMetaInterface.TYPE_INTEGER ) );
//rowMeta.addValueMeta( new ValueMeta( "Field2", ValueMetaInterface.TYPE_NUMBER ) );
rowMeta.addValueMeta( ValueMetaFactory.createValueMeta( "Field2", ValueMetaInterface.TYPE_NUMBER ) );
// rowMeta.addValueMeta( new ValueMeta( "Field3", ValueMetaInterface.TYPE_STRING ) );
rowMeta.addValueMeta( ValueMetaFactory.createValueMeta( "Field3", ValueMetaInterface.TYPE_STRING ));
// rowMeta.addValueMeta( new ValueMeta( "Field4", ValueMetaInterface.TYPE_BOOLEAN ) );
rowMeta.addValueMeta( ValueMetaFactory.createValueMeta( "Field4", ValueMetaInterface.TYPE_BOOLEAN ));
// rowMeta.addValueMeta( new ValueMeta( "Field5", ValueMetaInterface.TYPE_DATE ) );
rowMeta.addValueMeta( ValueMetaFactory.createValueMeta( "Field5", ValueMetaInterface.TYPE_DATE ) );
// rowMeta.addValueMeta( new ValueMeta( "Field6", ValueMetaInterface.TYPE_TIMESTAMP ) );
rowMeta.addValueMeta( ValueMetaFactory.createValueMeta( "Field6", ValueMetaInterface.TYPE_TIMESTAMP ) );
// rowMeta.addValueMeta( new ValueMeta( "NullField", ValueMetaInterface.TYPE_STRING ) );
rowMeta.addValueMeta( ValueMetaFactory.createValueMeta( "NullField", ValueMetaInterface.TYPE_STRING ));
List<Object[]> data = new ArrayList<Object[]>();
data.add( rowData );
session.rowsToPythonDataFrame( rowMeta, data, "test" );
if ( session.checkIfPythonVariableIsSet( "test" ) ) {
RowMetaAndRows fromPy = session.rowsFromPythonDataFrame( "test", false );
System.err.println( "Nubmer of field metas returned: " + fromPy.m_rowMeta.size() );
System.err.println( "Number of rows returned: " + fromPy.m_rows.length );
for ( ValueMetaInterface v : fromPy.m_rowMeta.getValueMetaList() ) {
System.err.println( "Col: " + v.getName() + " Type: " + v.getType() );
}
} else {
System.err.println( "Variable 'test' does not seem to be set in python!!!!" );
}
session.executeScript( "x = 100\n" );
if ( session.checkIfPythonVariableIsSet( "x" ) ) {
System.err.println( "Var x is set!" );
}
PythonVariableType t = session.getPythonVariableType( "x" );
System.err.println( "X is of type " + t.toString() );
} catch ( Exception ex ) {
ex.printStackTrace();
}
}
}
| Fixes #10 - correct spelling of taskkill
| src/org/pentaho/python/PythonSession.java | Fixes #10 - correct spelling of taskkill | <ide><path>rc/org/pentaho/python/PythonSession.java
<ide> // try to kill process, just in case
<ide> ProcessBuilder killer;
<ide> if ( System.getProperty( "os.name" ).toLowerCase().contains( "win" ) ) {
<del> killer = new ProcessBuilder( "takskill", "/F", "/PID", "" + m_pythonPID );
<add> killer = new ProcessBuilder( "taskkill", "/F", "/PID", "" + m_pythonPID );
<ide> } else {
<ide> killer = new ProcessBuilder( "kill", "-9", "" + m_pythonPID );
<ide> } |
|
Java | mit | 937d26bf987495bc465e3588cfe6274774856733 | 0 | MontealegreLuis/hibernate-example | /**
* This source file is subject to the license that is bundled with this package in the file LICENSE.
*/
package com.codeup;
import com.codeup.console.Console;
import com.codeup.console.Menu;
import com.codeup.hibernate.repositories.CategoriesRepository;
import com.codeup.hibernate.Hibernate;
import com.codeup.hibernate.repositories.MoviesRepository;
import com.codeup.movies.console.actions.AddCategoryAction;
import com.codeup.movies.catalog.*;
import com.codeup.movies.console.CategoriesConsole;
import com.codeup.movies.console.MoviesConsole;
import com.codeup.movies.console.actions.AddMovieAction;
import com.codeup.movies.console.actions.SearchByCategoryAction;
import com.codeup.movies.console.actions.SearchMovieByTitleAction;
import org.hibernate.Session;
import java.util.Scanner;
public class Application {
public static void main(String[] args) {
Session session = Hibernate.openSession();
CategoriesRepository categories = new CategoriesRepository(session);
MoviesRepository movies = new MoviesRepository(session);
Scanner input = new Scanner(System.in).useDelimiter("\n");
Console console = new Console(input, System.out);
MoviesConsole moviesConsole = new MoviesConsole(console);
AddMovieAction addMovie = new AddMovieAction(
new AddMovie(movies),
moviesConsole,
categories
);
AddCategoryAction addCategory = new AddCategoryAction(
new AddCategory(categories),
new CategoriesConsole(console)
);
SearchMovieByTitleAction searchMovieByTitle = new SearchMovieByTitleAction(
new SearchMovieByTitle(movies),
moviesConsole
);
SearchByCategoryAction searchByCategory = new SearchByCategoryAction(
new SearchByCategory(movies),
moviesConsole,
categories
);
Menu menu = new Menu(console);
menu.addOption("Add a movie", addMovie);
menu.addOption("Add a category", addCategory);
menu.addOption("Search a movie by its title", searchMovieByTitle);
menu.addOption("View movies by category", searchByCategory);
menu.setExitMessage("Thank you!");
menu.run();
session.close();
input.close();
System.exit(0);
}
}
| src/main/java/com/codeup/Application.java | /**
* This source file is subject to the license that is bundled with this package in the file LICENSE.
*/
package com.codeup;
import com.codeup.console.Console;
import com.codeup.console.Menu;
import com.codeup.hibernate.repositories.CategoriesRepository;
import com.codeup.hibernate.Hibernate;
import com.codeup.hibernate.repositories.MoviesRepository;
import com.codeup.movies.console.actions.AddCategoryAction;
import com.codeup.movies.catalog.*;
import com.codeup.movies.console.CategoriesConsole;
import com.codeup.movies.console.MoviesConsole;
import com.codeup.movies.console.actions.AddMovieAction;
import com.codeup.movies.console.actions.SearchByCategoryAction;
import com.codeup.movies.console.actions.SearchMovieByTitleAction;
import org.hibernate.Session;
import java.util.Scanner;
public class Application {
public static void main(String[] args) {
Session session = Hibernate.openSession();
CategoriesRepository categories = new CategoriesRepository(session);
MoviesRepository movies = new MoviesRepository(session);
Scanner input = new Scanner(System.in).useDelimiter("\n");
Console console = new Console(input, System.out);
MoviesConsole moviesConsole = new MoviesConsole(console);
AddMovieAction addMovie = new AddMovieAction(
new AddMovie(movies),
moviesConsole,
categories
);
AddCategoryAction addCategory = new AddCategoryAction(
new AddCategory(categories),
new CategoriesConsole(console)
);
SearchMovieByTitleAction searchMovieByTitle = new SearchMovieByTitleAction(
new SearchMovieByTitle(movies),
moviesConsole
);
SearchByCategoryAction searchByCategory = new SearchByCategoryAction(
new SearchByCategory(movies),
moviesConsole,
categories
);
Menu menu = new Menu(console);
menu.addOption("Add a movie", addMovie);
menu.addOption("Add a category", addCategory);
menu.addOption("Search a movie by its title", searchMovieByTitle);
menu.addOption("View movies by category", searchByCategory);
menu.setExitMessage("Thank you!");
menu.run();
session.close();
input.close();
}
}
| Force exit in main application.
| src/main/java/com/codeup/Application.java | Force exit in main application. | <ide><path>rc/main/java/com/codeup/Application.java
<ide>
<ide> session.close();
<ide> input.close();
<add> System.exit(0);
<ide> }
<ide> } |
|
Java | epl-1.0 | 9c61c4942deec38823beda0473a74f174c292c0d | 0 | smeup/asup,smeup/asup,smeup/asup | package org.smeup.sys.os.prtf.base.api;
import javax.inject.Inject;
import org.smeup.sys.dk.core.annotation.Supported;
import org.smeup.sys.dk.core.annotation.ToDo;
import org.smeup.sys.il.data.QBinary;
import org.smeup.sys.il.data.QCharacter;
import org.smeup.sys.il.data.QDataStructWrapper;
import org.smeup.sys.il.data.QDatetime;
import org.smeup.sys.il.data.QDecimal;
import org.smeup.sys.il.data.QEnum;
import org.smeup.sys.il.data.QScroller;
import org.smeup.sys.il.data.annotation.DataDef;
import org.smeup.sys.il.data.annotation.Entry;
import org.smeup.sys.il.data.annotation.Program;
import org.smeup.sys.il.data.annotation.Special;
import org.smeup.sys.il.data.def.BinaryType;
import org.smeup.sys.il.data.def.DatetimeType;
import org.smeup.sys.il.memo.QResourceManager;
import org.smeup.sys.il.memo.QResourceReader;
import org.smeup.sys.il.memo.Scope;
import org.smeup.sys.os.core.OperatingSystemRuntimeException;
import org.smeup.sys.os.core.jobs.QJob;
import org.smeup.sys.os.file.QFile;
import org.smeup.sys.os.file.QFileManager;
import org.smeup.sys.os.file.QFileOverride;
import org.smeup.sys.os.file.QOperatingSystemFileFactory;
import org.smeup.sys.os.file.QPrinterFile;
@Program(name = "QDMOVRPR")
public @Supported class PrinterFileOverride {
public static enum QCPFMSG {
}
@Inject
private QFileManager fileManager;
@Inject
private QResourceManager resourceManager;
@Inject
private QJob job;
public @Entry void main(
@ToDo @DataDef(length = 10) QEnum<FILEBEINGOVERRIDDENEnum, QCharacter> fileBeingOverridden,
@ToDo @DataDef(qualified = true) OVERRIDINGTOPRINTERFILE overridingToPrinterFile,
DEVICE device,
@DataDef(length = 1) QEnum<PRINTERDEVICETYPEEnum, QCharacter> printerDeviceType,
@ToDo PAGESIZE pageSize,
@ToDo @DataDef(precision = 3, scale = 1) QEnum<LINESPERINCHEnum, QDecimal> linesPerInch,
@ToDo @DataDef(precision = 3, scale = 1) QEnum<CHARACTERSPERINCHEnum, QDecimal> charactersPerInch,
FRONTMARGIN frontMargin,
BACKMARGIN backMargin,
@ToDo @DataDef(binaryType = BinaryType.SHORT) QBinary overflowLineNumber,
@DataDef(length = 1) QEnum<FOLDRECORDSEnum, QCharacter> foldRecords,
UNPRINTABLECHARACTERACTION unprintableCharacterAction,
@DataDef(length = 1) QEnum<ALIGNPAGEEnum, QCharacter> alignPage,
@DataDef(binaryType = BinaryType.SHORT) QEnum<SOURCEDRAWEREnum, QBinary> sourceDrawer,
@DataDef(binaryType = BinaryType.INTEGER) QEnum<OUTPUTBINEnum, QBinary> outputBin,
FONT font,
@DataDef(length = 1) QEnum<FORMFEEDEnum, QCharacter> formFeed,
@DataDef(length = 1) QEnum<PRINTQUALITYEnum, QCharacter> printQuality,
@DataDef(length = 1) QEnum<CONTROLCHARACTEREnum, QCharacter> controlCharacter,
@DataDef(binaryType=BinaryType.INTEGER) QBinary channel,
@DataDef(length = 1) QEnum<FIDELITYEnum, QCharacter> fidelity,
CHARACTERIDENTIFIER characterIdentifier,
@DataDef(length = 1) QEnum<DECIMALFORMATEnum, QCharacter> decimalFormat,
FONTCHARACTERSET fontCharacterSet,
CODEDFONT codedFont,
@DataDef(qualified = true) PAGEDEFINITION pageDefinition,
@DataDef(qualified = true) FORMDEFINITION formDefinition,
@DataDef(dimension = 4, length = 4) QEnum<AFPCHARACTERSEnum, QScroller<QCharacter>> aFPCharacters,
@DataDef(length = 1) QEnum<TABLEREFERENCECHARACTERSEnum, QCharacter> tableReferenceCharacters,
@ToDo @DataDef(binaryType = BinaryType.SHORT) QEnum<DEGREEOFPAGEROTATIONEnum, QBinary> degreeOfPageRotation,
@DataDef(binaryType = BinaryType.SHORT) QEnum<PAGESPERSIDEEnum, QBinary> pagesPerSide,
@DataDef(length = 1) QEnum<REDUCEOUTPUTEnum, QCharacter> reduceOutput,
@DataDef(length = 30) QCharacter printText,
@DataDef(binaryType = BinaryType.SHORT) QEnum<HARDWAREJUSTIFICATIONEnum, QBinary> hardwareJustification,
@DataDef(length = 1) QEnum<PRINTONBOTHSIDESEnum, QCharacter> printOnBothSides,
@DataDef(length = 1) QEnum<UNITOFMEASUREEnum, QCharacter> unitOfMeasure,
FRONTSIDEOVERLAY frontSideOverlay,
BACKSIDEOVERLAY backSideOverlay,
@DataDef(length = 1) QEnum<CONVERTLINEDATAEnum, QCharacter> convertLineData,
@DataDef(length = 1) QEnum<IPDSPASSTHROUGHEnum, QCharacter> iPDSPassThrough,
@DataDef(dimension = 4, length = 10) QEnum<USERRESOURCELIBRARYLISTEnum, QScroller<QCharacter>> userResourceLibraryList,
@DataDef(length = 1) QEnum<CORNERSTAPLEEnum, QCharacter> cornerStaple,
EDGESTITCH edgeStitch,
SADDLESTITCH saddleStitch,
@DataDef(length = 1) QEnum<FONTRESOLUTIONFORFORMATTINGEnum, QCharacter> fontResolutionForFormatting,
@ToDo @DataDef(length = 1) QEnum<DEFERWRITEEnum, QCharacter> deferWrite,
@DataDef(length = 1) QEnum<SPOOLTHEDATAEnum, QCharacter> spoolTheData,
@ToDo @DataDef(qualified = true) OUTPUTQUEUE outputQueue,
@ToDo @DataDef(length = 10) QEnum<FORMTYPEEnum, QCharacter> formType,
@ToDo @DataDef(binaryType = BinaryType.SHORT) QBinary copies,
PAGERANGETOPRINT pageRangeToPrint,
@DataDef(binaryType = BinaryType.INTEGER) QEnum<MAXSPOOLEDOUTPUTRECORDSEnum, QBinary> maxSpooledOutputRecords,
@DataDef(binaryType = BinaryType.SHORT) QBinary fileSeparators,
@DataDef(length = 1) QEnum<SPOOLEDOUTPUTSCHEDULEEnum, QCharacter> spooledOutputSchedule,
@ToDo @DataDef(length = 1) QEnum<HOLDSPOOLEDFILEEnum, QCharacter> holdSpooledFile,
@ToDo @DataDef(length = 1) QEnum<SAVESPOOLEDFILEEnum, QCharacter> saveSpooledFile,
@DataDef(length = 1) QEnum<OUTPUTPRIORITYONOUTQEnum, QCharacter> outputPriorityonOUTQ,
@DataDef(length = 10) QEnum<USERDATAEnum, QCharacter> userData,
@DataDef(length = 10) QEnum<SPOOLFILEOWNEREnum, QCharacter> spoolFileOwner,
@DataDef(dimension = 4, length = 10) QEnum<USERDEFINEDOPTIONEnum, QScroller<QCharacter>> userDefinedOption,
@DataDef(length = 255) QEnum<USERDEFINEDDATAEnum, QCharacter> userDefinedData,
USERDEFINEDOBJECT userDefinedObject,
@DataDef(length = 10) QEnum<SPOOLFILENAMEEnum, QCharacter> spoolFileName,
@DataDef(datetimeType = DatetimeType.DATE) QEnum<EXPIRATIONDATEFORFILEEnum, QDatetime> expirationDateForFile,
@DataDef(binaryType = BinaryType.SHORT) QBinary daysUntilFileExpires,
@DataDef(length = 1) QEnum<USERSPECIFIEDDBCSDATAEnum, QCharacter> userSpecifiedDBCSData,
@DataDef(length = 1) QEnum<DBCSEXTENSIONCHARACTERSEnum, QCharacter> dBCSExtensionCharacters,
@DataDef(length = 1) QEnum<DBCSCHARACTERROTATIONEnum, QCharacter> dBCSCharacterRotation,
@DataDef(length = 1) QEnum<DBCSCHARACTERSPERINCHEnum, QCharacter> dBCSCharactersPerInch,
@DataDef(length = 1) QEnum<DBCSSOSISPACINGEnum, QCharacter> dBCSSOSISpacing,
DBCSCODEDFONT dBCSCodedFont,
@DataDef(length = 5000) QEnum<TOSTREAMFILEEnum, QCharacter> toStreamFile,
@DataDef(qualified = true) WORKSTATIONCUSTOMIZINGOBJECT workstationCustomizingObject,
@DataDef(binaryType = BinaryType.SHORT) QEnum<MAXIMUMFILEWAITTIMEEnum, QBinary> maximumFileWaitTime,
@DataDef(length = 1) QEnum<RECORDFORMATLEVELCHECKEnum, QCharacter> recordFormatLevelCheck,
@DataDef(length = 1) QEnum<SECUREFROMOTHEROVERRIDESEnum, QCharacter> secureFromOtherOverrides,
@ToDo @DataDef(length = 1) QEnum<OVERRIDESCOPEEnum, QCharacter> overrideScope,
@ToDo @DataDef(length = 1) QEnum<SHAREOPENDATAPATHEnum, QCharacter> shareOpenDataPath,
@DataDef(length = 1) QEnum<OPENSCOPEEnum, QCharacter> openScope) {
QFileOverride fileOverride = QOperatingSystemFileFactory.eINSTANCE.createFileOverride();
fileOverride.setName(name(fileBeingOverridden));
QPrinterFile qFile = qFile(overridingToPrinterFile);
//TODO: set attributes from command parameters
fileOverride.setFileTo(qFile);
fileManager.setFileOverride(job.getContext(), fileOverride);
}
private QPrinterFile qFile(OVERRIDINGTOPRINTERFILE overridingToPrinterFile) {
switch (overridingToPrinterFile.name.asEnum()) {
case FILE:
return QOperatingSystemFileFactory.eINSTANCE.createPrinterFile();
case OTHER:
QResourceReader<QFile> fileReader = findReader(overridingToPrinterFile.library);
QFile qFile = fileReader.lookup(overridingToPrinterFile.name.asData().trimR());
if (qFile == null) {
throw new OperatingSystemRuntimeException("File not found: " + overridingToPrinterFile.name.asString());
}
if (!(qFile instanceof QPrinterFile)) {
throw new OperatingSystemRuntimeException("Wrong file type: " + overridingToPrinterFile.name.asString());
}
return (QPrinterFile) qFile;
}
throw new RuntimeException("Shuld not happen");
}
private QResourceReader<QFile> findReader(QEnum<OVERRIDINGTOPRINTERFILE.LIBRARYEnum, QCharacter> library) {
switch (library.asEnum()) {
case CURLIB:
return resourceManager.getResourceReader(job, QFile.class, Scope.CURRENT_LIBRARY);
case LIBL:
return resourceManager.getResourceReader(job, QFile.class, Scope.LIBRARY_LIST);
case OTHER:
return resourceManager.getResourceReader(job, QFile.class, library.asData().trimR());
}
throw new RuntimeException("Shuld not happen");
}
private String name(QEnum<FILEBEINGOVERRIDDENEnum, QCharacter> fileBeingOverridden) {
switch(fileBeingOverridden.asEnum()) {
case PRTF:
return "*PRTF";
case OTHER:
return fileBeingOverridden.asData().trimR();
}
throw new RuntimeException("Shuld not happen");
}
public static enum FILEBEINGOVERRIDDENEnum {
PRTF, OTHER
}
public static class OVERRIDINGTOPRINTERFILE extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(length = 10)
public QEnum<NAMEEnum, QCharacter> name;
@DataDef(length = 10, value = "*LIBL")
public QEnum<LIBRARYEnum, QCharacter> library;
public static enum NAMEEnum {
FILE, OTHER
}
public static enum LIBRARYEnum {
LIBL, CURLIB, OTHER
}
}
public static class DEVICE extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(length = 10)
public QEnum<PRINTEREnum, QCharacter> printer;
public static enum PRINTEREnum {
SYSVAL, JOB, OTHER
}
}
public static enum PRINTERDEVICETYPEEnum {
@Special(value = "X'00'")
SCS, @Special(value = "X'01'")
IPDS, @Special(value = "X'05'")
USERASCII, @Special(value = "X'02'")
AFPDS, @Special(value = "X'03'")
LINE, @Special(value = "X'04'")
AFPDSLINE
}
public static class PAGESIZE extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(precision = 6, scale = 3)
public QDecimal pageLength;
@DataDef(precision = 6, scale = 3)
public QDecimal pageWidth;
@DataDef(length = 1, value = "*ROWCOL")
public QEnum<MEASUREMENTMETHODEnum, QCharacter> measurementMethod;
public static enum MEASUREMENTMETHODEnum {
@Special(value = "R")
ROWCOL, @Special(value = "U")
UOM
}
}
public static enum LINESPERINCHEnum {
NUM_3_0, NUM_4_0, NUM_6_0, NUM_7_5, NUM_8_0, NUM_9_0, NUM_12_0
}
public static enum CHARACTERSPERINCHEnum {
NUM_5_0, NUM_10_0, NUM_12_0, NUM_13_3, NUM_15_0, NUM_16_7, NUM_18_0, NUM_20_0
}
public static class FRONTMARGIN extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(precision = 5, scale = 3)
public QEnum<OFFSETDOWNEnum, QDecimal> offsetDown;
@DataDef(precision = 5, scale = 3)
public QDecimal offsetAcross;
public static enum OFFSETDOWNEnum {
@Special(value = "-2.000")
DEVD, OTHER
}
}
public static class BACKMARGIN extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(precision = 5, scale = 3)
public QEnum<OFFSETDOWNEnum, QDecimal> offsetDown;
@DataDef(precision = 5, scale = 3)
public QDecimal offsetAcross;
public static enum OFFSETDOWNEnum {
@Special(value = "-1.000")
FRONTMGN, @Special(value = "-2.000")
DEVD, OTHER
}
}
public static enum FOLDRECORDSEnum {
@Special(value = "N")
NO, @Special(value = "Y")
YES
}
public static class UNPRINTABLECHARACTERACTION extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(length = 1)
public QEnum<REPLACECHARACTEREnum, QCharacter> replaceCharacter;
@DataDef(length = 1, value = "*BLANK")
public QEnum<REPLACEMENTCHARACTEREnum, QCharacter> replacementCharacter;
public static enum REPLACECHARACTEREnum {
@Special(value = "N")
NO, @Special(value = "Y")
YES
}
public static enum REPLACEMENTCHARACTEREnum {
@Special(value = "X'40'")
BLANK, OTHER
}
}
public static enum ALIGNPAGEEnum {
@Special(value = "N")
NO, @Special(value = "Y")
YES
}
public static enum SOURCEDRAWEREnum {
@Special(value = "-1")
E1, @Special(value = "-2")
FORMDF, OTHER
}
public static enum OUTPUTBINEnum {
@Special(value = "0")
DEVD, OTHER
}
public static class FONT extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(length = 10)
public QEnum<IDENTIFIEREnum, QCharacter> identifier;
@DataDef(precision = 4, scale = 1, value = "*NONE")
public QEnum<POINTSIZEEnum, QDecimal> pointSize;
public static enum IDENTIFIEREnum {
CPI, DEVD, @Special(value = "2")
NUM_2, @Special(value = "002")
NUM_002, @Special(value = "3")
NUM_3, @Special(value = "003")
NUM_003, @Special(value = "5")
NUM_5, @Special(value = "005")
NUM_005, @Special(value = "8")
NUM_8, @Special(value = "008")
NUM_008, @Special(value = "10")
NUM_10, @Special(value = "010")
NUM_010, @Special(value = "11")
NUM_11, @Special(value = "011")
NUM_011, @Special(value = "12")
NUM_12, @Special(value = "012")
NUM_012, @Special(value = "13")
NUM_13, @Special(value = "013")
NUM_013, @Special(value = "18")
NUM_18, @Special(value = "018")
NUM_018, @Special(value = "19")
NUM_19, @Special(value = "019")
NUM_019, @Special(value = "20")
NUM_20, @Special(value = "020")
NUM_020, @Special(value = "21")
NUM_21, @Special(value = "021")
NUM_021, @Special(value = "25")
NUM_25, @Special(value = "025")
NUM_025, @Special(value = "26")
NUM_26, @Special(value = "026")
NUM_026, @Special(value = "30")
NUM_30, @Special(value = "030")
NUM_030, @Special(value = "31")
NUM_31, @Special(value = "031")
NUM_031, @Special(value = "36")
NUM_36, @Special(value = "036")
NUM_036, @Special(value = "38")
NUM_38, @Special(value = "038")
NUM_038, @Special(value = "39")
NUM_39, @Special(value = "039")
NUM_039, @Special(value = "40")
NUM_40, @Special(value = "040")
NUM_040, @Special(value = "41")
NUM_41, @Special(value = "041")
NUM_041, @Special(value = "42")
NUM_42, @Special(value = "042")
NUM_042, @Special(value = "43")
NUM_43, @Special(value = "043")
NUM_043, @Special(value = "44")
NUM_44, @Special(value = "044")
NUM_044, @Special(value = "46")
NUM_46, @Special(value = "046")
NUM_046, @Special(value = "49")
NUM_49, @Special(value = "049")
NUM_049, @Special(value = "50")
NUM_50, @Special(value = "050")
NUM_050, @Special(value = "51")
NUM_51, @Special(value = "051")
NUM_051, @Special(value = "52")
NUM_52, @Special(value = "052")
NUM_052, @Special(value = "55")
NUM_55, @Special(value = "055")
NUM_055, @Special(value = "61")
NUM_61, @Special(value = "061")
NUM_061, @Special(value = "62")
NUM_62, @Special(value = "062")
NUM_062, @Special(value = "63")
NUM_63, @Special(value = "063")
NUM_063, @Special(value = "64")
NUM_64, @Special(value = "064")
NUM_064, @Special(value = "66")
NUM_66, @Special(value = "066")
NUM_066, @Special(value = "68")
NUM_68, @Special(value = "068")
NUM_068, @Special(value = "69")
NUM_69, @Special(value = "069")
NUM_069, @Special(value = "70")
NUM_70, @Special(value = "070")
NUM_070, @Special(value = "71")
NUM_71, @Special(value = "071")
NUM_071, @Special(value = "72")
NUM_72, @Special(value = "072")
NUM_072, @Special(value = "74")
NUM_74, @Special(value = "074")
NUM_074, @Special(value = "75")
NUM_75, @Special(value = "075")
NUM_075, @Special(value = "76")
NUM_76, @Special(value = "076")
NUM_076, @Special(value = "78")
NUM_78, @Special(value = "078")
NUM_078, @Special(value = "80")
NUM_80, @Special(value = "080")
NUM_080, @Special(value = "84")
NUM_84, @Special(value = "084")
NUM_084, @Special(value = "85")
NUM_85, @Special(value = "085")
NUM_085, @Special(value = "86")
NUM_86, @Special(value = "086")
NUM_086, @Special(value = "87")
NUM_87, @Special(value = "087")
NUM_087, @Special(value = "91")
NUM_91, @Special(value = "091")
NUM_091, @Special(value = "92")
NUM_92, @Special(value = "092")
NUM_092, @Special(value = "95")
NUM_95, @Special(value = "095")
NUM_095, @Special(value = "96")
NUM_96, @Special(value = "096")
NUM_096, @Special(value = "98")
NUM_98, @Special(value = "098")
NUM_098, @Special(value = "99")
NUM_99, @Special(value = "099")
NUM_099, @Special(value = "101")
NUM_101, @Special(value = "102")
NUM_102, @Special(value = "103")
NUM_103, @Special(value = "109")
NUM_109, @Special(value = "110")
NUM_110, @Special(value = "111")
NUM_111, @Special(value = "112")
NUM_112, @Special(value = "154")
NUM_154, @Special(value = "155")
NUM_155, @Special(value = "157")
NUM_157, @Special(value = "158")
NUM_158, @Special(value = "159")
NUM_159, @Special(value = "160")
NUM_160, @Special(value = "162")
NUM_162, @Special(value = "163")
NUM_163, @Special(value = "164")
NUM_164, @Special(value = "167")
NUM_167, @Special(value = "168")
NUM_168, @Special(value = "173")
NUM_173, @Special(value = "174")
NUM_174, @Special(value = "175")
NUM_175, @Special(value = "178")
NUM_178, @Special(value = "179")
NUM_179, @Special(value = "180")
NUM_180, @Special(value = "181")
NUM_181, @Special(value = "182")
NUM_182, @Special(value = "183")
NUM_183, @Special(value = "186")
NUM_186, @Special(value = "187")
NUM_187, @Special(value = "188")
NUM_188, @Special(value = "189")
NUM_189, @Special(value = "190")
NUM_190, @Special(value = "191")
NUM_191, @Special(value = "194")
NUM_194, @Special(value = "195")
NUM_195, @Special(value = "204")
NUM_204, @Special(value = "205")
NUM_205, @Special(value = "211")
NUM_211, @Special(value = "212")
NUM_212, @Special(value = "221")
NUM_221, @Special(value = "222")
NUM_222, @Special(value = "223")
NUM_223, @Special(value = "225")
NUM_225, @Special(value = "226")
NUM_226, @Special(value = "229")
NUM_229, @Special(value = "230")
NUM_230, @Special(value = "232")
NUM_232, @Special(value = "233")
NUM_233, @Special(value = "234")
NUM_234, @Special(value = "244")
NUM_244, @Special(value = "245")
NUM_245, @Special(value = "247")
NUM_247, @Special(value = "248")
NUM_248, @Special(value = "249")
NUM_249, @Special(value = "252")
NUM_252, @Special(value = "253")
NUM_253, @Special(value = "254")
NUM_254, @Special(value = "255")
NUM_255, @Special(value = "256")
NUM_256, @Special(value = "258")
NUM_258, @Special(value = "259")
NUM_259, @Special(value = "279")
NUM_279, @Special(value = "281")
NUM_281, @Special(value = "282")
NUM_282, @Special(value = "285")
NUM_285, @Special(value = "290")
NUM_290, @Special(value = "300")
NUM_300, @Special(value = "304")
NUM_304, @Special(value = "305")
NUM_305, @Special(value = "306")
NUM_306, @Special(value = "307")
NUM_307, @Special(value = "318")
NUM_318, @Special(value = "319")
NUM_319, @Special(value = "400")
NUM_400, @Special(value = "404")
NUM_404, @Special(value = "416")
NUM_416, @Special(value = "420")
NUM_420, @Special(value = "424")
NUM_424, @Special(value = "428")
NUM_428, @Special(value = "432")
NUM_432, @Special(value = "434")
NUM_434, @Special(value = "435")
NUM_435, @Special(value = "751")
NUM_751, @Special(value = "752")
NUM_752, @Special(value = "753")
NUM_753, @Special(value = "754")
NUM_754, @Special(value = "755")
NUM_755, @Special(value = "756")
NUM_756, @Special(value = "757")
NUM_757, @Special(value = "758")
NUM_758, @Special(value = "759")
NUM_759, @Special(value = "760")
NUM_760, @Special(value = "761")
NUM_761, @Special(value = "762")
NUM_762, @Special(value = "763")
NUM_763, @Special(value = "764")
NUM_764, @Special(value = "765")
NUM_765, @Special(value = "1051")
NUM_1051, @Special(value = "1053")
NUM_1053, @Special(value = "1056")
NUM_1056, @Special(value = "1351")
NUM_1351, @Special(value = "1653")
NUM_1653, @Special(value = "1803")
NUM_1803, @Special(value = "2103")
NUM_2103, @Special(value = "2304")
NUM_2304, @Special(value = "2305")
NUM_2305, @Special(value = "2306")
NUM_2306, @Special(value = "2307")
NUM_2307, @Special(value = "2308")
NUM_2308, @Special(value = "2309")
NUM_2309, @Special(value = "2310")
NUM_2310, @Special(value = "2311")
NUM_2311, @Special(value = "4407")
NUM_4407, @Special(value = "4427")
NUM_4427, @Special(value = "4535")
NUM_4535, @Special(value = "4919")
NUM_4919, @Special(value = "4939")
NUM_4939, @Special(value = "5047")
NUM_5047, @Special(value = "5067")
NUM_5067, @Special(value = "5687")
NUM_5687, @Special(value = "5707")
NUM_5707, @Special(value = "5815")
NUM_5815, @Special(value = "5835")
NUM_5835, @Special(value = "5943")
NUM_5943, @Special(value = "6199")
NUM_6199, @Special(value = "6219")
NUM_6219, @Special(value = "6327")
NUM_6327, @Special(value = "6347")
NUM_6347, @Special(value = "8503")
NUM_8503, @Special(value = "8523")
NUM_8523, @Special(value = "8631")
NUM_8631, @Special(value = "8651")
NUM_8651, @Special(value = "8759")
NUM_8759, @Special(value = "8779")
NUM_8779, @Special(value = "8887")
NUM_8887, @Special(value = "8907")
NUM_8907, @Special(value = "12855")
NUM_12855, @Special(value = "12875")
NUM_12875, @Special(value = "16951")
NUM_16951, @Special(value = "16971")
NUM_16971, @Special(value = "17079")
NUM_17079, @Special(value = "17099")
NUM_17099, @Special(value = "33335")
NUM_33335, @Special(value = "33355")
NUM_33355, @Special(value = "33463")
NUM_33463, @Special(value = "33483")
NUM_33483, @Special(value = "33591")
NUM_33591, @Special(value = "33601")
NUM_33601, @Special(value = "33719")
NUM_33719, @Special(value = "33729")
NUM_33729, @Special(value = "34103")
NUM_34103, @Special(value = "34123")
NUM_34123, @Special(value = "34231")
NUM_34231, @Special(value = "34251")
NUM_34251, @Special(value = "37431")
NUM_37431, @Special(value = "41783")
NUM_41783, @Special(value = "41803")
NUM_41803, OTHER
}
public static enum POINTSIZEEnum {
@Special(value = "0.0")
NONE, OTHER
}
}
public static enum FORMFEEDEnum {
@Special(value = "X'00'")
DEVD, @Special(value = "X'01'")
CONT, @Special(value = "X'02'")
CUT, @Special(value = "X'04'")
CONT2, @Special(value = "X'03'")
AUTOCUT
}
public static enum PRINTQUALITYEnum {
@Special(value = "X'00'")
STD, @Special(value = "X'03'")
DEVD, @Special(value = "X'01'")
DRAFT, @Special(value = "X'02'")
NLQ, @Special(value = "X'04'")
FASTDRAFT
}
public static enum CONTROLCHARACTEREnum {
@Special(value = "X'00'")
NONE, @Special(value = "X'01'")
FCFC, @Special(value = "X'02'")
MACHINE
}
public static class CHANNELVALUES extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(binaryType = BinaryType.SHORT)
public QBinary channel;
}
public static enum FIDELITYEnum {
@Special(value = "C")
CONTENT, @Special(value = "A")
ABSOLUTE
}
public static class CHARACTERIDENTIFIER extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(binaryType = BinaryType.SHORT)
public QEnum<GRAPHICCHARACTERSETEnum, QBinary> graphicCharacterSet;
@DataDef(binaryType = BinaryType.SHORT)
public QBinary codePage;
public static enum GRAPHICCHARACTERSETEnum {
@Special(value = "0")
DEVD, @Special(value = "-1")
SYSVAL, @Special(value = "-2")
JOBCCSID, @Special(value = "-3")
CHRIDCTL, OTHER
}
}
public static enum DECIMALFORMATEnum {
@Special(value = "X'00'")
FILE, @Special(value = "X'80'")
JOB
}
public static class FONTCHARACTERSET extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(qualified = true)
public QEnum<CHARACTERSETEnum, FONTCHARACTERSET.CHARACTERSET> characterSet;
@DataDef(qualified = true)
public FONTCHARACTERSET.CODEPAGE codePage;
@DataDef(precision = 4, scale = 1, value = "*NONE")
public QEnum<POINTSIZEEnum, QDecimal> pointSize;
public static class CHARACTERSET extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(length = 8)
public QCharacter name;
@DataDef(length = 10, value = "*LIBL")
public QEnum<LIBRARYEnum, QCharacter> library;
public static enum LIBRARYEnum {
LIBL, CURLIB, OTHER
}
}
public static enum CHARACTERSETEnum {
FONT, OTHER
}
public static class CODEPAGE extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(length = 8)
public QCharacter name;
@DataDef(length = 10, value = "*LIBL")
public QEnum<LIBRARYEnum, QCharacter> library;
public static enum LIBRARYEnum {
LIBL, CURLIB, OTHER
}
}
public static enum POINTSIZEEnum {
@Special(value = "0.0")
NONE, OTHER
}
}
public static class CODEDFONT extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(qualified = true)
public QEnum<CODEDFONTEnum, CODEDFONT.CODEDFONTStruct> codedFont;
@DataDef(precision = 4, scale = 1, value = "*NONE")
public QEnum<POINTSIZEEnum, QDecimal> pointSize;
public static class CODEDFONTStruct extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(length = 8)
public QCharacter name;
@DataDef(length = 10, value = "*LIBL")
public QEnum<LIBRARYEnum, QCharacter> library;
public static enum LIBRARYEnum {
LIBL, CURLIB, OTHER
}
}
public static enum CODEDFONTEnum {
FNTCHRSET, OTHER
}
public static enum POINTSIZEEnum {
@Special(value = "0.0")
NONE, OTHER
}
}
public static class PAGEDEFINITION extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(length = 10)
public QEnum<NAMEEnum, QCharacter> name;
@DataDef(length = 10, value = "*LIBL")
public QEnum<LIBRARYEnum, QCharacter> library;
public static enum NAMEEnum {
NONE, OTHER
}
public static enum LIBRARYEnum {
LIBL, CURLIB, OTHER
}
}
public static class FORMDEFINITION extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(length = 10)
public QEnum<NAMEEnum, QCharacter> name;
@DataDef(length = 10, value = "*LIBL")
public QEnum<LIBRARYEnum, QCharacter> library;
public static enum NAMEEnum {
NONE, DEVD, OTHER
}
public static enum LIBRARYEnum {
LIBL, CURLIB, OTHER
}
}
public static enum AFPCHARACTERSEnum {
@Special(value = "*NON")
NONE, OTHER
}
public static enum TABLEREFERENCECHARACTERSEnum {
@Special(value = "X'00'")
NO, @Special(value = "X'01'")
YES
}
public static enum DEGREEOFPAGEROTATIONEnum {
@Special(value = "-2")
AUTO, @Special(value = "0")
DEVD, @Special(value = "-1")
COR, @Special(value = "360")
NUM_0, @Special(value = "90")
NUM_90, @Special(value = "180")
NUM_180, @Special(value = "270")
NUM_270
}
public static enum PAGESPERSIDEEnum {
@Special(value = "0")
NUM_1, OTHER
}
public static enum REDUCEOUTPUTEnum {
@Special(value = "X'00'")
TEXT, @Special(value = "X'01'")
NONE
}
public static enum HARDWAREJUSTIFICATIONEnum {
NUM_0, NUM_50, NUM_100
}
public static enum PRINTONBOTHSIDESEnum {
@Special(value = "X'00'")
NO, @Special(value = "X'01'")
YES, @Special(value = "X'02'")
TUMBLE, @Special(value = "X'FF'")
FORMDF
}
public static enum UNITOFMEASUREEnum {
@Special(value = "X'00'")
INCH, @Special(value = "X'01'")
CM
}
public static class FRONTSIDEOVERLAY extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(qualified = true)
public QEnum<OVERLAYEnum, FRONTSIDEOVERLAY.OVERLAY> overlay;
@DataDef(precision = 5, scale = 3, value = "0")
public QDecimal offsetDown;
@DataDef(precision = 5, scale = 3, value = "0")
public QDecimal offsetAcross;
public static class OVERLAY extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(length = 8)
public QCharacter name;
@DataDef(length = 10, value = "*LIBL")
public QEnum<LIBRARYEnum, QCharacter> library;
public static enum LIBRARYEnum {
LIBL, CURLIB, OTHER
}
}
public static enum OVERLAYEnum {
NONE, OTHER
}
}
public static class BACKSIDEOVERLAY extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(qualified = true)
public QEnum<OVERLAYEnum, BACKSIDEOVERLAY.OVERLAY> overlay;
@DataDef(precision = 5, scale = 3, value = "0")
public QDecimal offsetDown;
@DataDef(precision = 5, scale = 3, value = "0")
public QDecimal offsetAcross;
@DataDef(length = 1, value = "*NOCONSTANT")
public QEnum<CONSTANTBACKEnum, QCharacter> constantBack;
public static class OVERLAY extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(length = 8)
public QCharacter name;
@DataDef(length = 10, value = "*LIBL")
public QEnum<LIBRARYEnum, QCharacter> library;
public static enum LIBRARYEnum {
LIBL, CURLIB, OTHER
}
}
public static enum OVERLAYEnum {
@Special(value = "*FRONT")
FRONTOVL, NONE, OTHER
}
public static enum CONSTANTBACKEnum {
@Special(value = "N")
NOCONSTANT, @Special(value = "C")
CONSTANT
}
}
public static enum CONVERTLINEDATAEnum {
@Special(value = "X'00'")
NO, @Special(value = "X'80'")
YES
}
public static enum IPDSPASSTHROUGHEnum {
@Special(value = "X'02'")
YES, @Special(value = "X'01'")
NO, @Special(value = "X'00'")
DEVD
}
public static enum USERRESOURCELIBRARYLISTEnum {
DEVD, NONE, JOBLIBL, CURLIB, OTHER
}
public static enum CORNERSTAPLEEnum {
@Special(value = "X'00'")
NONE, @Special(value = "X'01'")
BOTRIGHT, @Special(value = "X'02'")
TOPRIGHT, @Special(value = "X'03'")
TOPLEFT, @Special(value = "X'04'")
BOTLEFT, @Special(value = "X'FF'")
DEVD
}
public static class EDGESTITCH extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(length = 1)
public QEnum<REFERENCEEDGEEnum, QCharacter> referenceEdge;
@DataDef(precision = 7, scale = 4)
public QEnum<REFERENCEEDGEOFFSETEnum, QDecimal> referenceEdgeOffset;
@DataDef(binaryType = BinaryType.SHORT)
public QEnum<NUMBEROFSTAPLESEnum, QBinary> numberOfStaples;
@DataDef(dimension = 122, precision = 7, scale = 4)
public QEnum<STAPLEOFFSETSEnum, QScroller<QDecimal>> stapleOffsets;
public static enum REFERENCEEDGEEnum {
@Special(value = "X'00'")
NONE, @Special(value = "X'01'")
BOT, @Special(value = "X'02'")
RIGHT, @Special(value = "X'03'")
TOP, @Special(value = "X'04'")
LEFT, @Special(value = "X'FF'")
DEVD
}
public static enum REFERENCEEDGEOFFSETEnum {
@Special(value = "-1.0000")
DEVD, OTHER
}
public static enum NUMBEROFSTAPLESEnum {
@Special(value = "-1")
DEVD, OTHER
}
public static enum STAPLEOFFSETSEnum {
@Special(value = "-1.0000")
DEVD, OTHER
}
}
public static class SADDLESTITCH extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(length = 1)
public QEnum<REFERENCEEDGEEnum, QCharacter> referenceEdge;
@DataDef(binaryType = BinaryType.SHORT)
public QEnum<NUMBEROFSTAPLESEnum, QBinary> numberOfStaples;
@DataDef(dimension = 122, precision = 7, scale = 4)
public QEnum<STAPLEOFFSETSEnum, QScroller<QDecimal>> stapleOffsets;
public static enum REFERENCEEDGEEnum {
@Special(value = "X'00'")
NONE, @Special(value = "X'03'")
TOP, @Special(value = "X'04'")
LEFT, @Special(value = "X'FF'")
DEVD
}
public static enum NUMBEROFSTAPLESEnum {
@Special(value = "-1")
DEVD, OTHER
}
public static enum STAPLEOFFSETSEnum {
@Special(value = "-1.0000")
DEVD, OTHER
}
}
public static enum FONTRESOLUTIONFORFORMATTINGEnum {
@Special(value = "X'00'")
DEVD, @Special(value = "X'01'")
SEARCH, @Special(value = "X'02'")
NUM_240, @Special(value = "X'03'")
NUM_300
}
public static enum DEFERWRITEEnum {
@Special(value = "X'00'")
YES, @Special(value = "X'01'")
NO
}
public static enum SPOOLTHEDATAEnum {
@Special(value = "Y")
YES, @Special(value = "N")
NO
}
public static class OUTPUTQUEUE extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(length = 10)
public QEnum<NAMEEnum, QCharacter> name;
@DataDef(length = 10, value = "*LIBL")
public QEnum<LIBRARYEnum, QCharacter> library;
public static enum NAMEEnum {
DEV, JOB, OTHER
}
public static enum LIBRARYEnum {
LIBL, CURLIB, OTHER
}
}
public static enum FORMTYPEEnum {
STD, OTHER
}
public static class PAGERANGETOPRINT extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(binaryType = BinaryType.INTEGER)
public QEnum<STARTINGPAGEEnum, QBinary> startingPage;
@DataDef(binaryType = BinaryType.INTEGER)
public QEnum<ENDINGPAGEEnum, QBinary> endingPage;
public static enum STARTINGPAGEEnum {
@Special(value = "0")
NUM_1, @Special(value = "-1")
ENDPAGE, OTHER
}
public static enum ENDINGPAGEEnum {
@Special(value = "0")
END, OTHER
}
}
public static enum MAXSPOOLEDOUTPUTRECORDSEnum {
@Special(value = "0")
NOMAX, OTHER
}
public static enum SPOOLEDOUTPUTSCHEDULEEnum {
@Special(value = "J")
JOBEND, @Special(value = "F")
FILEEND, @Special(value = "I")
IMMED
}
public static enum HOLDSPOOLEDFILEEnum {
@Special(value = "N")
NO, @Special(value = "Y")
YES
}
public static enum SAVESPOOLEDFILEEnum {
@Special(value = "N")
NO, @Special(value = "Y")
YES
}
public static enum OUTPUTPRIORITYONOUTQEnum {
@Special(value = "X'00'")
JOB, @Special(value = "X'01'")
NUM_1, @Special(value = "X'02'")
NUM_2, @Special(value = "X'03'")
NUM_3, @Special(value = "X'04'")
NUM_4, @Special(value = "X'05'")
NUM_5, @Special(value = "X'06'")
NUM_6, @Special(value = "X'07'")
NUM_7, @Special(value = "X'08'")
NUM_8, @Special(value = "X'09'")
NUM_9
}
public static enum USERDATAEnum {
SOURCE, OTHER
}
public static enum SPOOLFILEOWNEREnum {
CURUSRPRF, JOB, CURGRPPRF, JOBGRPPRF
}
public static enum USERDEFINEDOPTIONEnum {
NONE, OTHER
}
public static enum USERDEFINEDDATAEnum {
NONE, OTHER
}
public static class USERDEFINEDOBJECT extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(qualified = true)
public QEnum<OBJECTEnum, USERDEFINEDOBJECT.OBJECT> object;
@DataDef(length = 10)
public QEnum<OBJECTTYPEEnum, QCharacter> objectType;
public static class OBJECT extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(length = 10)
public QCharacter name;
@DataDef(length = 10, value = "*LIBL")
public QEnum<LIBRARYEnum, QCharacter> library;
public static enum LIBRARYEnum {
LIBL, CURLIB, OTHER
}
}
public static enum OBJECTEnum {
NONE, OTHER
}
public static enum OBJECTTYPEEnum {
@Special(value = "DTAARA")
DTAARA, @Special(value = "DTAQ")
DTAQ, @Special(value = "FILE")
FILE, @Special(value = "PSFCFG")
PSFCFG, @Special(value = "USRIDX")
USRIDX, @Special(value = "USRQ")
USRQ, @Special(value = "USRSPC")
USRSPC
}
}
public static enum SPOOLFILENAMEEnum {
FILE, OTHER
}
public static enum EXPIRATIONDATEFORFILEEnum {
@Special(value = "0000000")
NONE, @Special(value = "0999998")
DAYS, OTHER
}
public static enum USERSPECIFIEDDBCSDATAEnum {
@Special(value = "N")
NO, @Special(value = "Y")
YES
}
public static enum DBCSEXTENSIONCHARACTERSEnum {
@Special(value = "Y")
YES, @Special(value = "N")
NO
}
public static enum DBCSCHARACTERROTATIONEnum {
@Special(value = "N")
NO, @Special(value = "Y")
YES
}
public static enum DBCSCHARACTERSPERINCHEnum {
@Special(value = "X'00'")
CPI, @Special(value = "X'01'")
CONDENSED, @Special(value = "X'05'")
NUM_5, @Special(value = "X'06'")
NUM_6, @Special(value = "X'0A'")
NUM_10
}
public static enum DBCSSOSISPACINGEnum {
@Special(value = "X'00'")
YES, @Special(value = "X'01'")
NO, @Special(value = "X'02'")
RIGHT
}
public static class DBCSCODEDFONT extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(qualified = true)
public QEnum<DBCSCODEDFONTEnum, DBCSCODEDFONT.DBCSCODEDFONTStruct> dBCSCodedFont;
@DataDef(precision = 4, scale = 1, value = "*NONE")
public QEnum<POINTSIZEEnum, QDecimal> pointSize;
public static class DBCSCODEDFONTStruct extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(length = 8)
public QCharacter name;
@DataDef(length = 10, value = "*LIBL")
public QEnum<LIBRARYEnum, QCharacter> library;
public static enum LIBRARYEnum {
LIBL, CURLIB, OTHER
}
}
public static enum DBCSCODEDFONTEnum {
SYSVAL, OTHER
}
public static enum POINTSIZEEnum {
@Special(value = "0.0")
NONE, OTHER
}
}
public static enum TOSTREAMFILEEnum {
NONE, OTHER
}
public static class WORKSTATIONCUSTOMIZINGOBJECT extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(length = 10)
public QEnum<NAMEEnum, QCharacter> name;
@DataDef(length = 10, value = "*LIBL")
public QEnum<LIBRARYEnum, QCharacter> library;
public static enum NAMEEnum {
NONE, PDF, OTHER
}
public static enum LIBRARYEnum {
LIBL, CURLIB, OTHER
}
}
public static enum MAXIMUMFILEWAITTIMEEnum {
@Special(value = "-1")
IMMED, @Special(value = "0")
CLS, OTHER
}
public static enum RECORDFORMATLEVELCHECKEnum {
@Special(value = "N")
NO
}
public static enum SECUREFROMOTHEROVERRIDESEnum {
@Special(value = "N")
NO, @Special(value = "Y")
YES
}
public static enum OVERRIDESCOPEEnum {
@Special(value = "A")
ACTGRPDFN, @Special(value = "I")
CALLLVL, @Special(value = "J")
JOB
}
public static enum SHAREOPENDATAPATHEnum {
@Special(value = "N")
NO, @Special(value = "Y")
YES
}
public static enum OPENSCOPEEnum {
@Special(value = "A")
ACTGRPDFN, @Special(value = "J")
JOB
}
}
| org.smeup.sys.os.prtf.base/src/org/smeup/sys/os/prtf/base/api/PrinterFileOverride.java | package org.smeup.sys.os.prtf.base.api;
import org.smeup.sys.dk.core.annotation.Supported;
import org.smeup.sys.dk.core.annotation.ToDo;
import org.smeup.sys.il.data.QBinary;
import org.smeup.sys.il.data.QCharacter;
import org.smeup.sys.il.data.QDataStructWrapper;
import org.smeup.sys.il.data.QDatetime;
import org.smeup.sys.il.data.QDecimal;
import org.smeup.sys.il.data.QEnum;
import org.smeup.sys.il.data.QScroller;
import org.smeup.sys.il.data.annotation.DataDef;
import org.smeup.sys.il.data.annotation.Entry;
import org.smeup.sys.il.data.annotation.Program;
import org.smeup.sys.il.data.annotation.Special;
import org.smeup.sys.il.data.def.BinaryType;
import org.smeup.sys.il.data.def.DatetimeType;
@Program(name = "QDMOVRPR")
public @Supported class PrinterFileOverride {
public static enum QCPFMSG {
}
public @Entry void main(
@ToDo @DataDef(length = 10) QEnum<FILEBEINGOVERRIDDENEnum, QCharacter> fileBeingOverridden,
@ToDo @DataDef(qualified = true) OVERRIDINGTOPRINTERFILE overridingToPrinterFile,
DEVICE device,
@DataDef(length = 1) QEnum<PRINTERDEVICETYPEEnum, QCharacter> printerDeviceType,
@ToDo PAGESIZE pageSize,
@ToDo @DataDef(precision = 3, scale = 1) QEnum<LINESPERINCHEnum, QDecimal> linesPerInch,
@ToDo @DataDef(precision = 3, scale = 1) QEnum<CHARACTERSPERINCHEnum, QDecimal> charactersPerInch,
FRONTMARGIN frontMargin,
BACKMARGIN backMargin,
@ToDo @DataDef(binaryType = BinaryType.SHORT) QBinary overflowLineNumber,
@DataDef(length = 1) QEnum<FOLDRECORDSEnum, QCharacter> foldRecords,
UNPRINTABLECHARACTERACTION unprintableCharacterAction,
@DataDef(length = 1) QEnum<ALIGNPAGEEnum, QCharacter> alignPage,
@DataDef(binaryType = BinaryType.SHORT) QEnum<SOURCEDRAWEREnum, QBinary> sourceDrawer,
@DataDef(binaryType = BinaryType.INTEGER) QEnum<OUTPUTBINEnum, QBinary> outputBin,
FONT font,
@DataDef(length = 1) QEnum<FORMFEEDEnum, QCharacter> formFeed,
@DataDef(length = 1) QEnum<PRINTQUALITYEnum, QCharacter> printQuality,
@DataDef(length = 1) QEnum<CONTROLCHARACTEREnum, QCharacter> controlCharacter,
@DataDef(binaryType=BinaryType.INTEGER) QBinary channel,
@DataDef(length = 1) QEnum<FIDELITYEnum, QCharacter> fidelity,
CHARACTERIDENTIFIER characterIdentifier,
@DataDef(length = 1) QEnum<DECIMALFORMATEnum, QCharacter> decimalFormat,
FONTCHARACTERSET fontCharacterSet,
CODEDFONT codedFont,
@DataDef(qualified = true) PAGEDEFINITION pageDefinition,
@DataDef(qualified = true) FORMDEFINITION formDefinition,
@DataDef(dimension = 4, length = 4) QEnum<AFPCHARACTERSEnum, QScroller<QCharacter>> aFPCharacters,
@DataDef(length = 1) QEnum<TABLEREFERENCECHARACTERSEnum, QCharacter> tableReferenceCharacters,
@ToDo @DataDef(binaryType = BinaryType.SHORT) QEnum<DEGREEOFPAGEROTATIONEnum, QBinary> degreeOfPageRotation,
@DataDef(binaryType = BinaryType.SHORT) QEnum<PAGESPERSIDEEnum, QBinary> pagesPerSide,
@DataDef(length = 1) QEnum<REDUCEOUTPUTEnum, QCharacter> reduceOutput,
@DataDef(length = 30) QCharacter printText,
@DataDef(binaryType = BinaryType.SHORT) QEnum<HARDWAREJUSTIFICATIONEnum, QBinary> hardwareJustification,
@DataDef(length = 1) QEnum<PRINTONBOTHSIDESEnum, QCharacter> printOnBothSides,
@DataDef(length = 1) QEnum<UNITOFMEASUREEnum, QCharacter> unitOfMeasure,
FRONTSIDEOVERLAY frontSideOverlay,
BACKSIDEOVERLAY backSideOverlay,
@DataDef(length = 1) QEnum<CONVERTLINEDATAEnum, QCharacter> convertLineData,
@DataDef(length = 1) QEnum<IPDSPASSTHROUGHEnum, QCharacter> iPDSPassThrough,
@DataDef(dimension = 4, length = 10) QEnum<USERRESOURCELIBRARYLISTEnum, QScroller<QCharacter>> userResourceLibraryList,
@DataDef(length = 1) QEnum<CORNERSTAPLEEnum, QCharacter> cornerStaple,
EDGESTITCH edgeStitch,
SADDLESTITCH saddleStitch,
@DataDef(length = 1) QEnum<FONTRESOLUTIONFORFORMATTINGEnum, QCharacter> fontResolutionForFormatting,
@ToDo @DataDef(length = 1) QEnum<DEFERWRITEEnum, QCharacter> deferWrite,
@DataDef(length = 1) QEnum<SPOOLTHEDATAEnum, QCharacter> spoolTheData,
@ToDo @DataDef(qualified = true) OUTPUTQUEUE outputQueue,
@ToDo @DataDef(length = 10) QEnum<FORMTYPEEnum, QCharacter> formType,
@ToDo @DataDef(binaryType = BinaryType.SHORT) QBinary copies,
PAGERANGETOPRINT pageRangeToPrint,
@DataDef(binaryType = BinaryType.INTEGER) QEnum<MAXSPOOLEDOUTPUTRECORDSEnum, QBinary> maxSpooledOutputRecords,
@DataDef(binaryType = BinaryType.SHORT) QBinary fileSeparators,
@DataDef(length = 1) QEnum<SPOOLEDOUTPUTSCHEDULEEnum, QCharacter> spooledOutputSchedule,
@ToDo @DataDef(length = 1) QEnum<HOLDSPOOLEDFILEEnum, QCharacter> holdSpooledFile,
@ToDo @DataDef(length = 1) QEnum<SAVESPOOLEDFILEEnum, QCharacter> saveSpooledFile,
@DataDef(length = 1) QEnum<OUTPUTPRIORITYONOUTQEnum, QCharacter> outputPriorityonOUTQ,
@DataDef(length = 10) QEnum<USERDATAEnum, QCharacter> userData,
@DataDef(length = 10) QEnum<SPOOLFILEOWNEREnum, QCharacter> spoolFileOwner,
@DataDef(dimension = 4, length = 10) QEnum<USERDEFINEDOPTIONEnum, QScroller<QCharacter>> userDefinedOption,
@DataDef(length = 255) QEnum<USERDEFINEDDATAEnum, QCharacter> userDefinedData,
USERDEFINEDOBJECT userDefinedObject,
@DataDef(length = 10) QEnum<SPOOLFILENAMEEnum, QCharacter> spoolFileName,
@DataDef(datetimeType = DatetimeType.DATE) QEnum<EXPIRATIONDATEFORFILEEnum, QDatetime> expirationDateForFile,
@DataDef(binaryType = BinaryType.SHORT) QBinary daysUntilFileExpires,
@DataDef(length = 1) QEnum<USERSPECIFIEDDBCSDATAEnum, QCharacter> userSpecifiedDBCSData,
@DataDef(length = 1) QEnum<DBCSEXTENSIONCHARACTERSEnum, QCharacter> dBCSExtensionCharacters,
@DataDef(length = 1) QEnum<DBCSCHARACTERROTATIONEnum, QCharacter> dBCSCharacterRotation,
@DataDef(length = 1) QEnum<DBCSCHARACTERSPERINCHEnum, QCharacter> dBCSCharactersPerInch,
@DataDef(length = 1) QEnum<DBCSSOSISPACINGEnum, QCharacter> dBCSSOSISpacing,
DBCSCODEDFONT dBCSCodedFont,
@DataDef(length = 5000) QEnum<TOSTREAMFILEEnum, QCharacter> toStreamFile,
@DataDef(qualified = true) WORKSTATIONCUSTOMIZINGOBJECT workstationCustomizingObject,
@DataDef(binaryType = BinaryType.SHORT) QEnum<MAXIMUMFILEWAITTIMEEnum, QBinary> maximumFileWaitTime,
@DataDef(length = 1) QEnum<RECORDFORMATLEVELCHECKEnum, QCharacter> recordFormatLevelCheck,
@DataDef(length = 1) QEnum<SECUREFROMOTHEROVERRIDESEnum, QCharacter> secureFromOtherOverrides,
@ToDo @DataDef(length = 1) QEnum<OVERRIDESCOPEEnum, QCharacter> overrideScope,
@ToDo @DataDef(length = 1) QEnum<SHAREOPENDATAPATHEnum, QCharacter> shareOpenDataPath,
@DataDef(length = 1) QEnum<OPENSCOPEEnum, QCharacter> openScope) {
}
public static enum FILEBEINGOVERRIDDENEnum {
PRTF, OTHER
}
public static class OVERRIDINGTOPRINTERFILE extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(length = 10)
public QEnum<NAMEEnum, QCharacter> name;
@DataDef(length = 10, value = "*LIBL")
public QEnum<LIBRARYEnum, QCharacter> library;
public static enum NAMEEnum {
FILE, OTHER
}
public static enum LIBRARYEnum {
LIBL, CURLIB, OTHER
}
}
public static class DEVICE extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(length = 10)
public QEnum<PRINTEREnum, QCharacter> printer;
public static enum PRINTEREnum {
SYSVAL, JOB, OTHER
}
}
public static enum PRINTERDEVICETYPEEnum {
@Special(value = "X'00'")
SCS, @Special(value = "X'01'")
IPDS, @Special(value = "X'05'")
USERASCII, @Special(value = "X'02'")
AFPDS, @Special(value = "X'03'")
LINE, @Special(value = "X'04'")
AFPDSLINE
}
public static class PAGESIZE extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(precision = 6, scale = 3)
public QDecimal pageLength;
@DataDef(precision = 6, scale = 3)
public QDecimal pageWidth;
@DataDef(length = 1, value = "*ROWCOL")
public QEnum<MEASUREMENTMETHODEnum, QCharacter> measurementMethod;
public static enum MEASUREMENTMETHODEnum {
@Special(value = "R")
ROWCOL, @Special(value = "U")
UOM
}
}
public static enum LINESPERINCHEnum {
NUM_3_0, NUM_4_0, NUM_6_0, NUM_7_5, NUM_8_0, NUM_9_0, NUM_12_0
}
public static enum CHARACTERSPERINCHEnum {
NUM_5_0, NUM_10_0, NUM_12_0, NUM_13_3, NUM_15_0, NUM_16_7, NUM_18_0, NUM_20_0
}
public static class FRONTMARGIN extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(precision = 5, scale = 3)
public QEnum<OFFSETDOWNEnum, QDecimal> offsetDown;
@DataDef(precision = 5, scale = 3)
public QDecimal offsetAcross;
public static enum OFFSETDOWNEnum {
@Special(value = "-2.000")
DEVD, OTHER
}
}
public static class BACKMARGIN extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(precision = 5, scale = 3)
public QEnum<OFFSETDOWNEnum, QDecimal> offsetDown;
@DataDef(precision = 5, scale = 3)
public QDecimal offsetAcross;
public static enum OFFSETDOWNEnum {
@Special(value = "-1.000")
FRONTMGN, @Special(value = "-2.000")
DEVD, OTHER
}
}
public static enum FOLDRECORDSEnum {
@Special(value = "N")
NO, @Special(value = "Y")
YES
}
public static class UNPRINTABLECHARACTERACTION extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(length = 1)
public QEnum<REPLACECHARACTEREnum, QCharacter> replaceCharacter;
@DataDef(length = 1, value = "*BLANK")
public QEnum<REPLACEMENTCHARACTEREnum, QCharacter> replacementCharacter;
public static enum REPLACECHARACTEREnum {
@Special(value = "N")
NO, @Special(value = "Y")
YES
}
public static enum REPLACEMENTCHARACTEREnum {
@Special(value = "X'40'")
BLANK, OTHER
}
}
public static enum ALIGNPAGEEnum {
@Special(value = "N")
NO, @Special(value = "Y")
YES
}
public static enum SOURCEDRAWEREnum {
@Special(value = "-1")
E1, @Special(value = "-2")
FORMDF, OTHER
}
public static enum OUTPUTBINEnum {
@Special(value = "0")
DEVD, OTHER
}
public static class FONT extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(length = 10)
public QEnum<IDENTIFIEREnum, QCharacter> identifier;
@DataDef(precision = 4, scale = 1, value = "*NONE")
public QEnum<POINTSIZEEnum, QDecimal> pointSize;
public static enum IDENTIFIEREnum {
CPI, DEVD, @Special(value = "2")
NUM_2, @Special(value = "002")
NUM_002, @Special(value = "3")
NUM_3, @Special(value = "003")
NUM_003, @Special(value = "5")
NUM_5, @Special(value = "005")
NUM_005, @Special(value = "8")
NUM_8, @Special(value = "008")
NUM_008, @Special(value = "10")
NUM_10, @Special(value = "010")
NUM_010, @Special(value = "11")
NUM_11, @Special(value = "011")
NUM_011, @Special(value = "12")
NUM_12, @Special(value = "012")
NUM_012, @Special(value = "13")
NUM_13, @Special(value = "013")
NUM_013, @Special(value = "18")
NUM_18, @Special(value = "018")
NUM_018, @Special(value = "19")
NUM_19, @Special(value = "019")
NUM_019, @Special(value = "20")
NUM_20, @Special(value = "020")
NUM_020, @Special(value = "21")
NUM_21, @Special(value = "021")
NUM_021, @Special(value = "25")
NUM_25, @Special(value = "025")
NUM_025, @Special(value = "26")
NUM_26, @Special(value = "026")
NUM_026, @Special(value = "30")
NUM_30, @Special(value = "030")
NUM_030, @Special(value = "31")
NUM_31, @Special(value = "031")
NUM_031, @Special(value = "36")
NUM_36, @Special(value = "036")
NUM_036, @Special(value = "38")
NUM_38, @Special(value = "038")
NUM_038, @Special(value = "39")
NUM_39, @Special(value = "039")
NUM_039, @Special(value = "40")
NUM_40, @Special(value = "040")
NUM_040, @Special(value = "41")
NUM_41, @Special(value = "041")
NUM_041, @Special(value = "42")
NUM_42, @Special(value = "042")
NUM_042, @Special(value = "43")
NUM_43, @Special(value = "043")
NUM_043, @Special(value = "44")
NUM_44, @Special(value = "044")
NUM_044, @Special(value = "46")
NUM_46, @Special(value = "046")
NUM_046, @Special(value = "49")
NUM_49, @Special(value = "049")
NUM_049, @Special(value = "50")
NUM_50, @Special(value = "050")
NUM_050, @Special(value = "51")
NUM_51, @Special(value = "051")
NUM_051, @Special(value = "52")
NUM_52, @Special(value = "052")
NUM_052, @Special(value = "55")
NUM_55, @Special(value = "055")
NUM_055, @Special(value = "61")
NUM_61, @Special(value = "061")
NUM_061, @Special(value = "62")
NUM_62, @Special(value = "062")
NUM_062, @Special(value = "63")
NUM_63, @Special(value = "063")
NUM_063, @Special(value = "64")
NUM_64, @Special(value = "064")
NUM_064, @Special(value = "66")
NUM_66, @Special(value = "066")
NUM_066, @Special(value = "68")
NUM_68, @Special(value = "068")
NUM_068, @Special(value = "69")
NUM_69, @Special(value = "069")
NUM_069, @Special(value = "70")
NUM_70, @Special(value = "070")
NUM_070, @Special(value = "71")
NUM_71, @Special(value = "071")
NUM_071, @Special(value = "72")
NUM_72, @Special(value = "072")
NUM_072, @Special(value = "74")
NUM_74, @Special(value = "074")
NUM_074, @Special(value = "75")
NUM_75, @Special(value = "075")
NUM_075, @Special(value = "76")
NUM_76, @Special(value = "076")
NUM_076, @Special(value = "78")
NUM_78, @Special(value = "078")
NUM_078, @Special(value = "80")
NUM_80, @Special(value = "080")
NUM_080, @Special(value = "84")
NUM_84, @Special(value = "084")
NUM_084, @Special(value = "85")
NUM_85, @Special(value = "085")
NUM_085, @Special(value = "86")
NUM_86, @Special(value = "086")
NUM_086, @Special(value = "87")
NUM_87, @Special(value = "087")
NUM_087, @Special(value = "91")
NUM_91, @Special(value = "091")
NUM_091, @Special(value = "92")
NUM_92, @Special(value = "092")
NUM_092, @Special(value = "95")
NUM_95, @Special(value = "095")
NUM_095, @Special(value = "96")
NUM_96, @Special(value = "096")
NUM_096, @Special(value = "98")
NUM_98, @Special(value = "098")
NUM_098, @Special(value = "99")
NUM_99, @Special(value = "099")
NUM_099, @Special(value = "101")
NUM_101, @Special(value = "102")
NUM_102, @Special(value = "103")
NUM_103, @Special(value = "109")
NUM_109, @Special(value = "110")
NUM_110, @Special(value = "111")
NUM_111, @Special(value = "112")
NUM_112, @Special(value = "154")
NUM_154, @Special(value = "155")
NUM_155, @Special(value = "157")
NUM_157, @Special(value = "158")
NUM_158, @Special(value = "159")
NUM_159, @Special(value = "160")
NUM_160, @Special(value = "162")
NUM_162, @Special(value = "163")
NUM_163, @Special(value = "164")
NUM_164, @Special(value = "167")
NUM_167, @Special(value = "168")
NUM_168, @Special(value = "173")
NUM_173, @Special(value = "174")
NUM_174, @Special(value = "175")
NUM_175, @Special(value = "178")
NUM_178, @Special(value = "179")
NUM_179, @Special(value = "180")
NUM_180, @Special(value = "181")
NUM_181, @Special(value = "182")
NUM_182, @Special(value = "183")
NUM_183, @Special(value = "186")
NUM_186, @Special(value = "187")
NUM_187, @Special(value = "188")
NUM_188, @Special(value = "189")
NUM_189, @Special(value = "190")
NUM_190, @Special(value = "191")
NUM_191, @Special(value = "194")
NUM_194, @Special(value = "195")
NUM_195, @Special(value = "204")
NUM_204, @Special(value = "205")
NUM_205, @Special(value = "211")
NUM_211, @Special(value = "212")
NUM_212, @Special(value = "221")
NUM_221, @Special(value = "222")
NUM_222, @Special(value = "223")
NUM_223, @Special(value = "225")
NUM_225, @Special(value = "226")
NUM_226, @Special(value = "229")
NUM_229, @Special(value = "230")
NUM_230, @Special(value = "232")
NUM_232, @Special(value = "233")
NUM_233, @Special(value = "234")
NUM_234, @Special(value = "244")
NUM_244, @Special(value = "245")
NUM_245, @Special(value = "247")
NUM_247, @Special(value = "248")
NUM_248, @Special(value = "249")
NUM_249, @Special(value = "252")
NUM_252, @Special(value = "253")
NUM_253, @Special(value = "254")
NUM_254, @Special(value = "255")
NUM_255, @Special(value = "256")
NUM_256, @Special(value = "258")
NUM_258, @Special(value = "259")
NUM_259, @Special(value = "279")
NUM_279, @Special(value = "281")
NUM_281, @Special(value = "282")
NUM_282, @Special(value = "285")
NUM_285, @Special(value = "290")
NUM_290, @Special(value = "300")
NUM_300, @Special(value = "304")
NUM_304, @Special(value = "305")
NUM_305, @Special(value = "306")
NUM_306, @Special(value = "307")
NUM_307, @Special(value = "318")
NUM_318, @Special(value = "319")
NUM_319, @Special(value = "400")
NUM_400, @Special(value = "404")
NUM_404, @Special(value = "416")
NUM_416, @Special(value = "420")
NUM_420, @Special(value = "424")
NUM_424, @Special(value = "428")
NUM_428, @Special(value = "432")
NUM_432, @Special(value = "434")
NUM_434, @Special(value = "435")
NUM_435, @Special(value = "751")
NUM_751, @Special(value = "752")
NUM_752, @Special(value = "753")
NUM_753, @Special(value = "754")
NUM_754, @Special(value = "755")
NUM_755, @Special(value = "756")
NUM_756, @Special(value = "757")
NUM_757, @Special(value = "758")
NUM_758, @Special(value = "759")
NUM_759, @Special(value = "760")
NUM_760, @Special(value = "761")
NUM_761, @Special(value = "762")
NUM_762, @Special(value = "763")
NUM_763, @Special(value = "764")
NUM_764, @Special(value = "765")
NUM_765, @Special(value = "1051")
NUM_1051, @Special(value = "1053")
NUM_1053, @Special(value = "1056")
NUM_1056, @Special(value = "1351")
NUM_1351, @Special(value = "1653")
NUM_1653, @Special(value = "1803")
NUM_1803, @Special(value = "2103")
NUM_2103, @Special(value = "2304")
NUM_2304, @Special(value = "2305")
NUM_2305, @Special(value = "2306")
NUM_2306, @Special(value = "2307")
NUM_2307, @Special(value = "2308")
NUM_2308, @Special(value = "2309")
NUM_2309, @Special(value = "2310")
NUM_2310, @Special(value = "2311")
NUM_2311, @Special(value = "4407")
NUM_4407, @Special(value = "4427")
NUM_4427, @Special(value = "4535")
NUM_4535, @Special(value = "4919")
NUM_4919, @Special(value = "4939")
NUM_4939, @Special(value = "5047")
NUM_5047, @Special(value = "5067")
NUM_5067, @Special(value = "5687")
NUM_5687, @Special(value = "5707")
NUM_5707, @Special(value = "5815")
NUM_5815, @Special(value = "5835")
NUM_5835, @Special(value = "5943")
NUM_5943, @Special(value = "6199")
NUM_6199, @Special(value = "6219")
NUM_6219, @Special(value = "6327")
NUM_6327, @Special(value = "6347")
NUM_6347, @Special(value = "8503")
NUM_8503, @Special(value = "8523")
NUM_8523, @Special(value = "8631")
NUM_8631, @Special(value = "8651")
NUM_8651, @Special(value = "8759")
NUM_8759, @Special(value = "8779")
NUM_8779, @Special(value = "8887")
NUM_8887, @Special(value = "8907")
NUM_8907, @Special(value = "12855")
NUM_12855, @Special(value = "12875")
NUM_12875, @Special(value = "16951")
NUM_16951, @Special(value = "16971")
NUM_16971, @Special(value = "17079")
NUM_17079, @Special(value = "17099")
NUM_17099, @Special(value = "33335")
NUM_33335, @Special(value = "33355")
NUM_33355, @Special(value = "33463")
NUM_33463, @Special(value = "33483")
NUM_33483, @Special(value = "33591")
NUM_33591, @Special(value = "33601")
NUM_33601, @Special(value = "33719")
NUM_33719, @Special(value = "33729")
NUM_33729, @Special(value = "34103")
NUM_34103, @Special(value = "34123")
NUM_34123, @Special(value = "34231")
NUM_34231, @Special(value = "34251")
NUM_34251, @Special(value = "37431")
NUM_37431, @Special(value = "41783")
NUM_41783, @Special(value = "41803")
NUM_41803, OTHER
}
public static enum POINTSIZEEnum {
@Special(value = "0.0")
NONE, OTHER
}
}
public static enum FORMFEEDEnum {
@Special(value = "X'00'")
DEVD, @Special(value = "X'01'")
CONT, @Special(value = "X'02'")
CUT, @Special(value = "X'04'")
CONT2, @Special(value = "X'03'")
AUTOCUT
}
public static enum PRINTQUALITYEnum {
@Special(value = "X'00'")
STD, @Special(value = "X'03'")
DEVD, @Special(value = "X'01'")
DRAFT, @Special(value = "X'02'")
NLQ, @Special(value = "X'04'")
FASTDRAFT
}
public static enum CONTROLCHARACTEREnum {
@Special(value = "X'00'")
NONE, @Special(value = "X'01'")
FCFC, @Special(value = "X'02'")
MACHINE
}
public static class CHANNELVALUES extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(binaryType = BinaryType.SHORT)
public QBinary channel;
}
public static enum FIDELITYEnum {
@Special(value = "C")
CONTENT, @Special(value = "A")
ABSOLUTE
}
public static class CHARACTERIDENTIFIER extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(binaryType = BinaryType.SHORT)
public QEnum<GRAPHICCHARACTERSETEnum, QBinary> graphicCharacterSet;
@DataDef(binaryType = BinaryType.SHORT)
public QBinary codePage;
public static enum GRAPHICCHARACTERSETEnum {
@Special(value = "0")
DEVD, @Special(value = "-1")
SYSVAL, @Special(value = "-2")
JOBCCSID, @Special(value = "-3")
CHRIDCTL, OTHER
}
}
public static enum DECIMALFORMATEnum {
@Special(value = "X'00'")
FILE, @Special(value = "X'80'")
JOB
}
public static class FONTCHARACTERSET extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(qualified = true)
public QEnum<CHARACTERSETEnum, FONTCHARACTERSET.CHARACTERSET> characterSet;
@DataDef(qualified = true)
public FONTCHARACTERSET.CODEPAGE codePage;
@DataDef(precision = 4, scale = 1, value = "*NONE")
public QEnum<POINTSIZEEnum, QDecimal> pointSize;
public static class CHARACTERSET extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(length = 8)
public QCharacter name;
@DataDef(length = 10, value = "*LIBL")
public QEnum<LIBRARYEnum, QCharacter> library;
public static enum LIBRARYEnum {
LIBL, CURLIB, OTHER
}
}
public static enum CHARACTERSETEnum {
FONT, OTHER
}
public static class CODEPAGE extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(length = 8)
public QCharacter name;
@DataDef(length = 10, value = "*LIBL")
public QEnum<LIBRARYEnum, QCharacter> library;
public static enum LIBRARYEnum {
LIBL, CURLIB, OTHER
}
}
public static enum POINTSIZEEnum {
@Special(value = "0.0")
NONE, OTHER
}
}
public static class CODEDFONT extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(qualified = true)
public QEnum<CODEDFONTEnum, CODEDFONT.CODEDFONTStruct> codedFont;
@DataDef(precision = 4, scale = 1, value = "*NONE")
public QEnum<POINTSIZEEnum, QDecimal> pointSize;
public static class CODEDFONTStruct extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(length = 8)
public QCharacter name;
@DataDef(length = 10, value = "*LIBL")
public QEnum<LIBRARYEnum, QCharacter> library;
public static enum LIBRARYEnum {
LIBL, CURLIB, OTHER
}
}
public static enum CODEDFONTEnum {
FNTCHRSET, OTHER
}
public static enum POINTSIZEEnum {
@Special(value = "0.0")
NONE, OTHER
}
}
public static class PAGEDEFINITION extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(length = 10)
public QEnum<NAMEEnum, QCharacter> name;
@DataDef(length = 10, value = "*LIBL")
public QEnum<LIBRARYEnum, QCharacter> library;
public static enum NAMEEnum {
NONE, OTHER
}
public static enum LIBRARYEnum {
LIBL, CURLIB, OTHER
}
}
public static class FORMDEFINITION extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(length = 10)
public QEnum<NAMEEnum, QCharacter> name;
@DataDef(length = 10, value = "*LIBL")
public QEnum<LIBRARYEnum, QCharacter> library;
public static enum NAMEEnum {
NONE, DEVD, OTHER
}
public static enum LIBRARYEnum {
LIBL, CURLIB, OTHER
}
}
public static enum AFPCHARACTERSEnum {
@Special(value = "*NON")
NONE, OTHER
}
public static enum TABLEREFERENCECHARACTERSEnum {
@Special(value = "X'00'")
NO, @Special(value = "X'01'")
YES
}
public static enum DEGREEOFPAGEROTATIONEnum {
@Special(value = "-2")
AUTO, @Special(value = "0")
DEVD, @Special(value = "-1")
COR, @Special(value = "360")
NUM_0, @Special(value = "90")
NUM_90, @Special(value = "180")
NUM_180, @Special(value = "270")
NUM_270
}
public static enum PAGESPERSIDEEnum {
@Special(value = "0")
NUM_1, OTHER
}
public static enum REDUCEOUTPUTEnum {
@Special(value = "X'00'")
TEXT, @Special(value = "X'01'")
NONE
}
public static enum HARDWAREJUSTIFICATIONEnum {
NUM_0, NUM_50, NUM_100
}
public static enum PRINTONBOTHSIDESEnum {
@Special(value = "X'00'")
NO, @Special(value = "X'01'")
YES, @Special(value = "X'02'")
TUMBLE, @Special(value = "X'FF'")
FORMDF
}
public static enum UNITOFMEASUREEnum {
@Special(value = "X'00'")
INCH, @Special(value = "X'01'")
CM
}
public static class FRONTSIDEOVERLAY extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(qualified = true)
public QEnum<OVERLAYEnum, FRONTSIDEOVERLAY.OVERLAY> overlay;
@DataDef(precision = 5, scale = 3, value = "0")
public QDecimal offsetDown;
@DataDef(precision = 5, scale = 3, value = "0")
public QDecimal offsetAcross;
public static class OVERLAY extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(length = 8)
public QCharacter name;
@DataDef(length = 10, value = "*LIBL")
public QEnum<LIBRARYEnum, QCharacter> library;
public static enum LIBRARYEnum {
LIBL, CURLIB, OTHER
}
}
public static enum OVERLAYEnum {
NONE, OTHER
}
}
public static class BACKSIDEOVERLAY extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(qualified = true)
public QEnum<OVERLAYEnum, BACKSIDEOVERLAY.OVERLAY> overlay;
@DataDef(precision = 5, scale = 3, value = "0")
public QDecimal offsetDown;
@DataDef(precision = 5, scale = 3, value = "0")
public QDecimal offsetAcross;
@DataDef(length = 1, value = "*NOCONSTANT")
public QEnum<CONSTANTBACKEnum, QCharacter> constantBack;
public static class OVERLAY extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(length = 8)
public QCharacter name;
@DataDef(length = 10, value = "*LIBL")
public QEnum<LIBRARYEnum, QCharacter> library;
public static enum LIBRARYEnum {
LIBL, CURLIB, OTHER
}
}
public static enum OVERLAYEnum {
@Special(value = "*FRONT")
FRONTOVL, NONE, OTHER
}
public static enum CONSTANTBACKEnum {
@Special(value = "N")
NOCONSTANT, @Special(value = "C")
CONSTANT
}
}
public static enum CONVERTLINEDATAEnum {
@Special(value = "X'00'")
NO, @Special(value = "X'80'")
YES
}
public static enum IPDSPASSTHROUGHEnum {
@Special(value = "X'02'")
YES, @Special(value = "X'01'")
NO, @Special(value = "X'00'")
DEVD
}
public static enum USERRESOURCELIBRARYLISTEnum {
DEVD, NONE, JOBLIBL, CURLIB, OTHER
}
public static enum CORNERSTAPLEEnum {
@Special(value = "X'00'")
NONE, @Special(value = "X'01'")
BOTRIGHT, @Special(value = "X'02'")
TOPRIGHT, @Special(value = "X'03'")
TOPLEFT, @Special(value = "X'04'")
BOTLEFT, @Special(value = "X'FF'")
DEVD
}
public static class EDGESTITCH extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(length = 1)
public QEnum<REFERENCEEDGEEnum, QCharacter> referenceEdge;
@DataDef(precision = 7, scale = 4)
public QEnum<REFERENCEEDGEOFFSETEnum, QDecimal> referenceEdgeOffset;
@DataDef(binaryType = BinaryType.SHORT)
public QEnum<NUMBEROFSTAPLESEnum, QBinary> numberOfStaples;
@DataDef(dimension = 122, precision = 7, scale = 4)
public QEnum<STAPLEOFFSETSEnum, QScroller<QDecimal>> stapleOffsets;
public static enum REFERENCEEDGEEnum {
@Special(value = "X'00'")
NONE, @Special(value = "X'01'")
BOT, @Special(value = "X'02'")
RIGHT, @Special(value = "X'03'")
TOP, @Special(value = "X'04'")
LEFT, @Special(value = "X'FF'")
DEVD
}
public static enum REFERENCEEDGEOFFSETEnum {
@Special(value = "-1.0000")
DEVD, OTHER
}
public static enum NUMBEROFSTAPLESEnum {
@Special(value = "-1")
DEVD, OTHER
}
public static enum STAPLEOFFSETSEnum {
@Special(value = "-1.0000")
DEVD, OTHER
}
}
public static class SADDLESTITCH extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(length = 1)
public QEnum<REFERENCEEDGEEnum, QCharacter> referenceEdge;
@DataDef(binaryType = BinaryType.SHORT)
public QEnum<NUMBEROFSTAPLESEnum, QBinary> numberOfStaples;
@DataDef(dimension = 122, precision = 7, scale = 4)
public QEnum<STAPLEOFFSETSEnum, QScroller<QDecimal>> stapleOffsets;
public static enum REFERENCEEDGEEnum {
@Special(value = "X'00'")
NONE, @Special(value = "X'03'")
TOP, @Special(value = "X'04'")
LEFT, @Special(value = "X'FF'")
DEVD
}
public static enum NUMBEROFSTAPLESEnum {
@Special(value = "-1")
DEVD, OTHER
}
public static enum STAPLEOFFSETSEnum {
@Special(value = "-1.0000")
DEVD, OTHER
}
}
public static enum FONTRESOLUTIONFORFORMATTINGEnum {
@Special(value = "X'00'")
DEVD, @Special(value = "X'01'")
SEARCH, @Special(value = "X'02'")
NUM_240, @Special(value = "X'03'")
NUM_300
}
public static enum DEFERWRITEEnum {
@Special(value = "X'00'")
YES, @Special(value = "X'01'")
NO
}
public static enum SPOOLTHEDATAEnum {
@Special(value = "Y")
YES, @Special(value = "N")
NO
}
public static class OUTPUTQUEUE extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(length = 10)
public QEnum<NAMEEnum, QCharacter> name;
@DataDef(length = 10, value = "*LIBL")
public QEnum<LIBRARYEnum, QCharacter> library;
public static enum NAMEEnum {
DEV, JOB, OTHER
}
public static enum LIBRARYEnum {
LIBL, CURLIB, OTHER
}
}
public static enum FORMTYPEEnum {
STD, OTHER
}
public static class PAGERANGETOPRINT extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(binaryType = BinaryType.INTEGER)
public QEnum<STARTINGPAGEEnum, QBinary> startingPage;
@DataDef(binaryType = BinaryType.INTEGER)
public QEnum<ENDINGPAGEEnum, QBinary> endingPage;
public static enum STARTINGPAGEEnum {
@Special(value = "0")
NUM_1, @Special(value = "-1")
ENDPAGE, OTHER
}
public static enum ENDINGPAGEEnum {
@Special(value = "0")
END, OTHER
}
}
public static enum MAXSPOOLEDOUTPUTRECORDSEnum {
@Special(value = "0")
NOMAX, OTHER
}
public static enum SPOOLEDOUTPUTSCHEDULEEnum {
@Special(value = "J")
JOBEND, @Special(value = "F")
FILEEND, @Special(value = "I")
IMMED
}
public static enum HOLDSPOOLEDFILEEnum {
@Special(value = "N")
NO, @Special(value = "Y")
YES
}
public static enum SAVESPOOLEDFILEEnum {
@Special(value = "N")
NO, @Special(value = "Y")
YES
}
public static enum OUTPUTPRIORITYONOUTQEnum {
@Special(value = "X'00'")
JOB, @Special(value = "X'01'")
NUM_1, @Special(value = "X'02'")
NUM_2, @Special(value = "X'03'")
NUM_3, @Special(value = "X'04'")
NUM_4, @Special(value = "X'05'")
NUM_5, @Special(value = "X'06'")
NUM_6, @Special(value = "X'07'")
NUM_7, @Special(value = "X'08'")
NUM_8, @Special(value = "X'09'")
NUM_9
}
public static enum USERDATAEnum {
SOURCE, OTHER
}
public static enum SPOOLFILEOWNEREnum {
CURUSRPRF, JOB, CURGRPPRF, JOBGRPPRF
}
public static enum USERDEFINEDOPTIONEnum {
NONE, OTHER
}
public static enum USERDEFINEDDATAEnum {
NONE, OTHER
}
public static class USERDEFINEDOBJECT extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(qualified = true)
public QEnum<OBJECTEnum, USERDEFINEDOBJECT.OBJECT> object;
@DataDef(length = 10)
public QEnum<OBJECTTYPEEnum, QCharacter> objectType;
public static class OBJECT extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(length = 10)
public QCharacter name;
@DataDef(length = 10, value = "*LIBL")
public QEnum<LIBRARYEnum, QCharacter> library;
public static enum LIBRARYEnum {
LIBL, CURLIB, OTHER
}
}
public static enum OBJECTEnum {
NONE, OTHER
}
public static enum OBJECTTYPEEnum {
@Special(value = "DTAARA")
DTAARA, @Special(value = "DTAQ")
DTAQ, @Special(value = "FILE")
FILE, @Special(value = "PSFCFG")
PSFCFG, @Special(value = "USRIDX")
USRIDX, @Special(value = "USRQ")
USRQ, @Special(value = "USRSPC")
USRSPC
}
}
public static enum SPOOLFILENAMEEnum {
FILE, OTHER
}
public static enum EXPIRATIONDATEFORFILEEnum {
@Special(value = "0000000")
NONE, @Special(value = "0999998")
DAYS, OTHER
}
public static enum USERSPECIFIEDDBCSDATAEnum {
@Special(value = "N")
NO, @Special(value = "Y")
YES
}
public static enum DBCSEXTENSIONCHARACTERSEnum {
@Special(value = "Y")
YES, @Special(value = "N")
NO
}
public static enum DBCSCHARACTERROTATIONEnum {
@Special(value = "N")
NO, @Special(value = "Y")
YES
}
public static enum DBCSCHARACTERSPERINCHEnum {
@Special(value = "X'00'")
CPI, @Special(value = "X'01'")
CONDENSED, @Special(value = "X'05'")
NUM_5, @Special(value = "X'06'")
NUM_6, @Special(value = "X'0A'")
NUM_10
}
public static enum DBCSSOSISPACINGEnum {
@Special(value = "X'00'")
YES, @Special(value = "X'01'")
NO, @Special(value = "X'02'")
RIGHT
}
public static class DBCSCODEDFONT extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(qualified = true)
public QEnum<DBCSCODEDFONTEnum, DBCSCODEDFONT.DBCSCODEDFONTStruct> dBCSCodedFont;
@DataDef(precision = 4, scale = 1, value = "*NONE")
public QEnum<POINTSIZEEnum, QDecimal> pointSize;
public static class DBCSCODEDFONTStruct extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(length = 8)
public QCharacter name;
@DataDef(length = 10, value = "*LIBL")
public QEnum<LIBRARYEnum, QCharacter> library;
public static enum LIBRARYEnum {
LIBL, CURLIB, OTHER
}
}
public static enum DBCSCODEDFONTEnum {
SYSVAL, OTHER
}
public static enum POINTSIZEEnum {
@Special(value = "0.0")
NONE, OTHER
}
}
public static enum TOSTREAMFILEEnum {
NONE, OTHER
}
public static class WORKSTATIONCUSTOMIZINGOBJECT extends QDataStructWrapper {
private static final long serialVersionUID = 1L;
@DataDef(length = 10)
public QEnum<NAMEEnum, QCharacter> name;
@DataDef(length = 10, value = "*LIBL")
public QEnum<LIBRARYEnum, QCharacter> library;
public static enum NAMEEnum {
NONE, PDF, OTHER
}
public static enum LIBRARYEnum {
LIBL, CURLIB, OTHER
}
}
public static enum MAXIMUMFILEWAITTIMEEnum {
@Special(value = "-1")
IMMED, @Special(value = "0")
CLS, OTHER
}
public static enum RECORDFORMATLEVELCHECKEnum {
@Special(value = "N")
NO
}
public static enum SECUREFROMOTHEROVERRIDESEnum {
@Special(value = "N")
NO, @Special(value = "Y")
YES
}
public static enum OVERRIDESCOPEEnum {
@Special(value = "A")
ACTGRPDFN, @Special(value = "I")
CALLLVL, @Special(value = "J")
JOB
}
public static enum SHAREOPENDATAPATHEnum {
@Special(value = "N")
NO, @Special(value = "Y")
YES
}
public static enum OPENSCOPEEnum {
@Special(value = "A")
ACTGRPDFN, @Special(value = "J")
JOB
}
}
| OVRPRTF - Primissima implementazione | org.smeup.sys.os.prtf.base/src/org/smeup/sys/os/prtf/base/api/PrinterFileOverride.java | OVRPRTF - Primissima implementazione | <ide><path>rg.smeup.sys.os.prtf.base/src/org/smeup/sys/os/prtf/base/api/PrinterFileOverride.java
<ide> package org.smeup.sys.os.prtf.base.api;
<add>
<add>import javax.inject.Inject;
<ide>
<ide> import org.smeup.sys.dk.core.annotation.Supported;
<ide> import org.smeup.sys.dk.core.annotation.ToDo;
<ide> import org.smeup.sys.il.data.annotation.Special;
<ide> import org.smeup.sys.il.data.def.BinaryType;
<ide> import org.smeup.sys.il.data.def.DatetimeType;
<add>import org.smeup.sys.il.memo.QResourceManager;
<add>import org.smeup.sys.il.memo.QResourceReader;
<add>import org.smeup.sys.il.memo.Scope;
<add>import org.smeup.sys.os.core.OperatingSystemRuntimeException;
<add>import org.smeup.sys.os.core.jobs.QJob;
<add>import org.smeup.sys.os.file.QFile;
<add>import org.smeup.sys.os.file.QFileManager;
<add>import org.smeup.sys.os.file.QFileOverride;
<add>import org.smeup.sys.os.file.QOperatingSystemFileFactory;
<add>import org.smeup.sys.os.file.QPrinterFile;
<ide>
<ide> @Program(name = "QDMOVRPR")
<ide> public @Supported class PrinterFileOverride {
<ide> public static enum QCPFMSG {
<ide> }
<add>
<add> @Inject
<add> private QFileManager fileManager;
<add> @Inject
<add> private QResourceManager resourceManager;
<add> @Inject
<add> private QJob job;
<ide>
<ide> public @Entry void main(
<ide> @ToDo @DataDef(length = 10) QEnum<FILEBEINGOVERRIDDENEnum, QCharacter> fileBeingOverridden,
<ide> @ToDo @DataDef(length = 1) QEnum<OVERRIDESCOPEEnum, QCharacter> overrideScope,
<ide> @ToDo @DataDef(length = 1) QEnum<SHAREOPENDATAPATHEnum, QCharacter> shareOpenDataPath,
<ide> @DataDef(length = 1) QEnum<OPENSCOPEEnum, QCharacter> openScope) {
<add>
<add> QFileOverride fileOverride = QOperatingSystemFileFactory.eINSTANCE.createFileOverride();
<add> fileOverride.setName(name(fileBeingOverridden));
<add> QPrinterFile qFile = qFile(overridingToPrinterFile);
<add> //TODO: set attributes from command parameters
<add> fileOverride.setFileTo(qFile);
<add>
<add> fileManager.setFileOverride(job.getContext(), fileOverride);
<add> }
<add>
<add> private QPrinterFile qFile(OVERRIDINGTOPRINTERFILE overridingToPrinterFile) {
<add> switch (overridingToPrinterFile.name.asEnum()) {
<add> case FILE:
<add> return QOperatingSystemFileFactory.eINSTANCE.createPrinterFile();
<add> case OTHER:
<add> QResourceReader<QFile> fileReader = findReader(overridingToPrinterFile.library);
<add> QFile qFile = fileReader.lookup(overridingToPrinterFile.name.asData().trimR());
<add>
<add> if (qFile == null) {
<add> throw new OperatingSystemRuntimeException("File not found: " + overridingToPrinterFile.name.asString());
<add> }
<add>
<add> if (!(qFile instanceof QPrinterFile)) {
<add> throw new OperatingSystemRuntimeException("Wrong file type: " + overridingToPrinterFile.name.asString());
<add> }
<add>
<add> return (QPrinterFile) qFile;
<add> }
<add> throw new RuntimeException("Shuld not happen");
<add> }
<add>
<add> private QResourceReader<QFile> findReader(QEnum<OVERRIDINGTOPRINTERFILE.LIBRARYEnum, QCharacter> library) {
<add> switch (library.asEnum()) {
<add> case CURLIB:
<add> return resourceManager.getResourceReader(job, QFile.class, Scope.CURRENT_LIBRARY);
<add> case LIBL:
<add> return resourceManager.getResourceReader(job, QFile.class, Scope.LIBRARY_LIST);
<add> case OTHER:
<add> return resourceManager.getResourceReader(job, QFile.class, library.asData().trimR());
<add> }
<add> throw new RuntimeException("Shuld not happen");
<add> }
<add>
<add> private String name(QEnum<FILEBEINGOVERRIDDENEnum, QCharacter> fileBeingOverridden) {
<add> switch(fileBeingOverridden.asEnum()) {
<add> case PRTF:
<add> return "*PRTF";
<add> case OTHER:
<add> return fileBeingOverridden.asData().trimR();
<add> }
<add> throw new RuntimeException("Shuld not happen");
<ide> }
<ide>
<ide> public static enum FILEBEINGOVERRIDDENEnum {
<ide>
<ide> public static class OVERRIDINGTOPRINTERFILE extends QDataStructWrapper {
<ide> private static final long serialVersionUID = 1L;
<add>
<ide> @DataDef(length = 10)
<ide> public QEnum<NAMEEnum, QCharacter> name;
<add>
<ide> @DataDef(length = 10, value = "*LIBL")
<ide> public QEnum<LIBRARYEnum, QCharacter> library;
<ide> |
|
Java | apache-2.0 | f9be1dd5a2fba5e1982c05453f1039dbd9d064f1 | 0 | pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus | /**
* Copyright 2007-2008 University Of Southern California
*
* <p>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
*
* <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 edu.isi.pegasus.planner.transfer.sls;
import edu.isi.pegasus.common.logging.LogManager;
import edu.isi.pegasus.common.util.PegasusURL;
import edu.isi.pegasus.common.util.Separator;
import edu.isi.pegasus.planner.catalog.TransformationCatalog;
import edu.isi.pegasus.planner.catalog.replica.ReplicaCatalogEntry;
import edu.isi.pegasus.planner.catalog.site.classes.FileServer;
import edu.isi.pegasus.planner.catalog.site.classes.FileServerType.OPERATION;
import edu.isi.pegasus.planner.catalog.site.classes.SiteCatalogEntry;
import edu.isi.pegasus.planner.catalog.site.classes.SiteStore;
import edu.isi.pegasus.planner.catalog.transformation.TransformationCatalogEntry;
import edu.isi.pegasus.planner.catalog.transformation.classes.Container;
import edu.isi.pegasus.planner.catalog.transformation.classes.TCType;
import edu.isi.pegasus.planner.classes.FileTransfer;
import edu.isi.pegasus.planner.classes.Job;
import edu.isi.pegasus.planner.classes.PegasusBag;
import edu.isi.pegasus.planner.classes.PegasusFile;
import edu.isi.pegasus.planner.classes.PlannerCache;
import edu.isi.pegasus.planner.classes.Profile;
import edu.isi.pegasus.planner.common.PegasusProperties;
import edu.isi.pegasus.planner.mapper.StagingMapper;
import edu.isi.pegasus.planner.namespace.ENV;
import edu.isi.pegasus.planner.namespace.Pegasus;
import edu.isi.pegasus.planner.transfer.SLS;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
/**
* This uses the transfer executable distributed with Pegasus to do the second level staging.
*
* @author Karan Vahi
* @version $Revision$
*/
public class Transfer implements SLS {
/** The transformation namespace for the transfer job. */
public static final String TRANSFORMATION_NAMESPACE = "pegasus";
/**
* The name of the underlying transformation that is queried for in the Transformation Catalog.
*/
public static final String TRANSFORMATION_NAME = "transfer";
/** The version number for the transfer job. */
public static final String TRANSFORMATION_VERSION = null;
/** The derivation namespace for for the transfer job. */
public static final String DERIVATION_NAMESPACE = "pegasus";
/** The name of the underlying derivation. */
public static final String DERIVATION_NAME = "transfer";
/** The derivation version number for the transfer job. */
public static final String DERIVATION_VERSION = "1.0";
/** The default number of threads pegasus-transfer uses */
public static final int DEFAULT_NUMBER_OF_THREADS = 1;
/** A short description of the transfer implementation. */
public static final String DESCRIPTION = "Pegasus Transfer Wrapper around GUC";
/** The executable basename */
public static final String EXECUTABLE_BASENAME = "pegasus-transfer";
/** The handle to the site catalog. */
protected SiteStore mSiteStore;
/** The handle to the transformation catalog. */
protected TransformationCatalog mTCHandle;
/** The handle to the properties. */
protected PegasusProperties mProps;
/** The handle to the logging manager. */
protected LogManager mLogger;
/** Any extra arguments that need to be passed ahead to the s3 client invocation. */
protected String mExtraArguments;
/** Boolean to track whether to stage sls file or not */
protected boolean mStageSLSFile;
/**
* A SimpleFile Replica Catalog, that tracks all the files that are being materialized as part
* of workflow execution.
*/
private PlannerCache mPlannerCache;
/**
* This member variable if set causes the destination URL for the symlink jobs to have
* symlink:// url if the pool attributed associated with the pfn is same as a particular jobs
* execution pool.
*/
protected boolean mUseSymLinks;
/** Handle to the staging mapper to determine addon's for LFN's per site. */
protected StagingMapper mStagingMapper;
/** The dial for integrity checking */
protected PegasusProperties.INTEGRITY_DIAL mIntegrityDial;
/** The default constructor. */
public Transfer() {}
/**
* Initializes the SLS implementation.
*
* @param bag the bag of objects. Contains access to catalogs etc.
*/
public void initialize(PegasusBag bag) {
mProps = bag.getPegasusProperties();
mLogger = bag.getLogger();
mSiteStore = bag.getHandleToSiteStore();
mTCHandle = bag.getHandleToTransformationCatalog();
mStagingMapper = bag.getStagingMapper();
mExtraArguments = mProps.getSLSTransferArguments();
mStageSLSFile = mProps.stageSLSFilesViaFirstLevelStaging();
mPlannerCache = bag.getHandleToPlannerCache();
mUseSymLinks = mProps.getUseOfSymbolicLinks();
mIntegrityDial = mProps.getIntegrityDial();
}
/**
* Returns a boolean whether the SLS implementation does a condor based modification or not. By
* condor based modification we mean whether it uses condor specific classads to achieve the
* second level staging or not.
*
* @return false
*/
public boolean doesCondorModifications() {
return false;
}
/**
* Constructs a command line invocation for a job, with a given sls file. The SLS maybe null. In
* the case where SLS impl does not read from a file, it is advised to create a file in
* generateSLSXXX methods, and then read the file in this function and put it on the command
* line.
*
* @param job the job that is being sls enabled
* @param slsFile the slsFile can be null
* @return invocation string
*/
public String invocationString(Job job, File slsFile) {
StringBuffer invocation = new StringBuffer();
TransformationCatalogEntry entry = this.getTransformationCatalogEntry(job.getSiteHandle());
String executable =
(entry == null)
? this.getExecutableBasename()
: // nothing in the transformation catalog, rely on the executable basenmae
entry.getPhysicalTransformation(); // rely on what is in the
// transformation catalog
invocation.append(executable);
// get the value if any that is present in the associated compute job
// that should take care of the properties also
int threads = Transfer.DEFAULT_NUMBER_OF_THREADS;
if (job.vdsNS.containsKey(Pegasus.TRANSFER_THREADS_KEY)) {
try {
threads = Integer.parseInt(job.vdsNS.getStringValue(Pegasus.TRANSFER_THREADS_KEY));
} catch (Exception e) {
mLogger.log(
"Invalid value picked up for Pegasus profile "
+ Pegasus.TRANSFER_THREADS_KEY
+ " PegasusLite job "
+ job.getID(),
LogManager.ERROR_MESSAGE_LEVEL);
}
}
invocation.append(" --threads ").append(threads).append(" ");
// append any extra arguments set by user
String args = job.vdsNS.getStringValue(Pegasus.TRANSFER_SLS_ARGUMENTS_KEY);
if (args != null) {
invocation.append(" ").append(args);
}
if (slsFile != null) {
// add the required arguments to transfer
invocation.append(" -f ");
// we add absolute path if the sls files are staged via
// first level staging
if (this.mStageSLSFile) {
invocation.append(slsFile.getAbsolutePath());
} else {
// only the basename
invocation.append(slsFile.getName());
}
}
return invocation.toString();
}
/**
* Returns a boolean indicating whether it will an input file for a job to do the transfers.
* Transfer reads from stdin the file transfers that it needs to do. Always returns true, as we
* need to transfer the proxy always.
*
* @param job the job being detected.
* @return true
*/
public boolean needsSLSInputTransfers(Job job) {
return true;
}
/**
* Returns a boolean indicating whether it will an output file for a job to do the transfers.
* Transfer reads from stdin the file transfers that it needs to do.
*
* @param job the job being detected.
* @return true
*/
public boolean needsSLSOutputTransfers(Job job) {
Set files = job.getOutputFiles();
return !(files == null || files.isEmpty());
}
/**
* Returns the LFN of sls input file.
*
* @param job Job
* @return the name of the sls input file.
*/
public String getSLSInputLFN(Job job) {
StringBuffer lfn = new StringBuffer();
lfn.append("sls_").append(job.getName()).append(".in");
return lfn.toString();
}
/**
* Returns the LFN of sls output file.
*
* @param job Job
* @return the name of the sls input file.
*/
public String getSLSOutputLFN(Job job) {
StringBuffer lfn = new StringBuffer();
lfn.append("sls_").append(job.getName()).append(".out");
return lfn.toString();
}
/**
* Generates a second level staging file of the input files to the worker node directory.
*
* @param job job for which the file is being created
* @param fileName name of the file that needs to be written out.
* @param stagingSiteServer the file server on the staging site to be used for retrieval of
* files i.e the get operation
* @param stagingSiteDirectory directory on the head node of the staging site.
* @param workerNodeDirectory worker node directory
* @return a Collection of FileTransfer objects listing the transfers that need to be done.
* @see #needsSLSInputTransfers( Job)
*/
public Collection<FileTransfer> determineSLSInputTransfers(
Job job,
String fileName,
FileServer stagingSiteServer,
String stagingSiteDirectory,
String workerNodeDirectory) {
// sanity check
if (!needsSLSInputTransfers(job)) {
mLogger.log(
"Not Writing out a SLS input file for job " + job.getName(),
LogManager.DEBUG_MESSAGE_LEVEL);
return null;
}
Set files = job.getInputFiles();
// To handle for null conditions?
// File sls = null;
Collection<FileTransfer> result = new LinkedList();
String destDir = workerNodeDirectory;
// PM-1197 check to see if a job is to be launched in a container
Container c = job.getContainer();
String containerLFN = null;
if (c != null) {
containerLFN = c.getLFN();
if (this.mUseSymLinks && c.getMountPoints().isEmpty()) {
mLogger.log(
"Symlink of data files will be disabled because job "
+ job.getID()
+ " is launched in a container and no host mounts specified "
+ containerLFN,
LogManager.DEBUG_MESSAGE_LEVEL);
}
}
String computeSite = job.getSiteHandle();
SiteCatalogEntry computeSiteEntry = this.mSiteStore.lookup(computeSite);
// To do. distinguish the sls file from the other input files
for (Iterator it = files.iterator(); it.hasNext(); ) {
PegasusFile pf = (PegasusFile) it.next();
String lfn = pf.getLFN();
if (lfn.equals(ENV.X509_USER_PROXY_KEY)) {
// ignore the proxy file for time being
// as we picking it from the head node directory
continue;
}
FileTransfer ft = new FileTransfer();
ft.setLFN(pf.getLFN());
// ensure that right type gets associated, especially
// whether a file is a checkpoint file or not
ft.setType(pf.getType());
// create the default path from the directory
// on the head node
StringBuffer url = new StringBuffer();
Collection<ReplicaCatalogEntry> cacheLocations = null;
Collection<ReplicaCatalogEntry> sources = new LinkedList();
boolean symlink = false;
if (pf.doBypassStaging()) {
// PM-698
// we retrieve the URL from the Planner Cache as a get URL
// bypassed URL's are stored as GET urls in the cache and
// associated with the compute site
// PM 1002 first we try and find a tighter match on the compute site
// and then the loose match
cacheLocations = mPlannerCache.lookupAllEntries(lfn, computeSite, OPERATION.get);
if (cacheLocations.isEmpty()) {
mLogger.log(
"Unable to find location of lfn in planner(get) cache with input staging bypassed "
+ lfn
+ " for job "
+ job.getID(),
LogManager.DEBUG_MESSAGE_LEVEL);
}
}
if (cacheLocations == null || cacheLocations.isEmpty()) {
String stagingSite = job.getStagingSiteHandle();
// PM-1787 the source URL can be a file URL if source URL logically on the same site
// where job OR
// staging site is local and the compute site is visible to the local site
boolean useFileURLAsSource =
stagingSite.equals(computeSite)
|| (stagingSite.equals("local")
&& computeSiteEntry.isVisibleToLocalSite());
if (useFileURLAsSource) {
// construct the source URL as a file url
url.append(PegasusURL.FILE_URL_SCHEME)
.append("//")
.append(stagingSiteDirectory);
} else {
url.append(
mSiteStore.getExternalWorkDirectoryURL(stagingSiteServer, stagingSite));
}
// construct the location with respect to the staging site
if (mUseSymLinks && useFileURLAsSource) {
symlink = true;
if (pf.isExecutable()) {
// PM-734 for executable files we can have the source url as file url
// but we cannot have the destination URL as symlink://
// as we want to do chmod on the local copy on the worker node
symlink = false;
}
if (pf.isCheckpointFile()) {
// we never symlink checkpoint files
symlink = false;
}
}
// PM-833 append the relative staging site add on directory
url.append(File.separator)
.append(mStagingMapper.getRelativeDirectory(stagingSite, lfn));
url.append(File.separator).append(lfn);
// ft.addSource( stagingSite, url.toString() );
sources.add(new ReplicaCatalogEntry(url.toString(), stagingSite));
} else {
// construct the URL wrt to the planner cache location
// PM-1014 go through all the candidates returned from the planner cache
for (ReplicaCatalogEntry cacheLocation : cacheLocations) {
url = new StringBuffer();
url.append(cacheLocation.getPFN());
// ft.addSource(cacheLocation);
sources.add((ReplicaCatalogEntry) cacheLocation.clone());
symlink =
(mUseSymLinks
&& // specified in configuration
!pf.isCheckpointFile()
&& // can only do symlinks for data files . not checkpoint files
!pf.isExecutable()
&& // can only do symlinks for data files . not executables
cacheLocation.getResourceHandle().equals(job.getSiteHandle())
&& // source URL logically on the same site where job is to be
// run
url.toString()
.startsWith(
PegasusURL.FILE_URL_SCHEME)); // source URL is a
// file URL
}
}
if (symlink && containerLFN != null) {
// PM-1197 special handling for the case where job is to be
// launched in a container.Normally, we can only symlink the
// container image.
if (!pf.getLFN().equals(containerLFN)) {
symlink = false;
// PM-1298 check if source file directory is mounted
for (ReplicaCatalogEntry source : sources) {
String sourceURL = source.getPFN();
String replacedURL = c.getPathInContainer(sourceURL);
if (replacedURL != null) {
symlink = true;
source.setPFN(replacedURL);
// we don't want pegasus-transfer to fail in PegasusLite
// on the missing source path that is only visible in the container
ft.setVerifySymlinkSource(false);
mLogger.log(
"Replaced source URL on host "
+ sourceURL
+ " with path in the container "
+ source.getPFN(),
LogManager.DEBUG_MESSAGE_LEVEL);
}
}
}
}
// add all the sources
for (ReplicaCatalogEntry source : sources) {
ft.addSource(source);
}
// if the source URL is already present at the compute site
// and is a file URL, then the destination URL has to be a symlink
String destURLScheme =
(symlink)
? PegasusURL.SYMLINK_URL_SCHEME
: PegasusURL.FILE_URL_SCHEME; // default is file URL
// PM-1375 check the dial to see if we need to check checksum for this
// or not, and turn off if nosymlink
if (symlink && mIntegrityDial == PegasusProperties.INTEGRITY_DIAL.nosymlink) {
pf.setForIntegrityChecking(false);
}
// destination
url = new StringBuffer();
url.append(destURLScheme)
.append("//")
.append(destDir)
.append(File.separator)
.append(pf.getLFN());
ft.addDestination(job.getSiteHandle(), url.toString());
result.add(ft);
}
return result;
}
/**
* Generates a second level staging file of the input files to the worker node directory.
*
* @param job the job for which the file is being created
* @param fileName the name of the file that needs to be written out.
* @param stagingSiteServer the file server on the staging site to be used for retrieval of
* files i.e the put operation
* @param stagingSiteDirectory the directory on the head node of the staging site.
* @param workerNodeDirectory the worker node directory
* @return a Collection of FileTransfer objects listing the transfers that need to be done.
* @see #needsSLSOutputTransfers( Job)
*/
public Collection<FileTransfer> determineSLSOutputTransfers(
Job job,
String fileName,
FileServer stagingSiteServer,
String stagingSiteDirectory,
String workerNodeDirectory) {
// sanity check
if (!needsSLSOutputTransfers(job)) {
mLogger.log(
"Not Writing out a SLS output file for job " + job.getName(),
LogManager.DEBUG_MESSAGE_LEVEL);
return null;
}
// To handle for null conditions?
// File sls = null;
Collection<FileTransfer> result = new LinkedList();
Set files = job.getOutputFiles();
String sourceDir = workerNodeDirectory;
PegasusFile pf;
String stagingSite = job.getStagingSiteHandle();
String computeSite = job.getSiteHandle();
SiteCatalogEntry computeSiteEntry = this.mSiteStore.lookup(computeSite);
// To do. distinguish the sls file from the other input files
for (Iterator it = files.iterator(); it.hasNext(); ) {
pf = (PegasusFile) it.next();
String lfn = pf.getLFN();
FileTransfer ft = new FileTransfer();
// ensure that right type gets associated, especially
// whether a file is a checkpoint file or not
ft.setType(pf.getType());
// source
StringBuffer url = new StringBuffer();
url.append("file://").append(sourceDir).append(File.separator).append(lfn);
ft.addSource(job.getSiteHandle(), url.toString());
// destination
url = new StringBuffer();
// PM-1787 the destination URL can be a file URL if the compute site and staging site
// are same
// OR
// staging site is local and the compute site is visible to the local site
boolean useFileURLAsSource =
stagingSite.equals(computeSite)
|| (stagingSite.equals("local")
&& computeSiteEntry.isVisibleToLocalSite());
if (mUseSymLinks && useFileURLAsSource) {
// PM-1108 symlinking is turned on and the compute site for
// the job is the same the staging site. This means that
// the shared-scratch directory used on the staging site is locally
// accessible to the compute nodes. So we can go directly via the
// filesystem to copy the file
url.append(PegasusURL.FILE_URL_SCHEME).append("//").append(stagingSiteDirectory);
} else {
// PM-1108 we go through the external file server interface, since
// staging site is remote to the compute site
// on the head node
url.append(
mSiteStore.getExternalWorkDirectoryURL(
stagingSiteServer, job.getStagingSiteHandle()));
}
// PM-833 append the relative staging site add on directory
url.append(File.separator)
.append(mStagingMapper.getRelativeDirectory(stagingSite, lfn));
url.append(File.separator).append(lfn);
ft.addDestination(stagingSite, url.toString());
result.add(ft);
}
return result;
}
/**
* Modifies a compute job for second level staging. The only modification it does is add the
* appropriate environment varialbes to the job
*
* @param job the job to be modified.
* @param stagingSiteURLPrefix the url prefix for the server on the staging site
* @param stagingSitedirectory the directory on the staging site, where the inp
* @param workerNodeDirectory the directory in the worker node tmp
* @return boolean indicating whether job was successfully modified or not.
*/
public boolean modifyJobForWorkerNodeExecution(
Job job,
String stagingSiteURLPrefix,
String stagingSitedirectory,
String workerNodeDirectory) {
List envs = this.getEnvironmentVariables(job.getSiteHandle());
if (envs == null || envs.isEmpty()) {
// no hard failure.
mLogger.log(
"No special environment set for "
+ Separator.combine(
this.TRANSFORMATION_NAMESPACE,
this.TRANSFORMATION_NAME,
this.TRANSFORMATION_VERSION)
+ " for job "
+ job.getID(),
LogManager.TRACE_MESSAGE_LEVEL);
return true;
}
for (Iterator it = envs.iterator(); it.hasNext(); ) {
job.envVariables.checkKeyInNS((Profile) it.next());
}
return true;
}
/**
* Retrieves the transformation catalog entry for the executable that is being used to transfer
* the files in the implementation. If an entry is not specified in the Transformation Catalog,
* then null is returned.
*
* @param siteHandle the handle of the site where the transformation is to be searched.
* @return the transformation catalog entry if found, else null.
*/
public TransformationCatalogEntry getTransformationCatalogEntry(String siteHandle) {
List tcentries = null;
try {
// namespace and version are null for time being
tcentries =
mTCHandle.lookup(
Transfer.TRANSFORMATION_NAMESPACE,
Transfer.TRANSFORMATION_NAME,
Transfer.TRANSFORMATION_VERSION,
siteHandle,
TCType.INSTALLED);
} catch (Exception e) {
mLogger.log(
"Unable to retrieve entry from TC for "
+ Separator.combine(
Transfer.TRANSFORMATION_NAMESPACE,
Transfer.TRANSFORMATION_NAME,
Transfer.TRANSFORMATION_VERSION)
+ " Cause:"
+ e,
LogManager.DEBUG_MESSAGE_LEVEL);
}
return (tcentries == null) ? null : (TransformationCatalogEntry) tcentries.get(0);
}
/**
* Returns a default TC entry to be used in case entry is not found in the transformation
* catalog.
*
* @param namespace the namespace of the transfer transformation
* @param name the logical name of the transfer transformation
* @param version the version of the transfer transformation
* @param executableBasename the basename of the executable
* @param site the site for which the default entry is required.
* @return the default entry.
*/
protected TransformationCatalogEntry defaultTCEntry(
String namespace, String name, String version, String executableBasename, String site) {
TransformationCatalogEntry defaultTCEntry = null;
// check if PEGASUS_HOME is set
String home = mSiteStore.getPegasusHome(site);
// if PEGASUS_HOME is not set, use VDS_HOME
home = (home == null) ? mSiteStore.getVDSHome(site) : home;
mLogger.log(
"Creating a default TC entry for "
+ Separator.combine(namespace, name, version)
+ " at site "
+ site,
LogManager.DEBUG_MESSAGE_LEVEL);
// if home is still null
if (home == null) {
// cannot create default TC
mLogger.log(
"Unable to create a default entry for "
+ Separator.combine(namespace, name, version)
+ " as PEGASUS_HOME or VDS_HOME is not set in Site Catalog",
LogManager.DEBUG_MESSAGE_LEVEL);
// set the flag back to true
return defaultTCEntry;
}
// remove trailing / if specified
home =
(home.charAt(home.length() - 1) == File.separatorChar)
? home.substring(0, home.length() - 1)
: home;
// construct the path to it
StringBuffer path = new StringBuffer();
path.append(home)
.append(File.separator)
.append("bin")
.append(File.separator)
.append(Transfer.EXECUTABLE_BASENAME);
defaultTCEntry = new TransformationCatalogEntry(namespace, name, version);
defaultTCEntry.setPhysicalTransformation(path.toString());
defaultTCEntry.setResourceId(site);
defaultTCEntry.setType(TCType.INSTALLED);
defaultTCEntry.setSysInfo(this.mSiteStore.lookup(site).getSysInfo());
// register back into the transformation catalog
// so that we do not need to worry about creating it again
try {
mTCHandle.insert(defaultTCEntry, false);
} catch (Exception e) {
// just log as debug. as this is more of a performance improvement
// than anything else
mLogger.log(
"Unable to register in the TC the default entry "
+ defaultTCEntry.getLogicalTransformation()
+ " for site "
+ site,
e,
LogManager.DEBUG_MESSAGE_LEVEL);
}
mLogger.log(
"Created entry with path " + defaultTCEntry.getPhysicalTransformation(),
LogManager.DEBUG_MESSAGE_LEVEL);
return defaultTCEntry;
}
/**
* Returns the environment profiles that are required for the default entry to sensibly work.
* Tries to retrieve the following variables
*
* <pre>
* PEGASUS_HOME
* GLOBUS_LOCATION
* </pre>
*
* @param site the site where the job is going to run.
* @return List of environment variables, else empty list if none are found
*/
protected List getEnvironmentVariables(String site) {
List result = new ArrayList(2);
String pegasusHome = mSiteStore.getEnvironmentVariable(site, "PEGASUS_HOME");
if (pegasusHome != null) {
// we have both the environment variables
result.add(new Profile(Profile.ENV, "PEGASUS_HOME", pegasusHome));
}
String globus = mSiteStore.getEnvironmentVariable(site, "GLOBUS_LOCATION");
if (globus != null) {
result.add(new Profile(Profile.ENV, "GLOBUS_LOCATION", globus));
}
return result;
}
/**
* Return the executable basename for transfer executable used.
*
* @return the executable basename.
*/
protected String getExecutableBasename() {
return Transfer.EXECUTABLE_BASENAME;
}
/**
* Complains for head node url prefix not specified
*
* @param site the site handle
* @throws RuntimeException when URL Prefix cannot be determined for various reason.
*/
protected void complainForHeadNodeURLPrefix(String site) {
this.complainForHeadNodeURLPrefix(null, site);
}
/**
* Complains for head node url prefix not specified
*
* @param job the related job if any
* @param site the site handle
* @throws RuntimeException when URL Prefix cannot be determined for various reason.
*/
protected void complainForHeadNodeURLPrefix(Job job, String site) {
StringBuffer error = new StringBuffer();
if (job != null) {
error.append("[SLS Transfer] For job (").append(job.getID()).append(").");
}
error.append(
"Unable to determine URL Prefix for the FileServer for scratch shared file system on site: ")
.append(site);
throw new RuntimeException(error.toString());
}
/**
* Returns a textual description of the transfer mode.
*
* @return a short textual description
*/
public String getDescription() {
return "SLS backend using pegasus-transfer to worker node";
}
}
| src/edu/isi/pegasus/planner/transfer/sls/Transfer.java | /**
* Copyright 2007-2008 University Of Southern California
*
* <p>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
*
* <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 edu.isi.pegasus.planner.transfer.sls;
import edu.isi.pegasus.common.logging.LogManager;
import edu.isi.pegasus.common.util.PegasusURL;
import edu.isi.pegasus.common.util.Separator;
import edu.isi.pegasus.planner.catalog.TransformationCatalog;
import edu.isi.pegasus.planner.catalog.replica.ReplicaCatalogEntry;
import edu.isi.pegasus.planner.catalog.site.classes.FileServer;
import edu.isi.pegasus.planner.catalog.site.classes.FileServerType.OPERATION;
import edu.isi.pegasus.planner.catalog.site.classes.SiteCatalogEntry;
import edu.isi.pegasus.planner.catalog.site.classes.SiteStore;
import edu.isi.pegasus.planner.catalog.transformation.TransformationCatalogEntry;
import edu.isi.pegasus.planner.catalog.transformation.classes.Container;
import edu.isi.pegasus.planner.catalog.transformation.classes.TCType;
import edu.isi.pegasus.planner.classes.FileTransfer;
import edu.isi.pegasus.planner.classes.Job;
import edu.isi.pegasus.planner.classes.PegasusBag;
import edu.isi.pegasus.planner.classes.PegasusFile;
import edu.isi.pegasus.planner.classes.PlannerCache;
import edu.isi.pegasus.planner.classes.Profile;
import edu.isi.pegasus.planner.common.PegasusProperties;
import edu.isi.pegasus.planner.mapper.StagingMapper;
import edu.isi.pegasus.planner.namespace.ENV;
import edu.isi.pegasus.planner.namespace.Pegasus;
import edu.isi.pegasus.planner.transfer.SLS;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
/**
* This uses the transfer executable distributed with Pegasus to do the second level staging.
*
* @author Karan Vahi
* @version $Revision$
*/
public class Transfer implements SLS {
/** The transformation namespace for the transfer job. */
public static final String TRANSFORMATION_NAMESPACE = "pegasus";
/**
* The name of the underlying transformation that is queried for in the Transformation Catalog.
*/
public static final String TRANSFORMATION_NAME = "transfer";
/** The version number for the transfer job. */
public static final String TRANSFORMATION_VERSION = null;
/** The derivation namespace for for the transfer job. */
public static final String DERIVATION_NAMESPACE = "pegasus";
/** The name of the underlying derivation. */
public static final String DERIVATION_NAME = "transfer";
/** The derivation version number for the transfer job. */
public static final String DERIVATION_VERSION = "1.0";
/** The default number of threads pegasus-transfer uses */
public static final int DEFAULT_NUMBER_OF_THREADS = 1;
/** A short description of the transfer implementation. */
public static final String DESCRIPTION = "Pegasus Transfer Wrapper around GUC";
/** The executable basename */
public static final String EXECUTABLE_BASENAME = "pegasus-transfer";
/** The handle to the site catalog. */
protected SiteStore mSiteStore;
/** The handle to the transformation catalog. */
protected TransformationCatalog mTCHandle;
/** The handle to the properties. */
protected PegasusProperties mProps;
/** The handle to the logging manager. */
protected LogManager mLogger;
/** Any extra arguments that need to be passed ahead to the s3 client invocation. */
protected String mExtraArguments;
/** Boolean to track whether to stage sls file or not */
protected boolean mStageSLSFile;
/**
* A SimpleFile Replica Catalog, that tracks all the files that are being materialized as part
* of workflow execution.
*/
private PlannerCache mPlannerCache;
/**
* This member variable if set causes the destination URL for the symlink jobs to have
* symlink:// url if the pool attributed associated with the pfn is same as a particular jobs
* execution pool.
*/
protected boolean mUseSymLinks;
/** Handle to the staging mapper to determine addon's for LFN's per site. */
protected StagingMapper mStagingMapper;
/** The dial for integrity checking */
protected PegasusProperties.INTEGRITY_DIAL mIntegrityDial;
/** The default constructor. */
public Transfer() {}
/**
* Initializes the SLS implementation.
*
* @param bag the bag of objects. Contains access to catalogs etc.
*/
public void initialize(PegasusBag bag) {
mProps = bag.getPegasusProperties();
mLogger = bag.getLogger();
mSiteStore = bag.getHandleToSiteStore();
mTCHandle = bag.getHandleToTransformationCatalog();
mStagingMapper = bag.getStagingMapper();
mExtraArguments = mProps.getSLSTransferArguments();
mStageSLSFile = mProps.stageSLSFilesViaFirstLevelStaging();
mPlannerCache = bag.getHandleToPlannerCache();
mUseSymLinks = mProps.getUseOfSymbolicLinks();
mIntegrityDial = mProps.getIntegrityDial();
}
/**
* Returns a boolean whether the SLS implementation does a condor based modification or not. By
* condor based modification we mean whether it uses condor specific classads to achieve the
* second level staging or not.
*
* @return false
*/
public boolean doesCondorModifications() {
return false;
}
/**
* Constructs a command line invocation for a job, with a given sls file. The SLS maybe null. In
* the case where SLS impl does not read from a file, it is advised to create a file in
* generateSLSXXX methods, and then read the file in this function and put it on the command
* line.
*
* @param job the job that is being sls enabled
* @param slsFile the slsFile can be null
* @return invocation string
*/
public String invocationString(Job job, File slsFile) {
StringBuffer invocation = new StringBuffer();
TransformationCatalogEntry entry = this.getTransformationCatalogEntry(job.getSiteHandle());
String executable =
(entry == null)
? this.getExecutableBasename()
: // nothing in the transformation catalog, rely on the executable basenmae
entry.getPhysicalTransformation(); // rely on what is in the
// transformation catalog
invocation.append(executable);
// get the value if any that is present in the associated compute job
// that should take care of the properties also
int threads = Transfer.DEFAULT_NUMBER_OF_THREADS;
if (job.vdsNS.containsKey(Pegasus.TRANSFER_THREADS_KEY)) {
try {
threads = Integer.parseInt(job.vdsNS.getStringValue(Pegasus.TRANSFER_THREADS_KEY));
} catch (Exception e) {
mLogger.log(
"Invalid value picked up for Pegasus profile "
+ Pegasus.TRANSFER_THREADS_KEY
+ " PegasusLite job "
+ job.getID(),
LogManager.ERROR_MESSAGE_LEVEL);
}
}
invocation.append(" --threads ").append(threads).append(" ");
// append any extra arguments set by user
String args = job.vdsNS.getStringValue(Pegasus.TRANSFER_SLS_ARGUMENTS_KEY);
if (args != null) {
invocation.append(" ").append(args);
}
if (slsFile != null) {
// add the required arguments to transfer
invocation.append(" -f ");
// we add absolute path if the sls files are staged via
// first level staging
if (this.mStageSLSFile) {
invocation.append(slsFile.getAbsolutePath());
} else {
// only the basename
invocation.append(slsFile.getName());
}
}
return invocation.toString();
}
/**
* Returns a boolean indicating whether it will an input file for a job to do the transfers.
* Transfer reads from stdin the file transfers that it needs to do. Always returns true, as we
* need to transfer the proxy always.
*
* @param job the job being detected.
* @return true
*/
public boolean needsSLSInputTransfers(Job job) {
return true;
}
/**
* Returns a boolean indicating whether it will an output file for a job to do the transfers.
* Transfer reads from stdin the file transfers that it needs to do.
*
* @param job the job being detected.
* @return true
*/
public boolean needsSLSOutputTransfers(Job job) {
Set files = job.getOutputFiles();
return !(files == null || files.isEmpty());
}
/**
* Returns the LFN of sls input file.
*
* @param job Job
* @return the name of the sls input file.
*/
public String getSLSInputLFN(Job job) {
StringBuffer lfn = new StringBuffer();
lfn.append("sls_").append(job.getName()).append(".in");
return lfn.toString();
}
/**
* Returns the LFN of sls output file.
*
* @param job Job
* @return the name of the sls input file.
*/
public String getSLSOutputLFN(Job job) {
StringBuffer lfn = new StringBuffer();
lfn.append("sls_").append(job.getName()).append(".out");
return lfn.toString();
}
/**
* Generates a second level staging file of the input files to the worker node directory.
*
* @param job job for which the file is being created
* @param fileName name of the file that needs to be written out.
* @param stagingSiteServer the file server on the staging site to be used for retrieval of
* files i.e the get operation
* @param stagingSiteDirectory directory on the head node of the staging site.
* @param workerNodeDirectory worker node directory
* @return a Collection of FileTransfer objects listing the transfers that need to be done.
* @see #needsSLSInputTransfers( Job)
*/
public Collection<FileTransfer> determineSLSInputTransfers(
Job job,
String fileName,
FileServer stagingSiteServer,
String stagingSiteDirectory,
String workerNodeDirectory) {
// sanity check
if (!needsSLSInputTransfers(job)) {
mLogger.log(
"Not Writing out a SLS input file for job " + job.getName(),
LogManager.DEBUG_MESSAGE_LEVEL);
return null;
}
Set files = job.getInputFiles();
// To handle for null conditions?
// File sls = null;
Collection<FileTransfer> result = new LinkedList();
String destDir = workerNodeDirectory;
// PM-1197 check to see if a job is to be launched in a container
Container c = job.getContainer();
String containerLFN = null;
if (c != null) {
containerLFN = c.getLFN();
if (this.mUseSymLinks && c.getMountPoints().isEmpty()) {
mLogger.log(
"Symlink of data files will be disabled because job "
+ job.getID()
+ " is launched in a container and no host mounts specified "
+ containerLFN,
LogManager.DEBUG_MESSAGE_LEVEL);
}
}
// To do. distinguish the sls file from the other input files
for (Iterator it = files.iterator(); it.hasNext(); ) {
PegasusFile pf = (PegasusFile) it.next();
String lfn = pf.getLFN();
if (lfn.equals(ENV.X509_USER_PROXY_KEY)) {
// ignore the proxy file for time being
// as we picking it from the head node directory
continue;
}
FileTransfer ft = new FileTransfer();
ft.setLFN(pf.getLFN());
// ensure that right type gets associated, especially
// whether a file is a checkpoint file or not
ft.setType(pf.getType());
// create the default path from the directory
// on the head node
StringBuffer url = new StringBuffer();
Collection<ReplicaCatalogEntry> cacheLocations = null;
Collection<ReplicaCatalogEntry> sources = new LinkedList();
boolean symlink = false;
String computeSite = job.getSiteHandle();
SiteCatalogEntry computeSiteEntry = this.mSiteStore.lookup(computeSite);
if (pf.doBypassStaging()) {
// PM-698
// we retrieve the URL from the Planner Cache as a get URL
// bypassed URL's are stored as GET urls in the cache and
// associated with the compute site
// PM 1002 first we try and find a tighter match on the compute site
// and then the loose match
cacheLocations = mPlannerCache.lookupAllEntries(lfn, computeSite, OPERATION.get);
if (cacheLocations.isEmpty()) {
mLogger.log(
"Unable to find location of lfn in planner(get) cache with input staging bypassed "
+ lfn
+ " for job "
+ job.getID(),
LogManager.DEBUG_MESSAGE_LEVEL);
}
}
if (cacheLocations == null || cacheLocations.isEmpty()) {
String stagingSite = job.getStagingSiteHandle();
// PM-1787 the source URL can be a file URL if source URL logically on the same site
// where job OR
// staging site is local and the compute site is visible to the local site
boolean useFileURLAsSource =
stagingSite.equals(computeSite)
|| (stagingSite.equals("local")
&& computeSiteEntry.isVisibleToLocalSite());
if (useFileURLAsSource) {
// construct the source URL as a file url
url.append(PegasusURL.FILE_URL_SCHEME)
.append("//")
.append(stagingSiteDirectory);
} else {
url.append(
mSiteStore.getExternalWorkDirectoryURL(stagingSiteServer, stagingSite));
}
// construct the location with respect to the staging site
if (mUseSymLinks && useFileURLAsSource) {
symlink = true;
if (pf.isExecutable()) {
// PM-734 for executable files we can have the source url as file url
// but we cannot have the destination URL as symlink://
// as we want to do chmod on the local copy on the worker node
symlink = false;
}
if (pf.isCheckpointFile()) {
// we never symlink checkpoint files
symlink = false;
}
}
// PM-833 append the relative staging site add on directory
url.append(File.separator)
.append(mStagingMapper.getRelativeDirectory(stagingSite, lfn));
url.append(File.separator).append(lfn);
// ft.addSource( stagingSite, url.toString() );
sources.add(new ReplicaCatalogEntry(url.toString(), stagingSite));
} else {
// construct the URL wrt to the planner cache location
// PM-1014 go through all the candidates returned from the planner cache
for (ReplicaCatalogEntry cacheLocation : cacheLocations) {
url = new StringBuffer();
url.append(cacheLocation.getPFN());
// ft.addSource(cacheLocation);
sources.add((ReplicaCatalogEntry) cacheLocation.clone());
symlink =
(mUseSymLinks
&& // specified in configuration
!pf.isCheckpointFile()
&& // can only do symlinks for data files . not checkpoint files
!pf.isExecutable()
&& // can only do symlinks for data files . not executables
cacheLocation.getResourceHandle().equals(job.getSiteHandle())
&& // source URL logically on the same site where job is to be
// run
url.toString()
.startsWith(
PegasusURL.FILE_URL_SCHEME)); // source URL is a
// file URL
}
}
if (symlink && containerLFN != null) {
// PM-1197 special handling for the case where job is to be
// launched in a container.Normally, we can only symlink the
// container image.
if (!pf.getLFN().equals(containerLFN)) {
symlink = false;
// PM-1298 check if source file directory is mounted
for (ReplicaCatalogEntry source : sources) {
String sourceURL = source.getPFN();
String replacedURL = c.getPathInContainer(sourceURL);
if (replacedURL != null) {
symlink = true;
source.setPFN(replacedURL);
// we don't want pegasus-transfer to fail in PegasusLite
// on the missing source path that is only visible in the container
ft.setVerifySymlinkSource(false);
mLogger.log(
"Replaced source URL on host "
+ sourceURL
+ " with path in the container "
+ source.getPFN(),
LogManager.DEBUG_MESSAGE_LEVEL);
}
}
}
}
// add all the sources
for (ReplicaCatalogEntry source : sources) {
ft.addSource(source);
}
// if the source URL is already present at the compute site
// and is a file URL, then the destination URL has to be a symlink
String destURLScheme =
(symlink)
? PegasusURL.SYMLINK_URL_SCHEME
: PegasusURL.FILE_URL_SCHEME; // default is file URL
// PM-1375 check the dial to see if we need to check checksum for this
// or not, and turn off if nosymlink
if (symlink && mIntegrityDial == PegasusProperties.INTEGRITY_DIAL.nosymlink) {
pf.setForIntegrityChecking(false);
}
// destination
url = new StringBuffer();
url.append(destURLScheme)
.append("//")
.append(destDir)
.append(File.separator)
.append(pf.getLFN());
ft.addDestination(job.getSiteHandle(), url.toString());
result.add(ft);
}
return result;
}
/**
* Generates a second level staging file of the input files to the worker node directory.
*
* @param job the job for which the file is being created
* @param fileName the name of the file that needs to be written out.
* @param stagingSiteServer the file server on the staging site to be used for retrieval of
* files i.e the put operation
* @param stagingSiteDirectory the directory on the head node of the staging site.
* @param workerNodeDirectory the worker node directory
* @return a Collection of FileTransfer objects listing the transfers that need to be done.
* @see #needsSLSOutputTransfers( Job)
*/
public Collection<FileTransfer> determineSLSOutputTransfers(
Job job,
String fileName,
FileServer stagingSiteServer,
String stagingSiteDirectory,
String workerNodeDirectory) {
// sanity check
if (!needsSLSOutputTransfers(job)) {
mLogger.log(
"Not Writing out a SLS output file for job " + job.getName(),
LogManager.DEBUG_MESSAGE_LEVEL);
return null;
}
// To handle for null conditions?
// File sls = null;
Collection<FileTransfer> result = new LinkedList();
Set files = job.getOutputFiles();
String sourceDir = workerNodeDirectory;
PegasusFile pf;
String stagingSite = job.getStagingSiteHandle();
String computeSite = job.getSiteHandle();
// To do. distinguish the sls file from the other input files
for (Iterator it = files.iterator(); it.hasNext(); ) {
pf = (PegasusFile) it.next();
String lfn = pf.getLFN();
FileTransfer ft = new FileTransfer();
// ensure that right type gets associated, especially
// whether a file is a checkpoint file or not
ft.setType(pf.getType());
// source
StringBuffer url = new StringBuffer();
url.append("file://").append(sourceDir).append(File.separator).append(lfn);
ft.addSource(job.getSiteHandle(), url.toString());
// destination
url = new StringBuffer();
if (mUseSymLinks && computeSite.equals(stagingSite)) {
// PM-1108 symlinking is turned on and the compute site for
// the job is the same the staging site. This means that
// the shared-scratch directory used on the staging site is locally
// accessible to the compute nodes. So we can go directly via the
// filesystem to copy the file
url.append(PegasusURL.FILE_URL_SCHEME).append("//").append(stagingSiteDirectory);
} else {
// PM-1108 we go through the external file server interface, since
// staging site is remote to the compute site
// on the head node
url.append(
mSiteStore.getExternalWorkDirectoryURL(
stagingSiteServer, job.getStagingSiteHandle()));
}
// PM-833 append the relative staging site add on directory
url.append(File.separator)
.append(mStagingMapper.getRelativeDirectory(stagingSite, lfn));
url.append(File.separator).append(lfn);
ft.addDestination(stagingSite, url.toString());
result.add(ft);
}
return result;
}
/**
* Modifies a compute job for second level staging. The only modification it does is add the
* appropriate environment varialbes to the job
*
* @param job the job to be modified.
* @param stagingSiteURLPrefix the url prefix for the server on the staging site
* @param stagingSitedirectory the directory on the staging site, where the inp
* @param workerNodeDirectory the directory in the worker node tmp
* @return boolean indicating whether job was successfully modified or not.
*/
public boolean modifyJobForWorkerNodeExecution(
Job job,
String stagingSiteURLPrefix,
String stagingSitedirectory,
String workerNodeDirectory) {
List envs = this.getEnvironmentVariables(job.getSiteHandle());
if (envs == null || envs.isEmpty()) {
// no hard failure.
mLogger.log(
"No special environment set for "
+ Separator.combine(
this.TRANSFORMATION_NAMESPACE,
this.TRANSFORMATION_NAME,
this.TRANSFORMATION_VERSION)
+ " for job "
+ job.getID(),
LogManager.TRACE_MESSAGE_LEVEL);
return true;
}
for (Iterator it = envs.iterator(); it.hasNext(); ) {
job.envVariables.checkKeyInNS((Profile) it.next());
}
return true;
}
/**
* Retrieves the transformation catalog entry for the executable that is being used to transfer
* the files in the implementation. If an entry is not specified in the Transformation Catalog,
* then null is returned.
*
* @param siteHandle the handle of the site where the transformation is to be searched.
* @return the transformation catalog entry if found, else null.
*/
public TransformationCatalogEntry getTransformationCatalogEntry(String siteHandle) {
List tcentries = null;
try {
// namespace and version are null for time being
tcentries =
mTCHandle.lookup(
Transfer.TRANSFORMATION_NAMESPACE,
Transfer.TRANSFORMATION_NAME,
Transfer.TRANSFORMATION_VERSION,
siteHandle,
TCType.INSTALLED);
} catch (Exception e) {
mLogger.log(
"Unable to retrieve entry from TC for "
+ Separator.combine(
Transfer.TRANSFORMATION_NAMESPACE,
Transfer.TRANSFORMATION_NAME,
Transfer.TRANSFORMATION_VERSION)
+ " Cause:"
+ e,
LogManager.DEBUG_MESSAGE_LEVEL);
}
return (tcentries == null) ? null : (TransformationCatalogEntry) tcentries.get(0);
}
/**
* Returns a default TC entry to be used in case entry is not found in the transformation
* catalog.
*
* @param namespace the namespace of the transfer transformation
* @param name the logical name of the transfer transformation
* @param version the version of the transfer transformation
* @param executableBasename the basename of the executable
* @param site the site for which the default entry is required.
* @return the default entry.
*/
protected TransformationCatalogEntry defaultTCEntry(
String namespace, String name, String version, String executableBasename, String site) {
TransformationCatalogEntry defaultTCEntry = null;
// check if PEGASUS_HOME is set
String home = mSiteStore.getPegasusHome(site);
// if PEGASUS_HOME is not set, use VDS_HOME
home = (home == null) ? mSiteStore.getVDSHome(site) : home;
mLogger.log(
"Creating a default TC entry for "
+ Separator.combine(namespace, name, version)
+ " at site "
+ site,
LogManager.DEBUG_MESSAGE_LEVEL);
// if home is still null
if (home == null) {
// cannot create default TC
mLogger.log(
"Unable to create a default entry for "
+ Separator.combine(namespace, name, version)
+ " as PEGASUS_HOME or VDS_HOME is not set in Site Catalog",
LogManager.DEBUG_MESSAGE_LEVEL);
// set the flag back to true
return defaultTCEntry;
}
// remove trailing / if specified
home =
(home.charAt(home.length() - 1) == File.separatorChar)
? home.substring(0, home.length() - 1)
: home;
// construct the path to it
StringBuffer path = new StringBuffer();
path.append(home)
.append(File.separator)
.append("bin")
.append(File.separator)
.append(Transfer.EXECUTABLE_BASENAME);
defaultTCEntry = new TransformationCatalogEntry(namespace, name, version);
defaultTCEntry.setPhysicalTransformation(path.toString());
defaultTCEntry.setResourceId(site);
defaultTCEntry.setType(TCType.INSTALLED);
defaultTCEntry.setSysInfo(this.mSiteStore.lookup(site).getSysInfo());
// register back into the transformation catalog
// so that we do not need to worry about creating it again
try {
mTCHandle.insert(defaultTCEntry, false);
} catch (Exception e) {
// just log as debug. as this is more of a performance improvement
// than anything else
mLogger.log(
"Unable to register in the TC the default entry "
+ defaultTCEntry.getLogicalTransformation()
+ " for site "
+ site,
e,
LogManager.DEBUG_MESSAGE_LEVEL);
}
mLogger.log(
"Created entry with path " + defaultTCEntry.getPhysicalTransformation(),
LogManager.DEBUG_MESSAGE_LEVEL);
return defaultTCEntry;
}
/**
* Returns the environment profiles that are required for the default entry to sensibly work.
* Tries to retrieve the following variables
*
* <pre>
* PEGASUS_HOME
* GLOBUS_LOCATION
* </pre>
*
* @param site the site where the job is going to run.
* @return List of environment variables, else empty list if none are found
*/
protected List getEnvironmentVariables(String site) {
List result = new ArrayList(2);
String pegasusHome = mSiteStore.getEnvironmentVariable(site, "PEGASUS_HOME");
if (pegasusHome != null) {
// we have both the environment variables
result.add(new Profile(Profile.ENV, "PEGASUS_HOME", pegasusHome));
}
String globus = mSiteStore.getEnvironmentVariable(site, "GLOBUS_LOCATION");
if (globus != null) {
result.add(new Profile(Profile.ENV, "GLOBUS_LOCATION", globus));
}
return result;
}
/**
* Return the executable basename for transfer executable used.
*
* @return the executable basename.
*/
protected String getExecutableBasename() {
return Transfer.EXECUTABLE_BASENAME;
}
/**
* Complains for head node url prefix not specified
*
* @param site the site handle
* @throws RuntimeException when URL Prefix cannot be determined for various reason.
*/
protected void complainForHeadNodeURLPrefix(String site) {
this.complainForHeadNodeURLPrefix(null, site);
}
/**
* Complains for head node url prefix not specified
*
* @param job the related job if any
* @param site the site handle
* @throws RuntimeException when URL Prefix cannot be determined for various reason.
*/
protected void complainForHeadNodeURLPrefix(Job job, String site) {
StringBuffer error = new StringBuffer();
if (job != null) {
error.append("[SLS Transfer] For job (").append(job.getID()).append(").");
}
error.append(
"Unable to determine URL Prefix for the FileServer for scratch shared file system on site: ")
.append(site);
throw new RuntimeException(error.toString());
}
/**
* Returns a textual description of the transfer mode.
*
* @return a short textual description
*/
public String getDescription() {
return "SLS backend using pegasus-transfer to worker node";
}
}
| For the stage out transfers in PegasusLite nonshared fs mode, the destination URL can be a file URL if the compute site and staging site are same OR staging site is local and the compute site is visible to the local site. The file URL replacement is only triggered when symlinking is turned on.
| src/edu/isi/pegasus/planner/transfer/sls/Transfer.java | For the stage out transfers in PegasusLite nonshared fs mode, the destination URL can be a file URL if the compute site and staging site are same OR staging site is local and the compute site is visible to the local site. The file URL replacement is only triggered when symlinking is turned on. | <ide><path>rc/edu/isi/pegasus/planner/transfer/sls/Transfer.java
<ide> }
<ide> }
<ide>
<add> String computeSite = job.getSiteHandle();
<add> SiteCatalogEntry computeSiteEntry = this.mSiteStore.lookup(computeSite);
<add>
<ide> // To do. distinguish the sls file from the other input files
<ide> for (Iterator it = files.iterator(); it.hasNext(); ) {
<ide> PegasusFile pf = (PegasusFile) it.next();
<ide> Collection<ReplicaCatalogEntry> cacheLocations = null;
<ide> Collection<ReplicaCatalogEntry> sources = new LinkedList();
<ide> boolean symlink = false;
<del> String computeSite = job.getSiteHandle();
<del> SiteCatalogEntry computeSiteEntry = this.mSiteStore.lookup(computeSite);
<ide> if (pf.doBypassStaging()) {
<ide> // PM-698
<ide> // we retrieve the URL from the Planner Cache as a get URL
<ide> PegasusFile pf;
<ide> String stagingSite = job.getStagingSiteHandle();
<ide> String computeSite = job.getSiteHandle();
<add> SiteCatalogEntry computeSiteEntry = this.mSiteStore.lookup(computeSite);
<ide>
<ide> // To do. distinguish the sls file from the other input files
<ide> for (Iterator it = files.iterator(); it.hasNext(); ) {
<ide> // destination
<ide> url = new StringBuffer();
<ide>
<del> if (mUseSymLinks && computeSite.equals(stagingSite)) {
<add> // PM-1787 the destination URL can be a file URL if the compute site and staging site
<add> // are same
<add> // OR
<add> // staging site is local and the compute site is visible to the local site
<add> boolean useFileURLAsSource =
<add> stagingSite.equals(computeSite)
<add> || (stagingSite.equals("local")
<add> && computeSiteEntry.isVisibleToLocalSite());
<add>
<add> if (mUseSymLinks && useFileURLAsSource) {
<ide> // PM-1108 symlinking is turned on and the compute site for
<ide> // the job is the same the staging site. This means that
<ide> // the shared-scratch directory used on the staging site is locally |
|
Java | apache-2.0 | a742157849a020ca500531247dfd06e11ab6c39e | 0 | PotapovMS/Software-testing-training | package ru.stqa.pft.addressbook.appmanager;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.Select;
import org.testng.Assert;
import ru.stqa.pft.addressbook.model.ContactData;
/**
* Created by Максим on 22.04.2016.
*/
public class ContactHelper extends HelperBase {
public ContactHelper(WebDriver wd) {
super(wd);
}
public void returnToHomePage() {
click(By.linkText("home"));
}
public void submitContactCreation() {
click(By.xpath("//div[@id='content']/form/input[21]"));
}
public void fillContactForm(ContactData contactData, boolean creation) {
type(By.name("firstname"), contactData.getFirstname());
type(By.name("middlename"), contactData.getMiddlename());
type(By.name("lastname"), contactData.getLastname());
type(By.name("nickname"), contactData.getNickname());
type(By.name("title"), contactData.getTitle());
type(By.name("company"), contactData.getCompany());
type(By.name("address"), contactData.getAddress());
type(By.name("home"), contactData.getHomePhoneNumber());
type(By.name("mobile"), contactData.getMobilePhoneNumber());
type(By.name("work"), contactData.getWorkPhoneNumber());
type(By.name("fax"), contactData.getFaxNumber());
click(By.name("email2"));
click(By.name("email"));
type(By.name("email2"), contactData.getSecondEmail());
type(By.name("email3"), contactData.getThirdEmail());
type(By.name("homepage"), contactData.getHomepage());
if (!wd.findElement(By.xpath("//div[@id='content']/form/select[1]//option[1]")).isSelected()) {
wd.findElement(By.xpath("//div[@id='content']/form/select[1]//option[1]")).click();
}
if (creation){
new Select(wd.findElement(By.name("new_group"))).selectByVisibleText(contactData.getGroup());
} else {
Assert.assertFalse(isElementPresent(By.name("new_group")));
}
}
public void selectContact() {
click(By.name("selected[]"));
}
public void submitContactDeletion() {
click(By.xpath("//div[@id='content']/form[2]/div[2]/input"));
wd.switchTo().alert().accept();
}
public void editContact() {
click(By.xpath("//table[@id='maintable']/tbody/tr[2]/td[8]/a/img"));
}
public void submitContactModification() {
click(By.xpath("//div[@id='content']/form[1]/input[1]"));
}
}
| addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/appmanager/ContactHelper.java | package ru.stqa.pft.addressbook.appmanager;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.Select;
import org.testng.Assert;
import ru.stqa.pft.addressbook.model.ContactData;
/**
* Created by Максим on 22.04.2016.
*/
public class ContactHelper extends HelperBase {
public ContactHelper(WebDriver wd) {
super(wd);
}
public void returnToHomePage() {
click(By.linkText("home"));
}
public void submitContactCreation() {
click(By.xpath("//div[@id='content']/form/input[21]"));
click(By.name("searchform"));
}
public void fillContactForm(ContactData contactData, boolean creation) {
type(By.name("firstname"), contactData.getFirstname());
type(By.name("middlename"), contactData.getMiddlename());
type(By.name("lastname"), contactData.getLastname());
type(By.name("nickname"), contactData.getNickname());
type(By.name("title"), contactData.getTitle());
type(By.name("company"), contactData.getCompany());
type(By.name("address"), contactData.getAddress());
type(By.name("home"), contactData.getHomePhoneNumber());
type(By.name("mobile"), contactData.getMobilePhoneNumber());
type(By.name("work"), contactData.getWorkPhoneNumber());
type(By.name("fax"), contactData.getFaxNumber());
click(By.name("email2"));
click(By.name("email"));
type(By.name("email2"), contactData.getSecondEmail());
type(By.name("email3"), contactData.getThirdEmail());
type(By.name("homepage"), contactData.getHomepage());
if (!wd.findElement(By.xpath("//div[@id='content']/form/select[1]//option[1]")).isSelected()) {
wd.findElement(By.xpath("//div[@id='content']/form/select[1]//option[1]")).click();
}
if (creation){
new Select(wd.findElement(By.name("new group"))).selectByVisibleText(contactData.getGroup());
} else {
Assert.assertFalse(isElementPresent(By.name("new group")));
}
}
public void selectContact() {
click(By.name("selected[]"));
}
public void submitContactDeletion() {
click(By.xpath("//div[@id='content']/form[2]/div[2]/input"));
wd.switchTo().alert().accept();
}
public void editContact() {
click(By.xpath("//table[@id='maintable']/tbody/tr[2]/td[8]/a/img"));
}
public void submitContactModification() {
click(By.xpath("//div[@id='content']/form[1]/input[1]"));
}
}
| Исправлена ошибка при модификации заполнения форм с почти одинаковым набором полей
| addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/appmanager/ContactHelper.java | Исправлена ошибка при модификации заполнения форм с почти одинаковым набором полей | <ide><path>ddressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/appmanager/ContactHelper.java
<ide>
<ide> public void submitContactCreation() {
<ide> click(By.xpath("//div[@id='content']/form/input[21]"));
<del> click(By.name("searchform"));
<ide> }
<ide>
<ide> public void fillContactForm(ContactData contactData, boolean creation) {
<ide> wd.findElement(By.xpath("//div[@id='content']/form/select[1]//option[1]")).click();
<ide> }
<ide> if (creation){
<del> new Select(wd.findElement(By.name("new group"))).selectByVisibleText(contactData.getGroup());
<add> new Select(wd.findElement(By.name("new_group"))).selectByVisibleText(contactData.getGroup());
<ide> } else {
<del> Assert.assertFalse(isElementPresent(By.name("new group")));
<add> Assert.assertFalse(isElementPresent(By.name("new_group")));
<ide> }
<ide> }
<ide> |
|
Java | epl-1.0 | d8f847a9bf03fadad3534a176570cacb64a2e9b4 | 0 | planetguy32/ForgeEssentials,Techjar/ForgeEssentials,ForgeEssentials/ForgeEssentialsMain,CityOfLearning/ForgeEssentials,liachmodded/ForgeEssentials,aschmois/ForgeEssentialsMain | package com.forgeessentials.worldborder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.world.WorldServer;
import net.minecraftforge.common.DimensionManager;
import net.minecraftforge.permissions.PermissionsManager.RegisteredPermValue;
import com.forgeessentials.core.commands.ForgeEssentialsCommandBase;
import com.forgeessentials.util.FunctionHelper;
import com.forgeessentials.util.OutputHandler;
import cpw.mods.fml.common.FMLCommonHandler;
public class CommandFiller extends ForgeEssentialsCommandBase {
// Zone name - filler
public static HashMap<Integer, TickTaskFill> map = new HashMap<Integer, TickTaskFill>();
@Override
public String getCommandName()
{
return "filler";
}
@Override
public void processCommandPlayer(EntityPlayer sender, String[] args)
{
if (FMLCommonHandler.instance().getEffectiveSide().isClient())
{
return;
}
execute(sender, args);
}
@Override
public void processCommandConsole(ICommandSender sender, String[] args)
{
if (FMLCommonHandler.instance().getEffectiveSide().isClient())
{
return;
}
execute(sender, args);
}
private void execute(ICommandSender sender, String[] args)
{
/*
* No world, Status update.
*/
if (args.length == 0)
{
// Header
String header = "--- Fillers active ---";
OutputHandler.chatNotification(sender, header);
// Actual info
for (Integer world : map.keySet())
{
OutputHandler.chatNotification(sender, world + ": " + map.get(world).getStatus());
}
// Footer
StringBuilder footer = new StringBuilder();
for (int i = 3; i < header.length(); i++)
{
footer.append("-");
}
OutputHandler.chatNotification(sender, footer.toString());
return;
}
/*
* Get the world
*/
WorldServer world = null;
if (FunctionHelper.isNumeric(args[0]))
{
world = DimensionManager.getWorld(parseInt(sender, args[0]));
}
else if ((args[0].equalsIgnoreCase("here") || args[0].equalsIgnoreCase("world")) && sender instanceof EntityPlayer)
{
world = (WorldServer) ((EntityPlayer) sender).worldObj;
}
if (world == null)
{
OutputHandler.chatError(sender, args[0] + " is not an ID of a loaded world.");
return;
}
if (args.length == 1)
{
if (map.containsKey(world.provider.dimensionId))
{
OutputHandler.chatConfirmation(sender, map.get(world.provider.dimensionId).getStatus());
}
else
{
OutputHandler.chatError(sender, "There is no filler running for that world.");
}
}
else
{
if (args[1].equalsIgnoreCase("start"))
{
if (!map.containsKey(world.provider.dimensionId))
{
map.put(world.provider.dimensionId, new TickTaskFill(world, sender, true));
}
else
{
OutputHandler.chatError(sender, "Filler already running for that world!");
}
}
else if (args[1].equalsIgnoreCase("stop"))
{
if (!map.containsKey(world.provider.dimensionId))
{
OutputHandler.chatError(sender, "There is no filler running for that world.");
}
else
{
map.get(world.provider.dimensionId).stop();
}
}
else if (args[1].equalsIgnoreCase("reset"))
{
if (!map.containsKey(world.provider.dimensionId))
{
map.put(world.provider.dimensionId, new TickTaskFill(world, sender, false));
}
else
{
OutputHandler.chatError(sender, "Filler already running for that world!");
}
}
else if (args[1].equalsIgnoreCase("speed"))
{
if (!map.containsKey(world.provider.dimensionId))
{
OutputHandler.chatError(sender, "There is no filler running for that world.");
}
else
{
if (args.length != 3)
{
OutputHandler.chatConfirmation(sender, "Current speed: " + map.get(world.provider.dimensionId));
}
else
{
map.get(world.provider.dimensionId).speed(parseIntWithMin(sender, args[2], 0));
if (map.get(world.provider.dimensionId).source != sender)
{
OutputHandler.chatError(sender, "Changed speed to " + args[2]);
}
}
}
}
}
}
@Override
public boolean canConsoleUseCommand()
{
return true;
}
@Override
public List<String> addTabCompletionOptions(ICommandSender sender, String[] args)
{
// Zone selection
if (args.length == 1)
{
ArrayList<String> list = new ArrayList<String>();
if (sender instanceof EntityPlayer)
{
list.add("world");
list.add("here");
}
for (int i : DimensionManager.getIDs())
{
list.add("" + i);
}
return getListOfStringsFromIterableMatchingLastWord(args, list);
}
if (args.length == 2)
{
return getListOfStringsMatchingLastWord(args, "start", "stop", "reset", "speed");
}
return null;
}
@Override
public String getPermissionNode()
{
return "fe.worldborder.filler";
}
@Override
public String getCommandUsage(ICommandSender sender)
{
return "/filler [worldID start|stop|reset|speed[value]]";
}
@Override
public RegisteredPermValue getDefaultPermission()
{
return RegisteredPermValue.OP;
}
}
| src/main/java/com/forgeessentials/worldborder/CommandFiller.java | package com.forgeessentials.worldborder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.world.WorldServer;
import net.minecraftforge.common.DimensionManager;
import net.minecraftforge.permissions.PermissionsManager.RegisteredPermValue;
import com.forgeessentials.core.commands.ForgeEssentialsCommandBase;
import com.forgeessentials.util.FunctionHelper;
import com.forgeessentials.util.OutputHandler;
import cpw.mods.fml.common.FMLCommonHandler;
public class CommandFiller extends ForgeEssentialsCommandBase {
// Zone name - filler
public static HashMap<Integer, TickTaskFill> map = new HashMap<Integer, TickTaskFill>();
@Override
public String getCommandName()
{
return "filler";
}
@Override
public void processCommandPlayer(EntityPlayer sender, String[] args)
{
if (FMLCommonHandler.instance().getEffectiveSide().isClient())
{
return;
}
execute(sender, args);
}
@Override
public void processCommandConsole(ICommandSender sender, String[] args)
{
if (FMLCommonHandler.instance().getEffectiveSide().isClient())
{
return;
}
execute(sender, args);
}
private void execute(ICommandSender sender, String[] args)
{
/*
* No world, Status update.
*/
if (args.length == 0)
{
// Header
String header = "--- Fillers active ---";
OutputHandler.chatNotification(sender, header);
// Actual info
for (Integer world : map.keySet())
{
OutputHandler.chatNotification(sender, world + ": " + map.get(world).getStatus());
}
// Footer
StringBuilder footer = new StringBuilder();
for (int i = 3; i < header.length(); i++)
{
footer.append("-");
}
OutputHandler.chatNotification(sender, footer.toString());
return;
}
/*
* Get the world
*/
WorldServer world = null;
if (FunctionHelper.isNumeric(args[0]))
{
world = DimensionManager.getWorld(parseInt(sender, args[0]));
}
else if ((args[0].equalsIgnoreCase("here") || args[0].equalsIgnoreCase("world")) && sender instanceof EntityPlayer)
{
world = (WorldServer) ((EntityPlayer) sender).worldObj;
}
if (world == null)
{
OutputHandler.chatError(sender, args[0] + " is not an ID of a loaded world.");
return;
}
if (args.length == 1)
{
if (map.containsKey(world.provider.dimensionId))
{
OutputHandler.chatConfirmation(sender, map.get(world.provider.dimensionId).getStatus());
}
else
{
OutputHandler.chatError(sender, "There is no filler running for that world.");
}
}
else
{
if (args[1].equalsIgnoreCase("start"))
{
if (!map.containsKey(world.provider.dimensionId))
{
map.put(world.provider.dimensionId, new TickTaskFill(world, sender, true));
}
else
{
OutputHandler.chatError(sender, "Filler already running for that world!");
}
}
else if (args[1].equalsIgnoreCase("stop"))
{
if (!map.containsKey(world.provider.dimensionId))
{
OutputHandler.chatError(sender, "There is no filler running for that world.");
}
else
{
map.get(world.provider.dimensionId).stop();
}
}
else if (args[1].equalsIgnoreCase("reset"))
{
if (!map.containsKey(world.provider.dimensionId))
{
map.put(world.provider.dimensionId, new TickTaskFill(world, sender, false));
}
else
{
OutputHandler.chatError(sender, "Filler already running for that world!");
}
}
else if (args[1].equalsIgnoreCase("speed"))
{
if (!map.containsKey(world.provider.dimensionId))
{
OutputHandler.chatError(sender, "There is no filler running for that world.");
}
else
{
if (args.length != 3)
{
OutputHandler.chatConfirmation(sender, "Current speed: " + map.get(world.provider.dimensionId));
}
else
{
map.get(world.provider.dimensionId).speed(parseIntWithMin(sender, args[2], 0));
if (map.get(world.provider.dimensionId).source != sender)
{
OutputHandler.chatError(sender, "Changed speed to " + args[2]);
}
}
}
}
}
}
@Override
public boolean canConsoleUseCommand()
{
return true;
}
@Override
public List<String> addTabCompletionOptions(ICommandSender sender, String[] args)
{
// Zone selection
if (args.length == 1)
{
ArrayList<String> list = new ArrayList<String>();
if (sender instanceof EntityPlayer)
{
list.add("world");
list.add("here");
}
for (int i : DimensionManager.getIDs())
{
list.add("" + i);
}
return getListOfStringsFromIterableMatchingLastWord(args, list);
}
if (args.length == 2)
{
return getListOfStringsMatchingLastWord(args, "start", "stop", "reset", "speed");
}
return null;
}
@Override
public String getPermissionNode()
{
return "fe.worldborder.filler";
}
@Override
public String getCommandUsage(ICommandSender sender)
{
return null;
}
@Override
public RegisteredPermValue getDefaultPermission()
{
return RegisteredPermValue.OP;
}
}
| Added command usage for /filler. Fixes #1052
| src/main/java/com/forgeessentials/worldborder/CommandFiller.java | Added command usage for /filler. Fixes #1052 | <ide><path>rc/main/java/com/forgeessentials/worldborder/CommandFiller.java
<ide> @Override
<ide> public String getCommandUsage(ICommandSender sender)
<ide> {
<del>
<del> return null;
<add> return "/filler [worldID start|stop|reset|speed[value]]";
<ide> }
<ide>
<ide> @Override |
|
Java | mit | 5a9ee728a66c3fb404f4ee4269896561c04c23c8 | 0 | bfranco94/ziptastic-java,Ziptastic/ziptastic-java | /*
* 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 Ziptastic_Object;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class Ziptastic {
private static String url = "https://zip.getziptastic.com/v3/US/";
private static String reverseUrl = "https://zip.getziptastic.com/v3/reverse/";
private static String apiKey;
public Ziptastic(String key) {
this.apiKey = key;
}
public static String GetFromLongLat(double latitude, double longitude, int radius) throws IOException{
String urlBuilder = reverseUrl;
urlBuilder = urlBuilder.concat(Double.toString(latitude) + "/" + Double.toString(longitude) + "/" + Integer.toString(radius));
return MakeRequest(urlBuilder);
}
public static String GetFromZipcode(int zipcode) throws IOException{
String urlBuilder = url;
urlBuilder = urlBuilder.concat(Integer.toString(zipcode));
return MakeRequest(urlBuilder);
}
private static String MakeRequest(String url) throws IOException{
String getData;
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("x-key", apiKey);
try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
HttpEntity entity = response.getEntity();
getData = EntityUtils.toString(entity);
EntityUtils.consume(entity);
}
}
return getData;
}
}
| Ziptastic/src/main/java/Ziptastic_Object/Ziptastic.java | /*
* 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 Ziptastic_Object;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class Ziptastic {
private static String url = "https://zip.getziptastic.com/v3/US/";
private static String apiKey;
public Ziptastic(String key) {
this.apiKey = key;
}
public static String GetFromZipcode(int zipcode) throws IOException{
String getData;
String urlBuilder = url;
urlBuilder = urlBuilder.concat(Integer.toString(zipcode));
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
HttpGet httpGet = new HttpGet(urlBuilder);
httpGet.addHeader("x-key", apiKey);
try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
HttpEntity entity = response.getEntity();
getData = EntityUtils.toString(entity);
EntityUtils.consume(entity);
}
}
return getData;
}
}
| Reverse Geocoding implemented.
Request moved into a separate method
Reverse/Forward Geocoding methods now create the URL which gets passed to the HTTP Request method. | Ziptastic/src/main/java/Ziptastic_Object/Ziptastic.java | Reverse Geocoding implemented. | <ide><path>iptastic/src/main/java/Ziptastic_Object/Ziptastic.java
<ide> public class Ziptastic {
<ide>
<ide> private static String url = "https://zip.getziptastic.com/v3/US/";
<add> private static String reverseUrl = "https://zip.getziptastic.com/v3/reverse/";
<ide> private static String apiKey;
<ide>
<ide> public Ziptastic(String key) {
<ide> this.apiKey = key;
<ide> }
<ide>
<add> public static String GetFromLongLat(double latitude, double longitude, int radius) throws IOException{
<add> String urlBuilder = reverseUrl;
<add>
<add> urlBuilder = urlBuilder.concat(Double.toString(latitude) + "/" + Double.toString(longitude) + "/" + Integer.toString(radius));
<add>
<add> return MakeRequest(urlBuilder);
<add> }
<add>
<ide> public static String GetFromZipcode(int zipcode) throws IOException{
<del>
<del> String getData;
<ide>
<ide> String urlBuilder = url;
<ide> urlBuilder = urlBuilder.concat(Integer.toString(zipcode));
<ide>
<add> return MakeRequest(urlBuilder);
<add> }
<add>
<add>
<add>
<add> private static String MakeRequest(String url) throws IOException{
<add>
<add> String getData;
<add>
<ide> try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
<ide>
<del> HttpGet httpGet = new HttpGet(urlBuilder);
<add> HttpGet httpGet = new HttpGet(url);
<ide> httpGet.addHeader("x-key", apiKey);
<ide>
<ide> try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
<ide> EntityUtils.consume(entity);
<ide>
<ide> }
<del> }
<del> return getData;
<add> }
<add> return getData;
<ide> }
<del>
<add>
<ide> } |
|
Java | apache-2.0 | 842e85d717e805865f77173670d96e6f74d2e061 | 0 | clhedrick/sakai,lorenamgUMU/sakai,bzhouduke123/sakai,duke-compsci290-spring2016/sakai,puramshetty/sakai,bkirschn/sakai,tl-its-umich-edu/sakai,kwedoff1/sakai,puramshetty/sakai,bzhouduke123/sakai,rodriguezdevera/sakai,frasese/sakai,lorenamgUMU/sakai,rodriguezdevera/sakai,puramshetty/sakai,duke-compsci290-spring2016/sakai,pushyamig/sakai,surya-janani/sakai,clhedrick/sakai,kingmook/sakai,conder/sakai,OpenCollabZA/sakai,ktakacs/sakai,Fudan-University/sakai,zqian/sakai,frasese/sakai,ouit0408/sakai,zqian/sakai,zqian/sakai,rodriguezdevera/sakai,Fudan-University/sakai,puramshetty/sakai,wfuedu/sakai,udayg/sakai,bkirschn/sakai,ouit0408/sakai,noondaysun/sakai,tl-its-umich-edu/sakai,surya-janani/sakai,ktakacs/sakai,bzhouduke123/sakai,duke-compsci290-spring2016/sakai,conder/sakai,liubo404/sakai,frasese/sakai,zqian/sakai,introp-software/sakai,kingmook/sakai,buckett/sakai-gitflow,ktakacs/sakai,Fudan-University/sakai,surya-janani/sakai,ktakacs/sakai,duke-compsci290-spring2016/sakai,willkara/sakai,conder/sakai,introp-software/sakai,bzhouduke123/sakai,bkirschn/sakai,ktakacs/sakai,Fudan-University/sakai,noondaysun/sakai,clhedrick/sakai,clhedrick/sakai,whumph/sakai,lorenamgUMU/sakai,whumph/sakai,lorenamgUMU/sakai,udayg/sakai,introp-software/sakai,bkirschn/sakai,joserabal/sakai,OpenCollabZA/sakai,joserabal/sakai,duke-compsci290-spring2016/sakai,tl-its-umich-edu/sakai,willkara/sakai,buckett/sakai-gitflow,buckett/sakai-gitflow,puramshetty/sakai,zqian/sakai,pushyamig/sakai,pushyamig/sakai,hackbuteer59/sakai,OpenCollabZA/sakai,surya-janani/sakai,whumph/sakai,wfuedu/sakai,puramshetty/sakai,colczr/sakai,ouit0408/sakai,whumph/sakai,Fudan-University/sakai,buckett/sakai-gitflow,wfuedu/sakai,liubo404/sakai,conder/sakai,Fudan-University/sakai,duke-compsci290-spring2016/sakai,colczr/sakai,pushyamig/sakai,noondaysun/sakai,liubo404/sakai,ouit0408/sakai,willkara/sakai,kwedoff1/sakai,liubo404/sakai,lorenamgUMU/sakai,tl-its-umich-edu/sakai,noondaysun/sakai,whumph/sakai,udayg/sakai,kingmook/sakai,hackbuteer59/sakai,wfuedu/sakai,bkirschn/sakai,willkara/sakai,willkara/sakai,wfuedu/sakai,OpenCollabZA/sakai,lorenamgUMU/sakai,kwedoff1/sakai,conder/sakai,conder/sakai,liubo404/sakai,willkara/sakai,pushyamig/sakai,OpenCollabZA/sakai,conder/sakai,ouit0408/sakai,introp-software/sakai,udayg/sakai,OpenCollabZA/sakai,kingmook/sakai,liubo404/sakai,pushyamig/sakai,pushyamig/sakai,introp-software/sakai,frasese/sakai,rodriguezdevera/sakai,bzhouduke123/sakai,kingmook/sakai,noondaysun/sakai,pushyamig/sakai,kwedoff1/sakai,surya-janani/sakai,liubo404/sakai,kwedoff1/sakai,duke-compsci290-spring2016/sakai,lorenamgUMU/sakai,willkara/sakai,colczr/sakai,ouit0408/sakai,joserabal/sakai,colczr/sakai,udayg/sakai,surya-janani/sakai,wfuedu/sakai,introp-software/sakai,ouit0408/sakai,clhedrick/sakai,willkara/sakai,wfuedu/sakai,buckett/sakai-gitflow,hackbuteer59/sakai,tl-its-umich-edu/sakai,OpenCollabZA/sakai,colczr/sakai,joserabal/sakai,frasese/sakai,surya-janani/sakai,hackbuteer59/sakai,wfuedu/sakai,Fudan-University/sakai,puramshetty/sakai,colczr/sakai,clhedrick/sakai,hackbuteer59/sakai,joserabal/sakai,noondaysun/sakai,tl-its-umich-edu/sakai,frasese/sakai,frasese/sakai,bzhouduke123/sakai,ktakacs/sakai,buckett/sakai-gitflow,kwedoff1/sakai,lorenamgUMU/sakai,joserabal/sakai,bkirschn/sakai,kingmook/sakai,bzhouduke123/sakai,whumph/sakai,hackbuteer59/sakai,buckett/sakai-gitflow,clhedrick/sakai,ktakacs/sakai,zqian/sakai,Fudan-University/sakai,bkirschn/sakai,kwedoff1/sakai,rodriguezdevera/sakai,ouit0408/sakai,joserabal/sakai,rodriguezdevera/sakai,liubo404/sakai,tl-its-umich-edu/sakai,conder/sakai,hackbuteer59/sakai,frasese/sakai,clhedrick/sakai,rodriguezdevera/sakai,buckett/sakai-gitflow,udayg/sakai,ktakacs/sakai,colczr/sakai,zqian/sakai,introp-software/sakai,whumph/sakai,OpenCollabZA/sakai,colczr/sakai,tl-its-umich-edu/sakai,noondaysun/sakai,udayg/sakai,introp-software/sakai,rodriguezdevera/sakai,bkirschn/sakai,bzhouduke123/sakai,kwedoff1/sakai,joserabal/sakai,kingmook/sakai,noondaysun/sakai,kingmook/sakai,puramshetty/sakai,whumph/sakai,duke-compsci290-spring2016/sakai,hackbuteer59/sakai,udayg/sakai,surya-janani/sakai,zqian/sakai | /**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008 The Sakai Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.osedu.org/licenses/ECL-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
package org.sakaiproject.user.tool;
import java.util.List;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.tanesha.recaptcha.ReCaptcha;
import net.tanesha.recaptcha.ReCaptchaFactory;
import net.tanesha.recaptcha.ReCaptchaResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.validator.EmailValidator;
import org.sakaiproject.authz.cover.SecurityService;
import org.sakaiproject.cheftool.Context;
import org.sakaiproject.cheftool.JetspeedRunData;
import org.sakaiproject.cheftool.PagedResourceActionII;
import org.sakaiproject.cheftool.PortletConfig;
import org.sakaiproject.cheftool.RunData;
import org.sakaiproject.cheftool.VelocityPortlet;
import org.sakaiproject.cheftool.api.Menu;
import org.sakaiproject.cheftool.api.MenuItem;
import org.sakaiproject.cheftool.menu.MenuEntry;
import org.sakaiproject.cheftool.menu.MenuImpl;
import org.sakaiproject.component.cover.ServerConfigurationService;
import org.sakaiproject.event.api.SessionState;
import org.sakaiproject.event.cover.UsageSessionService;
import org.sakaiproject.thread_local.cover.ThreadLocalManager;
import org.sakaiproject.tool.api.Session;
import org.sakaiproject.tool.cover.SessionManager;
import org.sakaiproject.user.api.Authentication;
import org.sakaiproject.user.api.AuthenticationException;
import org.sakaiproject.user.api.Evidence;
import org.sakaiproject.user.api.User;
import org.sakaiproject.user.api.UserAlreadyDefinedException;
import org.sakaiproject.user.api.UserEdit;
import org.sakaiproject.user.api.UserIdInvalidException;
import org.sakaiproject.user.api.UserLockedException;
import org.sakaiproject.user.api.UserNotDefinedException;
import org.sakaiproject.user.api.UserPermissionException;
import org.sakaiproject.user.cover.AuthenticationManager;
import org.sakaiproject.user.cover.UserDirectoryService;
import org.sakaiproject.util.ExternalTrustedEvidence;
import org.sakaiproject.util.RequestFilter;
import org.sakaiproject.util.ResourceLoader;
import org.sakaiproject.util.StringUtil;
/**
* <p>
* UsersAction is the Sakai users editor.
* </p>
*/
public class UsersAction extends PagedResourceActionII
{
private static ResourceLoader rb = new ResourceLoader("admin");
/**
* {@inheritDoc}
*/
protected List readResourcesPage(SessionState state, int first, int last)
{
// search?
String search = StringUtils.trimToNull((String) state.getAttribute(STATE_SEARCH));
if (search != null)
{
return UserDirectoryService.searchUsers(search, first, last);
}
return UserDirectoryService.getUsers(first, last);
}
/**
* {@inheritDoc}
*/
protected int sizeResources(SessionState state)
{
// search?
String search = StringUtils.trimToNull((String) state.getAttribute(STATE_SEARCH));
if (search != null)
{
return UserDirectoryService.countSearchUsers(search);
}
return UserDirectoryService.countUsers();
}
/**
* Populate the state object, if needed.
*/
protected void initState(SessionState state, VelocityPortlet portlet, JetspeedRunData rundata)
{
super.initState(state, portlet, rundata);
PortletConfig config = portlet.getPortletConfig();
if (state.getAttribute("single-user") == null)
{
state.setAttribute("single-user", new Boolean(config.getInitParameter("single-user", "false")));
state.setAttribute("include-password", new Boolean(config.getInitParameter("include-password", "true")));
}
if (state.getAttribute("create-user") == null)
{
state.setAttribute("create-user", new Boolean(config.getInitParameter("create-user", "false")));
state.setAttribute("create-login", new Boolean(config.getInitParameter("create-login", "false")));
}
if (state.getAttribute("create-type") == null)
{
state.setAttribute("create-type", config.getInitParameter("create-type", ""));
}
if (state.getAttribute("user.recaptcha-enabled") == null)
{
String publicKey = ServerConfigurationService.getString("user.recaptcha.public-key", "");
String privateKey = ServerConfigurationService.getString("user.recaptcha.private-key", "");
Boolean systemEnabled = ServerConfigurationService.getBoolean("user.recaptcha.enabled", false);
Boolean toolEnabled = Boolean.parseBoolean(config.getInitParameter("user.recaptcha-enabled", "false"));
Boolean enabled = systemEnabled && toolEnabled;
if (enabled)
{
if (publicKey == null || publicKey.length() == 0)
{
Log.warn("chef", "recaptcha is enabled but no public key is found.");
enabled = Boolean.FALSE;
}
if (privateKey == null || privateKey.length() == 0)
{
Log.warn("chef", "recaptcha is enabled but no private key is found.");
enabled = Boolean.FALSE;
}
}
state.setAttribute("user.recaptcha-public-key", publicKey);
state.setAttribute("user.recaptcha-private-key", privateKey);
state.setAttribute("user.recaptcha-enabled", enabled);
}
} // initState
/**
* build the context
*/
public String buildMainPanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state)
{
context.put("tlang", rb);
boolean singleUser = ((Boolean) state.getAttribute("single-user")).booleanValue();
boolean createUser = ((Boolean) state.getAttribute("create-user")).booleanValue();
// if not logged in as the super user, we won't do anything
if ((!singleUser) && (!createUser) && (!SecurityService.isSuperUser()))
{
context.put("tlang",rb);
return (String) getContext(rundata).get("template") + "_noaccess";
}
String template = null;
// for the create-user create-login case, we set this in the do so we can process the redirect here
if (state.getAttribute("redirect") != null)
{
state.removeAttribute("redirect");
Session s = SessionManager.getCurrentSession();
// TODO: Decide if this should be in "getPortalUrl"
// I don't think so but could be convinced - /chuck
String controllingPortal = (String) s.getAttribute("sakai-controlling-portal");
String portalUrl = ServerConfigurationService.getPortalUrl();
if ( controllingPortal != null ) {
portalUrl = portalUrl + "/" + controllingPortal;
}
sendParentRedirect((HttpServletResponse) ThreadLocalManager.get(RequestFilter.CURRENT_HTTP_RESPONSE),
portalUrl);
return template;
}
// put $action into context for menus, forms and links
context.put(Menu.CONTEXT_ACTION, state.getAttribute(STATE_ACTION));
// check mode and dispatch
String mode = (String) state.getAttribute("mode");
if ((singleUser) && (mode != null) && (mode.equals("edit")))
{
template = buildEditContext(state, context);
}
else if (singleUser)
{
String id = SessionManager.getCurrentSessionUserId();
state.setAttribute("user-id", id);
template = buildViewContext(state, context);
}
else if (createUser)
{
template = buildCreateContext(state, context);
}
else if (mode == null)
{
template = buildListContext(state, context);
}
else if (mode.equals("new"))
{
template = buildNewContext(state, context);
}
else if (mode.equals("edit"))
{
template = buildEditContext(state, context);
}
else if (mode.equals("confirm"))
{
template = buildConfirmRemoveContext(state, context);
}
else
{
Log.warn("chef", "UsersAction: mode: " + mode);
template = buildListContext(state, context);
}
String prefix = (String) getContext(rundata).get("template");
return prefix + template;
} // buildNormalContext
/**
* Build the context for the main list mode.
*/
private String buildListContext(SessionState state, Context context)
{
// put the service in the context
context.put("service", UserDirectoryService.getInstance());
// put all (internal) users into the context
context.put("users", prepPage(state));
// build the menu
Menu bar = new MenuImpl();
if (UserDirectoryService.allowAddUser())
{
bar.add(new MenuEntry(rb.getString("useact.newuse"), null, true, MenuItem.CHECKED_NA, "doNew"));
}
// add the paging commands
//addListPagingMenus(bar, state);
int pageSize = Integer.valueOf(state.getAttribute(STATE_PAGESIZE).toString()).intValue();
int currentPageNubmer = Integer.valueOf(state.getAttribute(STATE_CURRENT_PAGE).toString()).intValue();
int startNumber = pageSize * (currentPageNubmer - 1) + 1;
int endNumber = pageSize * currentPageNubmer;
int totalNumber = 0;
Object[] params;
ArrayList list = new ArrayList();
list.add(new Integer[]{Integer.valueOf(5)});
list.add(new Integer[]{Integer.valueOf(10)});
list.add(new Integer[]{Integer.valueOf(20)});
list.add(new Integer[]{Integer.valueOf(50)});
list.add(new Integer[]{Integer.valueOf(100)});
list.add(new Integer[]{Integer.valueOf(200)});
try
{
totalNumber = Integer.valueOf(state.getAttribute(STATE_NUM_MESSAGES).toString()).intValue();
}
catch (java.lang.NullPointerException ignore) {}
catch (java.lang.NumberFormatException ignore) {}
if (totalNumber < endNumber) endNumber = totalNumber;
params = new Object[]{startNumber, endNumber, totalNumber};
context.put("startNumber", Integer.valueOf(startNumber));
context.put("endNumber", Integer.valueOf(endNumber));
context.put("totalNumber", Integer.valueOf(totalNumber));
context.put("params", params);
context.put("list", list);
pagingInfoToContext(state, context);
// add the search commands
addSearchMenus(bar, state);
// add the refresh commands
addRefreshMenus(bar, state);
if (bar.size() > 0)
{
context.put(Menu.CONTEXT_MENU, bar);
}
return "_list";
} // buildListContext
/**
* Build the context for the new user mode.
*/
private String buildNewContext(SessionState state, Context context)
{
// put the service in the context
context.put("service", UserDirectoryService.getInstance());
// name the html form for user edit fields
context.put("form-name", "user-form");
// include the password fields?
context.put("incPw", state.getAttribute("include-password"));
context.put("incType", Boolean.valueOf(true));
context.put("superUser", Boolean.valueOf(SecurityService.isSuperUser()));
String value = (String) state.getAttribute("valueEid");
if (value != null) context.put("valueEid", value);
value = (String) state.getAttribute("valueFirstName");
if (value != null) context.put("valueFirstName", value);
value = (String) state.getAttribute("valueLastName");
if (value != null) context.put("valueLastName", value);
value = (String) state.getAttribute("valueEmail");
if (value != null) context.put("valueEmail", value);
value = (String) state.getAttribute("valueType");
if (value != null) context.put("valueType", value);
return "_edit";
} // buildNewContext
/**
* Build the context for the create user mode.
*/
private String buildCreateContext(SessionState state, Context context)
{
// put the service in the context
context.put("service", UserDirectoryService.getInstance());
// is the type to be pre-set
context.put("type", state.getAttribute("create-type"));
// password is required when using Gateway New Account tool
// attribute "create-user" is true only for New Account tool
context.put("pwRequired", state.getAttribute("create-user"));
String value = (String) state.getAttribute("valueEid");
if (value != null) context.put("valueEid", value);
value = (String) state.getAttribute("valueFirstName");
if (value != null) context.put("valueFirstName", value);
value = (String) state.getAttribute("valueLastName");
if (value != null) context.put("valueLastName", value);
value = (String) state.getAttribute("valueEmail");
if (value != null) context.put("valueEmail", value);
if ((Boolean)state.getAttribute("user.recaptcha-enabled"))
{
ReCaptcha captcha = ReCaptchaFactory.newReCaptcha((String)state.getAttribute("user.recaptcha-public-key"), (String)state.getAttribute("user.recaptcha-private-key"), false);
String captchaScript = captcha.createRecaptchaHtml((String)state.getAttribute("recaptcha-error"), null);
state.removeAttribute("recaptcha-error");
context.put("recaptchaScript", captchaScript);
}
return "_create";
} // buildCreateContext
/**
* Build the context for the new user mode.
*/
private String buildEditContext(SessionState state, Context context)
{
// put the service in the context
context.put("service", UserDirectoryService.getInstance());
// name the html form for user edit fields
context.put("form-name", "user-form");
// get the user to edit
UserEdit user = (UserEdit) state.getAttribute("user");
context.put("user", user);
// is super user/admin user?
context.put("superUser", Boolean.valueOf(SecurityService.isSuperUser()));
// include the password fields?
context.put("incPw", state.getAttribute("include-password"));
// include type fields (not if single user)
boolean singleUser = ((Boolean) state.getAttribute("single-user")).booleanValue();
context.put("incType", Boolean.valueOf(!singleUser));
// build the menu
// we need the form fields for the remove...
boolean menuPopulated = false;
Menu bar = new MenuImpl();
if ((!singleUser) && (UserDirectoryService.allowRemoveUser(user.getId())))
{
bar.add(new MenuEntry(rb.getString("useact.remuse"), null, true, MenuItem.CHECKED_NA, "doRemove", "user-form"));
menuPopulated = true;
}
if (menuPopulated)
{
context.put(Menu.CONTEXT_MENU, bar);
}
String value = (String) state.getAttribute("valueEid");
if (value != null) context.put("valueEid", value);
value = (String) state.getAttribute("valueFirstName");
if (value != null) context.put("valueFirstName", value);
value = (String) state.getAttribute("valueLastName");
if (value != null) context.put("valueLastName", value);
value = (String) state.getAttribute("valueEmail");
if (value != null) context.put("valueEmail", value);
value = (String) state.getAttribute("valueType");
if (value != null) context.put("valueType", value);
return "_edit";
} // buildEditContext
/**
* Build the context for the view user mode.
*/
private String buildViewContext(SessionState state, Context context)
{
if (Log.getLogger("chef").isDebugEnabled())
{
Log.debug("chef", this + ".buildViewContext");
}
// get current user's id
String id = (String) state.getAttribute("user-id");
// get the user and put in state as "user"
try
{
User user = UserDirectoryService.getUser(id);
context.put("user", user);
// name the html form for user edit fields
context.put("form-name", "user-form");
state.setAttribute("mode", "view");
// make sure we can do an edit
try
{
UserEdit edit = UserDirectoryService.editUser(id);
UserDirectoryService.cancelEdit(edit);
context.put("enableEdit", "true");
}
catch (UserNotDefinedException e)
{
}
catch (UserPermissionException e)
{
}
catch (UserLockedException e)
{
}
//SAK-19498
//check if user can change pw (this is used to determine if user should
//view createdBy and modifiedBy info (assuming you can't change pw for provided users)
if(UserDirectoryService.getInstance().allowUpdateUserPassword(id)){
context.put("viewCreatedModifiedBy", "true");
}
// disable auto-updates while not in list mode
disableObservers(state);
}
catch (UserNotDefinedException e)
{
Log.warn("chef", "UsersAction.doEdit: user not found: " + id);
Object[] params = new Object[]{id};
addAlert(state, rb.getFormattedMessage("useact.use_notfou", params));
state.removeAttribute("mode");
// make sure auto-updates are enabled
enableObserver(state);
}
return "_view";
} // buildViewContext
/**
* Build the context for the new user mode.
*/
private String buildConfirmRemoveContext(SessionState state, Context context)
{
// get the user to edit
UserEdit user = (UserEdit) state.getAttribute("user");
context.put("user", user);
return "_confirm_remove";
} // buildConfirmRemoveContext
/**
* doNew called when "eventSubmit_doNew" is in the request parameters to add a new user
*/
public void doNew(RunData data, Context context)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute("mode", "new");
// mark the user as new, so on cancel it can be deleted
state.setAttribute("new", "true");
// disable auto-updates while not in list mode
disableObservers(state);
} // doNew
/**
* doEdit called when "eventSubmit_doEdit" is in the request parameters to edit a user
*/
public void doEdit(RunData data, Context context)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
String id = data.getParameters().getString("id");
state.removeAttribute("user");
state.removeAttribute("newuser");
// get the user
try
{
UserEdit user = UserDirectoryService.editUser(id);
state.setAttribute("user", user);
state.setAttribute("mode", "edit");
// disable auto-updates while not in list mode
disableObservers(state);
}
catch (UserNotDefinedException e)
{
Log.warn("chef", "UsersAction.doEdit: user not found: " + id);
Object[] params = new Object[]{id};
addAlert(state, rb.getFormattedMessage("useact.use_notfou", params));
state.removeAttribute("mode");
// make sure auto-updates are enabled
enableObserver(state);
}
catch (UserPermissionException e)
{
addAlert(state, rb.getFormattedMessage("useact.youdonot1", new Object[]{id}));
state.removeAttribute("mode");
// make sure auto-updates are enabled
enableObserver(state);
}
catch (UserLockedException e)
{
addAlert(state, rb.getFormattedMessage("useact.somels", new Object[]{id}));
state.removeAttribute("mode");
// make sure auto-updates are enabled
enableObserver(state);
}
} // doEdit
/**
* doModify called when "eventSubmit_doModify" is in the request parameters to edit a user
*/
public void doModify(RunData data, Context context)
{
if (Log.getLogger("chef").isDebugEnabled())
{
Log.debug("chef", this + ".doModify");
}
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
String id = data.getParameters().getString("id");
state.removeAttribute("user");
state.removeAttribute("newuser");
// get the user
try
{
UserEdit user = UserDirectoryService.editUser(id);
state.setAttribute("user", user);
state.setAttribute("mode", "edit");
// disable auto-updates while not in list mode
disableObservers(state);
}
catch (UserNotDefinedException e)
{
Log.warn("chef", "UsersAction.doEdit: user not found: " + id);
Object[] params = new Object[]{id};
addAlert(state, rb.getFormattedMessage("useact.use_notfou", params));
state.removeAttribute("mode");
// make sure auto-updates are enabled
enableObserver(state);
}
catch (UserPermissionException e)
{
addAlert(state, rb.getFormattedMessage("useact.youdonot1", new Object[]{id}));
state.removeAttribute("mode");
// make sure auto-updates are enabled
enableObserver(state);
}
catch (UserLockedException e)
{
addAlert(state, rb.getFormattedMessage("useact.somels", new Object[]{id}));
state.removeAttribute("mode");
// make sure auto-updates are enabled
enableObserver(state);
}
} // doModify
/**
* doSave called when "eventSubmit_doSave" is in the request parameters to save user edits
*/
public void doSave(RunData data, Context context)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// read the form - if rejected, leave things as they are
if (!readUserForm(data, state)) return;
// commit the change
UserEdit edit = (UserEdit) state.getAttribute("user");
if (edit != null)
{
try
{
UserDirectoryService.commitEdit(edit);
}
catch (UserAlreadyDefinedException e)
{
// TODO: this means the EID value is not unique... when we implement EID fully, we need to check this and send it back to the user
Log.warn("chef", "UsersAction.doSave()" + e);
addAlert(state, rb.getString("useact.theuseid1"));
return;
}
}
User user = edit;
if (user == null)
{
user = (User) state.getAttribute("newuser");
}
// cleanup
state.removeAttribute("user");
state.removeAttribute("newuser");
state.removeAttribute("new");
state.removeAttribute("valueEid");
state.removeAttribute("valueFirstName");
state.removeAttribute("valueLastName");
state.removeAttribute("valueEmail");
state.removeAttribute("valueType");
// return to main mode
state.removeAttribute("mode");
// make sure auto-updates are enabled
enableObserver(state);
if ((user != null) && ((Boolean) state.getAttribute("create-login")).booleanValue())
{
try
{
// login - use the fact that we just created the account as external evidence
Evidence e = new ExternalTrustedEvidence(user.getEid());
Authentication a = AuthenticationManager.authenticate(e);
if (!UsageSessionService.login(a, (HttpServletRequest) ThreadLocalManager.get(RequestFilter.CURRENT_HTTP_REQUEST)))
{
addAlert(state, rb.getString("useact.tryloginagain"));
}
}
catch (AuthenticationException ex)
{
Log.warn("chef", "UsersAction.doSave: authentication failure: " + ex);
}
// redirect to home (on next build)
state.setAttribute("redirect", "");
}
} // doSave
/**
* doCancel called when "eventSubmit_doCancel" is in the request parameters to cancel user edits
*/
public void doCancel(RunData data, Context context)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// get the user
UserEdit user = (UserEdit) state.getAttribute("user");
if (user != null)
{
// if this was a new, delete the user
if ("true".equals(state.getAttribute("new")))
{
// remove
try
{
UserDirectoryService.removeUser(user);
}
catch (UserPermissionException e)
{
addAlert(state, rb.getFormattedMessage("useact.youdonot2", new Object[]{user.getId()}));
}
}
else
{
UserDirectoryService.cancelEdit(user);
}
}
// cleanup
state.removeAttribute("user");
state.removeAttribute("newuser");
state.removeAttribute("new");
state.removeAttribute("valueEid");
state.removeAttribute("valueFirstName");
state.removeAttribute("valueLastName");
state.removeAttribute("valueEmail");
state.removeAttribute("valueType");
// return to main mode
state.removeAttribute("mode");
// make sure auto-updates are enabled
enableObserver(state);
} // doCancel
/**
* doRemove called when "eventSubmit_doRemove" is in the request par ameters to confirm removal of the user
*/
public void doRemove(RunData data, Context context)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// read the form - if rejected, leave things as they are
if (!readUserForm(data, state)) return;
// go to remove confirm mode
state.setAttribute("mode", "confirm");
} // doRemove
/**
* doRemove_confirmed called when "eventSubmit_doRemove_confirmed" is in the request parameters to remove the user
*/
public void doRemove_confirmed(RunData data, Context context)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// get the user
UserEdit user = (UserEdit) state.getAttribute("user");
// remove
try
{
UserDirectoryService.removeUser(user);
}
catch (UserPermissionException e)
{
addAlert(state, rb.getFormattedMessage("useact.youdonot2", new Object[]{user.getId()}));
}
// cleanup
state.removeAttribute("user");
state.removeAttribute("newuser");
state.removeAttribute("new");
state.removeAttribute("valueEid");
state.removeAttribute("valueFirstName");
state.removeAttribute("valueLastName");
state.removeAttribute("valueEmail");
state.removeAttribute("valueType");
// go to main mode
state.removeAttribute("mode");
// make sure auto-updates are enabled
enableObserver(state);
} // doRemove_confirmed
/**
* doCancel_remove called when "eventSubmit_doCancel_remove" is in the request parameters to cancel user removal
*/
public void doCancel_remove(RunData data, Context context)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// return to edit mode
state.setAttribute("mode", "edit");
} // doCancel_remove
/**
* Read the user form and update the user in state.
*
* @return true if the form is accepted, false if there's a validation error (an alertMessage will be set)
*/
private boolean readUserForm(RunData data, SessionState state)
{
// boolean parameters and values
// --------------Mode--singleUser-createUser-typeEnable
// Admin New-----new---false------false------true
// Admin Update--edit--false------false------true
// Gateway New---null---false------true-------false
// Account Edit--edit--true-------false------false
// read the form
String id = StringUtils.trimToNull(data.getParameters().getString("id"));
String eid = StringUtils.trimToNull(data.getParameters().getString("eid"));
state.setAttribute("valueEid", eid);
String firstName = StringUtils.trimToNull(data.getParameters().getString("first-name"));
state.setAttribute("valueFirstName", firstName);
String lastName = StringUtils.trimToNull(data.getParameters().getString("last-name"));
state.setAttribute("valueLastName", lastName);
String email = StringUtils.trimToNull(data.getParameters().getString("email"));
state.setAttribute("valueEmail", email);
String pw = StringUtils.trimToNull(data.getParameters().getString("pw"));
String pwConfirm = StringUtils.trimToNull(data.getParameters().getString("pw0"));
String pwcur = StringUtils.trimToNull(data.getParameters().getString("pwcur"));
String mode = (String) state.getAttribute("mode");
boolean singleUser = ((Boolean) state.getAttribute("single-user")).booleanValue();
boolean createUser = ((Boolean) state.getAttribute("create-user")).booleanValue();
boolean typeEnable = false;
String type = null;
if ((mode != null) && (mode.equalsIgnoreCase("new")))
{
typeEnable = true;
}
else if ((mode != null) && (mode.equalsIgnoreCase("edit")) && (!singleUser))
{
typeEnable = true;
}
if (typeEnable)
{
// for the case of Admin User tool creating new user
type = StringUtils.trimToNull(data.getParameters().getString("type"));
state.setAttribute("valueType", type);
}
else
{
if (createUser)
{
// for the case of Gateway Account tool creating new user
type = (String) state.getAttribute("create-type");
}
}
if ((Boolean)state.getAttribute("user.recaptcha-enabled"))
{
String challengeField = data.getParameters().getString("recaptcha_challenge_field");
String responseField = data.getParameters().getString("recaptcha_response_field");
if (challengeField == null) challengeField = "";
if (responseField == null) responseField = "";
ReCaptcha captcha = ReCaptchaFactory.newReCaptcha((String)state.getAttribute("user.recaptcha-public-key"), (String)state.getAttribute("user.recaptcha-private-key"), false);
ReCaptchaResponse response = captcha.checkAnswer(data.getRequest().getRemoteAddr(), challengeField, responseField);
if (!response.isValid())
{
addAlert(state, rb.getString("useact.capterr"));
state.setAttribute("recaptcha-error", response.getErrorMessage());
return false;
}
}
//insure valid email address
//email.matches(".+@.+\\..+")
if(email != null && !EmailValidator.getInstance().isValid(email)) {
addAlert(state, rb.getString("useact.invemail"));
return false;
}
// get the user
UserEdit user = (UserEdit) state.getAttribute("user");
// add if needed
if (user == null)
{
// make sure we have eid
if (eid == null)
{
addAlert(state, rb.getString("usecre.eidmis"));
return false;
}
// if in create mode, make sure we have a password
if (createUser)
{
if (pw == null)
{
addAlert(state, rb.getString("usecre.pasismis"));
return false;
}
}
// make sure we have matching password fields
if (StringUtil.different(pw, pwConfirm))
{
addAlert(state, rb.getString("usecre.pass"));
return false;
}
try
{
// add the user in one step so that all you need is add not update permission
// (the added might be "anon", and anon has add but not update permission)
//SAK-18209 only an admin user should be able to specify a ID
if (!SecurityService.isSuperUser()) {
id = null;
}
User newUser = UserDirectoryService.addUser(id, eid, firstName, lastName, email, pw, type, null);
// put the user in the state
state.setAttribute("newuser", newUser);
}
catch (UserAlreadyDefinedException e)
{
addAlert(state, rb.getString("useact.theuseid1"));
return false;
}
catch (UserIdInvalidException e)
{
addAlert(state, rb.getString("useact.theuseid2"));
return false;
}
catch (UserPermissionException e)
{
addAlert(state, rb.getString("useact.youdonot3"));
return false;
}
}
// update
else
{
if (!user.isActiveEdit())
{
try
{
// add the user in one step so that all you need is add not update permission
// (the added might be "anon", and anon has add but not update permission)
user = UserDirectoryService.editUser(user.getId());
// put the user in the state
state.setAttribute("user", user);
}
catch (UserLockedException e)
{
addAlert(state, rb.getString("useact.somels"));
return false;
}
catch (UserNotDefinedException e)
{
Object[] params = new Object[]{id};
addAlert(state, rb.getFormattedMessage("useact.use_notfou", params));
return false;
}
catch (UserPermissionException e)
{
addAlert(state, rb.getString("useact.youdonot3"));
return false;
}
}
// eid, pw, type might not be editable
if (eid != null) user.setEid(eid);
user.setFirstName(firstName);
user.setLastName(lastName);
user.setEmail(email);
if (type != null) user.setType(type);
// make sure the old password matches, but don't check for super users
if (!SecurityService.isSuperUser()) {
if (!user.checkPassword(pwcur)) {
addAlert(state, rb.getString("usecre.curpass"));
return false;
}
}
// make sure we have matching password fields
if (StringUtil.different(pw, pwConfirm))
{
addAlert(state, rb.getString("usecre.pass"));
return false;
}
if (pw != null) user.setPassword(pw);
}
return true;
}
}
| user/user-tool/tool/src/java/org/sakaiproject/user/tool/UsersAction.java | /**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008 The Sakai Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.osedu.org/licenses/ECL-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
package org.sakaiproject.user.tool;
import java.util.List;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.tanesha.recaptcha.ReCaptcha;
import net.tanesha.recaptcha.ReCaptchaFactory;
import net.tanesha.recaptcha.ReCaptchaResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.validator.EmailValidator;
import org.sakaiproject.authz.cover.SecurityService;
import org.sakaiproject.cheftool.Context;
import org.sakaiproject.cheftool.JetspeedRunData;
import org.sakaiproject.cheftool.PagedResourceActionII;
import org.sakaiproject.cheftool.PortletConfig;
import org.sakaiproject.cheftool.RunData;
import org.sakaiproject.cheftool.VelocityPortlet;
import org.sakaiproject.cheftool.api.Menu;
import org.sakaiproject.cheftool.api.MenuItem;
import org.sakaiproject.cheftool.menu.MenuEntry;
import org.sakaiproject.cheftool.menu.MenuImpl;
import org.sakaiproject.component.cover.ServerConfigurationService;
import org.sakaiproject.event.api.SessionState;
import org.sakaiproject.event.cover.UsageSessionService;
import org.sakaiproject.thread_local.cover.ThreadLocalManager;
import org.sakaiproject.tool.api.Session;
import org.sakaiproject.tool.cover.SessionManager;
import org.sakaiproject.user.api.Authentication;
import org.sakaiproject.user.api.AuthenticationException;
import org.sakaiproject.user.api.Evidence;
import org.sakaiproject.user.api.User;
import org.sakaiproject.user.api.UserAlreadyDefinedException;
import org.sakaiproject.user.api.UserEdit;
import org.sakaiproject.user.api.UserIdInvalidException;
import org.sakaiproject.user.api.UserLockedException;
import org.sakaiproject.user.api.UserNotDefinedException;
import org.sakaiproject.user.api.UserPermissionException;
import org.sakaiproject.user.cover.AuthenticationManager;
import org.sakaiproject.user.cover.UserDirectoryService;
import org.sakaiproject.util.ExternalTrustedEvidence;
import org.sakaiproject.util.RequestFilter;
import org.sakaiproject.util.ResourceLoader;
import org.sakaiproject.util.StringUtil;
/**
* <p>
* UsersAction is the Sakai users editor.
* </p>
*/
public class UsersAction extends PagedResourceActionII
{
private static ResourceLoader rb = new ResourceLoader("admin");
/**
* {@inheritDoc}
*/
protected List readResourcesPage(SessionState state, int first, int last)
{
// search?
String search = StringUtils.trimToNull((String) state.getAttribute(STATE_SEARCH));
if (search != null)
{
return UserDirectoryService.searchUsers(search, first, last);
}
return UserDirectoryService.getUsers(first, last);
}
/**
* {@inheritDoc}
*/
protected int sizeResources(SessionState state)
{
// search?
String search = StringUtils.trimToNull((String) state.getAttribute(STATE_SEARCH));
if (search != null)
{
return UserDirectoryService.countSearchUsers(search);
}
return UserDirectoryService.countUsers();
}
/**
* Populate the state object, if needed.
*/
protected void initState(SessionState state, VelocityPortlet portlet, JetspeedRunData rundata)
{
super.initState(state, portlet, rundata);
PortletConfig config = portlet.getPortletConfig();
if (state.getAttribute("single-user") == null)
{
state.setAttribute("single-user", new Boolean(config.getInitParameter("single-user", "false")));
state.setAttribute("include-password", new Boolean(config.getInitParameter("include-password", "true")));
}
if (state.getAttribute("create-user") == null)
{
state.setAttribute("create-user", new Boolean(config.getInitParameter("create-user", "false")));
state.setAttribute("create-login", new Boolean(config.getInitParameter("create-login", "false")));
}
if (state.getAttribute("create-type") == null)
{
state.setAttribute("create-type", config.getInitParameter("create-type", ""));
}
if (state.getAttribute("user.recaptcha-enabled") == null)
{
String publicKey = ServerConfigurationService.getString("user.recaptcha.public-key", "");
String privateKey = ServerConfigurationService.getString("user.recaptcha.private-key", "");
Boolean systemEnabled = ServerConfigurationService.getBoolean("user.recaptcha.enabled", false);
Boolean toolEnabled = Boolean.parseBoolean(config.getInitParameter("user.recaptcha-enabled", "false"));
Boolean enabled = systemEnabled && toolEnabled;
if (enabled)
{
if (publicKey == null || publicKey.length() == 0)
{
Log.warn("chef", "recaptcha is enabled but no public key is found.");
enabled = Boolean.FALSE;
}
if (privateKey == null || privateKey.length() == 0)
{
Log.warn("chef", "recaptcha is enabled but no private key is found.");
enabled = Boolean.FALSE;
}
}
state.setAttribute("user.recaptcha-public-key", publicKey);
state.setAttribute("user.recaptcha-private-key", privateKey);
state.setAttribute("user.recaptcha-enabled", enabled);
}
} // initState
/**
* build the context
*/
public String buildMainPanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state)
{
context.put("tlang", rb);
boolean singleUser = ((Boolean) state.getAttribute("single-user")).booleanValue();
boolean createUser = ((Boolean) state.getAttribute("create-user")).booleanValue();
// if not logged in as the super user, we won't do anything
if ((!singleUser) && (!createUser) && (!SecurityService.isSuperUser()))
{
context.put("tlang",rb);
return (String) getContext(rundata).get("template") + "_noaccess";
}
String template = null;
// for the create-user create-login case, we set this in the do so we can process the redirect here
if (state.getAttribute("redirect") != null)
{
state.removeAttribute("redirect");
Session s = SessionManager.getCurrentSession();
// TODO: Decide if this should be in "getPortalUrl"
// I don't think so but could be convinced - /chuck
String controllingPortal = (String) s.getAttribute("sakai-controlling-portal");
String portalUrl = ServerConfigurationService.getPortalUrl();
if ( controllingPortal != null ) {
portalUrl = portalUrl + "/" + controllingPortal;
}
sendParentRedirect((HttpServletResponse) ThreadLocalManager.get(RequestFilter.CURRENT_HTTP_RESPONSE),
portalUrl);
return template;
}
// put $action into context for menus, forms and links
context.put(Menu.CONTEXT_ACTION, state.getAttribute(STATE_ACTION));
// check mode and dispatch
String mode = (String) state.getAttribute("mode");
if ((singleUser) && (mode != null) && (mode.equals("edit")))
{
template = buildEditContext(state, context);
}
else if (singleUser)
{
String id = SessionManager.getCurrentSessionUserId();
state.setAttribute("user-id", id);
template = buildViewContext(state, context);
}
else if (createUser)
{
template = buildCreateContext(state, context);
}
else if (mode == null)
{
template = buildListContext(state, context);
}
else if (mode.equals("new"))
{
template = buildNewContext(state, context);
}
else if (mode.equals("edit"))
{
template = buildEditContext(state, context);
}
else if (mode.equals("confirm"))
{
template = buildConfirmRemoveContext(state, context);
}
else
{
Log.warn("chef", "UsersAction: mode: " + mode);
template = buildListContext(state, context);
}
String prefix = (String) getContext(rundata).get("template");
return prefix + template;
} // buildNormalContext
/**
* Build the context for the main list mode.
*/
private String buildListContext(SessionState state, Context context)
{
// put the service in the context
context.put("service", UserDirectoryService.getInstance());
// put all (internal) users into the context
context.put("users", prepPage(state));
// build the menu
Menu bar = new MenuImpl();
if (UserDirectoryService.allowAddUser())
{
bar.add(new MenuEntry(rb.getString("useact.newuse"), null, true, MenuItem.CHECKED_NA, "doNew"));
}
// add the paging commands
//addListPagingMenus(bar, state);
int pageSize = Integer.valueOf(state.getAttribute(STATE_PAGESIZE).toString()).intValue();
int currentPageNubmer = Integer.valueOf(state.getAttribute(STATE_CURRENT_PAGE).toString()).intValue();
int startNumber = pageSize * (currentPageNubmer - 1) + 1;
int endNumber = pageSize * currentPageNubmer;
int totalNumber = 0;
Object[] params;
ArrayList list = new ArrayList();
list.add(new Integer[]{Integer.valueOf(5)});
list.add(new Integer[]{Integer.valueOf(10)});
list.add(new Integer[]{Integer.valueOf(20)});
list.add(new Integer[]{Integer.valueOf(50)});
list.add(new Integer[]{Integer.valueOf(100)});
list.add(new Integer[]{Integer.valueOf(200)});
try
{
totalNumber = Integer.valueOf(state.getAttribute(STATE_NUM_MESSAGES).toString()).intValue();
}
catch (java.lang.NullPointerException ignore) {}
catch (java.lang.NumberFormatException ignore) {}
if (totalNumber < endNumber) endNumber = totalNumber;
params = new Object[]{startNumber, endNumber, totalNumber};
context.put("startNumber", Integer.valueOf(startNumber));
context.put("endNumber", Integer.valueOf(endNumber));
context.put("totalNumber", Integer.valueOf(totalNumber));
context.put("params", params);
context.put("list", list);
pagingInfoToContext(state, context);
// add the search commands
addSearchMenus(bar, state);
// add the refresh commands
addRefreshMenus(bar, state);
if (bar.size() > 0)
{
context.put(Menu.CONTEXT_MENU, bar);
}
return "_list";
} // buildListContext
/**
* Build the context for the new user mode.
*/
private String buildNewContext(SessionState state, Context context)
{
// put the service in the context
context.put("service", UserDirectoryService.getInstance());
// include the password fields?
context.put("incPw", state.getAttribute("include-password"));
context.put("incType", Boolean.valueOf(true));
context.put("superUser", Boolean.valueOf(SecurityService.isSuperUser()));
String value = (String) state.getAttribute("valueEid");
if (value != null) context.put("valueEid", value);
value = (String) state.getAttribute("valueFirstName");
if (value != null) context.put("valueFirstName", value);
value = (String) state.getAttribute("valueLastName");
if (value != null) context.put("valueLastName", value);
value = (String) state.getAttribute("valueEmail");
if (value != null) context.put("valueEmail", value);
value = (String) state.getAttribute("valueType");
if (value != null) context.put("valueType", value);
return "_edit";
} // buildNewContext
/**
* Build the context for the create user mode.
*/
private String buildCreateContext(SessionState state, Context context)
{
// put the service in the context
context.put("service", UserDirectoryService.getInstance());
// is the type to be pre-set
context.put("type", state.getAttribute("create-type"));
// password is required when using Gateway New Account tool
// attribute "create-user" is true only for New Account tool
context.put("pwRequired", state.getAttribute("create-user"));
String value = (String) state.getAttribute("valueEid");
if (value != null) context.put("valueEid", value);
value = (String) state.getAttribute("valueFirstName");
if (value != null) context.put("valueFirstName", value);
value = (String) state.getAttribute("valueLastName");
if (value != null) context.put("valueLastName", value);
value = (String) state.getAttribute("valueEmail");
if (value != null) context.put("valueEmail", value);
if ((Boolean)state.getAttribute("user.recaptcha-enabled"))
{
ReCaptcha captcha = ReCaptchaFactory.newReCaptcha((String)state.getAttribute("user.recaptcha-public-key"), (String)state.getAttribute("user.recaptcha-private-key"), false);
String captchaScript = captcha.createRecaptchaHtml((String)state.getAttribute("recaptcha-error"), null);
state.removeAttribute("recaptcha-error");
context.put("recaptchaScript", captchaScript);
}
return "_create";
} // buildCreateContext
/**
* Build the context for the new user mode.
*/
private String buildEditContext(SessionState state, Context context)
{
// put the service in the context
context.put("service", UserDirectoryService.getInstance());
// name the html form for user edit fields
context.put("form-name", "user-form");
// get the user to edit
UserEdit user = (UserEdit) state.getAttribute("user");
context.put("user", user);
// is super user/admin user?
context.put("superUser", Boolean.valueOf(SecurityService.isSuperUser()));
// include the password fields?
context.put("incPw", state.getAttribute("include-password"));
// include type fields (not if single user)
boolean singleUser = ((Boolean) state.getAttribute("single-user")).booleanValue();
context.put("incType", Boolean.valueOf(!singleUser));
// build the menu
// we need the form fields for the remove...
boolean menuPopulated = false;
Menu bar = new MenuImpl();
if ((!singleUser) && (UserDirectoryService.allowRemoveUser(user.getId())))
{
bar.add(new MenuEntry(rb.getString("useact.remuse"), null, true, MenuItem.CHECKED_NA, "doRemove", "user-form"));
menuPopulated = true;
}
if (menuPopulated)
{
context.put(Menu.CONTEXT_MENU, bar);
}
String value = (String) state.getAttribute("valueEid");
if (value != null) context.put("valueEid", value);
value = (String) state.getAttribute("valueFirstName");
if (value != null) context.put("valueFirstName", value);
value = (String) state.getAttribute("valueLastName");
if (value != null) context.put("valueLastName", value);
value = (String) state.getAttribute("valueEmail");
if (value != null) context.put("valueEmail", value);
value = (String) state.getAttribute("valueType");
if (value != null) context.put("valueType", value);
return "_edit";
} // buildEditContext
/**
* Build the context for the view user mode.
*/
private String buildViewContext(SessionState state, Context context)
{
if (Log.getLogger("chef").isDebugEnabled())
{
Log.debug("chef", this + ".buildViewContext");
}
// get current user's id
String id = (String) state.getAttribute("user-id");
// get the user and put in state as "user"
try
{
User user = UserDirectoryService.getUser(id);
context.put("user", user);
// name the html form for user edit fields
context.put("form-name", "user-form");
state.setAttribute("mode", "view");
// make sure we can do an edit
try
{
UserEdit edit = UserDirectoryService.editUser(id);
UserDirectoryService.cancelEdit(edit);
context.put("enableEdit", "true");
}
catch (UserNotDefinedException e)
{
}
catch (UserPermissionException e)
{
}
catch (UserLockedException e)
{
}
//SAK-19498
//check if user can change pw (this is used to determine if user should
//view createdBy and modifiedBy info (assuming you can't change pw for provided users)
if(UserDirectoryService.getInstance().allowUpdateUserPassword(id)){
context.put("viewCreatedModifiedBy", "true");
}
// disable auto-updates while not in list mode
disableObservers(state);
}
catch (UserNotDefinedException e)
{
Log.warn("chef", "UsersAction.doEdit: user not found: " + id);
Object[] params = new Object[]{id};
addAlert(state, rb.getFormattedMessage("useact.use_notfou", params));
state.removeAttribute("mode");
// make sure auto-updates are enabled
enableObserver(state);
}
return "_view";
} // buildViewContext
/**
* Build the context for the new user mode.
*/
private String buildConfirmRemoveContext(SessionState state, Context context)
{
// get the user to edit
UserEdit user = (UserEdit) state.getAttribute("user");
context.put("user", user);
return "_confirm_remove";
} // buildConfirmRemoveContext
/**
* doNew called when "eventSubmit_doNew" is in the request parameters to add a new user
*/
public void doNew(RunData data, Context context)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute("mode", "new");
// mark the user as new, so on cancel it can be deleted
state.setAttribute("new", "true");
// disable auto-updates while not in list mode
disableObservers(state);
} // doNew
/**
* doEdit called when "eventSubmit_doEdit" is in the request parameters to edit a user
*/
public void doEdit(RunData data, Context context)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
String id = data.getParameters().getString("id");
state.removeAttribute("user");
state.removeAttribute("newuser");
// get the user
try
{
UserEdit user = UserDirectoryService.editUser(id);
state.setAttribute("user", user);
state.setAttribute("mode", "edit");
// disable auto-updates while not in list mode
disableObservers(state);
}
catch (UserNotDefinedException e)
{
Log.warn("chef", "UsersAction.doEdit: user not found: " + id);
Object[] params = new Object[]{id};
addAlert(state, rb.getFormattedMessage("useact.use_notfou", params));
state.removeAttribute("mode");
// make sure auto-updates are enabled
enableObserver(state);
}
catch (UserPermissionException e)
{
addAlert(state, rb.getFormattedMessage("useact.youdonot1", new Object[]{id}));
state.removeAttribute("mode");
// make sure auto-updates are enabled
enableObserver(state);
}
catch (UserLockedException e)
{
addAlert(state, rb.getFormattedMessage("useact.somels", new Object[]{id}));
state.removeAttribute("mode");
// make sure auto-updates are enabled
enableObserver(state);
}
} // doEdit
/**
* doModify called when "eventSubmit_doModify" is in the request parameters to edit a user
*/
public void doModify(RunData data, Context context)
{
if (Log.getLogger("chef").isDebugEnabled())
{
Log.debug("chef", this + ".doModify");
}
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
String id = data.getParameters().getString("id");
state.removeAttribute("user");
state.removeAttribute("newuser");
// get the user
try
{
UserEdit user = UserDirectoryService.editUser(id);
state.setAttribute("user", user);
state.setAttribute("mode", "edit");
// disable auto-updates while not in list mode
disableObservers(state);
}
catch (UserNotDefinedException e)
{
Log.warn("chef", "UsersAction.doEdit: user not found: " + id);
Object[] params = new Object[]{id};
addAlert(state, rb.getFormattedMessage("useact.use_notfou", params));
state.removeAttribute("mode");
// make sure auto-updates are enabled
enableObserver(state);
}
catch (UserPermissionException e)
{
addAlert(state, rb.getFormattedMessage("useact.youdonot1", new Object[]{id}));
state.removeAttribute("mode");
// make sure auto-updates are enabled
enableObserver(state);
}
catch (UserLockedException e)
{
addAlert(state, rb.getFormattedMessage("useact.somels", new Object[]{id}));
state.removeAttribute("mode");
// make sure auto-updates are enabled
enableObserver(state);
}
} // doModify
/**
* doSave called when "eventSubmit_doSave" is in the request parameters to save user edits
*/
public void doSave(RunData data, Context context)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// read the form - if rejected, leave things as they are
if (!readUserForm(data, state)) return;
// commit the change
UserEdit edit = (UserEdit) state.getAttribute("user");
if (edit != null)
{
try
{
UserDirectoryService.commitEdit(edit);
}
catch (UserAlreadyDefinedException e)
{
// TODO: this means the EID value is not unique... when we implement EID fully, we need to check this and send it back to the user
Log.warn("chef", "UsersAction.doSave()" + e);
addAlert(state, rb.getString("useact.theuseid1"));
return;
}
}
User user = edit;
if (user == null)
{
user = (User) state.getAttribute("newuser");
}
// cleanup
state.removeAttribute("user");
state.removeAttribute("newuser");
state.removeAttribute("new");
state.removeAttribute("valueEid");
state.removeAttribute("valueFirstName");
state.removeAttribute("valueLastName");
state.removeAttribute("valueEmail");
state.removeAttribute("valueType");
// return to main mode
state.removeAttribute("mode");
// make sure auto-updates are enabled
enableObserver(state);
if ((user != null) && ((Boolean) state.getAttribute("create-login")).booleanValue())
{
try
{
// login - use the fact that we just created the account as external evidence
Evidence e = new ExternalTrustedEvidence(user.getEid());
Authentication a = AuthenticationManager.authenticate(e);
if (!UsageSessionService.login(a, (HttpServletRequest) ThreadLocalManager.get(RequestFilter.CURRENT_HTTP_REQUEST)))
{
addAlert(state, rb.getString("useact.tryloginagain"));
}
}
catch (AuthenticationException ex)
{
Log.warn("chef", "UsersAction.doSave: authentication failure: " + ex);
}
// redirect to home (on next build)
state.setAttribute("redirect", "");
}
} // doSave
/**
* doCancel called when "eventSubmit_doCancel" is in the request parameters to cancel user edits
*/
public void doCancel(RunData data, Context context)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// get the user
UserEdit user = (UserEdit) state.getAttribute("user");
if (user != null)
{
// if this was a new, delete the user
if ("true".equals(state.getAttribute("new")))
{
// remove
try
{
UserDirectoryService.removeUser(user);
}
catch (UserPermissionException e)
{
addAlert(state, rb.getFormattedMessage("useact.youdonot2", new Object[]{user.getId()}));
}
}
else
{
UserDirectoryService.cancelEdit(user);
}
}
// cleanup
state.removeAttribute("user");
state.removeAttribute("newuser");
state.removeAttribute("new");
state.removeAttribute("valueEid");
state.removeAttribute("valueFirstName");
state.removeAttribute("valueLastName");
state.removeAttribute("valueEmail");
state.removeAttribute("valueType");
// return to main mode
state.removeAttribute("mode");
// make sure auto-updates are enabled
enableObserver(state);
} // doCancel
/**
* doRemove called when "eventSubmit_doRemove" is in the request par ameters to confirm removal of the user
*/
public void doRemove(RunData data, Context context)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// read the form - if rejected, leave things as they are
if (!readUserForm(data, state)) return;
// go to remove confirm mode
state.setAttribute("mode", "confirm");
} // doRemove
/**
* doRemove_confirmed called when "eventSubmit_doRemove_confirmed" is in the request parameters to remove the user
*/
public void doRemove_confirmed(RunData data, Context context)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// get the user
UserEdit user = (UserEdit) state.getAttribute("user");
// remove
try
{
UserDirectoryService.removeUser(user);
}
catch (UserPermissionException e)
{
addAlert(state, rb.getFormattedMessage("useact.youdonot2", new Object[]{user.getId()}));
}
// cleanup
state.removeAttribute("user");
state.removeAttribute("newuser");
state.removeAttribute("new");
state.removeAttribute("valueEid");
state.removeAttribute("valueFirstName");
state.removeAttribute("valueLastName");
state.removeAttribute("valueEmail");
state.removeAttribute("valueType");
// go to main mode
state.removeAttribute("mode");
// make sure auto-updates are enabled
enableObserver(state);
} // doRemove_confirmed
/**
* doCancel_remove called when "eventSubmit_doCancel_remove" is in the request parameters to cancel user removal
*/
public void doCancel_remove(RunData data, Context context)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// return to edit mode
state.setAttribute("mode", "edit");
} // doCancel_remove
/**
* Read the user form and update the user in state.
*
* @return true if the form is accepted, false if there's a validation error (an alertMessage will be set)
*/
private boolean readUserForm(RunData data, SessionState state)
{
// boolean parameters and values
// --------------Mode--singleUser-createUser-typeEnable
// Admin New-----new---false------false------true
// Admin Update--edit--false------false------true
// Gateway New---null---false------true-------false
// Account Edit--edit--true-------false------false
// read the form
String id = StringUtils.trimToNull(data.getParameters().getString("id"));
String eid = StringUtils.trimToNull(data.getParameters().getString("eid"));
state.setAttribute("valueEid", eid);
String firstName = StringUtils.trimToNull(data.getParameters().getString("first-name"));
state.setAttribute("valueFirstName", firstName);
String lastName = StringUtils.trimToNull(data.getParameters().getString("last-name"));
state.setAttribute("valueLastName", lastName);
String email = StringUtils.trimToNull(data.getParameters().getString("email"));
state.setAttribute("valueEmail", email);
String pw = StringUtils.trimToNull(data.getParameters().getString("pw"));
String pwConfirm = StringUtils.trimToNull(data.getParameters().getString("pw0"));
String pwcur = StringUtils.trimToNull(data.getParameters().getString("pwcur"));
String mode = (String) state.getAttribute("mode");
boolean singleUser = ((Boolean) state.getAttribute("single-user")).booleanValue();
boolean createUser = ((Boolean) state.getAttribute("create-user")).booleanValue();
boolean typeEnable = false;
String type = null;
if ((mode != null) && (mode.equalsIgnoreCase("new")))
{
typeEnable = true;
}
else if ((mode != null) && (mode.equalsIgnoreCase("edit")) && (!singleUser))
{
typeEnable = true;
}
if (typeEnable)
{
// for the case of Admin User tool creating new user
type = StringUtils.trimToNull(data.getParameters().getString("type"));
state.setAttribute("valueType", type);
}
else
{
if (createUser)
{
// for the case of Gateway Account tool creating new user
type = (String) state.getAttribute("create-type");
}
}
if ((Boolean)state.getAttribute("user.recaptcha-enabled"))
{
String challengeField = data.getParameters().getString("recaptcha_challenge_field");
String responseField = data.getParameters().getString("recaptcha_response_field");
if (challengeField == null) challengeField = "";
if (responseField == null) responseField = "";
ReCaptcha captcha = ReCaptchaFactory.newReCaptcha((String)state.getAttribute("user.recaptcha-public-key"), (String)state.getAttribute("user.recaptcha-private-key"), false);
ReCaptchaResponse response = captcha.checkAnswer(data.getRequest().getRemoteAddr(), challengeField, responseField);
if (!response.isValid())
{
addAlert(state, rb.getString("useact.capterr"));
state.setAttribute("recaptcha-error", response.getErrorMessage());
return false;
}
}
//insure valid email address
//email.matches(".+@.+\\..+")
if(email != null && !EmailValidator.getInstance().isValid(email)) {
addAlert(state, rb.getString("useact.invemail"));
return false;
}
// get the user
UserEdit user = (UserEdit) state.getAttribute("user");
// add if needed
if (user == null)
{
// make sure we have eid
if (eid == null)
{
addAlert(state, rb.getString("usecre.eidmis"));
return false;
}
// if in create mode, make sure we have a password
if (createUser)
{
if (pw == null)
{
addAlert(state, rb.getString("usecre.pasismis"));
return false;
}
}
// make sure we have matching password fields
if (StringUtil.different(pw, pwConfirm))
{
addAlert(state, rb.getString("usecre.pass"));
return false;
}
try
{
// add the user in one step so that all you need is add not update permission
// (the added might be "anon", and anon has add but not update permission)
//SAK-18209 only an admin user should be able to specify a ID
if (!SecurityService.isSuperUser()) {
id = null;
}
User newUser = UserDirectoryService.addUser(id, eid, firstName, lastName, email, pw, type, null);
// put the user in the state
state.setAttribute("newuser", newUser);
}
catch (UserAlreadyDefinedException e)
{
addAlert(state, rb.getString("useact.theuseid1"));
return false;
}
catch (UserIdInvalidException e)
{
addAlert(state, rb.getString("useact.theuseid2"));
return false;
}
catch (UserPermissionException e)
{
addAlert(state, rb.getString("useact.youdonot3"));
return false;
}
}
// update
else
{
if (!user.isActiveEdit())
{
try
{
// add the user in one step so that all you need is add not update permission
// (the added might be "anon", and anon has add but not update permission)
user = UserDirectoryService.editUser(user.getId());
// put the user in the state
state.setAttribute("user", user);
}
catch (UserLockedException e)
{
addAlert(state, rb.getString("useact.somels"));
return false;
}
catch (UserNotDefinedException e)
{
Object[] params = new Object[]{id};
addAlert(state, rb.getFormattedMessage("useact.use_notfou", params));
return false;
}
catch (UserPermissionException e)
{
addAlert(state, rb.getString("useact.youdonot3"));
return false;
}
}
// eid, pw, type might not be editable
if (eid != null) user.setEid(eid);
user.setFirstName(firstName);
user.setLastName(lastName);
user.setEmail(email);
if (type != null) user.setType(type);
// make sure the old password matches, but don't check for super users
if (!SecurityService.isSuperUser()) {
if (!user.checkPassword(pwcur)) {
addAlert(state, rb.getString("usecre.curpass"));
return false;
}
}
// make sure we have matching password fields
if (StringUtil.different(pw, pwConfirm))
{
addAlert(state, rb.getString("usecre.pass"));
return false;
}
if (pw != null) user.setPassword(pw);
}
return true;
}
}
| SAK-19730 add form-name variable to the template
git-svn-id: 470921d30149416e94c2486af53d02cfc164742e@94254 66ffb92e-73f9-0310-93c1-f5514f145a0a
| user/user-tool/tool/src/java/org/sakaiproject/user/tool/UsersAction.java | SAK-19730 add form-name variable to the template | <ide><path>ser/user-tool/tool/src/java/org/sakaiproject/user/tool/UsersAction.java
<ide> {
<ide> // put the service in the context
<ide> context.put("service", UserDirectoryService.getInstance());
<add>
<add> // name the html form for user edit fields
<add> context.put("form-name", "user-form");
<ide>
<ide> // include the password fields?
<ide> context.put("incPw", state.getAttribute("include-password")); |
|
Java | mit | e9248ac2b4a14211f4d68602edb4856a5b1d6db7 | 0 | Jacudibu/Bachelor-Thesis | package com.jacudibu.desktop;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.jacudibu.Core;
import com.jacudibu.ubiWrap.DFGParser;
import com.jacudibu.ubiWrap.UbiManager;
public class DesktopLauncher {
private static boolean debugMode = false;
private static boolean useUbitrack = true;
private static String ubiPath = "";
private static String dfgPath = "";
private static String[] arguments;
public static void main (String[] args) {
arguments = args;
searchUbitrackPathVariable();
parseArguments();
ubiPath = "C:\\Ubitrack\\" + ubiPath;
// ubiPath = "C:\\Ubitrack\\bin\\ubitrack"; // How it should look like
if (useUbitrack) {
UbiManager.init(ubiPath);
}
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
config.samples = 3; // Anti Aliasing
new LwjglApplication(new Core(debugMode), config);
if (useUbitrack && dfgPath.length() > 0) {
DFGParser.parse(dfgPath);
}
}
private static void parseArguments() {
int i = 0;
while (i < arguments.length) {
String currentArgument = arguments[i].toLowerCase();
if (currentArgument.startsWith("-")) {
currentArgument = currentArgument.substring(1);
}
i += parseArgument(currentArgument, i);
}
}
private static void searchUbitrackPathVariable() {
ubiPath = System.getenv("UBITRACK_COMPONENTS_PATH");
}
private static int parseArgument(String currentArgument, int index) {
if (currentArgument.equals("help") || currentArgument.equals("teachmesenpai") || currentArgument.equals("?")) {
printHelp();
return 1;
}
if (currentArgument.equals("ubipath")) {
ubiPath = arguments[index + 1];
return 2;
}
if (currentArgument.equals("noubitrack")) {
useUbitrack = false;
return 1;
}
if (currentArgument.equals("loaddfg")) {
dfgPath = arguments[index + 1];
return 2;
}
if (currentArgument.equals("loadsrg")) {
Core.startSRGPath = arguments[index + 1];
return 2;
}
if (currentArgument.equals("debug")) {
debugMode = true;
return 1;
}
if (currentArgument.equals("upupdowndownleftrightleftrightba")){
System.out.println("You are awesome!");
return 1;
}
System.out.println("Unknown Argument: " + currentArgument + "\n" +
"Enter help or ? for an overview of available arguments.");
return 1;
}
private static void printHelp() {
System.out.println("Fear not, young one: senpai noticed you! Available Commands:");
System.out.println("-ubipath PATH \n" +
"\tInitializes Ubitrack tracking. PATH needs to point to your ubitrack installation \n" +
"\tTry this if you system's PATH variable is not found for some reason.");
System.out.println("-noubitrack \n" +
"\tStops Ubitrack from being initialized, even if a path variable is found. \n" +
"\tUse this if your Ubitrack installation doesn't want to work no matter what you try.");
System.out.println("-dfg PATH \n" +
"\tLoad a DFG File at PATH as soon as the app launches.\n" +
"\tThis is basically just a shortcut if you want to skip the in-app filebrowser.");
System.out.println("-load PATH \n " +
"\tLoads the Spatial Relationship Graph at the given destination when the app launches.");
System.out.println("-debug \n" +
"\tDraws some funny colliders and other stuff. I don't know why you'd need that though.");
}
}
| desktop/src/com/jacudibu/desktop/DesktopLauncher.java | package com.jacudibu.desktop;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.jacudibu.Core;
import com.jacudibu.ubiWrap.DFGParser;
import com.jacudibu.ubiWrap.UbiManager;
public class DesktopLauncher {
private static boolean debugMode = false;
private static boolean useUbitrack = true;
private static String ubiPath = "";
private static String dfgPath = "";
private static String[] arguments;
public static void main (String[] args) {
arguments = args;
searchUbitrackPathVariable();
parseArguments();
ubiPath = "C:\\Ubitrack\\" + ubiPath;
// ubiPath = "C:\\Ubitrack\\bin\\ubitrack"; // How it should look like
if (useUbitrack) {
UbiManager.init(ubiPath);
}
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
config.samples = 3; // Anti Aliasing
new LwjglApplication(new Core(debugMode), config);
if (useUbitrack && dfgPath.length() > 0) {
DFGParser.parse(dfgPath);
}
}
private static void parseArguments() {
int i = 0;
while (i < arguments.length) {
String currentArgument = arguments[i].toLowerCase();
if (currentArgument.startsWith("-")) {
currentArgument = currentArgument.substring(1);
}
i += parseArgument(currentArgument, i);
}
}
private static void searchUbitrackPathVariable() {
ubiPath = System.getenv("UBITRACK_COMPONENTS_PATH");
}
private static int parseArgument(String currentArgument, int index) {
if (currentArgument.equals("help") || currentArgument.equals("teachmesenpai") || currentArgument.equals("?")) {
printHelp();
return 1;
}
if (currentArgument.equals("ubipath")) {
ubiPath = arguments[index + 1];
return 2;
}
if (currentArgument.equals("noubitrack")) {
useUbitrack = false;
return 1;
}
if (currentArgument.equals("dfg")) {
dfgPath = arguments[index + 1];
return 2;
}
if (currentArgument.equals("load")) {
Core.startSRGPath = arguments[index + 1];
return 2;
}
if (currentArgument.equals("debug")) {
debugMode = true;
return 1;
}
if (currentArgument.equals("upupdowndownleftrightleftrightba")){
System.out.println("You are awesome!");
return 1;
}
System.out.println("Unknown Argument: " + currentArgument + "\n" +
"Enter help or ? for an overview of available arguments.");
return 1;
}
private static void printHelp() {
System.out.println("Fear not, young one: senpai noticed you! Available Commands:");
System.out.println("-ubipath PATH \n" +
"\tInitializes Ubitrack tracking. PATH needs to point to your ubitrack installation \n" +
"\tTry this if you system's PATH variable is not found for some reason.");
System.out.println("-noubitrack \n" +
"\tStops Ubitrack from being initialized, even if a path variable is found. \n" +
"\tUse this if your Ubitrack installation doesn't want to work no matter what you try.");
System.out.println("-dfg PATH \n" +
"\tLoad a DFG File at PATH as soon as the app launches.\n" +
"\tThis is basically just a shortcut if you want to skip the in-app filebrowser.");
System.out.println("-load PATH \n " +
"\tLoads the Spatial Relationship Graph at the given destination when the app launches.");
System.out.println("-debug \n" +
"\tDraws some funny colliders and other stuff. I don't know why you'd need that though.");
}
}
| Updated Command Line Arguments for loading files
| desktop/src/com/jacudibu/desktop/DesktopLauncher.java | Updated Command Line Arguments for loading files | <ide><path>esktop/src/com/jacudibu/desktop/DesktopLauncher.java
<ide> return 1;
<ide> }
<ide>
<del> if (currentArgument.equals("dfg")) {
<add> if (currentArgument.equals("loaddfg")) {
<ide> dfgPath = arguments[index + 1];
<ide> return 2;
<ide> }
<ide>
<del> if (currentArgument.equals("load")) {
<add> if (currentArgument.equals("loadsrg")) {
<ide> Core.startSRGPath = arguments[index + 1];
<ide> return 2;
<ide> } |
|
Java | apache-2.0 | 092864eaec6e071ad16d9d9888dc8fb7cc1c06f5 | 0 | guusdk/Openfire,speedy01/Openfire,speedy01/Openfire,Gugli/Openfire,Gugli/Openfire,guusdk/Openfire,GregDThomas/Openfire,akrherz/Openfire,GregDThomas/Openfire,GregDThomas/Openfire,igniterealtime/Openfire,akrherz/Openfire,Gugli/Openfire,guusdk/Openfire,akrherz/Openfire,speedy01/Openfire,igniterealtime/Openfire,speedy01/Openfire,igniterealtime/Openfire,guusdk/Openfire,guusdk/Openfire,akrherz/Openfire,GregDThomas/Openfire,speedy01/Openfire,Gugli/Openfire,igniterealtime/Openfire,igniterealtime/Openfire,Gugli/Openfire,GregDThomas/Openfire,akrherz/Openfire | /**
* $Revision: $
* $Date: $
*
* Copyright (C) 2005-2008 Jive Software. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.openfire.http;
import java.io.*;
import java.net.InetAddress;
import java.net.URLDecoder;
import java.security.cert.X509Certificate;
import java.util.Date;
import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringEscapeUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.XMPPPacketReader;
import org.jivesoftware.openfire.auth.UnauthorizedException;
import org.jivesoftware.openfire.net.MXParser;
import org.jivesoftware.util.JiveGlobals;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
/**
* Servlet which handles requests to the HTTP binding service. It determines if there is currently
* an {@link HttpSession} related to the connection or if one needs to be created and then passes it
* off to the {@link HttpBindManager} for processing of the client request and formulating of the
* response.
*
* @author Alexander Wenckus
*/
public class HttpBindServlet extends HttpServlet {
private static final Logger Log = LoggerFactory.getLogger(HttpBindServlet.class);
private HttpSessionManager sessionManager;
private HttpBindManager boshManager;
private static XmlPullParserFactory factory;
static {
try {
factory = XmlPullParserFactory.newInstance(MXParser.class.getName(), null);
}
catch (XmlPullParserException e) {
Log.error("Error creating a parser factory", e);
}
}
private ThreadLocal<XMPPPacketReader> localReader = new ThreadLocal<XMPPPacketReader>();
public HttpBindServlet() {
}
@Override
public void init(ServletConfig servletConfig) throws ServletException {
super.init(servletConfig);
boshManager = HttpBindManager.getInstance();
sessionManager = boshManager.getSessionManager();
sessionManager.start();
}
@Override
public void destroy() {
super.destroy();
sessionManager.stop();
}
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// add CORS headers for all HTTP responses (errors, etc.)
if (boshManager.isCORSEnabled())
{
if (boshManager.isAllOriginsAllowed()) {
// Set the Access-Control-Allow-Origin header to * to allow all Origin to do the CORS
response.setHeader("Access-Control-Allow-Origin", HttpBindManager.HTTP_BIND_CORS_ALLOW_ORIGIN_DEFAULT);
} else {
// Get the Origin header from the request and check if it is in the allowed Origin Map.
// If it is allowed write it back to the Access-Control-Allow-Origin header of the respond.
final String origin = request.getHeader("Origin");
if (boshManager.isThisOriginAllowed(origin)) {
response.setHeader("Access-Control-Allow-Origin", origin);
}
}
response.setHeader("Access-Control-Allow-Methods", HttpBindManager.HTTP_BIND_CORS_ALLOW_METHODS_DEFAULT);
response.setHeader("Access-Control-Allow-Headers", HttpBindManager.HTTP_BIND_CORS_ALLOW_HEADERS_DEFAULT);
response.setHeader("Access-Control-Max-Age", HttpBindManager.HTTP_BIND_CORS_MAX_AGE_DEFAULT);
}
super.service(request, response);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
final AsyncContext context = request.startAsync();
boolean isScriptSyntaxEnabled = boshManager.isScriptSyntaxEnabled();
if(!isScriptSyntaxEnabled) {
sendLegacyError(context, BoshBindingError.itemNotFound);
return;
}
String queryString = request.getQueryString();
if (queryString == null || "".equals(queryString)) {
sendLegacyError(context, BoshBindingError.badRequest);
return;
} else if ("isBoshAvailable".equals(queryString)) {
response.setStatus(HttpServletResponse.SC_OK);
context.complete();
return;
}
queryString = URLDecoder.decode(queryString, "UTF-8");
processContent(context, queryString);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
final AsyncContext context = request.startAsync();
// Asynchronously reads the POSTed input, then triggers #processContent.
request.getInputStream().setReadListener(new ReadListenerImpl(context));
}
protected void processContent(AsyncContext context, String content)
throws IOException {
final String remoteAddress = getRemoteAddress(context);
// Parse document from the content.
Document document;
try {
document = getPacketReader().read(new StringReader(content), "UTF-8");
} catch (Exception ex) {
Log.warn("Error parsing request data from [" + remoteAddress + "]", ex);
sendLegacyError(context, BoshBindingError.badRequest);
return;
}
if (document == null) {
Log.info("The result of parsing request data from [" + remoteAddress + "] was a null-object.");
sendLegacyError(context, BoshBindingError.badRequest);
return;
}
final Element node = document.getRootElement();
if (node == null || !"body".equals(node.getName())) {
Log.info("Root element 'body' is missing from parsed request data from [" + remoteAddress + "]");
sendLegacyError(context, BoshBindingError.badRequest);
return;
}
final long rid = getLongAttribute(node.attributeValue("rid"), -1);
if (rid <= 0) {
Log.info("Root element 'body' does not contain a valid RID attribute value in parsed request data from [" + remoteAddress + "]");
sendLegacyError(context, BoshBindingError.badRequest, "Body-element is missing a RID (Request ID) value, or the provided value is a non-positive integer.");
return;
}
// Process the parsed document.
final String sid = node.attributeValue("sid");
if (sid == null) {
// When there's no Session ID, this should be a request to create a new session. If there's additional content,
// something is wrong.
if (node.elements().size() > 0) {
// invalid session request; missing sid
Log.info("Root element 'body' does not contain a SID attribute value in parsed request data from [" + remoteAddress + "]");
sendLegacyError(context, BoshBindingError.badRequest);
return;
}
// We have a new session
createNewSession(context, node);
}
else {
// When there exists a Session ID, new data for an existing session is being provided.
handleSessionRequest(sid, context, node);
}
}
protected void createNewSession(AsyncContext context, Element rootNode)
throws IOException
{
final long rid = getLongAttribute(rootNode.attributeValue("rid"), -1);
try {
final X509Certificate[] certificates = (X509Certificate[]) context.getRequest().getAttribute("javax.servlet.request.X509Certificate");
final HttpConnection connection = new HttpConnection(rid, context.getRequest().isSecure(), certificates, context);
final InetAddress address = InetAddress.getByName(context.getRequest().getRemoteAddr());
connection.setSession(sessionManager.createSession(address, rootNode, connection));
if (JiveGlobals.getBooleanProperty("log.httpbind.enabled", false)) {
Log.info(new Date() + ": HTTP RECV(" + connection.getSession().getStreamID().getID() + "): " + rootNode.asXML());
}
}
catch (UnauthorizedException e) {
// Server wasn't initialized yet.
sendLegacyError(context, BoshBindingError.internalServerError, "Server has not finished initialization." );
}
catch (HttpBindException e) {
sendLegacyError(context, BoshBindingError.internalServerError, "Server has not finished initialization." );
}
}
private void handleSessionRequest(String sid, AsyncContext context, Element rootNode)
throws IOException
{
if (JiveGlobals.getBooleanProperty("log.httpbind.enabled", false)) {
Log.info(new Date() + ": HTTP RECV(" + sid + "): " + rootNode.asXML());
}
HttpSession session = sessionManager.getSession(sid);
if (session == null) {
if (Log.isDebugEnabled()) {
Log.debug("Client provided invalid session: " + sid + ". [" +
context.getRequest().getRemoteAddr() + "]");
}
sendLegacyError(context, BoshBindingError.itemNotFound, "Invalid SID value.");
return;
}
final long rid = getLongAttribute(rootNode.attributeValue("rid"), -1);
synchronized (session) {
try {
session.forwardRequest(rid, context.getRequest().isSecure(), rootNode, context);
}
catch (HttpBindException e) {
sendError(session, context, e.getBindingError());
}
catch (HttpConnectionClosedException nc) {
Log.error("Error sending packet to client.", nc);
context.complete();
}
}
}
private XMPPPacketReader getPacketReader()
{
// Reader is associated with a new XMPPPacketReader
XMPPPacketReader reader = localReader.get();
if (reader == null) {
reader = new XMPPPacketReader();
reader.setXPPFactory(factory);
localReader.set(reader);
}
return reader;
}
public static void respond(HttpSession session, AsyncContext context, String content, boolean async) throws IOException
{
final HttpServletResponse response = ((HttpServletResponse) context.getResponse());
final HttpServletRequest request = ((HttpServletRequest) context.getRequest());
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("GET".equals(request.getMethod()) ? "text/javascript" : "text/xml");
response.setCharacterEncoding("UTF-8");
if ("GET".equals(request.getMethod())) {
if (JiveGlobals.getBooleanProperty("xmpp.httpbind.client.no-cache.enabled", true)) {
// Prevent caching of responses
response.addHeader("Cache-Control", "no-store");
response.addHeader("Cache-Control", "no-cache");
response.addHeader("Pragma", "no-cache");
}
content = "_BOSH_(\"" + StringEscapeUtils.escapeJavaScript(content) + "\")";
}
if (JiveGlobals.getBooleanProperty("log.httpbind.enabled", false)) {
System.out.println(new Date() + ": HTTP SENT(" + session.getStreamID().getID() + "): " + content);
}
final byte[] byteContent = content.getBytes("UTF-8");
if (async) {
response.getOutputStream().setWriteListener(new WriteListenerImpl(context, byteContent));
} else {
context.getResponse().getOutputStream().write(byteContent);
context.getResponse().getOutputStream().flush();
context.complete();
}
}
private void sendError(HttpSession session, AsyncContext context, BoshBindingError bindingError)
throws IOException
{
if (JiveGlobals.getBooleanProperty("log.httpbind.enabled", false)) {
System.out.println(new Date() + ": HTTP ERR(" + session.getStreamID().getID() + "): " + bindingError.getErrorType().getType() + ", " + bindingError.getCondition() + ".");
}
try {
if ((session.getMajorVersion() == 1 && session.getMinorVersion() >= 6) || session.getMajorVersion() > 1)
{
final String errorBody = createErrorBody(bindingError.getErrorType().getType(), bindingError.getCondition());
respond(session, context, errorBody, true);
} else {
sendLegacyError(context, bindingError);
}
}
finally {
if (bindingError.getErrorType() == BoshBindingError.Type.terminate) {
session.close();
}
}
}
protected static void sendLegacyError(AsyncContext context, BoshBindingError error, String message)
throws IOException
{
final HttpServletResponse response = (HttpServletResponse) context.getResponse();
if (message == null || message.trim().length() == 0) {
response.sendError(error.getLegacyErrorCode());
} else {
response.sendError(error.getLegacyErrorCode(), message);
}
context.complete();
}
protected static void sendLegacyError(AsyncContext context, BoshBindingError error)
throws IOException
{
sendLegacyError(context, error, null);
}
protected static String createEmptyBody(boolean terminate)
{
final Element body = DocumentHelper.createElement("body");
if (terminate) { body.addAttribute("type", "terminate"); }
body.addNamespace("", "http://jabber.org/protocol/httpbind");
return body.asXML();
}
protected static String createErrorBody(String type, String condition) {
final Element body = DocumentHelper.createElement("body");
body.addNamespace("", "http://jabber.org/protocol/httpbind");
body.addAttribute("type", type);
body.addAttribute("condition", condition);
return body.asXML();
}
protected static long getLongAttribute(String value, long defaultValue) {
if (value == null || "".equals(value)) {
return defaultValue;
}
try {
return Long.valueOf(value);
}
catch (Exception ex) {
return defaultValue;
}
}
protected static int getIntAttribute(String value, int defaultValue) {
if (value == null || "".equals(value)) {
return defaultValue;
}
try {
return Integer.valueOf(value);
}
catch (Exception ex) {
return defaultValue;
}
}
protected static String getRemoteAddress(AsyncContext context)
{
String remoteAddress = null;
if (context.getRequest() != null && context.getRequest().getRemoteAddr() != null) {
remoteAddress = context.getRequest().getRemoteAddr();
}
if (remoteAddress == null || remoteAddress.trim().length() == 0) {
remoteAddress = "<UNKNOWN ADDRESS>";
}
return remoteAddress;
}
class ReadListenerImpl implements ReadListener {
private final AsyncContext context;
private final StringBuilder buffer = new StringBuilder(512);
private final String remoteAddress;
ReadListenerImpl(AsyncContext context) {
this.context = context;
this.remoteAddress = getRemoteAddress(context);
}
@Override
public void onDataAvailable() throws IOException {
Log.trace("Data is available to be read from [" + remoteAddress + "]");
final ServletInputStream inputStream = context.getRequest().getInputStream();
byte b[] = new byte[1024];
int length;
while (inputStream.isReady() && (length = inputStream.read(b)) != -1) {
buffer.append(new String(b, 0, length));
}
}
@Override
public void onAllDataRead() throws IOException {
Log.trace("All data has been read from [" + remoteAddress + "]");
processContent(context, buffer.toString());
}
@Override
public void onError(Throwable throwable) {
Log.warn("Error reading request data from [" + remoteAddress + "]", throwable);
try {
sendLegacyError(context, BoshBindingError.badRequest);
} catch (IOException ex) {
Log.debug("Error while sending an error to ["+remoteAddress +"] in response to an earlier data-read failure.", ex);
}
}
}
static class WriteListenerImpl implements WriteListener {
private final AsyncContext context;
private final byte[] data;
private final String remoteAddress;
public WriteListenerImpl(AsyncContext context, byte[] data) {
this.context = context;
this.data = data;
this.remoteAddress = getRemoteAddress(context);
}
@Override
public void onWritePossible() throws IOException {
Log.trace("Data can be written to [" + remoteAddress + "]");
context.getResponse().getOutputStream().write(data);
context.complete();
}
@Override
public void onError(Throwable throwable) {
Log.warn("Error writing response data to [" + remoteAddress + "]", throwable);
context.complete();
}
}
}
| src/java/org/jivesoftware/openfire/http/HttpBindServlet.java | /**
* $Revision: $
* $Date: $
*
* Copyright (C) 2005-2008 Jive Software. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.openfire.http;
import java.io.*;
import java.net.InetAddress;
import java.net.URLDecoder;
import java.security.cert.X509Certificate;
import java.util.Date;
import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringEscapeUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.XMPPPacketReader;
import org.jivesoftware.openfire.auth.UnauthorizedException;
import org.jivesoftware.openfire.net.MXParser;
import org.jivesoftware.util.JiveGlobals;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
/**
* Servlet which handles requests to the HTTP binding service. It determines if there is currently
* an {@link HttpSession} related to the connection or if one needs to be created and then passes it
* off to the {@link HttpBindManager} for processing of the client request and formulating of the
* response.
*
* @author Alexander Wenckus
*/
public class HttpBindServlet extends HttpServlet {
private static final Logger Log = LoggerFactory.getLogger(HttpBindServlet.class);
private HttpSessionManager sessionManager;
private HttpBindManager boshManager;
private static XmlPullParserFactory factory;
static {
try {
factory = XmlPullParserFactory.newInstance(MXParser.class.getName(), null);
}
catch (XmlPullParserException e) {
Log.error("Error creating a parser factory", e);
}
}
private ThreadLocal<XMPPPacketReader> localReader = new ThreadLocal<XMPPPacketReader>();
public HttpBindServlet() {
}
@Override
public void init(ServletConfig servletConfig) throws ServletException {
super.init(servletConfig);
boshManager = HttpBindManager.getInstance();
sessionManager = boshManager.getSessionManager();
sessionManager.start();
}
@Override
public void destroy() {
super.destroy();
sessionManager.stop();
}
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// add CORS headers for all HTTP responses (errors, etc.)
if (boshManager.isCORSEnabled())
{
if (boshManager.isAllOriginsAllowed()) {
// Set the Access-Control-Allow-Origin header to * to allow all Origin to do the CORS
response.setHeader("Access-Control-Allow-Origin", HttpBindManager.HTTP_BIND_CORS_ALLOW_ORIGIN_DEFAULT);
} else {
// Get the Origin header from the request and check if it is in the allowed Origin Map.
// If it is allowed write it back to the Access-Control-Allow-Origin header of the respond.
final String origin = request.getHeader("Origin");
if (boshManager.isThisOriginAllowed(origin)) {
response.setHeader("Access-Control-Allow-Origin", origin);
}
}
response.setHeader("Access-Control-Allow-Methods", HttpBindManager.HTTP_BIND_CORS_ALLOW_METHODS_DEFAULT);
response.setHeader("Access-Control-Allow-Headers", HttpBindManager.HTTP_BIND_CORS_ALLOW_HEADERS_DEFAULT);
response.setHeader("Access-Control-Max-Age", HttpBindManager.HTTP_BIND_CORS_MAX_AGE_DEFAULT);
}
super.service(request, response);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
final AsyncContext context = request.startAsync();
boolean isScriptSyntaxEnabled = boshManager.isScriptSyntaxEnabled();
if(!isScriptSyntaxEnabled) {
sendLegacyError(context, BoshBindingError.itemNotFound);
return;
}
String queryString = request.getQueryString();
if (queryString == null || "".equals(queryString)) {
sendLegacyError(context, BoshBindingError.badRequest);
return;
} else if ("isBoshAvailable".equals(queryString)) {
response.setStatus(HttpServletResponse.SC_OK);
context.complete();
return;
}
queryString = URLDecoder.decode(queryString, "UTF-8");
processContent(context, queryString);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
final AsyncContext context = request.startAsync();
// Asynchronously reads the POSTed input, then triggers #processContent.
request.getInputStream().setReadListener(new ReadListenerImpl(context));
}
protected void processContent(AsyncContext context, String content)
throws IOException {
final String remoteAddress = getRemoteAddress(context);
// Parse document from the content.
Document document;
try {
document = getPacketReader().read(new StringReader(content), "UTF-8");
} catch (Exception ex) {
Log.warn("Error parsing request data from [" + remoteAddress + "]", ex);
sendLegacyError(context, BoshBindingError.badRequest);
return;
}
if (document == null) {
Log.info("The result of parsing request data from [" + remoteAddress + "] was a null-object.");
sendLegacyError(context, BoshBindingError.badRequest);
return;
}
final Element node = document.getRootElement();
if (node == null || !"body".equals(node.getName())) {
Log.info("Root element 'body' is missing from parsed request data from [" + remoteAddress + "]");
sendLegacyError(context, BoshBindingError.badRequest);
return;
}
final long rid = getLongAttribute(node.attributeValue("rid"), -1);
if (rid <= 0) {
Log.info("Root element 'body' does not contain a valid RID attribute value in parsed request data from [" + remoteAddress + "]");
sendLegacyError(context, BoshBindingError.badRequest, "Body-element is missing a RID (Request ID) value, or the provided value is a non-positive integer.");
return;
}
// Process the parsed document.
final String sid = node.attributeValue("sid");
if (sid == null) {
// When there's no Session ID, this should be a request to create a new session. If there's additional content,
// something is wrong.
if (node.elements().size() > 0) {
// invalid session request; missing sid
Log.info("Root element 'body' does not contain a SID attribute value in parsed request data from [" + remoteAddress + "]");
sendLegacyError(context, BoshBindingError.badRequest);
return;
}
// We have a new session
createNewSession(context, node);
}
else {
// When there exists a Session ID, new data for an existing session is being provided.
handleSessionRequest(sid, context, node);
}
}
protected void createNewSession(AsyncContext context, Element rootNode)
throws IOException
{
final long rid = getLongAttribute(rootNode.attributeValue("rid"), -1);
try {
final X509Certificate[] certificates = (X509Certificate[]) context.getRequest().getAttribute("javax.servlet.request.X509Certificate");
final HttpConnection connection = new HttpConnection(rid, context.getRequest().isSecure(), certificates, context);
final InetAddress address = InetAddress.getByName(context.getRequest().getRemoteAddr());
connection.setSession(sessionManager.createSession(address, rootNode, connection));
if (JiveGlobals.getBooleanProperty("log.httpbind.enabled", false)) {
Log.info(new Date() + ": HTTP RECV(" + connection.getSession().getStreamID().getID() + "): " + rootNode.asXML());
}
}
catch (UnauthorizedException e) {
// Server wasn't initialized yet.
sendLegacyError(context, BoshBindingError.internalServerError, "Server has not finished initialization." );
}
catch (HttpBindException e) {
sendLegacyError(context, BoshBindingError.internalServerError, "Server has not finished initialization." );
}
}
private void handleSessionRequest(String sid, AsyncContext context, Element rootNode)
throws IOException
{
if (JiveGlobals.getBooleanProperty("log.httpbind.enabled", false)) {
Log.info(new Date() + ": HTTP RECV(" + sid + "): " + rootNode.asXML());
}
HttpSession session = sessionManager.getSession(sid);
if (session == null) {
if (Log.isDebugEnabled()) {
Log.debug("Client provided invalid session: " + sid + ". [" +
context.getRequest().getRemoteAddr() + "]");
}
sendLegacyError(context, BoshBindingError.itemNotFound, "Invalid SID value.");
return;
}
final long rid = getLongAttribute(rootNode.attributeValue("rid"), -1);
synchronized (session) {
try {
session.forwardRequest(rid, context.getRequest().isSecure(), rootNode, context);
}
catch (HttpBindException e) {
sendError(session, context, e.getBindingError());
}
catch (HttpConnectionClosedException nc) {
Log.error("Error sending packet to client.", nc);
context.complete();
}
}
}
private XMPPPacketReader getPacketReader()
{
// Reader is associated with a new XMPPPacketReader
XMPPPacketReader reader = localReader.get();
if (reader == null) {
reader = new XMPPPacketReader();
reader.setXPPFactory(factory);
localReader.set(reader);
}
return reader;
}
public static void respond(HttpSession session, AsyncContext context, String content, boolean async) throws IOException
{
final HttpServletResponse response = ((HttpServletResponse) context.getResponse());
final HttpServletRequest request = ((HttpServletRequest) context.getRequest());
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("GET".equals(request.getMethod()) ? "text/javascript" : "text/xml");
response.setCharacterEncoding("UTF-8");
if ("GET".equals(request.getMethod())) {
if (JiveGlobals.getBooleanProperty("xmpp.httpbind.client.no-cache.enabled", true)) {
// Prevent caching of responses
response.addHeader("Cache-Control", "no-store");
response.addHeader("Cache-Control", "no-cache");
response.addHeader("Pragma", "no-cache");
}
content = "_BOSH_(\"" + StringEscapeUtils.escapeJavaScript(content) + "\")";
}
if (JiveGlobals.getBooleanProperty("log.httpbind.enabled", false)) {
System.out.println(new Date() + ": HTTP SENT(" + session.getStreamID().getID() + "): " + content);
}
final byte[] byteContent = content.getBytes("UTF-8");
if (async) {
response.getOutputStream().setWriteListener(new WriteListenerImpl(context, byteContent));
} else {
context.getResponse().getOutputStream().write(byteContent);
context.getResponse().getOutputStream().flush();
context.complete();
}
}
private void sendError(HttpSession session, AsyncContext context, BoshBindingError bindingError)
throws IOException
{
if (JiveGlobals.getBooleanProperty("log.httpbind.enabled", false)) {
System.out.println(new Date() + ": HTTP ERR(" + session.getStreamID().getID() + "): " + bindingError.getErrorType().getType() + ", " + bindingError.getCondition() + ".");
}
try {
if ((session.getMajorVersion() == 1 && session.getMinorVersion() >= 6) || session.getMajorVersion() > 1)
{
final String errorBody = createErrorBody(bindingError.getErrorType().getType(), bindingError.getCondition());
respond(session, context, errorBody, true);
} else {
sendLegacyError(context, bindingError);
}
}
finally {
if (bindingError.getErrorType() == BoshBindingError.Type.terminate) {
session.close();
}
}
}
protected static void sendLegacyError(AsyncContext context, BoshBindingError error, String message)
throws IOException
{
final HttpServletResponse response = (HttpServletResponse) context.getResponse();
if (message == null || message.trim().length() == 0) {
response.sendError(error.getLegacyErrorCode());
} else {
response.sendError(error.getLegacyErrorCode(), message);
}
context.complete();
}
protected static void sendLegacyError(AsyncContext context, BoshBindingError error)
throws IOException
{
sendLegacyError(context, error, null);
}
protected static String createEmptyBody(boolean terminate)
{
final Element body = DocumentHelper.createElement("body");
if (terminate) { body.addAttribute("type", "terminate"); }
body.addNamespace("", "http://jabber.org/protocol/httpbind");
return body.asXML();
}
protected static String createErrorBody(String type, String condition) {
final Element body = DocumentHelper.createElement("body");
body.addNamespace("", "http://jabber.org/protocol/httpbind");
body.addAttribute("type", type);
body.addAttribute("condition", condition);
return body.asXML();
}
protected static long getLongAttribute(String value, long defaultValue) {
if (value == null || "".equals(value)) {
return defaultValue;
}
try {
return Long.valueOf(value);
}
catch (Exception ex) {
return defaultValue;
}
}
protected static int getIntAttribute(String value, int defaultValue) {
if (value == null || "".equals(value)) {
return defaultValue;
}
try {
return Integer.valueOf(value);
}
catch (Exception ex) {
return defaultValue;
}
}
protected static String getRemoteAddress(AsyncContext context)
{
String remoteAddress = null;
if (context.getRequest() != null && context.getRequest().getRemoteAddr() != null) {
remoteAddress = context.getRequest().getRemoteAddr();
}
if (remoteAddress == null || remoteAddress.trim().length() == 0) {
remoteAddress = "<UNKNOWN ADDRESS>";
}
return remoteAddress;
}
class ReadListenerImpl implements ReadListener {
private final AsyncContext context;
private final StringBuilder buffer = new StringBuilder(512);
private final String remoteAddress;
ReadListenerImpl(AsyncContext context) {
this.context = context;
this.remoteAddress = getRemoteAddress(context);
}
@Override
public void onDataAvailable() throws IOException {
Log.trace("Data is available to be read from [" + remoteAddress + "]");
final ServletInputStream inputStream = context.getRequest().getInputStream();
byte b[] = new byte[1024];
int length;
while (inputStream.isReady() && (length = inputStream.read(b)) != -1) {
buffer.append(new String(b, 0, length));
}
}
@Override
public void onAllDataRead() throws IOException {
Log.trace("All data has been read from [" + remoteAddress + "]");
processContent(context, buffer.toString());
}
@Override
public void onError(Throwable throwable) {
Log.warn("Error reading request data from [" + remoteAddress + "]", throwable);
try {
sendLegacyError(context, BoshBindingError.badRequest);
} catch (IOException ex) {
Log.debug("Error while sending an error to ["+remoteAddress +"] in response to an earlier data-read failure.", ex);
}
}
}
static class WriteListenerImpl implements WriteListener {
private final AsyncContext context;
private final byte[] data;
private final String remoteAddress;
public WriteListenerImpl(AsyncContext context, byte[] data) {
this.context = context;
this.data = data;
this.remoteAddress = getRemoteAddress(context);
}
@Override
public void onWritePossible() throws IOException {
Log.trace("Data can be written to [" + remoteAddress + "]");
context.getResponse().setContentLength(data.length);
context.getResponse().getOutputStream().write(data);
context.complete();
}
@Override
public void onError(Throwable throwable) {
Log.warn("Error writing response data to [" + remoteAddress + "]", throwable);
context.complete();
}
}
}
| OF-885: Undoing force of content-length to prevent chunked encoding.
| src/java/org/jivesoftware/openfire/http/HttpBindServlet.java | OF-885: Undoing force of content-length to prevent chunked encoding. | <ide><path>rc/java/org/jivesoftware/openfire/http/HttpBindServlet.java
<ide> @Override
<ide> public void onWritePossible() throws IOException {
<ide> Log.trace("Data can be written to [" + remoteAddress + "]");
<del> context.getResponse().setContentLength(data.length);
<ide> context.getResponse().getOutputStream().write(data);
<ide> context.complete();
<ide> } |
|
Java | apache-2.0 | e477c3715b9e572e31f67a04079ad9839275022b | 0 | dita-ot/dita-ot,infotexture/dita-ot,drmacro/dita-ot,dita-ot/dita-ot,drmacro/dita-ot,dita-ot/dita-ot,infotexture/dita-ot,drmacro/dita-ot,infotexture/dita-ot,shaneataylor/dita-ot,infotexture/dita-ot,shaneataylor/dita-ot,drmacro/dita-ot,shaneataylor/dita-ot,dita-ot/dita-ot,dita-ot/dita-ot,shaneataylor/dita-ot,drmacro/dita-ot,shaneataylor/dita-ot,infotexture/dita-ot | /*
* This file is part of the DITA Open Toolkit project.
*
* Copyright 2004, 2005 IBM Corporation
*
* See the accompanying LICENSE file for applicable license.
*/
package org.dita.dost.reader;
import static org.dita.dost.util.Configuration.*;
import static org.dita.dost.util.Constants.*;
import static org.dita.dost.util.URLUtils.*;
import static org.dita.dost.reader.ChunkMapReader.*;
import java.net.URI;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import org.dita.dost.exception.DITAOTException;
import org.dita.dost.log.MessageBean;
import org.dita.dost.log.MessageUtils;
import org.dita.dost.util.DitaClass;
import org.dita.dost.util.Job;
import org.dita.dost.writer.AbstractXMLFilter;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
/**
* Parse relevant DITA files and collect information.
*
* <p>
* <strong>Not thread-safe</strong>. Instances can be reused by calling
* {@link #reset()} between calls to parse.
* </p>
*/
public final class GenListModuleReader extends AbstractXMLFilter {
public static final URI ROOT_URI = toURI("ROOT");
/** Output utilities */
private Job job;
/** Absolute basedir of the current parsing file */
private URI currentDir = null;
/** Flag for conref in parsing file */
private boolean hasConRef = false;
/** Flag for href in parsing file */
private boolean hasHref = false;
/** Flag for keyref in parsing file */
private boolean hasKeyRef = false;
/** Flag for whether parsing file contains coderef */
private boolean hasCodeRef = false;
/** Set of all the non-conref and non-copyto targets refered in current parsing file */
private final Set<Reference> nonConrefCopytoTargets = new LinkedHashSet<>(64);
/** Set of conref targets refered in current parsing file */
private final Set<URI> conrefTargets = new HashSet<>(32);
/** Set of href nonConrefCopytoTargets refered in current parsing file */
private final Set<URI> hrefTargets = new HashSet<>(32);
/** Set of subject schema files */
private final Set<URI> schemeSet = new HashSet<>(32);
/** Set of coderef or object target files */
private final Set<URI> coderefTargetSet = new HashSet<>(16);
/** Set of sources of those copy-to that were ignored */
private final Set<URI> ignoredCopytoSourceSet = new HashSet<>(16);
/** Map of copy-to target to souce */
private final Map<URI, URI> copytoMap = new HashMap<>(16);
/** Flag for conrefpush */
private boolean hasconaction = false;
/** foreign/unknown nesting level */
private int foreignLevel = 0;
/** Flag used to mark if current file is still valid after filtering */
private boolean isValidInput = false;
/** Set of outer dita files */
private final Set<URI> outDitaFilesSet = new HashSet<>(64);
/** Absolute system path to input file parent directory */
private URI rootDir = null;
/** Stack for @processing-role value */
private final Stack<String> processRoleStack = new Stack<>();
/** Topics with processing role of "resource-only" */
private final Set<URI> resourceOnlySet = new HashSet<>(32);
/** Topics with processing role of "normal" */
private final Set<URI> normalProcessingRoleSet = new HashSet<>(32);
/** Subject scheme relative file paths. */
private final Set<URI> schemeRefSet = new HashSet<>(32);
/** Relationship graph between subject schema. Keys are subject scheme map paths and values
* are subject scheme map paths, both relative to base directory. A key {@link #ROOT_URI} contains all subject scheme maps. */
private final Map<URI, Set<URI>> schemeRelationGraph = new LinkedHashMap<>();
/** Store the primary ditamap file name. */
private URI primaryDitamap;
private boolean isRootElement = true;
private DitaClass rootClass = null;
/**
* Set output utilities.
*
* @param job output utils
*/
public void setJob(final Job job) {
this.job = job;
}
/**
* Get out file set.
*
* @return out file set
*/
public Set<URI> getOutFilesSet() {
return outDitaFilesSet;
}
/**
* Get scheme set.
*
* @return scheme set
*/
public Set<URI> getSchemeSet() {
return schemeSet;
}
/**
* Get scheme ref set.
*
* @return scheme ref set
*/
public Set<URI> getSchemeRefSet() {
return schemeRefSet;
}
/**
* List of files with "@processing-role=resource-only".
*
* @return the resource-only set
*/
public Set<URI> getResourceOnlySet() {
final Set<URI> res = new HashSet<>(resourceOnlySet);
res.removeAll(normalProcessingRoleSet);
return res;
}
/**
* Is the processed file a DITA topic.
*
* @return {@code true} if DITA topic, otherwise {@code false}
*/
public boolean isDitaTopic() {
if (isRootElement) {
throw new IllegalStateException();
}
return rootClass == null || TOPIC_TOPIC.matches(rootClass);
}
/**
* Is the currently processed file a DITA map.
*
* @return {@code true} if DITA map, otherwise {@code false}
*/
public boolean isDitaMap() {
if (isRootElement) {
throw new IllegalStateException();
}
return rootClass != null && MAP_MAP.matches(rootClass);
}
/**
* Get relationship graph between subject schema. Keys are subject scheme map paths and values
* are subject scheme map paths, both relative to base directory. A key {@link #ROOT_URI} contains all subject scheme maps.
*
* @return relationship graph
*/
public Map<URI, Set<URI>> getRelationshipGrap() {
return schemeRelationGraph;
}
public void setPrimaryDitamap(final URI primaryDitamap) {
assert primaryDitamap.isAbsolute();
this.primaryDitamap = primaryDitamap;
this.rootDir = primaryDitamap.resolve(".");
}
/**
* To see if the parsed file has conref inside.
*
* @return true if has conref and false otherwise
*/
public boolean hasConRef() {
return hasConRef;
}
/**
* To see if the parsed file has keyref inside.
*
* @return true if has keyref and false otherwise
*/
public boolean hasKeyRef() {
return hasKeyRef;
}
/**
* To see if the parsed file has coderef inside.
*
* @return true if has coderef and false otherwise
*/
public boolean hasCodeRef() {
return hasCodeRef;
}
/**
* To see if the parsed file has href inside.
*
* @return true if has href and false otherwise
*/
public boolean hasHref() {
return hasHref;
}
/**
* Get all targets except copy-to.
*
* @return set of target file path with option format after
* {@link org.dita.dost.util.Constants#STICK STICK}
*/
public Set<Reference> getNonCopytoResult() {
final Set<Reference> nonCopytoSet = new LinkedHashSet<>(128);
nonCopytoSet.addAll(nonConrefCopytoTargets);
for (final URI f : conrefTargets) {
nonCopytoSet.add(new Reference(stripFragment(f)));
}
for (final URI f : copytoMap.values()) {
nonCopytoSet.add(new Reference(stripFragment(f)));
}
for (final URI f : ignoredCopytoSourceSet) {
nonCopytoSet.add(new Reference(stripFragment(f)));
}
for (final URI filename : coderefTargetSet) {
nonCopytoSet.add(new Reference(stripFragment(filename)));
}
return nonCopytoSet;
}
/**
* Get copy-to map.
*
* @return map of copy-to target to souce
*/
public Map<URI, URI> getCopytoMap() {
return copytoMap;
}
/**
* Get the href target.
*
* @return Returns the hrefTargets.
*/
public Set<URI> getHrefTargets() {
return hrefTargets;
}
/**
* Get conref targets.
*
* @return Returns the conrefTargets.
*/
public Set<URI> getConrefTargets() {
return conrefTargets;
}
/**
* Get coderef targets.
*
* @return Returns coderef targets.
*/
public Set<URI> getCoderefTargets() {
return coderefTargetSet;
}
/**
* Get outditafileslist.
*
* @return Returns the outditafileslist.
*/
public Set<URI> getOutDitaFilesSet() {
return outDitaFilesSet;
}
/**
* Get non-conref and non-copyto targets.
*
* @return Returns the nonConrefCopytoTargets.
*/
public Set<URI> getNonConrefCopytoTargets() {
final Set<URI> res = new HashSet<>(nonConrefCopytoTargets.size());
for (final Reference r : nonConrefCopytoTargets) {
res.add(r.filename);
}
return res;
}
/**
* Set current file absolute path
*
* @param currentFile absolute path to current file
*/
public void setCurrentFile(final URI currentFile) {
assert currentFile.isAbsolute();
super.setCurrentFile(currentFile);
currentDir = currentFile.resolve(".");
}
/**
* Check if the current file is valid after filtering.
*
* @return true if valid and false otherwise
*/
public boolean isValidInput() {
return isValidInput;
}
/**
* Check if the current file has conaction.
*
* @return true if has conaction and false otherwise
*/
public boolean hasConaction() {
return hasconaction;
}
/**
*
* Reset the internal variables.
*/
public void reset() {
hasKeyRef = false;
hasConRef = false;
hasHref = false;
hasCodeRef = false;
currentDir = null;
foreignLevel = 0;
isValidInput = false;
hasconaction = false;
coderefTargetSet.clear();
nonConrefCopytoTargets.clear();
hrefTargets.clear();
conrefTargets.clear();
copytoMap.clear();
ignoredCopytoSourceSet.clear();
outDitaFilesSet.clear();
schemeSet.clear();
schemeRefSet.clear();
processRoleStack.clear();
isRootElement = true;
rootClass = null;
// Don't clean resourceOnlySet or normalProcessingRoleSet
}
@Override
public void startDocument() throws SAXException {
if (currentDir == null) {
throw new IllegalStateException();
}
processRoleStack.push(ATTR_PROCESSING_ROLE_VALUE_NORMAL);
getContentHandler().startDocument();
}
@Override
public void startElement(final String uri, final String localName, final String qName, final Attributes atts)
throws SAXException {
handleRootElement(atts);
handleSubjectScheme(atts);
String processingRole = atts.getValue(ATTRIBUTE_NAME_PROCESSING_ROLE);
if (processingRole == null) {
processingRole = processRoleStack.peek();
}
processRoleStack.push(processingRole);
final URI href = toURI(atts.getValue(ATTRIBUTE_NAME_HREF));
final String scope = atts.getValue(ATTRIBUTE_NAME_SCOPE);
if (href != null && !ATTR_SCOPE_VALUE_EXTERNAL.equals(scope)) {
if (ATTR_PROCESSING_ROLE_VALUE_RESOURCE_ONLY.equals(processingRole)) {
resourceOnlySet.add(stripFragment(currentDir.resolve(href)));
} else {
normalProcessingRoleSet.add(stripFragment(currentDir.resolve(href)));
}
}
final String classValue = atts.getValue(ATTRIBUTE_NAME_CLASS);
if (foreignLevel > 0) {
foreignLevel++;
} else if (TOPIC_FOREIGN.matches(classValue) || TOPIC_UNKNOWN.matches(classValue)) {
foreignLevel++;
}
if (foreignLevel == 0) {
if (classValue == null && !ELEMENT_NAME_DITA.equals(localName)) {
logger.info(MessageUtils.getInstance().getMessage("DOTJ030I", localName).setLocation(atts).toString());
}
if (TOPIC_TOPIC.matches(classValue) || MAP_MAP.matches(classValue)) {
final String domains = atts.getValue(ATTRIBUTE_NAME_DOMAINS);
if (domains == null) {
logger.info(MessageUtils.getInstance().getMessage("DOTJ029I", localName).setLocation(atts).toString());
}
}
if ((MAP_MAP.matches(classValue)) || (TOPIC_TITLE.matches(classValue))) {
isValidInput = true;
}
parseConrefAttr(atts);
if (PR_D_CODEREF.matches(classValue)) {
parseCoderef(atts);
} else if (TOPIC_OBJECT.matches(classValue)) {
parseObject(atts);
} else if (MAP_TOPICREF.matches(classValue)) {
parseAttribute(atts, ATTRIBUTE_NAME_HREF);
parseAttribute(atts, ATTRIBUTE_NAME_COPY_TO);
} else {
parseAttribute(atts, ATTRIBUTE_NAME_HREF);
}
parseConactionAttr(atts);
parseConkeyrefAttr(atts);
parseKeyrefAttr(atts);
}
getContentHandler().startElement(uri, localName, qName, atts);
}
private void parseCoderef(final Attributes atts) {
final URI href = toURI(atts.getValue(ATTRIBUTE_NAME_HREF));
if (href == null) {
return;
}
final String attrScope = atts.getValue(ATTRIBUTE_NAME_SCOPE);
if (ATTR_SCOPE_VALUE_EXTERNAL.equals(attrScope) || ATTR_SCOPE_VALUE_PEER.equals(attrScope)
|| href.toString().startsWith(SHARP)) {
return;
}
hasCodeRef = true;
final URI filename = stripFragment(href.isAbsolute() ? href : currentDir.resolve(href));
assert filename.isAbsolute();
coderefTargetSet.add(filename);
}
private void parseObject(final Attributes atts) {
URI attrValue = toURI(atts.getValue(ATTRIBUTE_NAME_DATA));
if (attrValue == null) {
return;
}
URI filename;
final URI codebase = toURI(atts.getValue(ATTRIBUTE_NAME_CODEBASE));
if (codebase != null) {
if (codebase.isAbsolute()) {
filename = codebase.resolve(attrValue);
} else {
filename = currentDir.resolve(codebase).resolve(attrValue);
}
} else {
filename = currentDir.resolve(attrValue);
}
filename = stripFragment(filename);
assert filename.isAbsolute();
nonConrefCopytoTargets.add(new Reference(filename, ATTR_FORMAT_VALUE_HTML));
}
private void handleSubjectScheme(final Attributes atts) {
final URI href = toURI(atts.getValue(ATTRIBUTE_NAME_HREF));
final String classValue = atts.getValue(ATTRIBUTE_NAME_CLASS);
// Generate Scheme relationship graph
if (SUBJECTSCHEME_SUBJECTSCHEME.matches(classValue)) {
// Make it easy to do the BFS later.
final URI key = ROOT_URI;
final Set<URI> children = schemeRelationGraph.containsKey(key) ? schemeRelationGraph.get(key) : new LinkedHashSet<URI>();
children.add(currentFile);
schemeRelationGraph.put(key, children);
schemeRefSet.add(currentFile);
} else if (SUBJECTSCHEME_SCHEMEREF.matches(classValue)) {
if (href != null) {
final URI key = currentFile;
final Set<URI> children = schemeRelationGraph.containsKey(key) ? schemeRelationGraph.get(key) : new LinkedHashSet<URI>();
final URI child = currentFile.resolve(href);
children.add(child);
schemeRelationGraph.put(key, children);
}
}
}
private void handleRootElement(final Attributes atts) {
if (isRootElement) {
isRootElement = false;
final String classValue = atts.getValue(ATTRIBUTE_NAME_CLASS);
if (classValue != null) {
rootClass = new DitaClass(atts.getValue(ATTRIBUTE_NAME_CLASS));
}
}
}
@Override
public void endElement(final String uri, final String localName, final String qName) throws SAXException {
// @processing-role
processRoleStack.pop();
if (foreignLevel > 0) {
foreignLevel--;
assert foreignLevel >= 0;
}
getContentHandler().endElement(uri, localName, qName);
}
/**
* Clean up.
*/
@Override
public void endDocument() throws SAXException {
processRoleStack.pop();
getContentHandler().endDocument();
}
/**
* Parse the input attributes for needed information.
*
* @param atts all attributes
* @param attrName attributes to process
*/
private void parseAttribute(final Attributes atts, final String attrName) throws SAXException {
URI attrValue = toURI(atts.getValue(attrName));
if (attrValue == null) {
return;
}
final String attrClass = atts.getValue(ATTRIBUTE_NAME_CLASS);
final String attrScope = atts.getValue(ATTRIBUTE_NAME_SCOPE);
// external resource is filtered here.
if (ATTR_SCOPE_VALUE_EXTERNAL.equals(attrScope) || ATTR_SCOPE_VALUE_PEER.equals(attrScope)
// FIXME: testing for :// here is incorrect, rely on source scope instead
|| attrValue.toString().contains(COLON_DOUBLE_SLASH) || attrValue.toString().startsWith(SHARP)) {
return;
}
final URI filename = stripFragment(attrValue.isAbsolute() ? attrValue : currentDir.resolve(attrValue));
assert filename.isAbsolute();
final String attrType = atts.getValue(ATTRIBUTE_NAME_TYPE);
if (MAP_TOPICREF.matches(attrClass) && ATTR_TYPE_VALUE_SUBJECT_SCHEME.equalsIgnoreCase(attrType)) {
schemeSet.add(filename);
}
final String attrFormat = getFormat(atts);
if (ATTRIBUTE_NAME_HREF.equals(attrName)) {
hasHref = true;
// Collect non-conref and non-copyto targets
if ((followLinks()
|| (TOPIC_IMAGE.matches(attrClass) || DITAVAREF_D_DITAVALREF.matches(attrClass)))) {
nonConrefCopytoTargets.add(new Reference(filename, attrFormat));
}
}
if (isFormatDita(attrFormat)) {
if (ATTRIBUTE_NAME_HREF.equals(attrName)) {
if (followLinks()) {
hrefTargets.add(filename);
toOutFile(filename, atts);
}
} else if (ATTRIBUTE_NAME_COPY_TO.equals(attrName)) {
final URI copyTo = toURI(atts.getValue(ATTRIBUTE_NAME_HREF));
if (copyTo != null) {
if (copyTo.toString().isEmpty()) {
logger.warn("Copy-to task [href=\"\" copy-to=\"" + filename + "\"] was ignored.");
} else {
final URI value = stripFragment(currentDir.resolve(copyTo));
if (copytoMap.get(filename) != null) {
if (!value.equals(copytoMap.get(filename))) {
logger.warn(MessageUtils.getInstance().getMessage("DOTX065W", copyTo.toString(), filename.toString())
.setLocation(atts).toString());
}
ignoredCopytoSourceSet.add(value);
} else {
copytoMap.put(filename, value);
}
}
}
}
}
}
private String getFormat(Attributes atts) {
final String attrClass = atts.getValue(ATTRIBUTE_NAME_CLASS);
if (TOPIC_IMAGE.matches(attrClass)) {
return ATTR_FORMAT_VALUE_IMAGE;
} else if (TOPIC_OBJECT.matches(attrClass)) {
throw new IllegalArgumentException();
//return ATTR_FORMAT_VALUE_HTML;
} else {
return atts.getValue(ATTRIBUTE_NAME_FORMAT);
}
}
private void parseConrefAttr(final Attributes atts) throws SAXException {
String attrValue = atts.getValue(ATTRIBUTE_NAME_CONREF);
if (attrValue != null) {
hasConRef = true;
URI filename;
final URI target = toURI(attrValue);
if (isAbsolute(target)) {
filename = target;
} else if (attrValue.startsWith(SHARP)) {
filename = currentFile;
} else {
filename = currentDir.resolve(attrValue);
}
filename = stripFragment(filename);
// Collect only conref target topic files
conrefTargets.add(filename);
toOutFile(filename, atts);
}
}
private void parseConkeyrefAttr(final Attributes atts) {
final String conkeyref = atts.getValue(ATTRIBUTE_NAME_CONKEYREF);
if (conkeyref != null) {
hasConRef = true;
}
}
private final static String[] KEYREF_ATTRS = new String[] {
ATTRIBUTE_NAME_KEYREF,
ATTRIBUTE_NAME_CONKEYREF,
ATTRIBUTE_NAME_ARCHIVEKEYREFS,
ATTRIBUTE_NAME_CLASSIDKEYREF,
ATTRIBUTE_NAME_CODEBASEKEYREF,
ATTRIBUTE_NAME_DATAKEYREF
};
private void parseKeyrefAttr(final Attributes atts) {
for (final String attr: KEYREF_ATTRS) {
if (atts.getValue(attr) != null) {
hasKeyRef = true;
break;
}
}
}
private void parseConactionAttr(final Attributes atts) {
final String conaction = atts.getValue(ATTRIBUTE_NAME_CONACTION);
if (conaction != null) {
if (conaction.equals(ATTR_CONACTION_VALUE_MARK) || conaction.equals(ATTR_CONACTION_VALUE_PUSHREPLACE)) {
hasconaction = true;
}
}
}
/**
* Check if format is DITA topic.
*
* @param attrFormat format attribute value, may be {@code null}
* @return {@code true} if DITA topic, otherwise {@code false}
*/
public static boolean isFormatDita(final String attrFormat) {
if (attrFormat == null || attrFormat.equals(ATTR_FORMAT_VALUE_DITA)) {
return true;
}
for (final String f: ditaFormat) {
if (f.equals(attrFormat)) {
return true;
}
}
return false;
}
/**
* Check if path walks up in parent directories
*
* @param toCheckPath path to check
* @return {@code true} if path walks up, otherwise {@code false}
*/
private boolean isOutFile(final URI toCheckPath) {
return !toCheckPath.getPath().startsWith(rootDir.getPath());
}
/**
* Should links be followed.
*/
private boolean followLinks() {
return !job.getOnlyTopicInMap() || isDitaMap();
}
private void addToOutFilesSet(final URI hrefedFile) {
if (followLinks()) {
outDitaFilesSet.add(hrefedFile);
}
}
private void toOutFile(final URI filename, final Attributes atts) throws SAXException {
assert filename.isAbsolute();
final String[] prop = { filename.toString(), currentFile.toString() };
if (job.getGeneratecopyouter() == Job.Generate.NOT_GENERATEOUTTER) {
if (isOutFile(filename)) {
if (job.getOutterControl() == Job.OutterControl.FAIL) {
final MessageBean msgBean = MessageUtils.getInstance().getMessage("DOTJ035F", prop).setLocation(atts);
throw new SAXParseException(null, null, new DITAOTException(msgBean, null, msgBean.toString()));
} else if (job.getOutterControl() == Job.OutterControl.WARN) {
final MessageBean msgBean = MessageUtils.getInstance().getMessage("DOTJ036W", prop).setLocation(atts);
logger.warn(msgBean.toString());
}
addToOutFilesSet(filename);
}
}
}
/**
* File reference with path and optional format.
*/
public static class Reference {
/** Absolute URI reference */
public final URI filename;
/** Format of the reference */
public final String format;
public Reference(final URI filename, final String format) {
assert filename.isAbsolute() && filename.getFragment() == null;
this.filename = filename;
this.format = format;
}
public Reference(final URI filename) {
this(filename, null);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((filename == null) ? 0 : filename.hashCode());
// result = prime * result + ((format == null) ? 0 : format.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Reference)) {
return false;
}
final Reference other = (Reference) obj;
if (filename == null) {
if (other.filename != null) {
return false;
}
} else if (!filename.equals(other.filename)) {
return false;
}
// if (format == null) {
// if (other.format != null) {
// return false;
// }
// } else if (!format.equals(other.format)) {
// return false;
// }
return true;
}
}
} | src/main/java/org/dita/dost/reader/GenListModuleReader.java | /*
* This file is part of the DITA Open Toolkit project.
*
* Copyright 2004, 2005 IBM Corporation
*
* See the accompanying LICENSE file for applicable license.
*/
package org.dita.dost.reader;
import static org.dita.dost.util.Configuration.*;
import static org.dita.dost.util.Constants.*;
import static org.dita.dost.util.URLUtils.*;
import static org.dita.dost.reader.ChunkMapReader.*;
import java.net.URI;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import org.dita.dost.exception.DITAOTException;
import org.dita.dost.log.MessageBean;
import org.dita.dost.log.MessageUtils;
import org.dita.dost.util.DitaClass;
import org.dita.dost.util.Job;
import org.dita.dost.writer.AbstractXMLFilter;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
/**
* Parse relevant DITA files and collect information.
*
* <p>
* <strong>Not thread-safe</strong>. Instances can be reused by calling
* {@link #reset()} between calls to parse.
* </p>
*/
public final class GenListModuleReader extends AbstractXMLFilter {
public static final URI ROOT_URI = toURI("ROOT");
/** Output utilities */
private Job job;
/** Absolute basedir of the current parsing file */
private URI currentDir = null;
/** Flag for conref in parsing file */
private boolean hasConRef = false;
/** Flag for href in parsing file */
private boolean hasHref = false;
/** Flag for keyref in parsing file */
private boolean hasKeyRef = false;
/** Flag for whether parsing file contains coderef */
private boolean hasCodeRef = false;
/** Set of all the non-conref and non-copyto targets refered in current parsing file */
private final Set<Reference> nonConrefCopytoTargets = new LinkedHashSet<>(64);
/** Set of conref targets refered in current parsing file */
private final Set<URI> conrefTargets = new HashSet<>(32);
/** Set of href nonConrefCopytoTargets refered in current parsing file */
private final Set<URI> hrefTargets = new HashSet<>(32);
/** Set of subject schema files */
private final Set<URI> schemeSet = new HashSet<>(32);
/** Set of coderef or object target files */
private final Set<URI> coderefTargetSet = new HashSet<>(16);
/** Set of sources of those copy-to that were ignored */
private final Set<URI> ignoredCopytoSourceSet = new HashSet<>(16);
/** Map of copy-to target to souce */
private final Map<URI, URI> copytoMap = new HashMap<>(16);
/** Flag for conrefpush */
private boolean hasconaction = false;
/** foreign/unknown nesting level */
private int foreignLevel = 0;
/** Flag used to mark if current file is still valid after filtering */
private boolean isValidInput = false;
/** Set of outer dita files */
private final Set<URI> outDitaFilesSet = new HashSet<>(64);
/** Absolute system path to input file parent directory */
private URI rootDir = null;
/** Stack for @processing-role value */
private final Stack<String> processRoleStack = new Stack<>();
/** Topics with processing role of "resource-only" */
private final Set<URI> resourceOnlySet = new HashSet<>(32);
/** Topics with processing role of "normal" */
private final Set<URI> normalProcessingRoleSet = new HashSet<>(32);
/** Subject scheme relative file paths. */
private final Set<URI> schemeRefSet = new HashSet<>(32);
/** Relationship graph between subject schema. Keys are subject scheme map paths and values
* are subject scheme map paths, both relative to base directory. A key {@link #ROOT_URI} contains all subject scheme maps. */
private final Map<URI, Set<URI>> schemeRelationGraph = new LinkedHashMap<>();
/** Store the primary ditamap file name. */
private URI primaryDitamap;
private boolean isRootElement = true;
private DitaClass rootClass = null;
/**
* Set output utilities.
*
* @param job output utils
*/
public void setJob(final Job job) {
this.job = job;
}
/**
* Get out file set.
*
* @return out file set
*/
public Set<URI> getOutFilesSet() {
return outDitaFilesSet;
}
/**
* Get scheme set.
*
* @return scheme set
*/
public Set<URI> getSchemeSet() {
return schemeSet;
}
/**
* Get scheme ref set.
*
* @return scheme ref set
*/
public Set<URI> getSchemeRefSet() {
return schemeRefSet;
}
/**
* List of files with "@processing-role=resource-only".
*
* @return the resource-only set
*/
public Set<URI> getResourceOnlySet() {
final Set<URI> res = new HashSet<>(resourceOnlySet);
res.removeAll(normalProcessingRoleSet);
return res;
}
/**
* Is the processed file a DITA topic.
*
* @return {@code true} if DITA topic, otherwise {@code false}
*/
public boolean isDitaTopic() {
if (isRootElement) {
throw new IllegalStateException();
}
return rootClass == null || TOPIC_TOPIC.matches(rootClass);
}
/**
* Is the currently processed file a DITA map.
*
* @return {@code true} if DITA map, otherwise {@code false}
*/
public boolean isDitaMap() {
if (isRootElement) {
throw new IllegalStateException();
}
return rootClass != null && MAP_MAP.matches(rootClass);
}
/**
* Get relationship graph between subject schema. Keys are subject scheme map paths and values
* are subject scheme map paths, both relative to base directory. A key {@link #ROOT_URI} contains all subject scheme maps.
*
* @return relationship graph
*/
public Map<URI, Set<URI>> getRelationshipGrap() {
return schemeRelationGraph;
}
public void setPrimaryDitamap(final URI primaryDitamap) {
assert primaryDitamap.isAbsolute();
this.primaryDitamap = primaryDitamap;
this.rootDir = primaryDitamap.resolve(".");
}
/**
* To see if the parsed file has conref inside.
*
* @return true if has conref and false otherwise
*/
public boolean hasConRef() {
return hasConRef;
}
/**
* To see if the parsed file has keyref inside.
*
* @return true if has keyref and false otherwise
*/
public boolean hasKeyRef() {
return hasKeyRef;
}
/**
* To see if the parsed file has coderef inside.
*
* @return true if has coderef and false otherwise
*/
public boolean hasCodeRef() {
return hasCodeRef;
}
/**
* To see if the parsed file has href inside.
*
* @return true if has href and false otherwise
*/
public boolean hasHref() {
return hasHref;
}
/**
* Get all targets except copy-to.
*
* @return set of target file path with option format after
* {@link org.dita.dost.util.Constants#STICK STICK}
*/
public Set<Reference> getNonCopytoResult() {
final Set<Reference> nonCopytoSet = new LinkedHashSet<>(128);
nonCopytoSet.addAll(nonConrefCopytoTargets);
for (final URI f : conrefTargets) {
nonCopytoSet.add(new Reference(stripFragment(f)));
}
for (final URI f : copytoMap.values()) {
nonCopytoSet.add(new Reference(stripFragment(f)));
}
for (final URI f : ignoredCopytoSourceSet) {
nonCopytoSet.add(new Reference(stripFragment(f)));
}
for (final URI filename : coderefTargetSet) {
nonCopytoSet.add(new Reference(stripFragment(filename)));
}
return nonCopytoSet;
}
/**
* Get copy-to map.
*
* @return map of copy-to target to souce
*/
public Map<URI, URI> getCopytoMap() {
return copytoMap;
}
/**
* Get the href target.
*
* @return Returns the hrefTargets.
*/
public Set<URI> getHrefTargets() {
return hrefTargets;
}
/**
* Get conref targets.
*
* @return Returns the conrefTargets.
*/
public Set<URI> getConrefTargets() {
return conrefTargets;
}
/**
* Get coderef targets.
*
* @return Returns coderef targets.
*/
public Set<URI> getCoderefTargets() {
return coderefTargetSet;
}
/**
* Get outditafileslist.
*
* @return Returns the outditafileslist.
*/
public Set<URI> getOutDitaFilesSet() {
return outDitaFilesSet;
}
/**
* Get non-conref and non-copyto targets.
*
* @return Returns the nonConrefCopytoTargets.
*/
public Set<URI> getNonConrefCopytoTargets() {
final Set<URI> res = new HashSet<>(nonConrefCopytoTargets.size());
for (final Reference r : nonConrefCopytoTargets) {
res.add(r.filename);
}
return res;
}
/**
* Set current file absolute path
*
* @param currentFile absolute path to current file
*/
public void setCurrentFile(final URI currentFile) {
assert currentFile.isAbsolute();
super.setCurrentFile(currentFile);
currentDir = currentFile.resolve(".");
}
/**
* Check if the current file is valid after filtering.
*
* @return true if valid and false otherwise
*/
public boolean isValidInput() {
return isValidInput;
}
/**
* Check if the current file has conaction.
*
* @return true if has conaction and false otherwise
*/
public boolean hasConaction() {
return hasconaction;
}
/**
*
* Reset the internal variables.
*/
public void reset() {
hasKeyRef = false;
hasConRef = false;
hasHref = false;
hasCodeRef = false;
currentDir = null;
foreignLevel = 0;
isValidInput = false;
hasconaction = false;
coderefTargetSet.clear();
nonConrefCopytoTargets.clear();
hrefTargets.clear();
conrefTargets.clear();
copytoMap.clear();
ignoredCopytoSourceSet.clear();
outDitaFilesSet.clear();
schemeSet.clear();
schemeRefSet.clear();
processRoleStack.clear();
isRootElement = true;
rootClass = null;
// Don't clean resourceOnlySet or normalProcessingRoleSet
}
@Override
public void startDocument() throws SAXException {
if (currentDir == null) {
throw new IllegalStateException();
}
processRoleStack.push(ATTR_PROCESSING_ROLE_VALUE_NORMAL);
getContentHandler().startDocument();
}
@Override
public void startElement(final String uri, final String localName, final String qName, final Attributes atts)
throws SAXException {
handleRootElement(atts);
handleSubjectScheme(atts);
String processingRole = atts.getValue(ATTRIBUTE_NAME_PROCESSING_ROLE);
if (processingRole == null) {
processingRole = processRoleStack.peek();
}
processRoleStack.push(processingRole);
final URI href = toURI(atts.getValue(ATTRIBUTE_NAME_HREF));
final String scope = atts.getValue(ATTRIBUTE_NAME_SCOPE);
if (href != null && !ATTR_SCOPE_VALUE_EXTERNAL.equals(scope)) {
if (ATTR_PROCESSING_ROLE_VALUE_RESOURCE_ONLY.equals(processingRole)) {
resourceOnlySet.add(stripFragment(currentDir.resolve(href)));
} else {
normalProcessingRoleSet.add(stripFragment(currentDir.resolve(href)));
}
}
final String classValue = atts.getValue(ATTRIBUTE_NAME_CLASS);
if (foreignLevel > 0) {
foreignLevel++;
return;
} else if (TOPIC_FOREIGN.matches(classValue) || TOPIC_UNKNOWN.matches(classValue)) {
foreignLevel++;
}
if (classValue == null && !ELEMENT_NAME_DITA.equals(localName)) {
logger.info(MessageUtils.getInstance().getMessage("DOTJ030I", localName).setLocation(atts).toString());
}
if (TOPIC_TOPIC.matches(classValue) || MAP_MAP.matches(classValue)) {
final String domains = atts.getValue(ATTRIBUTE_NAME_DOMAINS);
if (domains == null) {
logger.info(MessageUtils.getInstance().getMessage("DOTJ029I", localName).setLocation(atts).toString());
}
}
if ((MAP_MAP.matches(classValue)) || (TOPIC_TITLE.matches(classValue))) {
isValidInput = true;
}
parseConrefAttr(atts);
if (PR_D_CODEREF.matches(classValue)) {
parseCoderef(atts);
} else if (TOPIC_OBJECT.matches(classValue)) {
parseObject(atts);
} else if (MAP_TOPICREF.matches(classValue)) {
parseAttribute(atts, ATTRIBUTE_NAME_HREF);
parseAttribute(atts, ATTRIBUTE_NAME_COPY_TO);
} else {
parseAttribute(atts, ATTRIBUTE_NAME_HREF);
}
parseConactionAttr(atts);
parseConkeyrefAttr(atts);
parseKeyrefAttr(atts);
getContentHandler().startElement(uri, localName, qName, atts);
}
private void parseCoderef(final Attributes atts) {
final URI href = toURI(atts.getValue(ATTRIBUTE_NAME_HREF));
if (href == null) {
return;
}
final String attrScope = atts.getValue(ATTRIBUTE_NAME_SCOPE);
if (ATTR_SCOPE_VALUE_EXTERNAL.equals(attrScope) || ATTR_SCOPE_VALUE_PEER.equals(attrScope)
|| href.toString().startsWith(SHARP)) {
return;
}
hasCodeRef = true;
final URI filename = stripFragment(href.isAbsolute() ? href : currentDir.resolve(href));
assert filename.isAbsolute();
coderefTargetSet.add(filename);
}
private void parseObject(final Attributes atts) {
URI attrValue = toURI(atts.getValue(ATTRIBUTE_NAME_DATA));
if (attrValue == null) {
return;
}
URI filename;
final URI codebase = toURI(atts.getValue(ATTRIBUTE_NAME_CODEBASE));
if (codebase != null) {
if (codebase.isAbsolute()) {
filename = codebase.resolve(attrValue);
} else {
filename = currentDir.resolve(codebase).resolve(attrValue);
}
} else {
filename = currentDir.resolve(attrValue);
}
filename = stripFragment(filename);
assert filename.isAbsolute();
nonConrefCopytoTargets.add(new Reference(filename, ATTR_FORMAT_VALUE_HTML));
}
private void handleSubjectScheme(final Attributes atts) {
final URI href = toURI(atts.getValue(ATTRIBUTE_NAME_HREF));
final String classValue = atts.getValue(ATTRIBUTE_NAME_CLASS);
// Generate Scheme relationship graph
if (SUBJECTSCHEME_SUBJECTSCHEME.matches(classValue)) {
// Make it easy to do the BFS later.
final URI key = ROOT_URI;
final Set<URI> children = schemeRelationGraph.containsKey(key) ? schemeRelationGraph.get(key) : new LinkedHashSet<URI>();
children.add(currentFile);
schemeRelationGraph.put(key, children);
schemeRefSet.add(currentFile);
} else if (SUBJECTSCHEME_SCHEMEREF.matches(classValue)) {
if (href != null) {
final URI key = currentFile;
final Set<URI> children = schemeRelationGraph.containsKey(key) ? schemeRelationGraph.get(key) : new LinkedHashSet<URI>();
final URI child = currentFile.resolve(href);
children.add(child);
schemeRelationGraph.put(key, children);
}
}
}
private void handleRootElement(final Attributes atts) {
if (isRootElement) {
isRootElement = false;
final String classValue = atts.getValue(ATTRIBUTE_NAME_CLASS);
if (classValue != null) {
rootClass = new DitaClass(atts.getValue(ATTRIBUTE_NAME_CLASS));
}
}
}
@Override
public void endElement(final String uri, final String localName, final String qName) throws SAXException {
// @processing-role
processRoleStack.pop();
if (foreignLevel > 0) {
foreignLevel--;
return;
}
getContentHandler().endElement(uri, localName, qName);
}
/**
* Clean up.
*/
@Override
public void endDocument() throws SAXException {
processRoleStack.pop();
getContentHandler().endDocument();
}
/**
* Parse the input attributes for needed information.
*
* @param atts all attributes
* @param attrName attributes to process
*/
private void parseAttribute(final Attributes atts, final String attrName) throws SAXException {
URI attrValue = toURI(atts.getValue(attrName));
if (attrValue == null) {
return;
}
final String attrClass = atts.getValue(ATTRIBUTE_NAME_CLASS);
final String attrScope = atts.getValue(ATTRIBUTE_NAME_SCOPE);
// external resource is filtered here.
if (ATTR_SCOPE_VALUE_EXTERNAL.equals(attrScope) || ATTR_SCOPE_VALUE_PEER.equals(attrScope)
// FIXME: testing for :// here is incorrect, rely on source scope instead
|| attrValue.toString().contains(COLON_DOUBLE_SLASH) || attrValue.toString().startsWith(SHARP)) {
return;
}
final URI filename = stripFragment(attrValue.isAbsolute() ? attrValue : currentDir.resolve(attrValue));
assert filename.isAbsolute();
final String attrType = atts.getValue(ATTRIBUTE_NAME_TYPE);
if (MAP_TOPICREF.matches(attrClass) && ATTR_TYPE_VALUE_SUBJECT_SCHEME.equalsIgnoreCase(attrType)) {
schemeSet.add(filename);
}
final String attrFormat = getFormat(atts);
if (ATTRIBUTE_NAME_HREF.equals(attrName)) {
hasHref = true;
// Collect non-conref and non-copyto targets
if ((followLinks()
|| (TOPIC_IMAGE.matches(attrClass) || DITAVAREF_D_DITAVALREF.matches(attrClass)))) {
nonConrefCopytoTargets.add(new Reference(filename, attrFormat));
}
}
if (isFormatDita(attrFormat)) {
if (ATTRIBUTE_NAME_HREF.equals(attrName)) {
if (followLinks()) {
hrefTargets.add(filename);
toOutFile(filename, atts);
}
} else if (ATTRIBUTE_NAME_COPY_TO.equals(attrName)) {
final URI copyTo = toURI(atts.getValue(ATTRIBUTE_NAME_HREF));
if (copyTo != null) {
if (copyTo.toString().isEmpty()) {
logger.warn("Copy-to task [href=\"\" copy-to=\"" + filename + "\"] was ignored.");
} else {
final URI value = stripFragment(currentDir.resolve(copyTo));
if (copytoMap.get(filename) != null) {
if (!value.equals(copytoMap.get(filename))) {
logger.warn(MessageUtils.getInstance().getMessage("DOTX065W", copyTo.toString(), filename.toString())
.setLocation(atts).toString());
}
ignoredCopytoSourceSet.add(value);
} else {
copytoMap.put(filename, value);
}
}
}
}
}
}
private String getFormat(Attributes atts) {
final String attrClass = atts.getValue(ATTRIBUTE_NAME_CLASS);
if (TOPIC_IMAGE.matches(attrClass)) {
return ATTR_FORMAT_VALUE_IMAGE;
} else if (TOPIC_OBJECT.matches(attrClass)) {
throw new IllegalArgumentException();
//return ATTR_FORMAT_VALUE_HTML;
} else {
return atts.getValue(ATTRIBUTE_NAME_FORMAT);
}
}
private void parseConrefAttr(final Attributes atts) throws SAXException {
String attrValue = atts.getValue(ATTRIBUTE_NAME_CONREF);
if (attrValue != null) {
hasConRef = true;
URI filename;
final URI target = toURI(attrValue);
if (isAbsolute(target)) {
filename = target;
} else if (attrValue.startsWith(SHARP)) {
filename = currentFile;
} else {
filename = currentDir.resolve(attrValue);
}
filename = stripFragment(filename);
// Collect only conref target topic files
conrefTargets.add(filename);
toOutFile(filename, atts);
}
}
private void parseConkeyrefAttr(final Attributes atts) {
final String conkeyref = atts.getValue(ATTRIBUTE_NAME_CONKEYREF);
if (conkeyref != null) {
hasConRef = true;
}
}
private final static String[] KEYREF_ATTRS = new String[] {
ATTRIBUTE_NAME_KEYREF,
ATTRIBUTE_NAME_CONKEYREF,
ATTRIBUTE_NAME_ARCHIVEKEYREFS,
ATTRIBUTE_NAME_CLASSIDKEYREF,
ATTRIBUTE_NAME_CODEBASEKEYREF,
ATTRIBUTE_NAME_DATAKEYREF
};
private void parseKeyrefAttr(final Attributes atts) {
for (final String attr: KEYREF_ATTRS) {
if (atts.getValue(attr) != null) {
hasKeyRef = true;
break;
}
}
}
private void parseConactionAttr(final Attributes atts) {
final String conaction = atts.getValue(ATTRIBUTE_NAME_CONACTION);
if (conaction != null) {
if (conaction.equals(ATTR_CONACTION_VALUE_MARK) || conaction.equals(ATTR_CONACTION_VALUE_PUSHREPLACE)) {
hasconaction = true;
}
}
}
/**
* Check if format is DITA topic.
*
* @param attrFormat format attribute value, may be {@code null}
* @return {@code true} if DITA topic, otherwise {@code false}
*/
public static boolean isFormatDita(final String attrFormat) {
if (attrFormat == null || attrFormat.equals(ATTR_FORMAT_VALUE_DITA)) {
return true;
}
for (final String f: ditaFormat) {
if (f.equals(attrFormat)) {
return true;
}
}
return false;
}
/**
* Check if path walks up in parent directories
*
* @param toCheckPath path to check
* @return {@code true} if path walks up, otherwise {@code false}
*/
private boolean isOutFile(final URI toCheckPath) {
return !toCheckPath.getPath().startsWith(rootDir.getPath());
}
/**
* Should links be followed.
*/
private boolean followLinks() {
return !job.getOnlyTopicInMap() || isDitaMap();
}
private void addToOutFilesSet(final URI hrefedFile) {
if (followLinks()) {
outDitaFilesSet.add(hrefedFile);
}
}
private void toOutFile(final URI filename, final Attributes atts) throws SAXException {
assert filename.isAbsolute();
final String[] prop = { filename.toString(), currentFile.toString() };
if (job.getGeneratecopyouter() == Job.Generate.NOT_GENERATEOUTTER) {
if (isOutFile(filename)) {
if (job.getOutterControl() == Job.OutterControl.FAIL) {
final MessageBean msgBean = MessageUtils.getInstance().getMessage("DOTJ035F", prop).setLocation(atts);
throw new SAXParseException(null, null, new DITAOTException(msgBean, null, msgBean.toString()));
} else if (job.getOutterControl() == Job.OutterControl.WARN) {
final MessageBean msgBean = MessageUtils.getInstance().getMessage("DOTJ036W", prop).setLocation(atts);
logger.warn(msgBean.toString());
}
addToOutFilesSet(filename);
}
}
}
/**
* File reference with path and optional format.
*/
public static class Reference {
/** Absolute URI reference */
public final URI filename;
/** Format of the reference */
public final String format;
public Reference(final URI filename, final String format) {
assert filename.isAbsolute() && filename.getFragment() == null;
this.filename = filename;
this.format = format;
}
public Reference(final URI filename) {
this(filename, null);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((filename == null) ? 0 : filename.hashCode());
// result = prime * result + ((format == null) ? 0 : format.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Reference)) {
return false;
}
final Reference other = (Reference) obj;
if (filename == null) {
if (other.filename != null) {
return false;
}
} else if (!filename.equals(other.filename)) {
return false;
}
// if (format == null) {
// if (other.format != null) {
// return false;
// }
// } else if (!format.equals(other.format)) {
// return false;
// }
return true;
}
}
} | Fix foreign content processing
| src/main/java/org/dita/dost/reader/GenListModuleReader.java | Fix foreign content processing | <ide><path>rc/main/java/org/dita/dost/reader/GenListModuleReader.java
<ide>
<ide> if (foreignLevel > 0) {
<ide> foreignLevel++;
<del> return;
<ide> } else if (TOPIC_FOREIGN.matches(classValue) || TOPIC_UNKNOWN.matches(classValue)) {
<ide> foreignLevel++;
<ide> }
<ide>
<del> if (classValue == null && !ELEMENT_NAME_DITA.equals(localName)) {
<del> logger.info(MessageUtils.getInstance().getMessage("DOTJ030I", localName).setLocation(atts).toString());
<del> }
<del>
<del> if (TOPIC_TOPIC.matches(classValue) || MAP_MAP.matches(classValue)) {
<del> final String domains = atts.getValue(ATTRIBUTE_NAME_DOMAINS);
<del> if (domains == null) {
<del> logger.info(MessageUtils.getInstance().getMessage("DOTJ029I", localName).setLocation(atts).toString());
<del> }
<del> }
<del>
<del> if ((MAP_MAP.matches(classValue)) || (TOPIC_TITLE.matches(classValue))) {
<del> isValidInput = true;
<del> }
<del>
<del> parseConrefAttr(atts);
<del> if (PR_D_CODEREF.matches(classValue)) {
<del> parseCoderef(atts);
<del> } else if (TOPIC_OBJECT.matches(classValue)) {
<del> parseObject(atts);
<del> } else if (MAP_TOPICREF.matches(classValue)) {
<del> parseAttribute(atts, ATTRIBUTE_NAME_HREF);
<del> parseAttribute(atts, ATTRIBUTE_NAME_COPY_TO);
<del> } else {
<del> parseAttribute(atts, ATTRIBUTE_NAME_HREF);
<del> }
<del> parseConactionAttr(atts);
<del> parseConkeyrefAttr(atts);
<del> parseKeyrefAttr(atts);
<add> if (foreignLevel == 0) {
<add> if (classValue == null && !ELEMENT_NAME_DITA.equals(localName)) {
<add> logger.info(MessageUtils.getInstance().getMessage("DOTJ030I", localName).setLocation(atts).toString());
<add> }
<add>
<add> if (TOPIC_TOPIC.matches(classValue) || MAP_MAP.matches(classValue)) {
<add> final String domains = atts.getValue(ATTRIBUTE_NAME_DOMAINS);
<add> if (domains == null) {
<add> logger.info(MessageUtils.getInstance().getMessage("DOTJ029I", localName).setLocation(atts).toString());
<add> }
<add> }
<add>
<add> if ((MAP_MAP.matches(classValue)) || (TOPIC_TITLE.matches(classValue))) {
<add> isValidInput = true;
<add> }
<add>
<add> parseConrefAttr(atts);
<add> if (PR_D_CODEREF.matches(classValue)) {
<add> parseCoderef(atts);
<add> } else if (TOPIC_OBJECT.matches(classValue)) {
<add> parseObject(atts);
<add> } else if (MAP_TOPICREF.matches(classValue)) {
<add> parseAttribute(atts, ATTRIBUTE_NAME_HREF);
<add> parseAttribute(atts, ATTRIBUTE_NAME_COPY_TO);
<add> } else {
<add> parseAttribute(atts, ATTRIBUTE_NAME_HREF);
<add> }
<add> parseConactionAttr(atts);
<add> parseConkeyrefAttr(atts);
<add> parseKeyrefAttr(atts);
<add> }
<ide>
<ide> getContentHandler().startElement(uri, localName, qName, atts);
<ide> }
<ide>
<ide> if (foreignLevel > 0) {
<ide> foreignLevel--;
<del> return;
<add> assert foreignLevel >= 0;
<ide> }
<ide>
<ide> getContentHandler().endElement(uri, localName, qName); |
|
JavaScript | mit | 9d7cb6eba242b912f7bdb5d6ddca9a34670a2335 | 0 | jrtnq514/spawn-it | /**
* Created by JT on 8/26/16.
*/
var chai = require('chai'),
should = chai.should(),
expect = chai.expect,
assert = chai.assert;
var location = require('./../../lib/modules/location');
describe('LOCATION', function() {
describe('city', function() {
describe('with state code', function() {
it('should return a string', function(done) {
var city = location.city('MO');
expect(city).to.be.a('string');
expect(city).to.not.equal(null);
expect(city).to.not.equal(undefined);
done();
});
});
describe('without state code', function() {
it('should return a string', function(done) {
var city = location.city();
expect(city).to.be.a('string');
expect(city).to.not.equal(null);
expect(city).to.not.equal(undefined);
done();
});
});
});
describe('state', function() {
it('should return an object', function(done) {
var state = location.state();
expect(state).to.be.a('object');
expect(state).to.not.equal(null);
expect(state).to.not.equal(undefined);
done();
});
it('should return a state and a code', function(done) {
var state = location.state();
expect(state.code).to.not.equal(undefined);
expect(state.state).to.not.equal(undefined);
done();
});
});
describe('planet', function() {
it('should return a string', function(done) {
var planet = location.planet();
expect(planet).to.be.a('string');
expect(planet).to.not.equal(null);
expect(planet).to.not.equal(undefined);
done();
});
});
});
| test/modules/location.js | /**
* Created by JT on 8/26/16.
*/
var chai = require('chai'),
should = chai.should(),
expect = chai.expect,
assert = chai.assert;
var location = require('./../../lib/modules/location');
describe('LOCATION', function() {
describe('city', function() {
it('should return a string', function(done) {
var city = location.city('MO');
expect(city).to.be.a('string');
expect(city).to.not.equal(null);
expect(city).to.not.equal(undefined);
done();
});
});
describe('state', function() {
it('should return an object', function(done) {
var state = location.state();
expect(state).to.be.a('object');
expect(state).to.not.equal(null);
expect(state).to.not.equal(undefined);
done();
});
it('should return a state and a code', function(done) {
var state = location.state();
expect(state.code).to.not.equal(undefined);
expect(state.state).to.not.equal(undefined);
done();
});
});
describe('planet', function() {
it('should return a string', function(done) {
var planet = location.planet();
expect(planet).to.be.a('string');
expect(planet).to.not.equal(null);
expect(planet).to.not.equal(undefined);
done();
});
});
});
| Adding test for without a statecode.
| test/modules/location.js | Adding test for without a statecode. | <ide><path>est/modules/location.js
<ide>
<ide> describe('city', function() {
<ide>
<del> it('should return a string', function(done) {
<del> var city = location.city('MO');
<del> expect(city).to.be.a('string');
<del> expect(city).to.not.equal(null);
<del> expect(city).to.not.equal(undefined);
<del> done();
<add> describe('with state code', function() {
<add> it('should return a string', function(done) {
<add> var city = location.city('MO');
<add> expect(city).to.be.a('string');
<add> expect(city).to.not.equal(null);
<add> expect(city).to.not.equal(undefined);
<add> done();
<add> });
<add> });
<add>
<add> describe('without state code', function() {
<add> it('should return a string', function(done) {
<add> var city = location.city();
<add> expect(city).to.be.a('string');
<add> expect(city).to.not.equal(null);
<add> expect(city).to.not.equal(undefined);
<add> done();
<add> });
<ide> });
<ide>
<ide> }); |
|
Java | apache-2.0 | dc40901ee131eaec6ee955fd976379c48d69b27f | 0 | smartnetworks/floodlight,kvm2116/floodlight,ZhangMenghao/Floodlight,fazevedo86/floodlight,m1k3lin0/SDNProject,onebsv1/floodlight,dhruvkakadiya/FloodlightLoadBalancer,cbarrin/EAGERFloodlight,alberthitanaya/floodlight-dnscollector,omkale/myfloodlight,fazevedo86/floodlight,duanjp8617/floodlight,rsharo/floodlight,alexreimers/floodlight,rizard/geni-cinema,xuraylei/floodlight,rizard/SOSForFloodlight,deepurple/floodlight,dhruvkakadiya/FloodlightLoadBalancer,rhoybeen/floodlightLB,TidyHuang/floodlight,dhruvkakadiya/FloodlightLoadBalancer,chinmaymhatre91/floodlight,pablotiburcio/AutoManIoT,m1k3lin0/SDNProject,andi-bigswitch/floodlight-oss,rizard/floodlight,thisthat/floodlight-controller,m1k3lin0/SDNProject,ZhangMenghao/Floodlight,moisesber/floodlight,JinWenQiang/FloodlightController,duanjp8617/floodlight,thisthat/floodlight-controller,floodlight/floodlight,AndreMantas/floodlight,duanjp8617/floodlight,rizard/geni-cinema,iluckydonkey/floodlight,geddings/floodlight,iluckydonkey/floodlight,chinmaymhatre91/floodlight,rizard/floodlight,alberthitanaya/floodlight-dnscollector,fazevedo86/floodlight,kvm2116/floodlight,AndreMantas/floodlight,omkale/myfloodlight,chinmaymhatre91/floodlight,deepurple/floodlight,deepurple/floodlight,dhruvkakadiya/FloodlightLoadBalancer,andi-bigswitch/floodlight-oss,chechoRP/floodlight,onebsv1/floodlight,woniu17/floodlight,xuraylei/floodlight,cbarrin/EAGERFloodlight,alberthitanaya/floodlight-dnscollector,rizard/SOSForFloodlight,moisesber/floodlight,rizard/SOSForFloodlight,onebsv1/floodlightworkbench,ZhangMenghao/Floodlight,onebsv1/floodlight,Pengfei-Lu/floodlight,fazevedo86/floodlight,rhoybeen/floodlightLB,rhoybeen/floodlightLB,deepurple/floodlight,rizard/fast-failover-demo,smartnetworks/floodlight,rhoybeen/floodlightLB,JinWenQiang/FloodlightController,rizard/fast-failover-demo,rizard/geni-cinema,alexreimers/floodlight,alexreimers/floodlight,alberthitanaya/floodlight-dnscollector,kvm2116/floodlight,deepurple/floodlight,rsharo/floodlight,rizard/geni-cinema,rsharo/floodlight,chechoRP/floodlight,chechoRP/floodlight,omkale/myfloodlight,iluckydonkey/floodlight,m1k3lin0/SDNProject,Pengfei-Lu/floodlight,TidyHuang/floodlight,TidyHuang/floodlight,woniu17/floodlight,JinWenQiang/FloodlightController,onebsv1/floodlightworkbench,xuraylei/floodlight,geddings/floodlight,duanjp8617/floodlight,netgroup/floodlight,smartnetworks/floodlight,Pengfei-Lu/floodlight,woniu17/floodlight,onebsv1/floodlightworkbench,AndreMantas/floodlight,pablotiburcio/AutoManIoT,rizard/geni-cinema,iluckydonkey/floodlight,ZhangMenghao/Floodlight,chechoRP/floodlight,thisthat/floodlight-controller,iluckydonkey/floodlight,alexreimers/floodlight,thisthat/floodlight-controller,netgroup/floodlight,JinWenQiang/FloodlightController,smartnetworks/floodlight,duanjp8617/floodlight,moisesber/floodlight,dhruvkakadiya/FloodlightLoadBalancer,rizard/fast-failover-demo,chinmaymhatre91/floodlight,pablotiburcio/AutoManIoT,rizard/fast-failover-demo,Pengfei-Lu/floodlight,floodlight/floodlight,TidyHuang/floodlight,cbarrin/EAGERFloodlight,rizard/fast-failover-demo,rhoybeen/floodlightLB,floodlight/floodlight,netgroup/floodlight,chinmaymhatre91/floodlight,netgroup/floodlight,geddings/floodlight,andi-bigswitch/floodlight-oss,chechoRP/floodlight,fazevedo86/floodlight,rizard/floodlight,smartnetworks/floodlight,m1k3lin0/SDNProject,Pengfei-Lu/floodlight,alberthitanaya/floodlight-dnscollector,alexreimers/floodlight,thisthat/floodlight-controller,ZhangMenghao/Floodlight,moisesber/floodlight,woniu17/floodlight,woniu17/floodlight,moisesber/floodlight,andi-bigswitch/floodlight-oss,netgroup/floodlight,JinWenQiang/FloodlightController,TidyHuang/floodlight | /**
* Copyright 2011,2012 Big Switch Networks, Inc.
* Originally created by David Erickson, Stanford University
*
* 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 net.floodlightcontroller.core.web.serializers;
import java.io.IOException;
import java.util.List;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonGenerator.Feature;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import net.floodlightcontroller.core.web.OFStatsTypeStrings;
import net.floodlightcontroller.core.web.StatsReply;
import org.projectfloodlight.openflow.protocol.OFActionType;
import org.projectfloodlight.openflow.protocol.OFBucket;
import org.projectfloodlight.openflow.protocol.OFBucketCounter;
import org.projectfloodlight.openflow.protocol.OFFeaturesReply;
import org.projectfloodlight.openflow.protocol.OFFlowStatsReply;
import org.projectfloodlight.openflow.protocol.OFFlowStatsEntry;
import org.projectfloodlight.openflow.protocol.OFDescStatsReply;
import org.projectfloodlight.openflow.protocol.OFGroupDescStatsEntry;
import org.projectfloodlight.openflow.protocol.OFGroupDescStatsReply;
import org.projectfloodlight.openflow.protocol.OFGroupFeaturesStatsReply;
import org.projectfloodlight.openflow.protocol.OFGroupStatsEntry;
import org.projectfloodlight.openflow.protocol.OFGroupStatsReply;
import org.projectfloodlight.openflow.protocol.OFMeterBandStats;
import org.projectfloodlight.openflow.protocol.OFMeterConfigStatsReply;
import org.projectfloodlight.openflow.protocol.OFMeterFeatures;
import org.projectfloodlight.openflow.protocol.OFMeterFeaturesStatsReply;
import org.projectfloodlight.openflow.protocol.OFMeterStats;
import org.projectfloodlight.openflow.protocol.OFMeterStatsReply;
import org.projectfloodlight.openflow.protocol.OFPortStatsReply;
import org.projectfloodlight.openflow.protocol.OFPortStatsEntry;
import org.projectfloodlight.openflow.protocol.OFPortDescStatsReply;
import org.projectfloodlight.openflow.protocol.OFPortDesc;
import org.projectfloodlight.openflow.protocol.OFTableFeatureProp;
import org.projectfloodlight.openflow.protocol.OFTableFeaturePropApplyActions;
import org.projectfloodlight.openflow.protocol.OFTableFeaturePropApplyActionsMiss;
import org.projectfloodlight.openflow.protocol.OFTableFeaturePropApplySetfield;
import org.projectfloodlight.openflow.protocol.OFTableFeaturePropApplySetfieldMiss;
import org.projectfloodlight.openflow.protocol.OFTableFeaturePropExperimenter;
import org.projectfloodlight.openflow.protocol.OFTableFeaturePropExperimenterMiss;
import org.projectfloodlight.openflow.protocol.OFTableFeaturePropInstructions;
import org.projectfloodlight.openflow.protocol.OFTableFeaturePropInstructionsMiss;
import org.projectfloodlight.openflow.protocol.OFTableFeaturePropMatch;
import org.projectfloodlight.openflow.protocol.OFTableFeaturePropNextTables;
import org.projectfloodlight.openflow.protocol.OFTableFeaturePropNextTablesMiss;
import org.projectfloodlight.openflow.protocol.OFTableFeaturePropWildcards;
import org.projectfloodlight.openflow.protocol.OFTableFeaturePropWriteActions;
import org.projectfloodlight.openflow.protocol.OFTableFeaturePropWriteActionsMiss;
import org.projectfloodlight.openflow.protocol.OFTableFeaturePropWriteSetfield;
import org.projectfloodlight.openflow.protocol.OFTableFeaturePropWriteSetfieldMiss;
import org.projectfloodlight.openflow.protocol.OFTableFeatures;
import org.projectfloodlight.openflow.protocol.OFTableFeaturesStatsReply;
import org.projectfloodlight.openflow.protocol.OFTableStatsEntry;
import org.projectfloodlight.openflow.protocol.OFTableStatsReply;
import org.projectfloodlight.openflow.protocol.actionid.OFActionId;
import org.projectfloodlight.openflow.protocol.instructionid.OFInstructionId;
import org.projectfloodlight.openflow.protocol.meterband.OFMeterBand;
import org.projectfloodlight.openflow.protocol.meterband.OFMeterBandDrop;
import org.projectfloodlight.openflow.protocol.meterband.OFMeterBandDscpRemark;
import org.projectfloodlight.openflow.protocol.meterband.OFMeterBandExperimenter;
import org.projectfloodlight.openflow.protocol.ver13.OFFlowModFlagsSerializerVer13;
import org.projectfloodlight.openflow.protocol.ver13.OFMeterBandTypeSerializerVer13;
// Use Loxigen's serializer
import org.projectfloodlight.openflow.protocol.ver13.OFPortFeaturesSerializerVer13;
import org.projectfloodlight.openflow.protocol.ver13.OFStatsReplyFlagsSerializerVer13;
import org.projectfloodlight.openflow.protocol.ver13.OFTableFeaturePropTypeSerializerVer13;
import org.projectfloodlight.openflow.protocol.ver12.OFFlowModFlagsSerializerVer12;
import org.projectfloodlight.openflow.protocol.ver12.OFPortConfigSerializerVer12;
import org.projectfloodlight.openflow.protocol.ver12.OFPortFeaturesSerializerVer12;
import org.projectfloodlight.openflow.protocol.ver12.OFPortStateSerializerVer12;
import org.projectfloodlight.openflow.protocol.ver12.OFStatsReplyFlagsSerializerVer12;
import org.projectfloodlight.openflow.protocol.ver11.OFFlowModFlagsSerializerVer11;
import org.projectfloodlight.openflow.protocol.ver11.OFPortConfigSerializerVer11;
import org.projectfloodlight.openflow.protocol.ver11.OFPortFeaturesSerializerVer11;
import org.projectfloodlight.openflow.protocol.ver11.OFPortStateSerializerVer11;
import org.projectfloodlight.openflow.protocol.ver11.OFStatsReplyFlagsSerializerVer11;
import org.projectfloodlight.openflow.protocol.ver10.OFPortConfigSerializerVer10;
import org.projectfloodlight.openflow.protocol.ver10.OFPortFeaturesSerializerVer10;
import org.projectfloodlight.openflow.protocol.ver10.OFPortStateSerializerVer10;
import org.projectfloodlight.openflow.protocol.ver10.OFStatsReplyFlagsSerializerVer10;
import org.projectfloodlight.openflow.protocol.ver13.OFPortStateSerializerVer13;
import org.projectfloodlight.openflow.protocol.ver13.OFPortConfigSerializerVer13;
import org.projectfloodlight.openflow.protocol.ver14.OFFlowModFlagsSerializerVer14;
import org.projectfloodlight.openflow.protocol.ver14.OFStatsReplyFlagsSerializerVer14;
import org.projectfloodlight.openflow.protocol.OFAggregateStatsReply;
import org.projectfloodlight.openflow.protocol.OFVersion;
import org.projectfloodlight.openflow.types.U32;
import org.projectfloodlight.openflow.types.U8;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Serialize any OFStatsReply or OFFeaturesReply in JSON
* wrapped by a StatsReply object.
*
* Use automatically by Jackson via JsonSerialize(using=StatsReplySerializer.class),
* or use the static functions within this class to serializer a specific OFStatType
* within another serializer.
*
* @author Ryan Izard, [email protected], [email protected]
*/
public class StatsReplySerializer extends JsonSerializer<StatsReply> {
protected static Logger logger = LoggerFactory.getLogger(StatsReplySerializer.class);
@SuppressWarnings("unchecked")
@Override
public void serialize(StatsReply reply, JsonGenerator jGen, SerializerProvider serializer) throws IOException, JsonProcessingException {
// Return a nice error to user if the request we're about to serialize was bad
if (reply.getValues() == null) {
jGen.writeStartObject();
jGen.writeObjectFieldStart("ERROR");
jGen.writeStringField(" ", "An error has occurred while proccesing your request,");
jGen.writeStringField(" *", "which might be due to one or more of the following:");
jGen.writeStringField(" * ", "-- An invalid DPID and/or stats/features request.");
jGen.writeStringField(" **", "-- The switch is not connected to the controller.");
jGen.writeStringField("* ", "-- The request specified is not supported by the switch's OpenFlow version.");
jGen.writeEndObject();
jGen.writeObjectFieldStart("Valid statistics and features strings are:");
jGen.writeStringField("1)", OFStatsTypeStrings.AGGREGATE);
jGen.writeStringField("2)", OFStatsTypeStrings.DESC);
jGen.writeStringField("3)", OFStatsTypeStrings.EXPERIMENTER);
jGen.writeStringField("4)", OFStatsTypeStrings.FEATURES);
jGen.writeStringField("5)", OFStatsTypeStrings.FLOW);
jGen.writeStringField("6)", OFStatsTypeStrings.GROUP);
jGen.writeStringField("7)", OFStatsTypeStrings.GROUP_DESC);
jGen.writeStringField("8)", OFStatsTypeStrings.GROUP_FEATURES);
jGen.writeStringField("9)", OFStatsTypeStrings.METER);
jGen.writeStringField("A)", OFStatsTypeStrings.METER_CONFIG);
jGen.writeStringField("B)", OFStatsTypeStrings.METER_FEATURES);
jGen.writeStringField("C)", OFStatsTypeStrings.PORT);
jGen.writeStringField("D)", OFStatsTypeStrings.PORT_DESC);
jGen.writeStringField("E)", OFStatsTypeStrings.QUEUE);
jGen.writeStringField("F)", OFStatsTypeStrings.TABLE);
jGen.writeStringField("G)", OFStatsTypeStrings.TABLE_FEATURES);
jGen.writeEndObject();
jGen.writeEndObject();
return;
}
jGen.configure(Feature.WRITE_NUMBERS_AS_STRINGS, true); // IMHO this just looks nicer and is easier to read if everything is quoted
jGen.writeStartObject();
if (reply.getStatType() == null) { // must be an OFFeaturesReply. getValues() was already checked for null above.
serializeFeaturesReply((OFFeaturesReply) reply.getValues(), jGen);
} else {
switch (reply.getStatType()) {
case PORT:
serializePortReply((List<OFPortStatsReply>) reply.getValues(), jGen);
break;
case QUEUE:
// handle queue
break;
case FLOW:
serializeFlowReply((List<OFFlowStatsReply>) reply.getValues(), jGen);
break;
case AGGREGATE:
serializeAggregateReply((List<OFAggregateStatsReply>) reply.getValues(), jGen);
break;
case DESC:
serializeDescReply((List<OFDescStatsReply>) reply.getValues(), jGen);
break;
case GROUP:
serializeGroupReply((List<OFGroupStatsReply>) reply.getValues(), jGen);
break;
case GROUP_DESC:
serializeGroupDescReply((List<OFGroupDescStatsReply>) reply.getValues(), jGen);
break;
case GROUP_FEATURES:
serializeGroupFeaturesReply((List<OFGroupFeaturesStatsReply>) reply.getValues(), jGen);
break;
case METER:
serializeMeterReply((List<OFMeterStatsReply>) reply.getValues(), jGen);
break;
case METER_CONFIG:
serializeMeterConfigReply((List<OFMeterConfigStatsReply>) reply.getValues(), jGen);
break;
case METER_FEATURES:
serializeMeterFeaturesReply((List<OFMeterFeaturesStatsReply>) reply.getValues(), jGen);
break;
case TABLE:
serializeTableReply((List<OFTableStatsReply>) reply.getValues(), jGen);
break;
case TABLE_FEATURES:
serializeTableFeaturesReply((List<OFTableFeaturesStatsReply>) reply.getValues(), jGen);
break;
case PORT_DESC:
serializePortDescReply((List<OFPortDescStatsReply>) reply.getValues(), jGen);
break;
case EXPERIMENTER:
break;
default:
break;
}
}
jGen.writeEndObject();
}
public static void serializeFeaturesReply(OFFeaturesReply fr, JsonGenerator jGen) throws IOException, JsonProcessingException {
/* Common to All OF Versions */
jGen.writeStringField("capabilities", fr.getCapabilities().toString());
jGen.writeStringField("dpid", fr.getDatapathId().toString());
jGen.writeNumberField("buffers", fr.getNBuffers());
jGen.writeNumberField("tables", fr.getNTables());
jGen.writeStringField("version", fr.getVersion().toString());
if (fr.getVersion().compareTo(OFVersion.OF_13) < 0) { // OF1.3+ break this out into port_config
serializePortDesc(fr.getPorts(), jGen);
}
if (fr.getVersion().compareTo(OFVersion.OF_10) == 0) {
String actions = "[";
for (OFActionType action : fr.getActions()) {
actions = actions + action.toString() + ", ";
}
actions = actions.substring(0, actions.length() - 2); // remove ending space+comma
actions = actions + "]";
jGen.writeStringField("actions", actions);
}
}
/***
* Serializes the Group Statistics Reply
* @author Naveen
* @param groupReplies
* @param jGen
* @throws IOException
* @throws JsonProcessingException
*/
public static void serializeGroupReply(List<OFGroupStatsReply> groupReplies, JsonGenerator jGen) throws IOException, JsonProcessingException{
OFGroupStatsReply groupReply = groupReplies.get(0); // we will get only one GroupReply and it will contains many OFGroupStatsEntry
jGen.writeStringField("version", groupReply.getVersion().toString()); //return the enum name
jGen.writeFieldName("group");
jGen.writeStartArray();
for(OFGroupStatsEntry entry : groupReply.getEntries()) {
jGen.writeStartObject();
jGen.writeStringField("groupNumber",entry.getGroup().toString());
jGen.writeNumberField("refCount", entry.getRefCount());
jGen.writeNumberField("packetCount", entry.getPacketCount().getValue());
jGen.writeNumberField("byteCount", entry.getByteCount().getValue());
jGen.writeFieldName("bucketCounters");
jGen.writeStartArray();
for(OFBucketCounter bCounter : entry.getBucketStats()) {
jGen.writeStartObject();
jGen.writeNumberField("packetCount", bCounter.getPacketCount().getValue());
jGen.writeNumberField("byteCount", bCounter.getByteCount().getValue());
jGen.writeEndObject();
}//end of for loop - BucketCounter
jGen.writeEndArray();
if (OFVersion.OF_13 == entry.getVersion()) {
jGen.writeNumberField("durationSec", entry.getDurationSec());
jGen.writeNumberField("durationNsec", entry.getDurationNsec());
}
jGen.writeEndObject();
}//end of for loop - groupStats
jGen.writeEndArray();
}
/***
* Serializes Group Desc Reply
* @author Naveen
* @param groupDescReplies
* @param jGen
* @throws IOException
* @throws JsonProcessingException
*/
public static void serializeGroupDescReply(List<OFGroupDescStatsReply> groupDescReplies, JsonGenerator jGen) throws IOException, JsonProcessingException{
OFGroupDescStatsReply groupDescReply = groupDescReplies.get(0);
jGen.writeStringField("version", groupDescReply.getVersion().toString()); //return the enum name
jGen.writeFieldName("groupDesc");
jGen.writeStartArray();
for(OFGroupDescStatsEntry entry : groupDescReply.getEntries()) {
jGen.writeStartObject();
jGen.writeStringField("groupType",entry.getGroupType().toString());
jGen.writeStringField("groupNumber",entry.getGroup().toString());
jGen.writeFieldName("buckets");
jGen.writeStartArray();
for(OFBucket buckets : entry.getBuckets()) {
jGen.writeStartObject();
jGen.writeNumberField("weight", buckets.getWeight());
jGen.writeNumberField("watchPortNumber", buckets.getWatchPort().getPortNumber());
jGen.writeStringField("watchGroup", buckets.getWatchGroup().toString());
OFActionListSerializer.serializeActions(jGen, buckets.getActions());
jGen.writeEndObject();
}//End of for loop - buckets
jGen.writeEndArray();//end of buckets
jGen.writeEndObject();//end of group Desc iteration
}//End of for loop - GroupDescStats
jGen.writeEndArray();//end of group Desc
}
/***
* Serializes Group Feature Reply
* @author Naveen
* @param groupFeaturesReplies
* @param jGen
* @throws IOException
* @throws JsonProcessingException
*/
public static void serializeGroupFeaturesReply(List<OFGroupFeaturesStatsReply> groupFeaturesReplies, JsonGenerator jGen) throws IOException, JsonProcessingException{
OFGroupFeaturesStatsReply groupFeaturesReply = groupFeaturesReplies.get(0);
jGen.writeStringField("version", groupFeaturesReply.getVersion().toString()); //return the enum name
jGen.writeFieldName("groupFeatures");
jGen.writeStartObject();
jGen.writeNumberField("capabilities",groupFeaturesReply.getCapabilities());
jGen.writeNumberField("maxGroupsAll",groupFeaturesReply.getMaxGroupsAll());
jGen.writeNumberField("maxGroupsSelect",groupFeaturesReply.getMaxGroupsSelect());
jGen.writeNumberField("maxGroupsIndirect",groupFeaturesReply.getMaxGroupsIndirect());
jGen.writeNumberField("maxGroupsFf",groupFeaturesReply.getMaxGroupsFf());
jGen.writeNumberField("actionsAll",groupFeaturesReply.getActionsAll());
jGen.writeNumberField("actionsSelect",groupFeaturesReply.getActionsSelect());
jGen.writeNumberField("actionsIndirect",groupFeaturesReply.getActionsIndirect());
jGen.writeNumberField("actionsFf",groupFeaturesReply.getActionsFf());
jGen.writeEndObject();//end of group Feature
}
/***
* Serializes the Meter Statistics Reply
* @author Naveen
* @param meterReplies
* @param jGen
* @throws IOException
* @throws JsonProcessingException
*/
public static void serializeMeterReply(List<OFMeterStatsReply> meterReplies, JsonGenerator jGen) throws IOException, JsonProcessingException{
OFMeterStatsReply meterReply = meterReplies.get(0); // we will get only one meterReply and it will contains many OFMeterStatsEntry ?
jGen.writeStringField("version", meterReply.getVersion().toString()); //return the enum name
jGen.writeFieldName("meter");
jGen.writeStartArray();
for(OFMeterStats entry : meterReply.getEntries()) {
jGen.writeStartObject();
jGen.writeNumberField("meterId",entry.getMeterId());
jGen.writeNumberField("flowCount", entry.getFlowCount());
jGen.writeNumberField("packetInCount", entry.getPacketInCount().getValue());
jGen.writeNumberField("byteInCount", entry.getByteInCount().getValue());
jGen.writeFieldName("meterBandStats");
jGen.writeStartArray();
for(OFMeterBandStats bandStats : entry.getBandStats()) {
jGen.writeStartObject();
jGen.writeNumberField("packetBandCount", bandStats.getPacketBandCount().getValue());
jGen.writeNumberField("byteBandCount", bandStats.getByteBandCount().getValue());
jGen.writeEndObject();
}//End of for loop - bandStats
jGen.writeEndArray();
jGen.writeNumberField("durationSec", entry.getDurationSec());
jGen.writeNumberField("durationNsec", entry.getDurationNsec());
jGen.writeEndObject();
}//End of for loop - MeterStats
jGen.writeEndArray();
}
/***
* Serializes Meter Feature Reply
* @author Naveen
* @param meterFeaturesReplies
* @param jGen
* @throws IOException
* @throws JsonProcessingException
*/
public static void serializeMeterFeaturesReply(List<OFMeterFeaturesStatsReply> meterFeaturesReplies, JsonGenerator jGen) throws IOException, JsonProcessingException{
OFMeterFeaturesStatsReply meterFeaturesReply = meterFeaturesReplies.get(0);
jGen.writeStringField("version", meterFeaturesReply.getVersion().toString()); //return the enum name
OFMeterFeatures meterFeatures = meterFeaturesReply.getFeatures();
jGen.writeFieldName("meterFeatures");
jGen.writeStartObject();
jGen.writeNumberField("maxGroupsAll",meterFeatures.getMaxMeter());
jGen.writeNumberField("maxGroupsSelect",meterFeatures.getBandTypes());
jGen.writeNumberField("capabilities",meterFeatures.getCapabilities());
jGen.writeNumberField("maxGroupsIndirect",meterFeatures.getMaxBands());
jGen.writeNumberField("maxGroupsFf",meterFeatures.getMaxColor());
jGen.writeEndObject();//end of group Feature
}
/***
* Serializes Meter Config Reply
* @author Naveen
* @param meterConfigReplies
* @param jGen
* @throws IOException
* @throws JsonProcessingException
*/
public static void serializeMeterConfigReply(List<OFMeterConfigStatsReply> meterConfigReplies, JsonGenerator jGen) throws IOException, JsonProcessingException{
OFMeterConfigStatsReply meterConfigReply = meterConfigReplies.get(0);
jGen.writeStringField("version", meterConfigReply.getVersion().toString()); //return the enum name
jGen.writeFieldName("meterConfig");
jGen.writeStartArray();
for(OFMeterBand band : meterConfigReply.getEntries()) {
jGen.writeStartObject();
short type = (short)band.getType();
jGen.writeNumberField("bandType",type);
switch (type) {
case OFMeterBandTypeSerializerVer13.DROP_VAL:
OFMeterBandDrop bandDrop = (OFMeterBandDrop) band;
jGen.writeNumberField("rate", bandDrop.getRate());
jGen.writeNumberField("burstSize", bandDrop.getBurstSize());
break;
case OFMeterBandTypeSerializerVer13.DSCP_REMARK_VAL:
OFMeterBandDscpRemark bandDscp = (OFMeterBandDscpRemark) band;
jGen.writeNumberField("rate", bandDscp.getRate());
jGen.writeNumberField("burstSize", bandDscp.getBurstSize());
jGen.writeNumberField("precLevel", bandDscp.getPrecLevel());
break;
case OFMeterBandTypeSerializerVer13.EXPERIMENTER_VAL:
OFMeterBandExperimenter bandExp = (OFMeterBandExperimenter) band;
jGen.writeNumberField("rate", bandExp.getRate());
jGen.writeNumberField("burstSize", bandExp.getBurstSize());
jGen.writeNumberField("experimenter", bandExp.getExperimenter());
break;
default:
// shouldn't ever get here
break;
}//end of Switch Case
jGen.writeEndObject();
}//end of for loop
jGen.writeEndArray();
}
/***
* Serializes Table Statistics
* @author Naveen
* @param tableReplies
* @param jGen
* @throws IOException
* @throws JsonProcessingException
*/
public static void serializeTableReply(List<OFTableStatsReply> tableReplies, JsonGenerator jGen) throws IOException, JsonProcessingException{
OFTableStatsReply tableReply = tableReplies.get(0); // we will get only one tableReply and it will contains many OFTableStatsEntry ?
jGen.writeStringField("version", tableReply.getVersion().toString()); //return the enum name
jGen.writeFieldName("table");
jGen.writeStartArray();
for(OFTableStatsEntry entry : tableReply.getEntries()) {
jGen.writeStartObject();
//Fields common to all OF versions
//For OF 1.3, only these fields are applicable
jGen.writeStringField("tableId",entry.getTableId().toString());
jGen.writeNumberField("activeCount", entry.getActiveCount());
jGen.writeNumberField("lookUpCount", entry.getLookupCount().getValue());
jGen.writeNumberField("matchCount", entry.getMatchedCount().getValue());
//Fields Applicable only for specific Versions
switch (entry.getVersion()) {
case OF_12:
//Fields applicable only to OF 1.2
jGen.writeNumberField("writeSetFields", entry.getWriteSetfields().getValue());
jGen.writeNumberField("applySetFields", entry.getApplySetfields().getValue());
jGen.writeNumberField("metaDataMatch", entry.getMetadataMatch().getValue());
jGen.writeNumberField("metaDataWrite", entry.getMetadataWrite().getValue());
case OF_11:
//Fields applicable to OF 1.1 & 1.2
jGen.writeStringField("match", entry.getMatch().toString());
jGen.writeNumberField("instructions", entry.getInstructions());
jGen.writeNumberField("writeActions", entry.getWriteActions());
jGen.writeNumberField("applyActions", entry.getApplyActions());
jGen.writeNumberField("config", entry.getConfig());
case OF_10:
//Fields applicable to OF 1.0, 1.1 & 1.2
jGen.writeStringField("name",entry.getName());
jGen.writeNumberField("wildcards", entry.getWildcards());
jGen.writeNumberField("maxEntries", entry.getMaxEntries());
break;
default:
//no extra fields for OF_13
break;
}//End of switch case
jGen.writeEndObject();
}//End of for loop
jGen.writeEndArray();
}
/***
* Serializes Table Features Reply
* @author Naveen
* @param tableFeaturesReplies
* @param jGen
* @throws IOException
* @throws JsonProcessingException
*/
public static void serializeTableFeaturesReply(List<OFTableFeaturesStatsReply> tableFeaturesReplies, JsonGenerator jGen) throws IOException, JsonProcessingException{
OFTableFeaturesStatsReply tableFeaturesReply = tableFeaturesReplies.get(0);
jGen.writeStringField("version", tableFeaturesReply.getVersion().toString()); //return the enum name
jGen.writeFieldName("tableFeatures");
jGen.writeStartArray();
for(OFTableFeatures tableFeature : tableFeaturesReply.getEntries()) {
jGen.writeStartObject();
jGen.writeNumberField("tableId", tableFeature.getTableId().getValue());
jGen.writeStringField("name", tableFeature.getName());
jGen.writeNumberField("metadataMatch", tableFeature.getMetadataMatch().getValue());
jGen.writeNumberField("metadataWrite", tableFeature.getMetadataWrite().getValue());
jGen.writeNumberField("config", tableFeature.getConfig());
jGen.writeNumberField("maxEntries", tableFeature.getMaxEntries());
jGen.writeFieldName("properties");
jGen.writeStartArray();
for (OFTableFeatureProp properties : tableFeature.getProperties()) {
jGen.writeStartObject();
short type = (short)properties.getType();
jGen.writeNumberField("tableFeaturePropType",type);
switch (type) {
case OFTableFeaturePropTypeSerializerVer13.INSTRUCTIONS_VAL:
OFTableFeaturePropInstructions propInstruct = (OFTableFeaturePropInstructions) properties;
jGen.writeFieldName("instructions");
jGen.writeStartArray();
for (OFInstructionId id : propInstruct.getInstructionIds()) {
jGen.writeStartObject();
jGen.writeString(id.getType().toString());
jGen.writeEndObject();
}
jGen.writeEndArray();
break;
case OFTableFeaturePropTypeSerializerVer13.INSTRUCTIONS_MISS_VAL:
OFTableFeaturePropInstructionsMiss propInstructMiss = (OFTableFeaturePropInstructionsMiss) properties;
jGen.writeFieldName("instructionsMiss");
jGen.writeStartArray();
for (OFInstructionId id : propInstructMiss.getInstructionIds()) {
jGen.writeStartObject();
jGen.writeString(id.getType().toString());
jGen.writeEndObject();
}
jGen.writeEndArray();
break;
case OFTableFeaturePropTypeSerializerVer13.NEXT_TABLES_VAL:
OFTableFeaturePropNextTables propNxtTables = (OFTableFeaturePropNextTables) properties;
jGen.writeFieldName("nextTables");
jGen.writeStartArray();
for (U8 id : propNxtTables.getNextTableIds()) {
jGen.writeStartObject();
jGen.writeNumber(id.getValue());
jGen.writeEndObject();
}
jGen.writeEndArray();
break;
case OFTableFeaturePropTypeSerializerVer13.NEXT_TABLES_MISS_VAL:
OFTableFeaturePropNextTablesMiss propNxtTablesMiss = (OFTableFeaturePropNextTablesMiss) properties;
jGen.writeFieldName("nextTablesMiss");
jGen.writeStartArray();
for (U8 id : propNxtTablesMiss.getNextTableIds()) {
jGen.writeStartObject();
jGen.writeNumber(id.getValue());
jGen.writeEndObject();
}
jGen.writeEndArray();
break;
case OFTableFeaturePropTypeSerializerVer13.WRITE_ACTIONS_VAL:
OFTableFeaturePropWriteActions propWrAct = (OFTableFeaturePropWriteActions) properties;
jGen.writeFieldName("writeActions");
jGen.writeStartArray();
for (OFActionId id : propWrAct.getActionIds()) {
jGen.writeStartObject();
jGen.writeString(id.getType().toString());
jGen.writeEndObject();
}
jGen.writeEndArray();
break;
case OFTableFeaturePropTypeSerializerVer13.WRITE_ACTIONS_MISS_VAL:
OFTableFeaturePropWriteActionsMiss propWrActMiss = (OFTableFeaturePropWriteActionsMiss) properties;
jGen.writeFieldName("writeActionsMiss");
jGen.writeStartArray();
for (OFActionId id : propWrActMiss.getActionIds()) {
jGen.writeStartObject();
jGen.writeString(id.getType().toString());
jGen.writeEndObject();
}
jGen.writeEndArray();
break;
case OFTableFeaturePropTypeSerializerVer13.APPLY_ACTIONS_VAL:
OFTableFeaturePropApplyActions propAppAct = (OFTableFeaturePropApplyActions) properties;
jGen.writeFieldName("applyActions");
jGen.writeStartArray();
for (OFActionId id : propAppAct.getActionIds()) {
jGen.writeStartObject();
jGen.writeString(id.getType().toString());
jGen.writeEndObject();
}
jGen.writeEndArray();
break;
case OFTableFeaturePropTypeSerializerVer13.APPLY_ACTIONS_MISS_VAL:
OFTableFeaturePropApplyActionsMiss propAppActMiss = (OFTableFeaturePropApplyActionsMiss) properties;
jGen.writeFieldName("applyActionsMiss");
jGen.writeStartArray();
for (OFActionId id : propAppActMiss.getActionIds()) {
jGen.writeStartObject();
jGen.writeString(id.getType().toString());
jGen.writeEndObject();
}
jGen.writeEndArray();
break;
case OFTableFeaturePropTypeSerializerVer13.MATCH_VAL:
OFTableFeaturePropMatch propMatch = (OFTableFeaturePropMatch) properties;
jGen.writeFieldName("match");
jGen.writeStartArray();
for (U32 id : propMatch.getOxmIds()) {
jGen.writeStartObject();
jGen.writeNumber(id.getValue());
jGen.writeEndObject();
}
jGen.writeEndArray();
break;
case OFTableFeaturePropTypeSerializerVer13.WILDCARDS_VAL:
OFTableFeaturePropWildcards propWildcards = (OFTableFeaturePropWildcards) properties;
jGen.writeFieldName("wildcards");
jGen.writeStartArray();
for (U32 id : propWildcards.getOxmIds()) {
jGen.writeStartObject();
jGen.writeNumber(id.getValue());
jGen.writeEndObject();
}
jGen.writeEndArray();
break;
case OFTableFeaturePropTypeSerializerVer13.WRITE_SETFIELD_VAL:
OFTableFeaturePropWriteSetfield propWrSetfield = (OFTableFeaturePropWriteSetfield) properties;
jGen.writeFieldName("writeSetfield");
jGen.writeStartArray();
for (U32 id : propWrSetfield.getOxmIds()) {
jGen.writeStartObject();
jGen.writeNumber(id.getValue());
jGen.writeEndObject();
}
jGen.writeEndArray();
break;
case OFTableFeaturePropTypeSerializerVer13.WRITE_SETFIELD_MISS_VAL:
OFTableFeaturePropWriteSetfieldMiss propWrSetfieldMiss = (OFTableFeaturePropWriteSetfieldMiss) properties;
jGen.writeFieldName("writeSetfieldMiss");
jGen.writeStartArray();
for (U32 id : propWrSetfieldMiss.getOxmIds()) {
jGen.writeStartObject();
jGen.writeNumber(id.getValue());
jGen.writeEndObject();
}
jGen.writeEndArray();
break;
case OFTableFeaturePropTypeSerializerVer13.APPLY_SETFIELD_VAL:
OFTableFeaturePropApplySetfield propAppSetfield = (OFTableFeaturePropApplySetfield) properties;
jGen.writeFieldName("applySetfield");
jGen.writeStartArray();
for (U32 id : propAppSetfield.getOxmIds()) {
jGen.writeStartObject();
jGen.writeNumber(id.getValue());
jGen.writeEndObject();
}
jGen.writeEndArray();
break;
case OFTableFeaturePropTypeSerializerVer13.APPLY_SETFIELD_MISS_VAL:
OFTableFeaturePropApplySetfieldMiss propAppSetfieldMiss = (OFTableFeaturePropApplySetfieldMiss) properties;
jGen.writeFieldName("applySetfieldMiss");
jGen.writeStartArray();
for (U32 id : propAppSetfieldMiss.getOxmIds()) {
jGen.writeStartObject();
jGen.writeNumber(id.getValue());
jGen.writeEndObject();
}
jGen.writeEndArray();
break;
case OFTableFeaturePropTypeSerializerVer13.EXPERIMENTER_VAL:
OFTableFeaturePropExperimenter propExp = (OFTableFeaturePropExperimenter) properties;
jGen.writeFieldName("experimenter");
jGen.writeStartObject();
jGen.writeNumberField("subType", propExp.getSubtype());
jGen.writeNumberField("experimenter", propExp.getExperimenter());
jGen.writeStringField("subType", propExp.getExperimenterData().toString());
jGen.writeEndObject();
break;
case OFTableFeaturePropTypeSerializerVer13.EXPERIMENTER_MISS_VAL:
OFTableFeaturePropExperimenterMiss propExpMiss = (OFTableFeaturePropExperimenterMiss) properties;
jGen.writeFieldName("experimenterMiss");
jGen.writeStartObject();
jGen.writeNumberField("subType", propExpMiss.getSubtype());
jGen.writeNumberField("experimenter", propExpMiss.getExperimenter());
jGen.writeStringField("subType", propExpMiss.getExperimenterData().toString());
jGen.writeEndObject();
break;
default:
// shouldn't ever get here
break;
}//end of Switch Case
jGen.writeEndObject();
}//end of for loop - properties
jGen.writeEndObject();
}//end of for loop - features
jGen.writeEndArray();
}
public static void serializePortReply(List<OFPortStatsReply> portReplies, JsonGenerator jGen) throws IOException, JsonProcessingException{
OFPortStatsReply portReply = portReplies.get(0); // we will get only one PortReply and it will contains many OFPortStatsEntry ?
jGen.writeStringField("version", portReply.getVersion().toString()); //return the enum name
jGen.writeFieldName("port");
jGen.writeStartArray();
for(OFPortStatsEntry entry : portReply.getEntries()) {
jGen.writeStartObject();
jGen.writeStringField("portNumber",entry.getPortNo().toString());
jGen.writeNumberField("receivePackets", entry.getRxPackets().getValue());
jGen.writeNumberField("transmitPackets", entry.getTxPackets().getValue());
jGen.writeNumberField("receiveBytes", entry.getRxBytes().getValue());
jGen.writeNumberField("transmitBytes", entry.getTxBytes().getValue());
jGen.writeNumberField("receiveDropped", entry.getRxDropped().getValue());
jGen.writeNumberField("transmitDropped", entry.getTxDropped().getValue());
jGen.writeNumberField("receiveErrors", entry.getRxErrors().getValue());
jGen.writeNumberField("transmitErrors", entry.getTxErrors().getValue());
jGen.writeNumberField("receiveFrameErrors", entry.getRxFrameErr().getValue());
jGen.writeNumberField("receiveOverrunErrors", entry.getRxOverErr().getValue());
jGen.writeNumberField("receiveCRCErrors", entry.getRxCrcErr().getValue());
jGen.writeNumberField("collisions", entry.getCollisions().getValue());
if (OFVersion.OF_13 == entry.getVersion()) {
jGen.writeNumberField("durationSec", entry.getDurationSec());
jGen.writeNumberField("durationNsec", entry.getDurationNsec());
}
jGen.writeEndObject();
}
jGen.writeEndArray();
}
public static void serializeFlowReply(List<OFFlowStatsReply> flowReplies, JsonGenerator jGen) throws IOException, JsonProcessingException{
/* start the array before each reply */
jGen.writeFieldName("flows");
jGen.writeStartArray();
for (OFFlowStatsReply flowReply : flowReplies) { // for each flow stats reply
List<OFFlowStatsEntry> entries = flowReply.getEntries();
for (OFFlowStatsEntry entry : entries) { // for each flow
jGen.writeStartObject();
// list flow stats/info
jGen.writeStringField("version", entry.getVersion().toString()); // return the enum name
jGen.writeNumberField("cookie", entry.getCookie().getValue());
jGen.writeStringField("tableId", entry.getTableId().toString());
jGen.writeNumberField("packetCount", entry.getPacketCount().getValue());
jGen.writeNumberField("byteCount", entry.getByteCount().getValue());
jGen.writeNumberField("durationSeconds", entry.getDurationSec());
jGen.writeNumberField("priority", entry.getPriority());
jGen.writeNumberField("idleTimeoutSec", entry.getIdleTimeout());
jGen.writeNumberField("hardTimeoutSec", entry.getHardTimeout());
switch (entry.getVersion()) {
case OF_10:
// flags not supported
break;
case OF_11:
jGen.writeNumberField("flags", OFFlowModFlagsSerializerVer11.toWireValue(entry.getFlags()));
break;
case OF_12:
jGen.writeNumberField("flags", OFFlowModFlagsSerializerVer12.toWireValue(entry.getFlags()));
break;
case OF_13:
jGen.writeNumberField("flags", OFFlowModFlagsSerializerVer13.toWireValue(entry.getFlags()));
break;
case OF_14:
jGen.writeNumberField("flags", OFFlowModFlagsSerializerVer14.toWireValue(entry.getFlags()));
break;
default:
logger.error("Could not decode OFVersion {}", entry.getVersion());
break;
}
MatchSerializer.serializeMatch(jGen, entry.getMatch());
// handle OF1.1+ instructions with actions within
if (entry.getVersion() == OFVersion.OF_10) {
jGen.writeObjectFieldStart("actions");
OFActionListSerializer.serializeActions(jGen, entry.getActions());
jGen.writeEndObject();
} else {
OFInstructionListSerializer.serializeInstructionList(jGen, entry.getInstructions());
}
jGen.writeEndObject();
} // end for each OFFlowStatsReply entry */
} // end for each OFStatsReply
//jGen.writeEndObject();
jGen.writeEndArray();
} // end method
public static void serializeDescReply(List<OFDescStatsReply> descReplies, JsonGenerator jGen) throws IOException, JsonProcessingException{
OFDescStatsReply descReply = descReplies.get(0); // There is only one descReply from the switch
jGen.writeObjectFieldStart("desc");
jGen.writeStringField("version", descReply.getVersion().toString()); //return the enum name
jGen.writeStringField("manufacturerDescription", descReply.getMfrDesc());
jGen.writeStringField("hardwareDescription", descReply.getHwDesc());
jGen.writeStringField("softwareDescription", descReply.getSwDesc());
jGen.writeStringField("serialNumber", descReply.getSerialNum());
jGen.writeStringField("datapathDescription", descReply.getDpDesc());
jGen.writeEndObject(); // end match
}
public static void serializeAggregateReply(List<OFAggregateStatsReply> aggregateReplies, JsonGenerator jGen) throws IOException, JsonProcessingException{
OFAggregateStatsReply aggregateReply = aggregateReplies.get(0); // There are only one aggregateReply from the switch
jGen.writeObjectFieldStart("aggregate");
jGen.writeStringField("version", aggregateReply.getVersion().toString()); //return the enum name
jGen.writeNumberField("flowCount", aggregateReply.getFlowCount());
jGen.writeNumberField("packetCount", aggregateReply.getPacketCount().getValue());
jGen.writeNumberField("byteCount", aggregateReply.getByteCount().getValue());
switch (aggregateReply.getVersion()) {
case OF_10:
jGen.writeNumberField("flags", OFStatsReplyFlagsSerializerVer10.toWireValue(aggregateReply.getFlags()));
break;
case OF_11:
jGen.writeNumberField("flags", OFStatsReplyFlagsSerializerVer11.toWireValue(aggregateReply.getFlags()));
break;
case OF_12:
jGen.writeNumberField("flags", OFStatsReplyFlagsSerializerVer12.toWireValue(aggregateReply.getFlags()));
break;
case OF_13:
jGen.writeNumberField("flags", OFStatsReplyFlagsSerializerVer13.toWireValue(aggregateReply.getFlags()));
break;
case OF_14:
jGen.writeNumberField("flags", OFStatsReplyFlagsSerializerVer14.toWireValue(aggregateReply.getFlags()));
break;
default:
break;
}
jGen.writeEndObject(); // end match
}
public static void serializePortDescReply(List<OFPortDescStatsReply> portDescReplies, JsonGenerator jGen) throws IOException, JsonProcessingException{
OFPortDescStatsReply portDescReply = portDescReplies.get(0); // we will get only one PortDescReply and it will contains many OFPortDescStatsEntry ?
jGen.writeStringField("version", portDescReply.getVersion().toString()); //return the enum name
serializePortDesc(portDescReply.getEntries(), jGen);
}
public static void serializePortDesc(List<OFPortDesc> portDescList, JsonGenerator jGen) throws IOException, JsonProcessingException {
jGen.writeFieldName("portDesc");
jGen.writeStartArray();
for(OFPortDesc entry : portDescList) {
jGen.writeStartObject();
jGen.writeStringField("portNumber",entry.getPortNo().toString());
jGen.writeStringField("hardwareAddress", entry.getHwAddr().toString());
jGen.writeStringField("name", entry.getName());
switch(entry.getVersion()) {
case OF_10:
jGen.writeNumberField("config", OFPortConfigSerializerVer10.toWireValue(entry.getConfig()));
jGen.writeNumberField("state", OFPortStateSerializerVer10.toWireValue(entry.getState()));
jGen.writeNumberField("currentFeatures", OFPortFeaturesSerializerVer10.toWireValue(entry.getCurr()));
jGen.writeNumberField("advertisedFeatures", OFPortFeaturesSerializerVer10.toWireValue(entry.getAdvertised()));
jGen.writeNumberField("supportedFeatures", OFPortFeaturesSerializerVer10.toWireValue(entry.getSupported()));
jGen.writeNumberField("peerFeatures", OFPortFeaturesSerializerVer10.toWireValue(entry.getPeer()));
break;
case OF_11:
jGen.writeNumberField("config", OFPortConfigSerializerVer11.toWireValue(entry.getConfig()));
jGen.writeNumberField("state", OFPortStateSerializerVer11.toWireValue(entry.getState()));
jGen.writeNumberField("currentFeatures", OFPortFeaturesSerializerVer11.toWireValue(entry.getCurr()));
jGen.writeNumberField("advertisedFeatures", OFPortFeaturesSerializerVer11.toWireValue(entry.getAdvertised()));
jGen.writeNumberField("supportedFeatures", OFPortFeaturesSerializerVer11.toWireValue(entry.getSupported()));
jGen.writeNumberField("peerFeatures", OFPortFeaturesSerializerVer11.toWireValue(entry.getPeer()));
break;
case OF_12:
jGen.writeNumberField("config", OFPortConfigSerializerVer12.toWireValue(entry.getConfig()));
jGen.writeNumberField("state", OFPortStateSerializerVer12.toWireValue(entry.getState()));
jGen.writeNumberField("currentFeatures", OFPortFeaturesSerializerVer12.toWireValue(entry.getCurr()));
jGen.writeNumberField("advertisedFeatures", OFPortFeaturesSerializerVer12.toWireValue(entry.getAdvertised()));
jGen.writeNumberField("supportedFeatures", OFPortFeaturesSerializerVer12.toWireValue(entry.getSupported()));
jGen.writeNumberField("peerFeatures", OFPortFeaturesSerializerVer12.toWireValue(entry.getPeer()));
break;
case OF_13:
jGen.writeNumberField("config", OFPortConfigSerializerVer13.toWireValue(entry.getConfig()));
jGen.writeNumberField("state", OFPortStateSerializerVer13.toWireValue(entry.getState()));
jGen.writeNumberField("currentFeatures", OFPortFeaturesSerializerVer13.toWireValue(entry.getCurr()));
jGen.writeNumberField("advertisedFeatures", OFPortFeaturesSerializerVer13.toWireValue(entry.getAdvertised()));
jGen.writeNumberField("supportedFeatures", OFPortFeaturesSerializerVer13.toWireValue(entry.getSupported()));
jGen.writeNumberField("peerFeatures", OFPortFeaturesSerializerVer13.toWireValue(entry.getPeer()));
break;
case OF_14:
// TODO
logger.error("OF1.4 OFPortDesc serializer not implemented");
}
if (OFVersion.OF_10 != entry.getVersion()) {
jGen.writeNumberField("currSpeed",entry.getCurrSpeed());
jGen.writeNumberField("maxSpeed",entry.getMaxSpeed());
}
jGen.writeEndObject();
}
jGen.writeEndArray();
}
}
| src/main/java/net/floodlightcontroller/core/web/serializers/StatsReplySerializer.java | /**
* Copyright 2011,2012 Big Switch Networks, Inc.
* Originally created by David Erickson, Stanford University
*
* 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 net.floodlightcontroller.core.web.serializers;
import java.io.IOException;
import java.util.List;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonGenerator.Feature;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import net.floodlightcontroller.core.web.OFStatsTypeStrings;
import net.floodlightcontroller.core.web.StatsReply;
import org.projectfloodlight.openflow.protocol.OFActionType;
import org.projectfloodlight.openflow.protocol.OFBucket;
import org.projectfloodlight.openflow.protocol.OFBucketCounter;
import org.projectfloodlight.openflow.protocol.OFFeaturesReply;
import org.projectfloodlight.openflow.protocol.OFFlowStatsReply;
import org.projectfloodlight.openflow.protocol.OFFlowStatsEntry;
import org.projectfloodlight.openflow.protocol.OFDescStatsReply;
import org.projectfloodlight.openflow.protocol.OFGroupDescStatsEntry;
import org.projectfloodlight.openflow.protocol.OFGroupDescStatsReply;
import org.projectfloodlight.openflow.protocol.OFGroupFeaturesStatsReply;
import org.projectfloodlight.openflow.protocol.OFGroupStatsEntry;
import org.projectfloodlight.openflow.protocol.OFGroupStatsReply;
import org.projectfloodlight.openflow.protocol.OFMeterBandStats;
import org.projectfloodlight.openflow.protocol.OFMeterConfigStatsReply;
import org.projectfloodlight.openflow.protocol.OFMeterFeatures;
import org.projectfloodlight.openflow.protocol.OFMeterFeaturesStatsReply;
import org.projectfloodlight.openflow.protocol.OFMeterStats;
import org.projectfloodlight.openflow.protocol.OFMeterStatsReply;
import org.projectfloodlight.openflow.protocol.OFPortStatsReply;
import org.projectfloodlight.openflow.protocol.OFPortStatsEntry;
import org.projectfloodlight.openflow.protocol.OFPortDescStatsReply;
import org.projectfloodlight.openflow.protocol.OFPortDesc;
import org.projectfloodlight.openflow.protocol.OFTableFeatureProp;
import org.projectfloodlight.openflow.protocol.OFTableFeaturePropApplyActions;
import org.projectfloodlight.openflow.protocol.OFTableFeaturePropApplyActionsMiss;
import org.projectfloodlight.openflow.protocol.OFTableFeaturePropApplySetfield;
import org.projectfloodlight.openflow.protocol.OFTableFeaturePropApplySetfieldMiss;
import org.projectfloodlight.openflow.protocol.OFTableFeaturePropExperimenter;
import org.projectfloodlight.openflow.protocol.OFTableFeaturePropExperimenterMiss;
import org.projectfloodlight.openflow.protocol.OFTableFeaturePropInstructions;
import org.projectfloodlight.openflow.protocol.OFTableFeaturePropInstructionsMiss;
import org.projectfloodlight.openflow.protocol.OFTableFeaturePropMatch;
import org.projectfloodlight.openflow.protocol.OFTableFeaturePropNextTables;
import org.projectfloodlight.openflow.protocol.OFTableFeaturePropNextTablesMiss;
import org.projectfloodlight.openflow.protocol.OFTableFeaturePropWildcards;
import org.projectfloodlight.openflow.protocol.OFTableFeaturePropWriteActions;
import org.projectfloodlight.openflow.protocol.OFTableFeaturePropWriteActionsMiss;
import org.projectfloodlight.openflow.protocol.OFTableFeaturePropWriteSetfield;
import org.projectfloodlight.openflow.protocol.OFTableFeaturePropWriteSetfieldMiss;
import org.projectfloodlight.openflow.protocol.OFTableFeatures;
import org.projectfloodlight.openflow.protocol.OFTableFeaturesStatsReply;
import org.projectfloodlight.openflow.protocol.OFTableStatsEntry;
import org.projectfloodlight.openflow.protocol.OFTableStatsReply;
import org.projectfloodlight.openflow.protocol.actionid.OFActionId;
import org.projectfloodlight.openflow.protocol.instructionid.OFInstructionId;
import org.projectfloodlight.openflow.protocol.meterband.OFMeterBand;
import org.projectfloodlight.openflow.protocol.meterband.OFMeterBandDrop;
import org.projectfloodlight.openflow.protocol.meterband.OFMeterBandDscpRemark;
import org.projectfloodlight.openflow.protocol.meterband.OFMeterBandExperimenter;
import org.projectfloodlight.openflow.protocol.ver13.OFFlowModFlagsSerializerVer13;
import org.projectfloodlight.openflow.protocol.ver13.OFMeterBandTypeSerializerVer13;
// Use Loxigen's serializer
import org.projectfloodlight.openflow.protocol.ver13.OFPortFeaturesSerializerVer13;
import org.projectfloodlight.openflow.protocol.ver13.OFStatsReplyFlagsSerializerVer13;
import org.projectfloodlight.openflow.protocol.ver13.OFTableFeaturePropTypeSerializerVer13;
import org.projectfloodlight.openflow.protocol.ver12.OFFlowModFlagsSerializerVer12;
import org.projectfloodlight.openflow.protocol.ver12.OFPortConfigSerializerVer12;
import org.projectfloodlight.openflow.protocol.ver12.OFPortFeaturesSerializerVer12;
import org.projectfloodlight.openflow.protocol.ver12.OFPortStateSerializerVer12;
import org.projectfloodlight.openflow.protocol.ver12.OFStatsReplyFlagsSerializerVer12;
import org.projectfloodlight.openflow.protocol.ver11.OFFlowModFlagsSerializerVer11;
import org.projectfloodlight.openflow.protocol.ver11.OFPortConfigSerializerVer11;
import org.projectfloodlight.openflow.protocol.ver11.OFPortFeaturesSerializerVer11;
import org.projectfloodlight.openflow.protocol.ver11.OFPortStateSerializerVer11;
import org.projectfloodlight.openflow.protocol.ver11.OFStatsReplyFlagsSerializerVer11;
import org.projectfloodlight.openflow.protocol.ver10.OFPortConfigSerializerVer10;
import org.projectfloodlight.openflow.protocol.ver10.OFPortFeaturesSerializerVer10;
import org.projectfloodlight.openflow.protocol.ver10.OFPortStateSerializerVer10;
import org.projectfloodlight.openflow.protocol.ver10.OFStatsReplyFlagsSerializerVer10;
import org.projectfloodlight.openflow.protocol.ver13.OFPortStateSerializerVer13;
import org.projectfloodlight.openflow.protocol.ver13.OFPortConfigSerializerVer13;
import org.projectfloodlight.openflow.protocol.ver14.OFFlowModFlagsSerializerVer14;
import org.projectfloodlight.openflow.protocol.ver14.OFStatsReplyFlagsSerializerVer14;
import org.projectfloodlight.openflow.protocol.OFAggregateStatsReply;
import org.projectfloodlight.openflow.protocol.OFVersion;
import org.projectfloodlight.openflow.types.U32;
import org.projectfloodlight.openflow.types.U8;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Serialize any OFStatsReply or OFFeaturesReply in JSON
* wrapped by a StatsReply object.
*
* Use automatically by Jackson via JsonSerialize(using=StatsReplySerializer.class),
* or use the static functions within this class to serializer a specific OFStatType
* within another serializer.
*
* @author Ryan Izard, [email protected], [email protected]
*/
public class StatsReplySerializer extends JsonSerializer<StatsReply> {
protected static Logger logger = LoggerFactory.getLogger(StatsReplySerializer.class);
@SuppressWarnings("unchecked")
@Override
public void serialize(StatsReply reply, JsonGenerator jGen, SerializerProvider serializer) throws IOException, JsonProcessingException {
// Return a nice error to user if the request we're about to serialize was bad
if (reply.getValues() == null) {
jGen.writeStartObject();
jGen.writeObjectFieldStart("ERROR");
jGen.writeStringField(" ", "An error has occurred while proccesing your request,");
jGen.writeStringField(" *", "which might be due to one or more of the following:");
jGen.writeStringField(" * ", "-- An invalid DPID and/or stats/features request.");
jGen.writeStringField(" **", "-- The switch is not connected to the controller.");
jGen.writeStringField("* ", "-- The request specified is not supported by the switch's OpenFlow version.");
jGen.writeEndObject();
jGen.writeObjectFieldStart("Valid statistics and features strings are:");
jGen.writeStringField("1)", OFStatsTypeStrings.AGGREGATE);
jGen.writeStringField("2)", OFStatsTypeStrings.DESC);
jGen.writeStringField("3)", OFStatsTypeStrings.EXPERIMENTER);
jGen.writeStringField("4)", OFStatsTypeStrings.FEATURES);
jGen.writeStringField("5)", OFStatsTypeStrings.FLOW);
jGen.writeStringField("6)", OFStatsTypeStrings.GROUP);
jGen.writeStringField("7)", OFStatsTypeStrings.GROUP_DESC);
jGen.writeStringField("8)", OFStatsTypeStrings.GROUP_FEATURES);
jGen.writeStringField("9)", OFStatsTypeStrings.METER);
jGen.writeStringField("A)", OFStatsTypeStrings.METER_CONFIG);
jGen.writeStringField("B)", OFStatsTypeStrings.METER_FEATURES);
jGen.writeStringField("C)", OFStatsTypeStrings.PORT);
jGen.writeStringField("D)", OFStatsTypeStrings.PORT_DESC);
jGen.writeStringField("E)", OFStatsTypeStrings.QUEUE);
jGen.writeStringField("F)", OFStatsTypeStrings.TABLE);
jGen.writeStringField("G)", OFStatsTypeStrings.TABLE_FEATURES);
jGen.writeEndObject();
jGen.writeEndObject();
return;
}
jGen.configure(Feature.WRITE_NUMBERS_AS_STRINGS, true); // IMHO this just looks nicer and is easier to read if everything is quoted
jGen.writeStartObject();
if (reply.getStatType() == null) { // must be an OFFeaturesReply. getValues() was already checked for null above.
serializeFeaturesReply((OFFeaturesReply) reply.getValues(), jGen);
} else {
switch (reply.getStatType()) {
case PORT:
serializePortReply((List<OFPortStatsReply>) reply.getValues(), jGen);
break;
case QUEUE:
// handle queue
break;
case FLOW:
serializeFlowReply((List<OFFlowStatsReply>) reply.getValues(), jGen);
break;
case AGGREGATE:
serializeAggregateReply((List<OFAggregateStatsReply>) reply.getValues(), jGen);
break;
case DESC:
serializeDescReply((List<OFDescStatsReply>) reply.getValues(), jGen);
break;
case GROUP:
serializeGroupReply((List<OFGroupStatsReply>) reply.getValues(), jGen);
break;
case GROUP_DESC:
serializeGroupDescReply((List<OFGroupDescStatsReply>) reply.getValues(), jGen);
break;
case GROUP_FEATURES:
serializeGroupFeaturesReply((List<OFGroupFeaturesStatsReply>) reply.getValues(), jGen);
break;
case METER:
serializeMeterReply((List<OFMeterStatsReply>) reply.getValues(), jGen);
break;
case METER_CONFIG:
serializeMeterConfigReply((List<OFMeterConfigStatsReply>) reply.getValues(), jGen);
break;
case METER_FEATURES:
serializeMeterFeaturesReply((List<OFMeterFeaturesStatsReply>) reply.getValues(), jGen);
break;
case TABLE:
serializeTableReply((List<OFTableStatsReply>) reply.getValues(), jGen);
break;
case TABLE_FEATURES:
serializeTableFeaturesReply((List<OFTableFeaturesStatsReply>) reply.getValues(), jGen);
break;
case PORT_DESC:
serializePortDescReply((List<OFPortDescStatsReply>) reply.getValues(), jGen);
break;
case EXPERIMENTER:
break;
default:
break;
}
}
jGen.writeEndObject();
}
public static void serializeFeaturesReply(OFFeaturesReply fr, JsonGenerator jGen) throws IOException, JsonProcessingException {
/* Common to All OF Versions */
jGen.writeStringField("capabilities", fr.getCapabilities().toString());
jGen.writeStringField("dpid", fr.getDatapathId().toString());
jGen.writeNumberField("buffers", fr.getNBuffers());
jGen.writeNumberField("tables", fr.getNTables());
jGen.writeStringField("version", fr.getVersion().toString());
if (fr.getVersion().compareTo(OFVersion.OF_13) < 0) { // OF1.3+ break this out into port_config
serializePortDesc(fr.getPorts(), jGen);
}
if (fr.getVersion().compareTo(OFVersion.OF_10) == 0) {
String actions = "[";
for (OFActionType action : fr.getActions()) {
actions = actions + action.toString() + ", ";
}
actions = actions.substring(0, actions.length() - 2); // remove ending space+comma
actions = actions + "]";
jGen.writeStringField("actions", actions);
}
}
/***
* Serializes the Group Statistics Reply
* @author Naveen
* @param groupReplies
* @param jGen
* @throws IOException
* @throws JsonProcessingException
*/
public static void serializeGroupReply(List<OFGroupStatsReply> groupReplies, JsonGenerator jGen) throws IOException, JsonProcessingException{
OFGroupStatsReply groupReply = groupReplies.get(0); // we will get only one GroupReply and it will contains many OFGroupStatsEntry
jGen.writeStringField("version", groupReply.getVersion().toString()); //return the enum name
jGen.writeFieldName("group");
jGen.writeStartArray();
for(OFGroupStatsEntry entry : groupReply.getEntries()) {
jGen.writeStartObject();
jGen.writeStringField("groupNumber",entry.getGroup().toString());
jGen.writeNumberField("refCount", entry.getRefCount());
jGen.writeNumberField("packetCount", entry.getPacketCount().getValue());
jGen.writeNumberField("byteCount", entry.getByteCount().getValue());
jGen.writeFieldName("bucketCounters");
jGen.writeStartArray();
for(OFBucketCounter bCounter : entry.getBucketStats()) {
jGen.writeStartObject();
jGen.writeNumberField("packetCount", bCounter.getPacketCount().getValue());
jGen.writeNumberField("byteCount", bCounter.getByteCount().getValue());
jGen.writeEndObject();
}//end of for loop - BucketCounter
jGen.writeEndArray();
if (OFVersion.OF_13 == entry.getVersion()) {
jGen.writeNumberField("durationSec", entry.getDurationSec());
jGen.writeNumberField("durationNsec", entry.getDurationNsec());
}
jGen.writeEndObject();
}//end of for loop - groupStats
jGen.writeEndArray();
}
/***
* Serializes Group Desc Reply
* @author Naveen
* @param groupDescReplies
* @param jGen
* @throws IOException
* @throws JsonProcessingException
*/
public static void serializeGroupDescReply(List<OFGroupDescStatsReply> groupDescReplies, JsonGenerator jGen) throws IOException, JsonProcessingException{
OFGroupDescStatsReply groupDescReply = groupDescReplies.get(0);
jGen.writeStringField("version", groupDescReply.getVersion().toString()); //return the enum name
jGen.writeFieldName("groupDesc");
jGen.writeStartArray();
for(OFGroupDescStatsEntry entry : groupDescReply.getEntries()) {
jGen.writeStartObject();
jGen.writeStringField("groupType",entry.getGroupType().toString());
jGen.writeStringField("groupNumber",entry.getGroup().toString());
jGen.writeFieldName("buckets");
jGen.writeStartArray();
for(OFBucket buckets : entry.getBuckets()) {
jGen.writeStartObject();
jGen.writeNumberField("weight", buckets.getWeight());
jGen.writeNumberField("watchPortNumber", buckets.getWatchPort().getPortNumber());
jGen.writeStringField("watchGroup", buckets.getWatchGroup().toString());
OFActionListSerializer.serializeActions(jGen, buckets.getActions());
jGen.writeEndObject();
}//End of for loop - buckets
jGen.writeEndArray();//end of buckets
jGen.writeEndObject();//end of group Desc iteration
}//End of for loop - GroupDescStats
jGen.writeEndArray();//end of group Desc
}
/***
* Serializes Group Feature Reply
* @author Naveen
* @param groupFeaturesReplies
* @param jGen
* @throws IOException
* @throws JsonProcessingException
*/
public static void serializeGroupFeaturesReply(List<OFGroupFeaturesStatsReply> groupFeaturesReplies, JsonGenerator jGen) throws IOException, JsonProcessingException{
OFGroupFeaturesStatsReply groupFeaturesReply = groupFeaturesReplies.get(0);
jGen.writeStringField("version", groupFeaturesReply.getVersion().toString()); //return the enum name
jGen.writeFieldName("groupFeatures");
jGen.writeStartObject();
jGen.writeNumberField("capabilities",groupFeaturesReply.getCapabilities());
jGen.writeNumberField("maxGroupsAll",groupFeaturesReply.getMaxGroupsAll());
jGen.writeNumberField("maxGroupsSelect",groupFeaturesReply.getMaxGroupsSelect());
jGen.writeNumberField("maxGroupsIndirect",groupFeaturesReply.getMaxGroupsIndirect());
jGen.writeNumberField("maxGroupsFf",groupFeaturesReply.getMaxGroupsFf());
jGen.writeNumberField("actionsAll",groupFeaturesReply.getActionsAll());
jGen.writeNumberField("actionsSelect",groupFeaturesReply.getActionsSelect());
jGen.writeNumberField("actionsIndirect",groupFeaturesReply.getActionsIndirect());
jGen.writeNumberField("actionsFf",groupFeaturesReply.getActionsFf());
jGen.writeEndObject();//end of group Feature
}
/***
* Serializes the Meter Statistics Reply
* @author Naveen
* @param meterReplies
* @param jGen
* @throws IOException
* @throws JsonProcessingException
*/
public static void serializeMeterReply(List<OFMeterStatsReply> meterReplies, JsonGenerator jGen) throws IOException, JsonProcessingException{
OFMeterStatsReply meterReply = meterReplies.get(0); // we will get only one meterReply and it will contains many OFMeterStatsEntry ?
jGen.writeStringField("version", meterReply.getVersion().toString()); //return the enum name
jGen.writeFieldName("meter");
jGen.writeStartArray();
for(OFMeterStats entry : meterReply.getEntries()) {
jGen.writeStartObject();
jGen.writeNumberField("meterId",entry.getMeterId());
jGen.writeNumberField("flowCount", entry.getFlowCount());
jGen.writeNumberField("packetInCount", entry.getPacketInCount().getValue());
jGen.writeNumberField("byteInCount", entry.getByteInCount().getValue());
jGen.writeFieldName("meterBandStats");
jGen.writeStartArray();
for(OFMeterBandStats bandStats : entry.getBandStats()) {
jGen.writeStartObject();
jGen.writeNumberField("packetBandCount", bandStats.getPacketBandCount().getValue());
jGen.writeNumberField("byteBandCount", bandStats.getByteBandCount().getValue());
jGen.writeEndObject();
}//End of for loop - bandStats
jGen.writeEndArray();
jGen.writeNumberField("durationSec", entry.getDurationSec());
jGen.writeNumberField("durationNsec", entry.getDurationNsec());
jGen.writeEndObject();
}//End of for loop - MeterStats
jGen.writeEndArray();
}
/***
* Serializes Meter Feature Reply
* @author Naveen
* @param meterFeaturesReplies
* @param jGen
* @throws IOException
* @throws JsonProcessingException
*/
public static void serializeMeterFeaturesReply(List<OFMeterFeaturesStatsReply> meterFeaturesReplies, JsonGenerator jGen) throws IOException, JsonProcessingException{
OFMeterFeaturesStatsReply meterFeaturesReply = meterFeaturesReplies.get(0);
jGen.writeStringField("version", meterFeaturesReply.getVersion().toString()); //return the enum name
OFMeterFeatures meterFeatures = meterFeaturesReply.getFeatures();
jGen.writeFieldName("meterFeatures");
jGen.writeStartObject();
jGen.writeNumberField("maxGroupsAll",meterFeatures.getMaxMeter());
jGen.writeNumberField("maxGroupsSelect",meterFeatures.getBandTypes());
jGen.writeNumberField("capabilities",meterFeatures.getCapabilities());
jGen.writeNumberField("maxGroupsIndirect",meterFeatures.getMaxBands());
jGen.writeNumberField("maxGroupsFf",meterFeatures.getMaxColor());
jGen.writeEndObject();//end of group Feature
}
/***
* Serializes Meter Config Reply
* @author Naveen
* @param meterConfigReplies
* @param jGen
* @throws IOException
* @throws JsonProcessingException
*/
public static void serializeMeterConfigReply(List<OFMeterConfigStatsReply> meterConfigReplies, JsonGenerator jGen) throws IOException, JsonProcessingException{
OFMeterConfigStatsReply meterConfigReply = meterConfigReplies.get(0);
jGen.writeStringField("version", meterConfigReply.getVersion().toString()); //return the enum name
jGen.writeFieldName("meterConfig");
jGen.writeStartArray();
for(OFMeterBand band : meterConfigReply.getEntries()) {
jGen.writeStartObject();
short type = (short)band.getType();
jGen.writeNumberField("bandType",type);
switch (type) {
case OFMeterBandTypeSerializerVer13.DROP_VAL:
OFMeterBandDrop bandDrop = (OFMeterBandDrop) band;
jGen.writeNumberField("rate", bandDrop.getRate());
jGen.writeNumberField("burstSize", bandDrop.getBurstSize());
break;
case OFMeterBandTypeSerializerVer13.DSCP_REMARK_VAL:
OFMeterBandDscpRemark bandDscp = (OFMeterBandDscpRemark) band;
jGen.writeNumberField("rate", bandDscp.getRate());
jGen.writeNumberField("burstSize", bandDscp.getBurstSize());
jGen.writeNumberField("precLevel", bandDscp.getPrecLevel());
break;
case OFMeterBandTypeSerializerVer13.EXPERIMENTER_VAL:
OFMeterBandExperimenter bandExp = (OFMeterBandExperimenter) band;
jGen.writeNumberField("rate", bandExp.getRate());
jGen.writeNumberField("burstSize", bandExp.getBurstSize());
jGen.writeNumberField("experimenter", bandExp.getExperimenter());
break;
default:
// shouldn't ever get here
break;
}//end of Switch Case
jGen.writeEndObject();
}//end of for loop
jGen.writeEndArray();
}
/***
* Serializes Table Statistics
* @author Naveen
* @param tableReplies
* @param jGen
* @throws IOException
* @throws JsonProcessingException
*/
public static void serializeTableReply(List<OFTableStatsReply> tableReplies, JsonGenerator jGen) throws IOException, JsonProcessingException{
OFTableStatsReply tableReply = tableReplies.get(0); // we will get only one tableReply and it will contains many OFTableStatsEntry ?
jGen.writeStringField("version", tableReply.getVersion().toString()); //return the enum name
jGen.writeFieldName("table");
jGen.writeStartArray();
for(OFTableStatsEntry entry : tableReply.getEntries()) {
jGen.writeStartObject();
//Fields common to all OF versions
//For OF 1.3, only these fields are applicable
jGen.writeStringField("tableId",entry.getTableId().toString());
jGen.writeNumberField("activeCount", entry.getActiveCount());
jGen.writeNumberField("lookUpCount", entry.getLookupCount().getValue());
jGen.writeNumberField("matchCount", entry.getMatchedCount().getValue());
//Fields Applicable only for specific Versions
switch (entry.getVersion()) {
case OF_12:
//Fields applicable only to OF 1.2
jGen.writeNumberField("writeSetFields", entry.getWriteSetfields().getValue());
jGen.writeNumberField("applySetFields", entry.getApplySetfields().getValue());
jGen.writeNumberField("metaDataMatch", entry.getMetadataMatch().getValue());
jGen.writeNumberField("metaDataWrite", entry.getMetadataWrite().getValue());
case OF_11:
//Fields applicable to OF 1.1 & 1.2
jGen.writeStringField("match", entry.getMatch().toString());
jGen.writeNumberField("instructions", entry.getInstructions());
jGen.writeNumberField("writeActions", entry.getWriteActions());
jGen.writeNumberField("applyActions", entry.getApplyActions());
jGen.writeNumberField("config", entry.getConfig());
case OF_10:
//Fields applicable to OF 1.0, 1.1 & 1.2
jGen.writeStringField("name",entry.getName());
jGen.writeNumberField("wildcards", entry.getWildcards());
jGen.writeNumberField("maxEntries", entry.getMaxEntries());
break;
default:
//no extra fields for OF_13
break;
}//End of switch case
jGen.writeEndObject();
}//End of for loop
jGen.writeEndArray();
}
/***
* Serializes Table Features Reply
* @author Naveen
* @param tableFeaturesReplies
* @param jGen
* @throws IOException
* @throws JsonProcessingException
*/
public static void serializeTableFeaturesReply(List<OFTableFeaturesStatsReply> tableFeaturesReplies, JsonGenerator jGen) throws IOException, JsonProcessingException{
OFTableFeaturesStatsReply tableFeaturesReply = tableFeaturesReplies.get(0);
jGen.writeStringField("version", tableFeaturesReply.getVersion().toString()); //return the enum name
jGen.writeFieldName("tableFeatures");
jGen.writeStartArray();
for(OFTableFeatures tableFeature : tableFeaturesReply.getEntries()) {
jGen.writeStartObject();
jGen.writeNumberField("tableId", tableFeature.getTableId().getValue());
jGen.writeStringField("name", tableFeature.getName());
jGen.writeNumberField("metadataMatch", tableFeature.getMetadataMatch().getValue());
jGen.writeNumberField("metadataWrite", tableFeature.getMetadataWrite().getValue());
jGen.writeNumberField("config", tableFeature.getConfig());
jGen.writeNumberField("maxEntries", tableFeature.getMaxEntries());
jGen.writeFieldName("properties");
jGen.writeStartArray();
for (OFTableFeatureProp properties : tableFeature.getProperties()) {
jGen.writeStartObject();
short type = (short)properties.getType();
jGen.writeNumberField("tableFeaturePropType",type);
switch (type) {
case OFTableFeaturePropTypeSerializerVer13.INSTRUCTIONS_VAL:
OFTableFeaturePropInstructions propInstruct = (OFTableFeaturePropInstructions) properties;
jGen.writeFieldName("instructions");
jGen.writeStartArray();
for (OFInstructionId id : propInstruct.getInstructionIds()) {
jGen.writeStartObject();
jGen.writeString(id.getType().toString());
jGen.writeEndObject();
}
jGen.writeEndArray();
break;
case OFTableFeaturePropTypeSerializerVer13.INSTRUCTIONS_MISS_VAL:
OFTableFeaturePropInstructionsMiss propInstructMiss = (OFTableFeaturePropInstructionsMiss) properties;
jGen.writeFieldName("instructionsMiss");
jGen.writeStartArray();
for (OFInstructionId id : propInstructMiss.getInstructionIds()) {
jGen.writeStartObject();
jGen.writeString(id.getType().toString());
jGen.writeEndObject();
}
jGen.writeEndArray();
break;
case OFTableFeaturePropTypeSerializerVer13.NEXT_TABLES_VAL:
OFTableFeaturePropNextTables propNxtTables = (OFTableFeaturePropNextTables) properties;
jGen.writeFieldName("nextTables");
jGen.writeStartArray();
for (U8 id : propNxtTables.getNextTableIds()) {
jGen.writeStartObject();
jGen.writeNumber(id.getValue());
jGen.writeEndObject();
}
jGen.writeEndArray();
break;
case OFTableFeaturePropTypeSerializerVer13.NEXT_TABLES_MISS_VAL:
OFTableFeaturePropNextTablesMiss propNxtTablesMiss = (OFTableFeaturePropNextTablesMiss) properties;
jGen.writeFieldName("nextTablesMiss");
jGen.writeStartArray();
for (U8 id : propNxtTablesMiss.getNextTableIds()) {
jGen.writeStartObject();
jGen.writeNumber(id.getValue());
jGen.writeEndObject();
}
jGen.writeEndArray();
break;
case OFTableFeaturePropTypeSerializerVer13.WRITE_ACTIONS_VAL:
OFTableFeaturePropWriteActions propWrAct = (OFTableFeaturePropWriteActions) properties;
jGen.writeFieldName("writeActions");
jGen.writeStartArray();
for (OFActionId id : propWrAct.getActionIds()) {
jGen.writeStartObject();
jGen.writeString(id.getType().toString());
jGen.writeEndObject();
}
jGen.writeEndArray();
break;
case OFTableFeaturePropTypeSerializerVer13.WRITE_ACTIONS_MISS_VAL:
OFTableFeaturePropWriteActionsMiss propWrActMiss = (OFTableFeaturePropWriteActionsMiss) properties;
jGen.writeFieldName("writeActionsMiss");
jGen.writeStartArray();
for (OFActionId id : propWrActMiss.getActionIds()) {
jGen.writeStartObject();
jGen.writeString(id.getType().toString());
jGen.writeEndObject();
}
jGen.writeEndArray();
break;
case OFTableFeaturePropTypeSerializerVer13.APPLY_ACTIONS_VAL:
OFTableFeaturePropApplyActions propAppAct = (OFTableFeaturePropApplyActions) properties;
jGen.writeFieldName("applyActions");
jGen.writeStartArray();
for (OFActionId id : propAppAct.getActionIds()) {
jGen.writeStartObject();
jGen.writeString(id.getType().toString());
jGen.writeEndObject();
}
jGen.writeEndArray();
break;
case OFTableFeaturePropTypeSerializerVer13.APPLY_ACTIONS_MISS_VAL:
OFTableFeaturePropApplyActionsMiss propAppActMiss = (OFTableFeaturePropApplyActionsMiss) properties;
jGen.writeFieldName("applyActionsMiss");
jGen.writeStartArray();
for (OFActionId id : propAppActMiss.getActionIds()) {
jGen.writeStartObject();
jGen.writeString(id.getType().toString());
jGen.writeEndObject();
}
jGen.writeEndArray();
break;
case OFTableFeaturePropTypeSerializerVer13.MATCH_VAL:
OFTableFeaturePropMatch propMatch = (OFTableFeaturePropMatch) properties;
jGen.writeFieldName("match");
jGen.writeStartArray();
for (U32 id : propMatch.getOxmIds()) {
jGen.writeStartObject();
jGen.writeNumber(id.getValue());
jGen.writeEndObject();
}
jGen.writeEndArray();
break;
case OFTableFeaturePropTypeSerializerVer13.WILDCARDS_VAL:
OFTableFeaturePropWildcards propWildcards = (OFTableFeaturePropWildcards) properties;
jGen.writeFieldName("wildcards");
jGen.writeStartArray();
for (U32 id : propWildcards.getOxmIds()) {
jGen.writeStartObject();
jGen.writeNumber(id.getValue());
jGen.writeEndObject();
}
jGen.writeEndArray();
break;
case OFTableFeaturePropTypeSerializerVer13.WRITE_SETFIELD_VAL:
OFTableFeaturePropWriteSetfield propWrSetfield = (OFTableFeaturePropWriteSetfield) properties;
jGen.writeFieldName("writeSetfield");
jGen.writeStartArray();
for (U32 id : propWrSetfield.getOxmIds()) {
jGen.writeStartObject();
jGen.writeNumber(id.getValue());
jGen.writeEndObject();
}
jGen.writeEndArray();
break;
case OFTableFeaturePropTypeSerializerVer13.WRITE_SETFIELD_MISS_VAL:
OFTableFeaturePropWriteSetfieldMiss propWrSetfieldMiss = (OFTableFeaturePropWriteSetfieldMiss) properties;
jGen.writeFieldName("writeSetfieldMiss");
jGen.writeStartArray();
for (U32 id : propWrSetfieldMiss.getOxmIds()) {
jGen.writeStartObject();
jGen.writeNumber(id.getValue());
jGen.writeEndObject();
}
jGen.writeEndArray();
break;
case OFTableFeaturePropTypeSerializerVer13.APPLY_SETFIELD_VAL:
OFTableFeaturePropApplySetfield propAppSetfield = (OFTableFeaturePropApplySetfield) properties;
jGen.writeFieldName("applySetfield");
jGen.writeStartArray();
for (U32 id : propAppSetfield.getOxmIds()) {
jGen.writeStartObject();
jGen.writeNumber(id.getValue());
jGen.writeEndObject();
}
jGen.writeEndArray();
break;
case OFTableFeaturePropTypeSerializerVer13.APPLY_SETFIELD_MISS_VAL:
OFTableFeaturePropApplySetfieldMiss propAppSetfieldMiss = (OFTableFeaturePropApplySetfieldMiss) properties;
jGen.writeFieldName("applySetfieldMiss");
jGen.writeStartArray();
for (U32 id : propAppSetfieldMiss.getOxmIds()) {
jGen.writeStartObject();
jGen.writeNumber(id.getValue());
jGen.writeEndObject();
}
jGen.writeEndArray();
break;
case OFTableFeaturePropTypeSerializerVer13.EXPERIMENTER_VAL:
OFTableFeaturePropExperimenter propExp = (OFTableFeaturePropExperimenter) properties;
jGen.writeFieldName("experimenter");
jGen.writeStartObject();
jGen.writeNumberField("subType", propExp.getSubtype());
jGen.writeNumberField("experimenter", propExp.getExperimenter());
jGen.writeStringField("subType", propExp.getExperimenterData().toString());
jGen.writeEndObject();
break;
case OFTableFeaturePropTypeSerializerVer13.EXPERIMENTER_MISS_VAL:
OFTableFeaturePropExperimenterMiss propExpMiss = (OFTableFeaturePropExperimenterMiss) properties;
jGen.writeFieldName("experimenterMiss");
jGen.writeStartObject();
jGen.writeNumberField("subType", propExpMiss.getSubtype());
jGen.writeNumberField("experimenter", propExpMiss.getExperimenter());
jGen.writeStringField("subType", propExpMiss.getExperimenterData().toString());
jGen.writeEndObject();
break;
default:
// shouldn't ever get here
break;
}//end of Switch Case
jGen.writeEndObject();
}//end of for loop - properties
jGen.writeEndObject();
}//end of for loop - features
jGen.writeEndArray();
}
public static void serializePortReply(List<OFPortStatsReply> portReplies, JsonGenerator jGen) throws IOException, JsonProcessingException{
OFPortStatsReply portReply = portReplies.get(0); // we will get only one PortReply and it will contains many OFPortStatsEntry ?
jGen.writeStringField("version", portReply.getVersion().toString()); //return the enum name
jGen.writeFieldName("port");
jGen.writeStartArray();
for(OFPortStatsEntry entry : portReply.getEntries()) {
jGen.writeStartObject();
jGen.writeStringField("portNumber",entry.getPortNo().toString());
jGen.writeNumberField("receivePackets", entry.getRxPackets().getValue());
jGen.writeNumberField("transmitPackets", entry.getTxPackets().getValue());
jGen.writeNumberField("receiveBytes", entry.getRxBytes().getValue());
jGen.writeNumberField("transmitBytes", entry.getTxBytes().getValue());
jGen.writeNumberField("receiveDropped", entry.getRxDropped().getValue());
jGen.writeNumberField("transmitDropped", entry.getTxDropped().getValue());
jGen.writeNumberField("receiveErrors", entry.getRxErrors().getValue());
jGen.writeNumberField("transmitErrors", entry.getTxErrors().getValue());
jGen.writeNumberField("receiveFrameErrors", entry.getRxFrameErr().getValue());
jGen.writeNumberField("receiveOverrunErrors", entry.getRxOverErr().getValue());
jGen.writeNumberField("receiveCRCErrors", entry.getRxCrcErr().getValue());
jGen.writeNumberField("collisions", entry.getCollisions().getValue());
if (OFVersion.OF_13 == entry.getVersion()) {
jGen.writeNumberField("durationSec", entry.getDurationSec());
jGen.writeNumberField("durationNsec", entry.getDurationNsec());
}
jGen.writeEndObject();
}
jGen.writeEndArray();
}
public static void serializeFlowReply(List<OFFlowStatsReply> flowReplies, JsonGenerator jGen) throws IOException, JsonProcessingException{
for (OFFlowStatsReply flowReply : flowReplies) { // for each flow stats reply
//Dose the switch will reply multiple OFFlowStatsReply ?
//Or we juse need to use the first item of the list.
List<OFFlowStatsEntry> entries = flowReply.getEntries();
jGen.writeFieldName("flows");
jGen.writeStartArray();
for (OFFlowStatsEntry entry : entries) { // for each flow
jGen.writeStartObject();
// list flow stats/info
jGen.writeStringField("version", entry.getVersion().toString()); // return the enum name
jGen.writeNumberField("cookie", entry.getCookie().getValue());
jGen.writeStringField("tableId", entry.getTableId().toString());
jGen.writeNumberField("packetCount", entry.getPacketCount().getValue());
jGen.writeNumberField("byteCount", entry.getByteCount().getValue());
jGen.writeNumberField("durationSeconds", entry.getDurationSec());
jGen.writeNumberField("priority", entry.getPriority());
jGen.writeNumberField("idleTimeoutSec", entry.getIdleTimeout());
jGen.writeNumberField("hardTimeoutSec", entry.getHardTimeout());
switch (entry.getVersion()) {
case OF_10:
// flags not supported
break;
case OF_11:
jGen.writeNumberField("flags", OFFlowModFlagsSerializerVer11.toWireValue(entry.getFlags()));
break;
case OF_12:
jGen.writeNumberField("flags", OFFlowModFlagsSerializerVer12.toWireValue(entry.getFlags()));
break;
case OF_13:
jGen.writeNumberField("flags", OFFlowModFlagsSerializerVer13.toWireValue(entry.getFlags()));
break;
case OF_14:
jGen.writeNumberField("flags", OFFlowModFlagsSerializerVer14.toWireValue(entry.getFlags()));
break;
default:
logger.error("Could not decode OFVersion {}", entry.getVersion());
break;
}
MatchSerializer.serializeMatch(jGen, entry.getMatch());
// handle OF1.1+ instructions with actions within
if (entry.getVersion() == OFVersion.OF_10) {
jGen.writeObjectFieldStart("actions");
OFActionListSerializer.serializeActions(jGen, entry.getActions());
jGen.writeEndObject();
} else {
OFInstructionListSerializer.serializeInstructionList(jGen, entry.getInstructions());
}
jGen.writeEndObject();
} // end for each OFFlowStatsReply entry
jGen.writeEndArray();
} // end for each OFStatsReply
} // end method
public static void serializeDescReply(List<OFDescStatsReply> descReplies, JsonGenerator jGen) throws IOException, JsonProcessingException{
OFDescStatsReply descReply = descReplies.get(0); // There is only one descReply from the switch
jGen.writeObjectFieldStart("desc");
jGen.writeStringField("version", descReply.getVersion().toString()); //return the enum name
jGen.writeStringField("manufacturerDescription", descReply.getMfrDesc());
jGen.writeStringField("hardwareDescription", descReply.getHwDesc());
jGen.writeStringField("softwareDescription", descReply.getSwDesc());
jGen.writeStringField("serialNumber", descReply.getSerialNum());
jGen.writeStringField("datapathDescription", descReply.getDpDesc());
jGen.writeEndObject(); // end match
}
public static void serializeAggregateReply(List<OFAggregateStatsReply> aggregateReplies, JsonGenerator jGen) throws IOException, JsonProcessingException{
OFAggregateStatsReply aggregateReply = aggregateReplies.get(0); // There are only one aggregateReply from the switch
jGen.writeObjectFieldStart("aggregate");
jGen.writeStringField("version", aggregateReply.getVersion().toString()); //return the enum name
jGen.writeNumberField("flowCount", aggregateReply.getFlowCount());
jGen.writeNumberField("packetCount", aggregateReply.getPacketCount().getValue());
jGen.writeNumberField("byteCount", aggregateReply.getByteCount().getValue());
switch (aggregateReply.getVersion()) {
case OF_10:
jGen.writeNumberField("flags", OFStatsReplyFlagsSerializerVer10.toWireValue(aggregateReply.getFlags()));
break;
case OF_11:
jGen.writeNumberField("flags", OFStatsReplyFlagsSerializerVer11.toWireValue(aggregateReply.getFlags()));
break;
case OF_12:
jGen.writeNumberField("flags", OFStatsReplyFlagsSerializerVer12.toWireValue(aggregateReply.getFlags()));
break;
case OF_13:
jGen.writeNumberField("flags", OFStatsReplyFlagsSerializerVer13.toWireValue(aggregateReply.getFlags()));
break;
case OF_14:
jGen.writeNumberField("flags", OFStatsReplyFlagsSerializerVer14.toWireValue(aggregateReply.getFlags()));
break;
default:
break;
}
jGen.writeEndObject(); // end match
}
public static void serializePortDescReply(List<OFPortDescStatsReply> portDescReplies, JsonGenerator jGen) throws IOException, JsonProcessingException{
OFPortDescStatsReply portDescReply = portDescReplies.get(0); // we will get only one PortDescReply and it will contains many OFPortDescStatsEntry ?
jGen.writeStringField("version", portDescReply.getVersion().toString()); //return the enum name
serializePortDesc(portDescReply.getEntries(), jGen);
}
public static void serializePortDesc(List<OFPortDesc> portDescList, JsonGenerator jGen) throws IOException, JsonProcessingException {
jGen.writeFieldName("portDesc");
jGen.writeStartArray();
for(OFPortDesc entry : portDescList) {
jGen.writeStartObject();
jGen.writeStringField("portNumber",entry.getPortNo().toString());
jGen.writeStringField("hardwareAddress", entry.getHwAddr().toString());
jGen.writeStringField("name", entry.getName());
switch(entry.getVersion()) {
case OF_10:
jGen.writeNumberField("config", OFPortConfigSerializerVer10.toWireValue(entry.getConfig()));
jGen.writeNumberField("state", OFPortStateSerializerVer10.toWireValue(entry.getState()));
jGen.writeNumberField("currentFeatures", OFPortFeaturesSerializerVer10.toWireValue(entry.getCurr()));
jGen.writeNumberField("advertisedFeatures", OFPortFeaturesSerializerVer10.toWireValue(entry.getAdvertised()));
jGen.writeNumberField("supportedFeatures", OFPortFeaturesSerializerVer10.toWireValue(entry.getSupported()));
jGen.writeNumberField("peerFeatures", OFPortFeaturesSerializerVer10.toWireValue(entry.getPeer()));
break;
case OF_11:
jGen.writeNumberField("config", OFPortConfigSerializerVer11.toWireValue(entry.getConfig()));
jGen.writeNumberField("state", OFPortStateSerializerVer11.toWireValue(entry.getState()));
jGen.writeNumberField("currentFeatures", OFPortFeaturesSerializerVer11.toWireValue(entry.getCurr()));
jGen.writeNumberField("advertisedFeatures", OFPortFeaturesSerializerVer11.toWireValue(entry.getAdvertised()));
jGen.writeNumberField("supportedFeatures", OFPortFeaturesSerializerVer11.toWireValue(entry.getSupported()));
jGen.writeNumberField("peerFeatures", OFPortFeaturesSerializerVer11.toWireValue(entry.getPeer()));
break;
case OF_12:
jGen.writeNumberField("config", OFPortConfigSerializerVer12.toWireValue(entry.getConfig()));
jGen.writeNumberField("state", OFPortStateSerializerVer12.toWireValue(entry.getState()));
jGen.writeNumberField("currentFeatures", OFPortFeaturesSerializerVer12.toWireValue(entry.getCurr()));
jGen.writeNumberField("advertisedFeatures", OFPortFeaturesSerializerVer12.toWireValue(entry.getAdvertised()));
jGen.writeNumberField("supportedFeatures", OFPortFeaturesSerializerVer12.toWireValue(entry.getSupported()));
jGen.writeNumberField("peerFeatures", OFPortFeaturesSerializerVer12.toWireValue(entry.getPeer()));
break;
case OF_13:
jGen.writeNumberField("config", OFPortConfigSerializerVer13.toWireValue(entry.getConfig()));
jGen.writeNumberField("state", OFPortStateSerializerVer13.toWireValue(entry.getState()));
jGen.writeNumberField("currentFeatures", OFPortFeaturesSerializerVer13.toWireValue(entry.getCurr()));
jGen.writeNumberField("advertisedFeatures", OFPortFeaturesSerializerVer13.toWireValue(entry.getAdvertised()));
jGen.writeNumberField("supportedFeatures", OFPortFeaturesSerializerVer13.toWireValue(entry.getSupported()));
jGen.writeNumberField("peerFeatures", OFPortFeaturesSerializerVer13.toWireValue(entry.getPeer()));
break;
case OF_14:
// TODO
logger.error("OF1.4 OFPortDesc serializer not implemented");
}
if (OFVersion.OF_10 != entry.getVersion()) {
jGen.writeNumberField("currSpeed",entry.getCurrSpeed());
jGen.writeNumberField("maxSpeed",entry.getMaxSpeed());
}
jGen.writeEndObject();
}
jGen.writeEndArray();
}
}
| Fixed issue where multipart flow replies would only show the last part/reply and not print the others. Only a REST API issue. This will also fix the Web UI where people reported not seeing all their flows.
| src/main/java/net/floodlightcontroller/core/web/serializers/StatsReplySerializer.java | Fixed issue where multipart flow replies would only show the last part/reply and not print the others. Only a REST API issue. This will also fix the Web UI where people reported not seeing all their flows. | <ide><path>rc/main/java/net/floodlightcontroller/core/web/serializers/StatsReplySerializer.java
<ide> }
<ide>
<ide> public static void serializeFlowReply(List<OFFlowStatsReply> flowReplies, JsonGenerator jGen) throws IOException, JsonProcessingException{
<add> /* start the array before each reply */
<add> jGen.writeFieldName("flows");
<add> jGen.writeStartArray();
<ide> for (OFFlowStatsReply flowReply : flowReplies) { // for each flow stats reply
<del> //Dose the switch will reply multiple OFFlowStatsReply ?
<del> //Or we juse need to use the first item of the list.
<ide> List<OFFlowStatsEntry> entries = flowReply.getEntries();
<del> jGen.writeFieldName("flows");
<del> jGen.writeStartArray();
<ide> for (OFFlowStatsEntry entry : entries) { // for each flow
<ide> jGen.writeStartObject();
<ide> // list flow stats/info
<ide> }
<ide>
<ide> jGen.writeEndObject();
<del> } // end for each OFFlowStatsReply entry
<del> jGen.writeEndArray();
<add> } // end for each OFFlowStatsReply entry */
<ide> } // end for each OFStatsReply
<add> //jGen.writeEndObject();
<add> jGen.writeEndArray();
<ide> } // end method
<ide>
<ide> public static void serializeDescReply(List<OFDescStatsReply> descReplies, JsonGenerator jGen) throws IOException, JsonProcessingException{ |
|
Java | apache-2.0 | 03d78720a3aeedc161d2f5c94987c791dfbf615a | 0 | GIP-RECIA/cas,zhoffice/cas,tduehr/cas,doodelicious/cas,rrenomeron/cas,GIP-RECIA/cas,William-Hill-Online/cas,William-Hill-Online/cas,robertoschwald/cas,William-Hill-Online/cas,tduehr/cas,frett/cas,gabedwrds/cas,tduehr/cas,petracvv/cas,creamer/cas,William-Hill-Online/cas,prigaux/cas,doodelicious/cas,zhoffice/cas,Unicon/cas,creamer/cas,Unicon/cas,dodok1/cas,gabedwrds/cas,yisiqi/cas,GIP-RECIA/cas,rrenomeron/cas,zawn/cas,prigaux/cas,zawn/cas,robertoschwald/cas,dodok1/cas,robertoschwald/cas,GIP-RECIA/cas,prigaux/cas,rrenomeron/cas,yisiqi/cas,yisiqi/cas,yisiqi/cas,creamer/cas,doodelicious/cas,doodelicious/cas,prigaux/cas,frett/cas,pmarasse/cas,zawn/cas,zhoffice/cas,pmarasse/cas,Unicon/cas,creamer/cas,tduehr/cas,pmarasse/cas,robertoschwald/cas,petracvv/cas,dodok1/cas,Unicon/cas,frett/cas,zawn/cas,frett/cas,Unicon/cas,pmarasse/cas,rrenomeron/cas,gabedwrds/cas,gabedwrds/cas,zhoffice/cas,dodok1/cas,petracvv/cas,GIP-RECIA/cas,rrenomeron/cas,petracvv/cas | package org.jasig.cas.config;
import java.util.Arrays;
import org.jasig.cas.support.openid.web.mvc.SmartOpenIdController;
import org.jasig.cas.web.AbstractDelegateController;
import org.jasig.cas.web.DelegatingController;
import org.openid4java.server.ServerManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.view.JstlView;
/**
* This this {@link OpenIdConfiguration}.
*
* @author Misagh Moayyed
* @since 4.3.0
*/
@Configuration("openidConfiguration")
public class OpenIdConfiguration {
private static final Logger LOGGER = LoggerFactory.getLogger(OpenIdConfiguration.class);
/**
* The Open id validate controller.
*/
@Autowired
@Qualifier("openIdValidateController")
private AbstractDelegateController openIdValidateController;
/**
* The Endpoint.
*/
@Value("${server.prefix:http://localhost:8080/cas}/login")
private String endpoint;
/**
* The Enforce rp id.
*/
@Value("${cas.openid.enforce.rpid:false}")
private boolean enforceRpId;
/**
* Cas open id service failure view jstl view.
*
* @return the jstl view
*/
@Bean(name="casOpenIdServiceFailureView")
public JstlView casOpenIdServiceFailureView() {
return new JstlView("/WEB-INF/view/jsp/protocol/openid/casOpenIdServiceFailureView.jsp");
}
/**
* Cas open id service success view jstl view.
*
* @return the jstl view
*/
@Bean(name="casOpenIdServiceSuccessView")
public JstlView casOpenIdServiceSuccessView() {
return new JstlView("/WEB-INF/view/jsp/protocol/openid/casOpenIdServiceSuccessView.jsp");
}
/**
* Cas open id association failure view jstl view.
*
* @return the jstl view
*/
@Bean(name="casOpenIdAssociationFailureView")
public JstlView casOpenIdAssociationFailureView() {
return new JstlView("/WEB-INF/view/jsp/protocol/openid/casOpenIdAssociationFailureView.jsp");
}
/**
* Cas open id association success view jstl view.
*
* @return the jstl view
*/
@Bean(name="casOpenIdAssociationSuccessView")
public JstlView casOpenIdAssociationSuccessView() {
return new JstlView("/WEB-INF/view/jsp/protocol/openid/casOpenIdAssociationSuccessView.jsp");
}
/**
* Open id provider view jstl view.
*
* @return the jstl view
*/
@Bean(name="openIdProviderView")
public JstlView openIdProviderView() {
return new JstlView("/WEB-INF/view/jsp/protocol/openid/user.jsp");
}
/**
* Openid delegating controller delegating controller.
*
* @return the delegating controller
*/
@Bean(name="openidDelegatingController")
public DelegatingController openidDelegatingController() {
final DelegatingController controller = new DelegatingController();
controller.setDelegates(Arrays.asList(
this.smartOpenIdAssociationController(),
this.openIdValidateController));
return controller;
}
@Bean(name="smartOpenIdAssociationController")
public AbstractDelegateController smartOpenIdAssociationController () {
return new SmartOpenIdController();
}
/**
* Server manager server manager.
*
* @return the server manager
*/
@Bean(name="serverManager")
public ServerManager serverManager() {
final ServerManager manager = new ServerManager();
manager.setOPEndpointUrl(this.endpoint);
manager.setEnforceRpId(this.enforceRpId);
LOGGER.info("Creating openid server manager with OP endpoint {}", this.endpoint);
return manager;
}
}
| cas-server-support-openid/src/main/java/org/jasig/cas/config/OpenIdConfiguration.java | package org.jasig.cas.config;
import org.jasig.cas.web.AbstractDelegateController;
import org.jasig.cas.web.DelegatingController;
import org.openid4java.server.ServerManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.view.JstlView;
import java.util.Arrays;
/**
* This this {@link OpenIdConfiguration}.
*
* @author Misagh Moayyed
* @since 4.3.0
*/
@Configuration("openidConfiguration")
public class OpenIdConfiguration {
/**
* The Smart open id association controller.
*/
@Autowired
@Qualifier("smartOpenIdAssociationController")
private AbstractDelegateController smartOpenIdAssociationController;
/**
* The Open id validate controller.
*/
@Autowired
@Qualifier("openIdValidateController")
private AbstractDelegateController openIdValidateController;
/**
* The Endpoint.
*/
@Value("${server.prefix}/login")
private String endpoint;
/**
* The Enforce rp id.
*/
@Value("${cas.openid.enforce.rpid:false}")
private boolean enforceRpId;
/**
* Cas open id service failure view jstl view.
*
* @return the jstl view
*/
@Bean(name="casOpenIdServiceFailureView")
public JstlView casOpenIdServiceFailureView() {
return new JstlView("/WEB-INF/view/jsp/protocol/openid/casOpenIdServiceFailureView.jsp");
}
/**
* Cas open id service success view jstl view.
*
* @return the jstl view
*/
@Bean(name="casOpenIdServiceSuccessView")
public JstlView casOpenIdServiceSuccessView() {
return new JstlView("/WEB-INF/view/jsp/protocol/openid/casOpenIdServiceSuccessView.jsp");
}
/**
* Cas open id association failure view jstl view.
*
* @return the jstl view
*/
@Bean(name="casOpenIdAssociationFailureView")
public JstlView casOpenIdAssociationFailureView() {
return new JstlView("/WEB-INF/view/jsp/protocol/openid/casOpenIdAssociationFailureView.jsp");
}
/**
* Cas open id association success view jstl view.
*
* @return the jstl view
*/
@Bean(name="casOpenIdAssociationSuccessView")
public JstlView casOpenIdAssociationSuccessView() {
return new JstlView("/WEB-INF/view/jsp/protocol/openid/casOpenIdAssociationSuccessView.jsp");
}
/**
* Open id provider view jstl view.
*
* @return the jstl view
*/
@Bean(name="openIdProviderView")
public JstlView openIdProviderView() {
return new JstlView("/WEB-INF/view/jsp/protocol/openid/user.jsp");
}
/**
* Openid delegating controller delegating controller.
*
* @return the delegating controller
*/
@Bean(name="openidDelegatingController")
public DelegatingController openidDelegatingController() {
final DelegatingController controller = new DelegatingController();
controller.setDelegates(Arrays.asList(this.smartOpenIdAssociationController,
this.openIdValidateController));
return controller;
}
/**
* Server manager server manager.
*
* @return the server manager
*/
@Bean(name="serverManager")
public ServerManager serverManager() {
final ServerManager manager = new ServerManager();
manager.setOPEndpointUrl(this.endpoint);
manager.setEnforceRpId(this.enforceRpId);
return manager;
}
}
| CAS-1550
changed the instantiation of SmartOpenIdAssociationController so that
ServerManager is instantiated with the correct values
| cas-server-support-openid/src/main/java/org/jasig/cas/config/OpenIdConfiguration.java | CAS-1550 changed the instantiation of SmartOpenIdAssociationController so that ServerManager is instantiated with the correct values | <ide><path>as-server-support-openid/src/main/java/org/jasig/cas/config/OpenIdConfiguration.java
<ide> package org.jasig.cas.config;
<ide>
<add>import java.util.Arrays;
<add>
<add>import org.jasig.cas.support.openid.web.mvc.SmartOpenIdController;
<ide> import org.jasig.cas.web.AbstractDelegateController;
<ide> import org.jasig.cas.web.DelegatingController;
<ide> import org.openid4java.server.ServerManager;
<add>import org.slf4j.Logger;
<add>import org.slf4j.LoggerFactory;
<ide> import org.springframework.beans.factory.annotation.Autowired;
<ide> import org.springframework.beans.factory.annotation.Qualifier;
<ide> import org.springframework.beans.factory.annotation.Value;
<ide> import org.springframework.context.annotation.Bean;
<ide> import org.springframework.context.annotation.Configuration;
<ide> import org.springframework.web.servlet.view.JstlView;
<del>
<del>import java.util.Arrays;
<ide>
<ide> /**
<ide> * This this {@link OpenIdConfiguration}.
<ide> @Configuration("openidConfiguration")
<ide> public class OpenIdConfiguration {
<ide>
<del> /**
<del> * The Smart open id association controller.
<del> */
<del> @Autowired
<del> @Qualifier("smartOpenIdAssociationController")
<del> private AbstractDelegateController smartOpenIdAssociationController;
<add> private static final Logger LOGGER = LoggerFactory.getLogger(OpenIdConfiguration.class);
<ide>
<ide> /**
<ide> * The Open id validate controller.
<ide> /**
<ide> * The Endpoint.
<ide> */
<del> @Value("${server.prefix}/login")
<add> @Value("${server.prefix:http://localhost:8080/cas}/login")
<ide> private String endpoint;
<ide>
<ide> /**
<ide> @Bean(name="openidDelegatingController")
<ide> public DelegatingController openidDelegatingController() {
<ide> final DelegatingController controller = new DelegatingController();
<del> controller.setDelegates(Arrays.asList(this.smartOpenIdAssociationController,
<add> controller.setDelegates(Arrays.asList(
<add> this.smartOpenIdAssociationController(),
<ide> this.openIdValidateController));
<ide> return controller;
<ide> }
<ide>
<add> @Bean(name="smartOpenIdAssociationController")
<add> public AbstractDelegateController smartOpenIdAssociationController () {
<add> return new SmartOpenIdController();
<add> }
<ide> /**
<ide> * Server manager server manager.
<ide> *
<ide> final ServerManager manager = new ServerManager();
<ide> manager.setOPEndpointUrl(this.endpoint);
<ide> manager.setEnforceRpId(this.enforceRpId);
<add> LOGGER.info("Creating openid server manager with OP endpoint {}", this.endpoint);
<ide> return manager;
<ide> }
<ide> } |
|
Java | mit | 5ecc3e7360ebb8a5de07eeed9a021b692eb8ecb4 | 0 | Crash-Test-Buddies/WiFi-Buddy | package edu.rit.se.wifibuddy;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.net.wifi.WpsInfo;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pGroup;
import android.net.wifi.p2p.WifiP2pInfo;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.nsd.WifiP2pDnsSdServiceInfo;
import android.net.wifi.p2p.nsd.WifiP2pDnsSdServiceRequest;
import android.net.wifi.p2p.nsd.WifiP2pServiceInfo;
import android.net.wifi.p2p.nsd.WifiP2pServiceRequest;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
// TODO: Add JavaDoc
public class WifiDirectHandler extends NonStopIntentService implements
WifiP2pManager.ConnectionInfoListener,
Handler.Callback{
private static final String ANDROID_SERVICE_NAME = "Wi-Fi Buddy";
public static final String TAG = "wfd_";
private final IBinder binder = new WifiTesterBinder();
public static final String SERVICE_MAP_KEY = "serviceMapKey";
public static final String MESSAGE_KEY = "messageKey";
private final String PEERS = "peers";
private final String WIFI_STATE = "wifiState";
private Map<String, DnsSdTxtRecord> dnsSdTxtRecordMap;
private Map<String, DnsSdService> dnsSdServiceMap;
private List<ServiceDiscoveryTask> serviceDiscoveryTasks;
private WifiP2pDeviceList peers;
private LocalBroadcastManager localBroadcastManager;
private BroadcastReceiver p2pBroadcastReceiver;
private BroadcastReceiver wifiBroadcastReceiver;
private WifiP2pServiceInfo wifiP2pServiceInfo;
private WifiP2pServiceRequest serviceRequest;
private Boolean isWifiP2pEnabled;
private Handler handler = new Handler((Handler.Callback) this);
private CommunicationManager communicationManager = null;
public static final int MESSAGE_READ = 0x400 + 1;
public static final int MY_HANDLE = 0x400 + 2;
public static final int COMMUNICATION_DISCONNECTED = 0x400 + 3;
public static final int SERVER_PORT = 4545;
private final int SERVICE_DISCOVERY_TIMEOUT = 120000;
private boolean isDiscovering = false;
private boolean isGroupOwner = false;
private boolean groupFormed = false;
private boolean serviceDiscoveryRegistered = false;
// Flag for creating a no prompt service
private boolean isCreatingNoPrompt = false;
private ServiceData noPromptServiceData;
// Variables created in onCreate()
private WifiP2pManager.Channel channel;
private WifiP2pManager wifiP2pManager;
private WifiManager wifiManager;
private WifiP2pDevice thisDevice;
private WifiP2pGroup wifiP2pGroup;
private List<ScanResult> wifiScanResults;
/** Constructor **/
public WifiDirectHandler() {
super(ANDROID_SERVICE_NAME);
dnsSdTxtRecordMap = new HashMap<>();
dnsSdServiceMap = new HashMap<>();
peers = new WifiP2pDeviceList();
}
/**
* Registers the Wi-Fi manager, registers the app with the Wi-Fi P2P framework, registers the
* P2P BroadcastReceiver, and registers a local BroadcastManager
*/
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "Creating WifiDirectHandler");
// Registers the Wi-Fi Manager and the Wi-Fi BroadcastReceiver
wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
registerWifiReceiver();
// Scans for available Wi-Fi networks
wifiManager.startScan();
if (wifiManager.isWifiEnabled()) {
Log.i(TAG, "Wi-Fi enabled on load");
} else {
Log.i(TAG, "Wi-Fi disabled on load");
}
// Registers a local BroadcastManager that is used to broadcast Intents to Activities
localBroadcastManager = LocalBroadcastManager.getInstance(this);
Log.i(TAG, "WifiDirectHandler created");
}
/**
* Registers the application with the Wi-Fi P2P framework
* Initializes the P2P manager and gets a P2P communication channel
*/
public void registerP2p() {
// Manages Wi-Fi P2P connectivity
wifiP2pManager = (WifiP2pManager) getSystemService(WIFI_P2P_SERVICE);
// initialize() registers the app with the Wi-Fi P2P framework
// Channel is used to communicate with the Wi-Fi P2P framework
// Main Looper is the Looper for the main thread of the current process
channel = wifiP2pManager.initialize(this, getMainLooper(), null);
Log.i(TAG, "Registered with Wi-Fi P2P framework");
}
/**
* Unregisters the application with the Wi-Fi P2P framework
*/
public void unregisterP2p() {
if (wifiP2pManager != null) {
wifiP2pManager = null;
channel = null;
thisDevice = null;
localBroadcastManager.sendBroadcast(new Intent(Action.DEVICE_CHANGED));
Log.i(TAG, "Unregistered with Wi-Fi P2P framework");
}
}
/**
* Registers a WifiDirectBroadcastReceiver with an IntentFilter listening for P2P Actions
*/
public void registerP2pReceiver() {
p2pBroadcastReceiver = new WifiDirectBroadcastReceiver();
IntentFilter intentFilter = new IntentFilter();
// Indicates a change in the list of available peers
intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
// Indicates a change in the Wi-Fi P2P status
intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
// Indicates the state of Wi-Fi P2P connectivity has changed
intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
// Indicates this device's details have changed.
intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
registerReceiver(p2pBroadcastReceiver, intentFilter);
Log.i(TAG, "P2P BroadcastReceiver registered");
}
/**
* Unregisters the WifiDirectBroadcastReceiver and IntentFilter
*/
public void unregisterP2pReceiver() {
if (p2pBroadcastReceiver != null) {
unregisterReceiver(p2pBroadcastReceiver);
p2pBroadcastReceiver = null;
Log.i(TAG, "P2P BroadcastReceiver unregistered");
}
}
public void registerWifiReceiver() {
wifiBroadcastReceiver = new WifiBroadcastReceiver();
IntentFilter wifiIntentFilter = new IntentFilter();
// Indicates that Wi-Fi has been enabled, disabled, enabling, disabling, or unknown
wifiIntentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
wifiIntentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
registerReceiver(wifiBroadcastReceiver, wifiIntentFilter);
Log.i(TAG, "Wi-Fi BroadcastReceiver registered");
}
public void unregisterWifiReceiver() {
if (wifiBroadcastReceiver != null) {
unregisterReceiver(wifiBroadcastReceiver);
wifiBroadcastReceiver = null;
Log.i(TAG, "Wi-Fi BroadcastReceiver unregistered");
}
}
public void unregisterWifi() {
if (wifiManager != null) {
wifiManager = null;
Log.i(TAG, "Wi-Fi manager unregistered");
}
}
/**
* The requested connection info is available
* @param wifiP2pInfo Wi-Fi P2P connection info
*/
@Override
public void onConnectionInfoAvailable(WifiP2pInfo wifiP2pInfo) {
Log.i(TAG, "Connection info available");
Log.i(TAG, "WifiP2pInfo: ");
Log.i(TAG, p2pInfoToString(wifiP2pInfo));
this.groupFormed = wifiP2pInfo.groupFormed;
this.isGroupOwner = wifiP2pInfo.isGroupOwner;
if (wifiP2pInfo.groupFormed) {
stopServiceDiscovery();
Thread handler;
if (wifiP2pInfo.isGroupOwner) {
Log.i(TAG, "Connected as group owner");
try {
handler = new OwnerSocketHandler(this.getHandler());
handler.start();
} catch (IOException e) {
Log.e(TAG, "Failed to create a server thread - " + e.getMessage());
return;
}
} else {
Log.i(TAG, "Connected as peer");
handler = new ClientSocketHandler(this.getHandler(), wifiP2pInfo.groupOwnerAddress);
handler.start();
}
localBroadcastManager.sendBroadcast(new Intent(Action.SERVICE_CONNECTED));
} else {
Log.w(TAG, "Group not formed");
}
localBroadcastManager.sendBroadcast(new Intent(Action.DEVICE_CHANGED));
}
// TODO add JavaDoc
public void addLocalService(String serviceName, HashMap<String, String> serviceRecord) {
// Logs information about local service
Log.i(TAG, "Adding local service: " + serviceName);
// Service information
wifiP2pServiceInfo = WifiP2pDnsSdServiceInfo.newInstance(
serviceName,
ServiceType.PRESENCE_TCP.toString(),
serviceRecord
);
// Only add a local service if clearLocalServices succeeds
wifiP2pManager.clearLocalServices(channel, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
// Add the local service
wifiP2pManager.addLocalService(channel, wifiP2pServiceInfo, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
Log.i(TAG, "Local service added");
}
@Override
public void onFailure(int reason) {
Log.e(TAG, "Failure adding local service: " + FailureReason.fromInteger(reason).toString());
wifiP2pServiceInfo = null;
}
});
}
@Override
public void onFailure(int reason) {
Log.e(TAG, "Failure clearing local services: " + FailureReason.fromInteger(reason).toString());
wifiP2pServiceInfo = null;
}
});
}
@Override
public void onDestroy() {
super.onDestroy();
stopServiceDiscovery();
removeGroup();
removePersistentGroups();
removeService();
unregisterP2pReceiver();
unregisterP2p();
unregisterWifiReceiver();
unregisterWifi();
Log.i(TAG, "Wifi Handler service destroyed");
}
/**
* Removes persistent/remembered groups
*
* Source: https://android.googlesource.com/platform/cts/+/jb-mr1-dev%5E1%5E2..jb-mr1-dev%5E1/
* Author: Nick Kralevich <[email protected]>
*
* WifiP2pManager.java has a method deletePersistentGroup(), but it is not accessible in the
* SDK. According to Vinit Deshpande <[email protected]>, it is a common Android paradigm to
* expose certain APIs in the SDK and hide others. This allows Android to maintain stability and
* security. As a workaround, this removePersistentGroups() method uses Java reflection to call
* the hidden method. We can list all the methods in WifiP2pManager and invoke "deletePersistentGroup"
* if it exists. This is used to remove all possible persistent/remembered groups.
*/
private void removePersistentGroups() {
try {
Method[] methods = WifiP2pManager.class.getMethods();
for (int i = 0; i < methods.length; i++) {
if (methods[i].getName().equals("deletePersistentGroup")) {
// Remove any persistent group
for (int netid = 0; netid < 32; netid++) {
methods[i].invoke(wifiP2pManager, channel, netid, null);
}
}
}
Log.i(TAG, "Persistent groups removed");
} catch(Exception e) {
Log.e(TAG, "Failure removing persistent groups: " + e.getMessage());
e.printStackTrace();
}
}
/**
* Removes the current WifiP2pGroup in the WifiP2pChannel.
*/
public void removeGroup() {
if (wifiP2pGroup != null) {
wifiP2pManager.removeGroup(channel, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
wifiP2pGroup = null;
groupFormed = false;
isGroupOwner = false;
Log.i(TAG, "Group removed");
}
@Override
public void onFailure(int reason) {
Log.e(TAG, "Failure removing group: " + FailureReason.fromInteger(reason).toString());
}
});
}
}
/*
* Registers listeners for DNS-SD services. These are callbacks invoked
* by the system when a service is actually discovered.
*/
private void registerServiceDiscoveryListeners() {
// DnsSdTxtRecordListener
// Interface for callback invocation when Bonjour TXT record is available for a service
// Used to listen for incoming records and get peer device information
WifiP2pManager.DnsSdTxtRecordListener txtRecordListener = new WifiP2pManager.DnsSdTxtRecordListener() {
@Override
public void onDnsSdTxtRecordAvailable(String fullDomainName, Map<String, String> txtRecordMap, WifiP2pDevice srcDevice) {
// Records of peer are available
Log.i(TAG, "Peer DNS-SD TXT Record available");
Intent intent = new Intent(Action.DNS_SD_TXT_RECORD_AVAILABLE);
localBroadcastManager.sendBroadcast(intent);
dnsSdTxtRecordMap.put(srcDevice.deviceAddress, new DnsSdTxtRecord(fullDomainName, txtRecordMap, srcDevice));
}
};
// DnsSdServiceResponseListener
// Interface for callback invocation when Bonjour service discovery response is received
// Used to get service information
WifiP2pManager.DnsSdServiceResponseListener serviceResponseListener = new WifiP2pManager.DnsSdServiceResponseListener() {
@Override
public void onDnsSdServiceAvailable(String instanceName, String registrationType, WifiP2pDevice srcDevice) {
// Not sure if we want to track the map here or just send the service in the request to let the caller do
// what it wants with it
Log.i(TAG, "DNS-SD service available");
Log.i(TAG, "Local service found: " + instanceName);
Log.i("TAG", "Source device: ");
Log.i(TAG, p2pDeviceToString(srcDevice));
dnsSdServiceMap.put(srcDevice.deviceAddress, new DnsSdService(instanceName, registrationType, srcDevice));
Intent intent = new Intent(Action.DNS_SD_SERVICE_AVAILABLE);
intent.putExtra(SERVICE_MAP_KEY, srcDevice.deviceAddress);
localBroadcastManager.sendBroadcast(intent);
}
};
wifiP2pManager.setDnsSdResponseListeners(channel, serviceResponseListener, txtRecordListener);
Log.i(TAG, "Service discovery listeners registered");
}
private void addServiceDiscoveryRequest() {
serviceRequest = WifiP2pDnsSdServiceRequest.newInstance();
// Tell the framework we want to scan for services. Prerequisite for discovering services
wifiP2pManager.addServiceRequest(channel, serviceRequest, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
Log.i(TAG, "Service discovery request added");
}
@Override
public void onFailure(int reason) {
Log.e(TAG, "Failure adding service discovery request: " + FailureReason.fromInteger(reason).toString());
serviceRequest = null;
}
});
}
/**
* Initiates a service discovery. This has a 2 minute timeout. To continuously
* discover services use continuouslyDiscoverServices
*/
public void discoverServices(){
// Initiates service discovery. Starts to scan for services we want to connect to
wifiP2pManager.discoverServices(channel, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
Log.i(TAG, "Service discovery initiated");
}
@Override
public void onFailure(int reason) {
Log.e(TAG, "Failure initiating service discovery: " + FailureReason.fromInteger(reason).toString());
}
});
}
/**
* Calls initial services discovery call and submits the first
* Discover task. This will continue until stopDiscoveringServices is called
*/
public void continuouslyDiscoverServices(){
Log.i(TAG, "Continuously Discover services called");
if (serviceDiscoveryRegistered == false) {
Log.i(TAG, "Setting up service discovery");
registerServiceDiscoveryListeners();
serviceDiscoveryRegistered = true;
}
// TODO Change this to give some sort of status
if (isDiscovering){
Log.w(TAG, "Services are still discovering, do not need to make this call");
} else {
addServiceDiscoveryRequest();
isDiscovering = true;
// List to track discovery tasks in progress
serviceDiscoveryTasks = new ArrayList<>();
// Make discover call and first discover task submission
discoverServices();
submitServiceDiscoveryTask();
}
}
public void stopServiceDiscovery() {
Log.i(TAG, "Stopping service discovery");
if (isDiscovering) {
dnsSdServiceMap = new HashMap<>();
dnsSdTxtRecordMap = new HashMap<>();
// Cancel all discover tasks that may be in progress
for (ServiceDiscoveryTask serviceDiscoveryTask : serviceDiscoveryTasks) {
serviceDiscoveryTask.cancel();
}
serviceDiscoveryTasks = null;
isDiscovering = false;
Log.i(TAG, "Service discovery stopped");
clearServiceDiscoveryRequests();
}
}
public void resetServiceDiscovery() {
Log.i(TAG, "Resetting service discovery");
stopServiceDiscovery();
continuouslyDiscoverServices();
}
/**
* Submits a new task to initiate service discovery after the discovery
* timeout period has expired
*/
private void submitServiceDiscoveryTask(){
Log.i(TAG, "Submitting service discovery task");
// Discover times out after 2 minutes so we set the timer to that
int timeToWait = SERVICE_DISCOVERY_TIMEOUT;
ServiceDiscoveryTask serviceDiscoveryTask = new ServiceDiscoveryTask();
Timer timer = new Timer();
// Submit the service discovery task and add it to the list
timer.schedule(serviceDiscoveryTask, timeToWait);
serviceDiscoveryTasks.add(serviceDiscoveryTask);
}
/**
* Timed task to initiate a new services discovery. Will recursively submit
* a new task as long as isDiscovering is true
*/
private class ServiceDiscoveryTask extends TimerTask {
public void run() {
discoverServices();
// Submit the next task if a stop call hasn't been made
if (isDiscovering) {
submitServiceDiscoveryTask();
}
// Remove this task from the list since it's complete
serviceDiscoveryTasks.remove(this);
}
}
public Map<String, DnsSdService> getDnsSdServiceMap(){
return dnsSdServiceMap;
}
public Map<String, DnsSdTxtRecord> getDnsSdTxtRecordMap() {
return dnsSdTxtRecordMap;
}
/**
* Uses wifiManager to determine if Wi-Fi is enabled
* @return Whether Wi-Fi is enabled or not
*/
public boolean isWifiEnabled() {
return wifiManager.isWifiEnabled();
}
/**
* Removes a registered local service.
*/
public void removeService() {
if(wifiP2pServiceInfo != null) {
Log.i(TAG, "Removing local service");
wifiP2pManager.removeLocalService(channel, wifiP2pServiceInfo, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
wifiP2pServiceInfo = null;
Intent intent = new Intent(Action.SERVICE_REMOVED);
localBroadcastManager.sendBroadcast(intent);
Log.i(TAG, "Local service removed");
}
@Override
public void onFailure(int reason) {
Log.e(TAG, "Failure removing local service: " + FailureReason.fromInteger(reason).toString());
}
});
wifiP2pServiceInfo = null;
} else {
Log.w(TAG, "No local service to remove");
}
}
private void clearServiceDiscoveryRequests() {
if (serviceRequest != null) {
wifiP2pManager.clearServiceRequests(channel, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
serviceRequest = null;
Log.i(TAG, "Service discovery requests cleared");
}
@Override
public void onFailure(int reason) {
Log.e(TAG, "Failure clearing service discovery requests: " + FailureReason.fromInteger(reason).toString());
}
});
}
}
/**
* Initiates a connection to a service
* @param service The service to connect to
*/
public void initiateConnectToService(DnsSdService service) {
// Device info of peer to connect to
WifiP2pConfig wifiP2pConfig = new WifiP2pConfig();
wifiP2pConfig.deviceAddress = service.getSrcDevice().deviceAddress;
wifiP2pConfig.wps.setup = WpsInfo.PBC;
// Starts a peer-to-peer connection with a device with the specified configuration
wifiP2pManager.connect(channel, wifiP2pConfig, new WifiP2pManager.ActionListener() {
// The ActionListener only notifies that initiation of connection has succeeded or failed
@Override
public void onSuccess() {
Log.i(TAG, "Initiating connection to service");
}
@Override
public void onFailure(int reason) {
Log.e(TAG, "Failure initiating connection to service: " + FailureReason.fromInteger(reason).toString());
}
});
}
/**
* Creates a service that can be connected to without prompting. This is possible by creating an
* access point and broadcasting the password for peers to use. Peers connect via normal wifi, not
* wifi direct, but the effect is the same.
*/
public void startAddingNoPromptService(ServiceData serviceData) {
if (wifiP2pServiceInfo != null) {
removeService();
}
isCreatingNoPrompt = true;
noPromptServiceData = serviceData;
wifiP2pManager.createGroup(channel, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
Log.i(TAG, "Group created successfully");
//Note that you will have to wait for WIFI_P2P_CONNECTION_CHANGED_INTENT for group info
}
@Override
public void onFailure(int reason) {
Log.i(TAG, "Group creation failed: " + FailureReason.fromInteger(reason));
}
});
}
/**
* Connects to a no prompt service
* @param service The service to connect to
*/
public void connectToNoPromptService(DnsSdService service) {
removeService();
WifiConfiguration configuration = new WifiConfiguration();
DnsSdTxtRecord txtRecord = dnsSdTxtRecordMap.get(service.getSrcDevice().deviceAddress);
if(txtRecord == null) {
Log.e(TAG, "No dnsSdTxtRecord found for the no prompt service");
return;
}
// Quotes around these are required
configuration.SSID = "\"" + txtRecord.getRecord().get(Keys.NO_PROMPT_NETWORK_NAME) + "\"";
configuration.preSharedKey = "\"" + txtRecord.getRecord().get(Keys.NO_PROMPT_NETWORK_PASS) + "\"";
int netId = wifiManager.addNetwork(configuration);
//disconnect form current network and connect to this one
wifiManager.disconnect();
wifiManager.enableNetwork(netId, true);
wifiManager.reconnect();
Log.i(TAG, "Connected to no prompt network");
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return binder;
}
@Override
protected void onHandleIntent(Intent intent) {
String action = intent.getAction();
Log.i(TAG, "Handling intent: " + action);
if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
// The list of discovered peers has changed
handlePeersChanged(intent);
} else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
// The state of Wi-Fi P2P connectivity has changed
handleConnectionChanged(intent);
} else if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
// Indicates whether Wi-Fi P2P is enabled
handleP2pStateChanged(intent);
} else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
// Indicates this device's configuration details have changed
handleThisDeviceChanged(intent);
} else if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action)) {
handleWifiStateChanged(intent);
} else if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action)) {
handleScanResultsAvailable(intent);
}
}
private void handleWifiStateChanged(Intent intent) {
Log.i(TAG, "Wi-Fi state changed");
int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, -1);
if (wifiState == WifiManager.WIFI_STATE_ENABLED) {
// Register app with Wi-Fi P2P framework, register WifiDirectBroadcastReceiver
Log.i(TAG, "Wi-Fi enabled");
registerP2p();
registerP2pReceiver();
} else if (wifiState == WifiManager.WIFI_STATE_DISABLED) {
// Remove local service, unregister app with Wi-Fi P2P framework, unregister P2pReceiver
Log.i(TAG, "Wi-Fi disabled");
clearServiceDiscoveryRequests();
removeService();
unregisterP2pReceiver();
unregisterP2p();
}
Log.e(TAG, "TESTTTT");
localBroadcastManager.sendBroadcast(new Intent(Action.WIFI_STATE_CHANGED));
}
private void handleScanResultsAvailable(Intent intent) {
Log.i(TAG, "Wi-Fi scan results available");
wifiScanResults = wifiManager.getScanResults();
Log.i(TAG, "There are " + (wifiScanResults.size() - 1) + " available networks");
for (ScanResult wifiScanResult : wifiScanResults) {
Log.i(TAG, wifiScanResult.SSID);
}
// Unregister the Wi-Fi receiver and register it again without the SCAN_RESULTS action
unregisterWifiReceiver();
wifiBroadcastReceiver = new WifiBroadcastReceiver();
IntentFilter intentFilter = new IntentFilter();
// Indicates that Wi-Fi has been enabled, disabled, enabling, disabling, or unknown
intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
registerReceiver(wifiBroadcastReceiver, intentFilter);
Log.i(TAG, "Wi-Fi BroadcastReceiver registered");
}
/**
* The list of discovered peers has changed
* Available extras: EXTRA_P2P_DEVICE_LIST
* @param intent
*/
private void handlePeersChanged(Intent intent) {
Log.i(TAG, "List of discovered peers changed");
if (wifiP2pManager != null) {
// Request the updated list of discovered peers from wifiP2PManager
wifiP2pManager.requestPeers(channel, new WifiP2pManager.PeerListListener() {
@Override
public void onPeersAvailable(WifiP2pDeviceList peers) {
WifiDirectHandler.this.peers = peers;
Intent intent = new Intent(Action.PEERS_CHANGED);
intent.putExtra(PEERS, peers);
localBroadcastManager.sendBroadcast(intent);
}
});
}
}
/**
* The state of Wi-Fi P2P connectivity has changed
* Here is where you can request group info
* Available extras: EXTRA_WIFI_P2P_INFO, EXTRA_NETWORK_INFO, EXTRA_WIFI_P2P_GROUP
* @param intent
*/
private void handleConnectionChanged(Intent intent) {
Log.i(TAG, "Wi-Fi P2P Connection Changed");
if(wifiP2pManager == null) {
return;
}
// Extra information from EXTRA_NETWORK_INFO
NetworkInfo networkInfo = intent.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);
if(networkInfo.isConnected()) {
Log.i(TAG, "Connected to P2P network. Requesting connection info");
wifiP2pManager.requestConnectionInfo(channel, WifiDirectHandler.this);
}
// Requests peer-to-peer group information
wifiP2pManager.requestGroupInfo(channel, new WifiP2pManager.GroupInfoListener() {
@Override
public void onGroupInfoAvailable(WifiP2pGroup wifiP2pGroup) {
if (wifiP2pGroup != null) {
Log.i(TAG, "Group info available");
Log.i(TAG, "WifiP2pGroup:");
Log.i(TAG, p2pGroupToString(wifiP2pGroup));
WifiDirectHandler.this.wifiP2pGroup = wifiP2pGroup;
}
}
});
}
/**
* Indicates whether Wi-Fi P2P is enabled
* Determine if Wi-Fi P2P mode is enabled or not, alert the Activity
* Available extras: EXTRA_WIFI_STATE
* Sticky Intent
* @param intent
*/
private void handleP2pStateChanged(Intent intent) {
Log.i(TAG, "Wi-Fi P2P State Changed:");
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
// Wi-Fi Direct is enabled
isWifiP2pEnabled = true;
Log.i(TAG, "- Wi-Fi Direct is enabled");
} else {
// Wi-Fi Direct is not enabled
isWifiP2pEnabled = false;
Log.i(TAG, "- Wi-Fi Direct is not enabled");
}
}
/**
* Indicates this device's configuration details have changed
* Sticky Intent
* @param intent
*/
private void handleThisDeviceChanged(Intent intent) {
Log.i(TAG, "This device changed");
// Extra information from EXTRA_WIFI_P2P_DEVICE
thisDevice = intent.getParcelableExtra(WifiP2pManager.EXTRA_WIFI_P2P_DEVICE);
// Logs extra information from EXTRA_WIFI_P2P_DEVICE
Log.i(TAG, p2pDeviceToString(thisDevice));
localBroadcastManager.sendBroadcast(new Intent(Action.DEVICE_CHANGED));
}
/**
* Toggle wifi
* @param wifiEnabled whether or not wifi should be enabled
*/
public void setWifiEnabled(boolean wifiEnabled) {
wifiManager.setWifiEnabled(wifiEnabled);
}
public Handler getHandler() {
return handler;
}
// TODO: Add JavaDoc
@Override
public boolean handleMessage(Message msg) {
Log.i(TAG, "handleMessage() called");
switch (msg.what) {
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String receivedMessage = new String(readBuf, 0, msg.arg1);
Log.i(TAG, "Received message: " + receivedMessage);
Intent messageReceivedIntent = new Intent(Action.MESSAGE_RECEIVED);
messageReceivedIntent.putExtra(MESSAGE_KEY, readBuf);
localBroadcastManager.sendBroadcast(messageReceivedIntent);
break;
case MY_HANDLE:
Object messageObject = msg.obj;
communicationManager = (CommunicationManager) messageObject;
break;
case COMMUNICATION_DISCONNECTED:
Log.i(TAG, "Handling communication disconnect");
localBroadcastManager.sendBroadcast(new Intent(Action.COMMUNICATION_DISCONNECTED));
break;
}
return true;
}
public CommunicationManager getCommunicationManager() {
return communicationManager;
}
/**
* Allows for binding to the service.
*/
public class WifiTesterBinder extends Binder {
public WifiDirectHandler getService() {
return WifiDirectHandler.this;
}
}
/**
* Actions that can be broadcast or received by the handler
*/
public class Action {
public static final String DNS_SD_TXT_RECORD_AVAILABLE = "dnsSdTxtRecordAdded",
DNS_SD_SERVICE_AVAILABLE = "dnsSdServiceAvailable",
SERVICE_REMOVED = "serviceRemoved",
PEERS_CHANGED = "peersChanged",
SERVICE_CONNECTED = "serviceConnected",
DEVICE_CHANGED = "deviceChanged",
MESSAGE_RECEIVED = "messageReceived",
WIFI_STATE_CHANGED = "wifiStateChanged",
COMMUNICATION_DISCONNECTED = "communicationDisconnected";
}
private class Keys {
public static final String NO_PROMPT_NETWORK_NAME = "networkName",
NO_PROMPT_NETWORK_PASS = "passphrase";
}
// TODO: Add JavaDoc
private class WifiDirectBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
onHandleIntent(intent);
}
}
// TODO: Add JavaDoc
private class WifiBroadcastReceiver extends BroadcastReceiver {
@Override public void onReceive(Context context, Intent intent) {
onHandleIntent(intent);
}
}
/**
* Takes a WifiP2pDevice and returns a String of readable device information
* @param wifiP2pDevice
* @return
*/
public String p2pDeviceToString(WifiP2pDevice wifiP2pDevice) {
if (wifiP2pDevice != null) {
String strDevice = "Device name: " + wifiP2pDevice.deviceName;
strDevice += "\nDevice address: " + wifiP2pDevice.deviceAddress;
if (wifiP2pDevice.equals(thisDevice)) {
strDevice += "\nIs group owner: " + isGroupOwner();
} else {
strDevice += "\nIs group owner: false";
}
strDevice += "\nStatus: " + deviceStatusToString(wifiP2pDevice.status) + "\n";
return strDevice;
} else {
Log.e(TAG, "WifiP2pDevice is null");
return "";
}
}
public String p2pInfoToString(WifiP2pInfo wifiP2pInfo) {
if (wifiP2pInfo != null) {
String strWifiP2pInfo = "Group formed: " + wifiP2pInfo.groupFormed;
strWifiP2pInfo += "\nIs group owner: " + wifiP2pInfo.isGroupOwner;
strWifiP2pInfo += "\nGroup owner address: " + wifiP2pInfo.groupOwnerAddress;
return strWifiP2pInfo;
} else {
Log.e(TAG, "WifiP2pInfo is null");
return "";
}
}
public String p2pGroupToString(WifiP2pGroup wifiP2pGroup) {
if (wifiP2pGroup != null) {
String strWifiP2pGroup = "Network name: " + wifiP2pGroup.getNetworkName();
strWifiP2pGroup += "\nIs group owner: " + wifiP2pGroup.isGroupOwner();
if (wifiP2pGroup.getOwner() != null) {
strWifiP2pGroup += "\nGroup owner: ";
strWifiP2pGroup += "\n" + p2pDeviceToString(wifiP2pGroup.getOwner());
}
if (wifiP2pGroup.getClientList() != null && !wifiP2pGroup.getClientList().isEmpty()) {
for (WifiP2pDevice client : wifiP2pGroup.getClientList()) {
strWifiP2pGroup += "\nClient: ";
strWifiP2pGroup += "\n" + p2pDeviceToString(client);
}
}
return strWifiP2pGroup;
} else {
Log.e(TAG, "WifiP2pGroup is null");
return "";
}
}
/**
* Translates a device status code to a readable String status
* @param status
* @return A readable String device status
*/
public String deviceStatusToString(int status) {
if (status == WifiP2pDevice.AVAILABLE) {
return "Available";
} else if (status == WifiP2pDevice.INVITED) {
return "Invited";
} else if (status == WifiP2pDevice.CONNECTED) {
return "Connected";
} else if (status == WifiP2pDevice.FAILED) {
return "Failed";
} else if (status == WifiP2pDevice.UNAVAILABLE) {
return "Unavailable";
} else {
return "Unknown";
}
}
public String getThisDeviceInfo() {
if (thisDevice == null) {
return "No Device Info";
} else {
if (thisDevice.deviceName.equals("")) {
thisDevice.deviceName = "Android Device";
}
return p2pDeviceToString(thisDevice);
}
}
public boolean isGroupOwner() {
return this.isGroupOwner;
}
public boolean isGroupFormed() {
return this.groupFormed;
}
public boolean isDiscovering() {
return this.isDiscovering;
}
public WifiP2pDevice getThisDevice() {
return this.thisDevice;
}
public WifiP2pServiceInfo getWifiP2pServiceInfo() {
return this.wifiP2pServiceInfo;
}
public List<ScanResult> getWifiScanResults() {
return wifiScanResults;
}
}
| wifibuddy/src/main/java/edu/rit/se/wifibuddy/WifiDirectHandler.java | package edu.rit.se.wifibuddy;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.net.wifi.WpsInfo;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pGroup;
import android.net.wifi.p2p.WifiP2pInfo;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.nsd.WifiP2pDnsSdServiceInfo;
import android.net.wifi.p2p.nsd.WifiP2pDnsSdServiceRequest;
import android.net.wifi.p2p.nsd.WifiP2pServiceInfo;
import android.net.wifi.p2p.nsd.WifiP2pServiceRequest;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
// TODO: Add JavaDoc
public class WifiDirectHandler extends NonStopIntentService implements
WifiP2pManager.ConnectionInfoListener,
Handler.Callback{
private static final String ANDROID_SERVICE_NAME = "Wi-Fi Buddy";
public static final String TAG = "wfd_";
private final IBinder binder = new WifiTesterBinder();
public static final String SERVICE_MAP_KEY = "serviceMapKey";
public static final String MESSAGE_KEY = "messageKey";
private final String PEERS = "peers";
private final String WIFI_STATE = "wifiState";
private Map<String, DnsSdTxtRecord> dnsSdTxtRecordMap;
private Map<String, DnsSdService> dnsSdServiceMap;
private List<ServiceDiscoveryTask> serviceDiscoveryTasks;
private WifiP2pDeviceList peers;
private LocalBroadcastManager localBroadcastManager;
private BroadcastReceiver p2pBroadcastReceiver;
private BroadcastReceiver wifiBroadcastReceiver;
private WifiP2pServiceInfo wifiP2pServiceInfo;
private WifiP2pServiceRequest serviceRequest;
private Boolean isWifiP2pEnabled;
private Handler handler = new Handler((Handler.Callback) this);
private CommunicationManager communicationManager = null;
public static final int MESSAGE_READ = 0x400 + 1;
public static final int MY_HANDLE = 0x400 + 2;
public static final int COMMUNICATION_DISCONNECTED = 0x400 + 3;
public static final int SERVER_PORT = 4545;
private final int SERVICE_DISCOVERY_TIMEOUT = 120000;
private boolean isDiscovering = false;
private boolean isGroupOwner = false;
private boolean groupFormed = false;
private boolean serviceDiscoveryRegistered = false;
// Flag for creating a no prompt service
private boolean isCreatingNoPrompt = false;
private ServiceData noPromptServiceData;
// Variables created in onCreate()
private WifiP2pManager.Channel channel;
private WifiP2pManager wifiP2pManager;
private WifiManager wifiManager;
private WifiP2pDevice thisDevice;
private WifiP2pGroup wifiP2pGroup;
private List<ScanResult> wifiScanResults;
/** Constructor **/
public WifiDirectHandler() {
super(ANDROID_SERVICE_NAME);
dnsSdTxtRecordMap = new HashMap<>();
dnsSdServiceMap = new HashMap<>();
peers = new WifiP2pDeviceList();
}
/**
* Registers the Wi-Fi manager, registers the app with the Wi-Fi P2P framework, registers the
* P2P BroadcastReceiver, and registers a local BroadcastManager
*/
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "Creating WifiDirectHandler");
// Registers the Wi-Fi Manager and the Wi-Fi BroadcastReceiver
wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
registerWifiReceiver();
// Scans for available Wi-Fi networks
wifiManager.startScan();
if (wifiManager.isWifiEnabled()) {
Log.i(TAG, "Wi-Fi enabled on load");
} else {
Log.i(TAG, "Wi-Fi disabled on load");
}
// Registers a local BroadcastManager that is used to broadcast Intents to Activities
localBroadcastManager = LocalBroadcastManager.getInstance(this);
Log.i(TAG, "WifiDirectHandler created");
}
/**
* Registers the application with the Wi-Fi P2P framework
* Initializes the P2P manager and gets a P2P communication channel
*/
public void registerP2p() {
// Manages Wi-Fi P2P connectivity
wifiP2pManager = (WifiP2pManager) getSystemService(WIFI_P2P_SERVICE);
// initialize() registers the app with the Wi-Fi P2P framework
// Channel is used to communicate with the Wi-Fi P2P framework
// Main Looper is the Looper for the main thread of the current process
channel = wifiP2pManager.initialize(this, getMainLooper(), null);
Log.i(TAG, "Registered with Wi-Fi P2P framework");
}
/**
* Unregisters the application with the Wi-Fi P2P framework
*/
public void unregisterP2p() {
if (wifiP2pManager != null) {
wifiP2pManager = null;
channel = null;
thisDevice = null;
localBroadcastManager.sendBroadcast(new Intent(Action.DEVICE_CHANGED));
Log.i(TAG, "Unregistered with Wi-Fi P2P framework");
}
}
/**
* Registers a WifiDirectBroadcastReceiver with an IntentFilter listening for P2P Actions
*/
public void registerP2pReceiver() {
p2pBroadcastReceiver = new WifiDirectBroadcastReceiver();
IntentFilter intentFilter = new IntentFilter();
// Indicates a change in the list of available peers
intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
// Indicates a change in the Wi-Fi P2P status
intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
// Indicates the state of Wi-Fi P2P connectivity has changed
intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
// Indicates this device's details have changed.
intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
registerReceiver(p2pBroadcastReceiver, intentFilter);
Log.i(TAG, "P2P BroadcastReceiver registered");
}
/**
* Unregisters the WifiDirectBroadcastReceiver and IntentFilter
*/
public void unregisterP2pReceiver() {
if (p2pBroadcastReceiver != null) {
unregisterReceiver(p2pBroadcastReceiver);
p2pBroadcastReceiver = null;
Log.i(TAG, "P2P BroadcastReceiver unregistered");
}
}
public void registerWifiReceiver() {
wifiBroadcastReceiver = new WifiBroadcastReceiver();
IntentFilter wifiIntentFilter = new IntentFilter();
// Indicates that Wi-Fi has been enabled, disabled, enabling, disabling, or unknown
wifiIntentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
wifiIntentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
registerReceiver(wifiBroadcastReceiver, wifiIntentFilter);
Log.i(TAG, "Wi-Fi BroadcastReceiver registered");
}
public void unregisterWifiReceiver() {
if (wifiBroadcastReceiver != null) {
unregisterReceiver(wifiBroadcastReceiver);
wifiBroadcastReceiver = null;
Log.i(TAG, "Wi-Fi BroadcastReceiver unregistered");
}
}
public void unregisterWifi() {
if (wifiManager != null) {
wifiManager = null;
Log.i(TAG, "Wi-Fi manager unregistered");
}
}
/**
* The requested connection info is available
* @param wifiP2pInfo Wi-Fi P2P connection info
*/
@Override
public void onConnectionInfoAvailable(WifiP2pInfo wifiP2pInfo) {
Log.i(TAG, "Connection info available");
Log.i(TAG, "WifiP2pInfo: ");
Log.i(TAG, p2pInfoToString(wifiP2pInfo));
this.groupFormed = wifiP2pInfo.groupFormed;
this.isGroupOwner = wifiP2pInfo.isGroupOwner;
if (wifiP2pInfo.groupFormed) {
stopServiceDiscovery();
Thread handler;
if (wifiP2pInfo.isGroupOwner) {
Log.i(TAG, "Connected as group owner");
try {
handler = new OwnerSocketHandler(this.getHandler());
handler.start();
} catch (IOException e) {
Log.e(TAG, "Failed to create a server thread - " + e.getMessage());
return;
}
} else {
Log.i(TAG, "Connected as peer");
handler = new ClientSocketHandler(this.getHandler(), wifiP2pInfo.groupOwnerAddress);
handler.start();
}
localBroadcastManager.sendBroadcast(new Intent(Action.SERVICE_CONNECTED));
} else {
Log.w(TAG, "Group not formed");
}
localBroadcastManager.sendBroadcast(new Intent(Action.DEVICE_CHANGED));
}
// TODO add JavaDoc
public void addLocalService(String serviceName, HashMap<String, String> serviceRecord) {
// Logs information about local service
Log.i(TAG, "Adding local service: " + serviceName);
// Service information
wifiP2pServiceInfo = WifiP2pDnsSdServiceInfo.newInstance(
serviceName,
ServiceType.PRESENCE_TCP.toString(),
serviceRecord
);
// Only add a local service if clearLocalServices succeeds
wifiP2pManager.clearLocalServices(channel, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
// Add the local service
wifiP2pManager.addLocalService(channel, wifiP2pServiceInfo, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
Log.i(TAG, "Local service added");
}
@Override
public void onFailure(int reason) {
Log.e(TAG, "Failure adding local service: " + FailureReason.fromInteger(reason).toString());
wifiP2pServiceInfo = null;
}
});
}
@Override
public void onFailure(int reason) {
Log.e(TAG, "Failure clearing local services: " + FailureReason.fromInteger(reason).toString());
wifiP2pServiceInfo = null;
}
});
}
@Override
public void onDestroy() {
super.onDestroy();
stopServiceDiscovery();
removeGroup();
removePersistentGroups();
removeService();
unregisterP2pReceiver();
unregisterP2p();
unregisterWifiReceiver();
unregisterWifi();
Log.i(TAG, "Wifi Handler service destroyed");
}
/**
* Removes persistent/remembered groups
*
* Source: https://android.googlesource.com/platform/cts/+/jb-mr1-dev%5E1%5E2..jb-mr1-dev%5E1/
* Author: Nick Kralevich <[email protected]>
*
* WifiP2pManager.java has a method deletePersistentGroup(), but it is not accessible in the
* SDK. According to Vinit Deshpande <[email protected]>, it is a common Android paradigm to
* expose certain APIs in the SDK and hide others. This allows Android to maintain stability and
* security. As a workaround, this removePersistentGroups() method uses Java reflection to call
* the hidden method. We can list all the methods in WifiP2pManager and invoke "deletePersistentGroup"
* if it exists. This is used to remove all possible persistent/remembered groups.
*/
private void removePersistentGroups() {
try {
Method[] methods = WifiP2pManager.class.getMethods();
for (int i = 0; i < methods.length; i++) {
if (methods[i].getName().equals("deletePersistentGroup")) {
// Remove any persistent group
for (int netid = 0; netid < 32; netid++) {
methods[i].invoke(wifiP2pManager, channel, netid, null);
}
}
}
Log.i(TAG, "Persistent groups removed");
} catch(Exception e) {
Log.e(TAG, "Failure removing persistent groups: " + e.getMessage());
e.printStackTrace();
}
}
/**
* Removes the current WifiP2pGroup in the WifiP2pChannel.
*/
public void removeGroup() {
if (wifiP2pGroup != null) {
wifiP2pManager.removeGroup(channel, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
wifiP2pGroup = null;
groupFormed = false;
isGroupOwner = false;
Log.i(TAG, "Group removed");
}
@Override
public void onFailure(int reason) {
Log.e(TAG, "Failure removing group: " + FailureReason.fromInteger(reason).toString());
}
});
}
}
/*
* Registers listeners for DNS-SD services. These are callbacks invoked
* by the system when a service is actually discovered.
*/
private void registerServiceDiscoveryListeners() {
// DnsSdTxtRecordListener
// Interface for callback invocation when Bonjour TXT record is available for a service
// Used to listen for incoming records and get peer device information
WifiP2pManager.DnsSdTxtRecordListener txtRecordListener = new WifiP2pManager.DnsSdTxtRecordListener() {
@Override
public void onDnsSdTxtRecordAvailable(String fullDomainName, Map<String, String> txtRecordMap, WifiP2pDevice srcDevice) {
// Records of peer are available
Log.i(TAG, "Peer DNS-SD TXT Record available");
Intent intent = new Intent(Action.DNS_SD_TXT_RECORD_AVAILABLE);
localBroadcastManager.sendBroadcast(intent);
dnsSdTxtRecordMap.put(srcDevice.deviceAddress, new DnsSdTxtRecord(fullDomainName, txtRecordMap, srcDevice));
}
};
// DnsSdServiceResponseListener
// Interface for callback invocation when Bonjour service discovery response is received
// Used to get service information
WifiP2pManager.DnsSdServiceResponseListener serviceResponseListener = new WifiP2pManager.DnsSdServiceResponseListener() {
@Override
public void onDnsSdServiceAvailable(String instanceName, String registrationType, WifiP2pDevice srcDevice) {
// Not sure if we want to track the map here or just send the service in the request to let the caller do
// what it wants with it
Log.i(TAG, "DNS-SD service available");
Log.i(TAG, "Local service found: " + instanceName);
Log.i("TAG", "Source device: ");
Log.i(TAG, p2pDeviceToString(srcDevice));
dnsSdServiceMap.put(srcDevice.deviceAddress, new DnsSdService(instanceName, registrationType, srcDevice));
Intent intent = new Intent(Action.DNS_SD_SERVICE_AVAILABLE);
intent.putExtra(SERVICE_MAP_KEY, srcDevice.deviceAddress);
localBroadcastManager.sendBroadcast(intent);
}
};
wifiP2pManager.setDnsSdResponseListeners(channel, serviceResponseListener, txtRecordListener);
Log.i(TAG, "Service discovery listeners registered");
}
private void addServiceDiscoveryRequest() {
serviceRequest = WifiP2pDnsSdServiceRequest.newInstance();
// Tell the framework we want to scan for services. Prerequisite for discovering services
wifiP2pManager.addServiceRequest(channel, serviceRequest, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
Log.i(TAG, "Service discovery request added");
}
@Override
public void onFailure(int reason) {
Log.e(TAG, "Failure adding service discovery request: " + FailureReason.fromInteger(reason).toString());
serviceRequest = null;
}
});
}
/**
* Initiates a service discovery. This has a 2 minute timeout. To continuously
* discover services use continuouslyDiscoverServices
*/
public void discoverServices(){
// Initiates service discovery. Starts to scan for services we want to connect to
wifiP2pManager.discoverServices(channel, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
Log.i(TAG, "Service discovery initiated");
}
@Override
public void onFailure(int reason) {
Log.e(TAG, "Failure initiating service discovery: " + FailureReason.fromInteger(reason).toString());
}
});
}
/**
* Calls initial services discovery call and submits the first
* Discover task. This will continue until stopDiscoveringServices is called
*/
public void continuouslyDiscoverServices(){
Log.i(TAG, "Continuously Discover services called");
if (serviceDiscoveryRegistered == false) {
Log.i(TAG, "Setting up service discovery");
registerServiceDiscoveryListeners();
serviceDiscoveryRegistered = true;
}
// TODO Change this to give some sort of status
if (isDiscovering){
Log.w(TAG, "Services are still discovering, do not need to make this call");
} else {
addServiceDiscoveryRequest();
isDiscovering = true;
// List to track discovery tasks in progress
serviceDiscoveryTasks = new ArrayList<>();
// Make discover call and first discover task submission
discoverServices();
submitServiceDiscoveryTask();
}
}
public void stopServiceDiscovery() {
Log.i(TAG, "Stopping service discovery");
if (isDiscovering) {
dnsSdServiceMap = new HashMap<>();
dnsSdTxtRecordMap = new HashMap<>();
// Cancel all discover tasks that may be in progress
for (ServiceDiscoveryTask serviceDiscoveryTask : serviceDiscoveryTasks) {
serviceDiscoveryTask.cancel();
}
serviceDiscoveryTasks = null;
isDiscovering = false;
Log.i(TAG, "Service discovery stopped");
clearServiceDiscoveryRequests();
}
}
public void resetServiceDiscovery() {
Log.i(TAG, "Resetting service discovery");
stopServiceDiscovery();
continuouslyDiscoverServices();
}
/**
* Submits a new task to initiate service discovery after the discovery
* timeout period has expired
*/
private void submitServiceDiscoveryTask(){
Log.i(TAG, "Submitting service discovery task");
// Discover times out after 2 minutes so we set the timer to that
int timeToWait = SERVICE_DISCOVERY_TIMEOUT;
ServiceDiscoveryTask serviceDiscoveryTask = new ServiceDiscoveryTask();
Timer timer = new Timer();
// Submit the service discovery task and add it to the list
timer.schedule(serviceDiscoveryTask, timeToWait);
serviceDiscoveryTasks.add(serviceDiscoveryTask);
}
/**
* Timed task to initiate a new services discovery. Will recursively submit
* a new task as long as isDiscovering is true
*/
private class ServiceDiscoveryTask extends TimerTask {
public void run() {
discoverServices();
// Submit the next task if a stop call hasn't been made
if (isDiscovering) {
submitServiceDiscoveryTask();
}
// Remove this task from the list since it's complete
serviceDiscoveryTasks.remove(this);
}
}
public Map<String, DnsSdService> getDnsSdServiceMap(){
return dnsSdServiceMap;
}
public Map<String, DnsSdTxtRecord> getDnsSdTxtRecordMap() {
return dnsSdTxtRecordMap;
}
/**
* Uses wifiManager to determine if Wi-Fi is enabled
* @return Whether Wi-Fi is enabled or not
*/
public boolean isWifiEnabled() {
return wifiManager.isWifiEnabled();
}
/**
* Removes a registered local service.
*/
public void removeService() {
if(wifiP2pServiceInfo != null) {
Log.i(TAG, "Removing local service");
wifiP2pManager.removeLocalService(channel, wifiP2pServiceInfo, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
wifiP2pServiceInfo = null;
Intent intent = new Intent(Action.SERVICE_REMOVED);
localBroadcastManager.sendBroadcast(intent);
Log.i(TAG, "Local service removed");
}
@Override
public void onFailure(int reason) {
Log.e(TAG, "Failure removing local service: " + FailureReason.fromInteger(reason).toString());
}
});
wifiP2pServiceInfo = null;
} else {
Log.w(TAG, "No local service to remove");
}
}
private void clearServiceDiscoveryRequests() {
if (serviceRequest != null) {
wifiP2pManager.clearServiceRequests(channel, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
serviceRequest = null;
Log.i(TAG, "Service discovery requests cleared");
}
@Override
public void onFailure(int reason) {
Log.e(TAG, "Failure clearing service discovery requests: " + FailureReason.fromInteger(reason).toString());
}
});
}
}
/**
* Initiates a connection to a service
* @param service The service to connect to
*/
public void initiateConnectToService(DnsSdService service) {
// Device info of peer to connect to
WifiP2pConfig wifiP2pConfig = new WifiP2pConfig();
wifiP2pConfig.deviceAddress = service.getSrcDevice().deviceAddress;
wifiP2pConfig.wps.setup = WpsInfo.PBC;
// Starts a peer-to-peer connection with a device with the specified configuration
wifiP2pManager.connect(channel, wifiP2pConfig, new WifiP2pManager.ActionListener() {
// The ActionListener only notifies that initiation of connection has succeeded or failed
@Override
public void onSuccess() {
Log.i(TAG, "Initiating connection to service");
}
@Override
public void onFailure(int reason) {
Log.e(TAG, "Failure initiating connection to service: " + FailureReason.fromInteger(reason).toString());
}
});
}
/**
* Creates a service that can be connected to without prompting. This is possible by creating an
* access point and broadcasting the password for peers to use. Peers connect via normal wifi, not
* wifi direct, but the effect is the same.
*/
public void startAddingNoPromptService(ServiceData serviceData) {
if (wifiP2pServiceInfo != null) {
removeService();
}
isCreatingNoPrompt = true;
noPromptServiceData = serviceData;
wifiP2pManager.createGroup(channel, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
Log.i(TAG, "Group created successfully");
//Note that you will have to wait for WIFI_P2P_CONNECTION_CHANGED_INTENT for group info
}
@Override
public void onFailure(int reason) {
Log.i(TAG, "Group creation failed: " + FailureReason.fromInteger(reason));
}
});
}
/**
* Connects to a no prompt service
* @param service The service to connect to
*/
public void connectToNoPromptService(DnsSdService service) {
removeService();
WifiConfiguration configuration = new WifiConfiguration();
DnsSdTxtRecord txtRecord = dnsSdTxtRecordMap.get(service.getSrcDevice().deviceAddress);
if(txtRecord == null) {
Log.e(TAG, "No dnsSdTxtRecord found for the no prompt service");
return;
}
// Quotes around these are required
configuration.SSID = "\"" + txtRecord.getRecord().get(Keys.NO_PROMPT_NETWORK_NAME) + "\"";
configuration.preSharedKey = "\"" + txtRecord.getRecord().get(Keys.NO_PROMPT_NETWORK_PASS) + "\"";
int netId = wifiManager.addNetwork(configuration);
//disconnect form current network and connect to this one
wifiManager.disconnect();
wifiManager.enableNetwork(netId, true);
wifiManager.reconnect();
Log.i(TAG, "Connected to no prompt network");
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return binder;
}
@Override
protected void onHandleIntent(Intent intent) {
String action = intent.getAction();
Log.i(TAG, "Handling intent: " + action);
if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
// The list of discovered peers has changed
handlePeersChanged(intent);
} else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
// The state of Wi-Fi P2P connectivity has changed
handleConnectionChanged(intent);
} else if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
// Indicates whether Wi-Fi P2P is enabled
handleP2pStateChanged(intent);
} else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
// Indicates this device's configuration details have changed
handleThisDeviceChanged(intent);
} else if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action)) {
handleWifiStateChanged(intent);
} else if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action)) {
handleScanResultsAvailable(intent);
}
}
private void handleWifiStateChanged(Intent intent) {
Log.i(TAG, "Wi-Fi state changed");
int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, -1);
if (wifiState == WifiManager.WIFI_STATE_ENABLED) {
// Register app with Wi-Fi P2P framework, register WifiDirectBroadcastReceiver
Log.i(TAG, "Wi-Fi enabled");
registerP2p();
registerP2pReceiver();
} else if (wifiState == WifiManager.WIFI_STATE_DISABLED) {
// Remove local service, unregister app with Wi-Fi P2P framework, unregister P2pReceiver
Log.i(TAG, "Wi-Fi disabled");
clearServiceDiscoveryRequests();
removeService();
unregisterP2pReceiver();
unregisterP2p();
}
localBroadcastManager.sendBroadcast(new Intent(Action.WIFI_STATE_CHANGED));
}
private void handleScanResultsAvailable(Intent intent) {
Log.i(TAG, "Wi-Fi scan results available");
wifiScanResults = wifiManager.getScanResults();
Log.i(TAG, "There are " + (wifiScanResults.size() - 1) + " available networks");
for (ScanResult wifiScanResult : wifiScanResults) {
Log.i(TAG, wifiScanResult.SSID);
}
// Unregister the Wi-Fi receiver and register it again without the SCAN_RESULTS action
unregisterWifiReceiver();
wifiBroadcastReceiver = new WifiBroadcastReceiver();
IntentFilter intentFilter = new IntentFilter();
// Indicates that Wi-Fi has been enabled, disabled, enabling, disabling, or unknown
intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
registerReceiver(wifiBroadcastReceiver, intentFilter);
Log.i(TAG, "Wi-Fi BroadcastReceiver registered");
}
/**
* The list of discovered peers has changed
* Available extras: EXTRA_P2P_DEVICE_LIST
* @param intent
*/
private void handlePeersChanged(Intent intent) {
Log.i(TAG, "List of discovered peers changed");
if (wifiP2pManager != null) {
// Request the updated list of discovered peers from wifiP2PManager
wifiP2pManager.requestPeers(channel, new WifiP2pManager.PeerListListener() {
@Override
public void onPeersAvailable(WifiP2pDeviceList peers) {
WifiDirectHandler.this.peers = peers;
Intent intent = new Intent(Action.PEERS_CHANGED);
intent.putExtra(PEERS, peers);
localBroadcastManager.sendBroadcast(intent);
}
});
}
}
/**
* The state of Wi-Fi P2P connectivity has changed
* Here is where you can request group info
* Available extras: EXTRA_WIFI_P2P_INFO, EXTRA_NETWORK_INFO, EXTRA_WIFI_P2P_GROUP
* @param intent
*/
private void handleConnectionChanged(Intent intent) {
Log.i(TAG, "Wi-Fi P2P Connection Changed");
if(wifiP2pManager == null) {
return;
}
// Extra information from EXTRA_NETWORK_INFO
NetworkInfo networkInfo = intent.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);
if(networkInfo.isConnected()) {
Log.i(TAG, "Connected to P2P network. Requesting connection info");
wifiP2pManager.requestConnectionInfo(channel, WifiDirectHandler.this);
}
// Requests peer-to-peer group information
wifiP2pManager.requestGroupInfo(channel, new WifiP2pManager.GroupInfoListener() {
@Override
public void onGroupInfoAvailable(WifiP2pGroup wifiP2pGroup) {
if (wifiP2pGroup != null) {
Log.i(TAG, "Group info available");
Log.i(TAG, "WifiP2pGroup:");
Log.i(TAG, p2pGroupToString(wifiP2pGroup));
WifiDirectHandler.this.wifiP2pGroup = wifiP2pGroup;
}
}
});
}
/**
* Indicates whether Wi-Fi P2P is enabled
* Determine if Wi-Fi P2P mode is enabled or not, alert the Activity
* Available extras: EXTRA_WIFI_STATE
* Sticky Intent
* @param intent
*/
private void handleP2pStateChanged(Intent intent) {
Log.i(TAG, "Wi-Fi P2P State Changed:");
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
// Wi-Fi Direct is enabled
isWifiP2pEnabled = true;
Log.i(TAG, "- Wi-Fi Direct is enabled");
} else {
// Wi-Fi Direct is not enabled
isWifiP2pEnabled = false;
Log.i(TAG, "- Wi-Fi Direct is not enabled");
}
}
/**
* Indicates this device's configuration details have changed
* Sticky Intent
* @param intent
*/
private void handleThisDeviceChanged(Intent intent) {
Log.i(TAG, "This device changed");
// Extra information from EXTRA_WIFI_P2P_DEVICE
thisDevice = intent.getParcelableExtra(WifiP2pManager.EXTRA_WIFI_P2P_DEVICE);
// Logs extra information from EXTRA_WIFI_P2P_DEVICE
Log.i(TAG, p2pDeviceToString(thisDevice));
localBroadcastManager.sendBroadcast(new Intent(Action.DEVICE_CHANGED));
}
/**
* Toggle wifi
* @param wifiEnabled whether or not wifi should be enabled
*/
public void setWifiEnabled(boolean wifiEnabled) {
wifiManager.setWifiEnabled(wifiEnabled);
}
public Handler getHandler() {
return handler;
}
// TODO: Add JavaDoc
@Override
public boolean handleMessage(Message msg) {
Log.i(TAG, "handleMessage() called");
switch (msg.what) {
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String receivedMessage = new String(readBuf, 0, msg.arg1);
Log.i(TAG, "Received message: " + receivedMessage);
Intent messageReceivedIntent = new Intent(Action.MESSAGE_RECEIVED);
messageReceivedIntent.putExtra(MESSAGE_KEY, readBuf);
localBroadcastManager.sendBroadcast(messageReceivedIntent);
break;
case MY_HANDLE:
Object messageObject = msg.obj;
communicationManager = (CommunicationManager) messageObject;
break;
case COMMUNICATION_DISCONNECTED:
Log.i(TAG, "Handling communication disconnect");
localBroadcastManager.sendBroadcast(new Intent(Action.COMMUNICATION_DISCONNECTED));
break;
}
return true;
}
public CommunicationManager getCommunicationManager() {
return communicationManager;
}
/**
* Allows for binding to the service.
*/
public class WifiTesterBinder extends Binder {
public WifiDirectHandler getService() {
return WifiDirectHandler.this;
}
}
/**
* Actions that can be broadcast or received by the handler
*/
public class Action {
public static final String DNS_SD_TXT_RECORD_AVAILABLE = "dnsSdTxtRecordAdded",
DNS_SD_SERVICE_AVAILABLE = "dnsSdServiceAvailable",
SERVICE_REMOVED = "serviceRemoved",
PEERS_CHANGED = "peersChanged",
SERVICE_CONNECTED = "serviceConnected",
DEVICE_CHANGED = "deviceChanged",
MESSAGE_RECEIVED = "messageReceived",
WIFI_STATE_CHANGED = "wifiStateChanged",
COMMUNICATION_DISCONNECTED = "communicationDisconnected";
}
private class Keys {
public static final String NO_PROMPT_NETWORK_NAME = "networkName",
NO_PROMPT_NETWORK_PASS = "passphrase";
}
// TODO: Add JavaDoc
private class WifiDirectBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
onHandleIntent(intent);
}
}
// TODO: Add JavaDoc
private class WifiBroadcastReceiver extends BroadcastReceiver {
@Override public void onReceive(Context context, Intent intent) {
onHandleIntent(intent);
}
}
/**
* Takes a WifiP2pDevice and returns a String of readable device information
* @param wifiP2pDevice
* @return
*/
public String p2pDeviceToString(WifiP2pDevice wifiP2pDevice) {
if (wifiP2pDevice != null) {
String strDevice = "Device name: " + wifiP2pDevice.deviceName;
strDevice += "\nDevice address: " + wifiP2pDevice.deviceAddress;
if (wifiP2pDevice.equals(thisDevice)) {
strDevice += "\nIs group owner: " + isGroupOwner();
} else {
strDevice += "\nIs group owner: false";
}
strDevice += "\nStatus: " + deviceStatusToString(wifiP2pDevice.status) + "\n";
return strDevice;
} else {
Log.e(TAG, "WifiP2pDevice is null");
return "";
}
}
public String p2pInfoToString(WifiP2pInfo wifiP2pInfo) {
if (wifiP2pInfo != null) {
String strWifiP2pInfo = "Group formed: " + wifiP2pInfo.groupFormed;
strWifiP2pInfo += "\nIs group owner: " + wifiP2pInfo.isGroupOwner;
strWifiP2pInfo += "\nGroup owner address: " + wifiP2pInfo.groupOwnerAddress;
return strWifiP2pInfo;
} else {
Log.e(TAG, "WifiP2pInfo is null");
return "";
}
}
public String p2pGroupToString(WifiP2pGroup wifiP2pGroup) {
if (wifiP2pGroup != null) {
String strWifiP2pGroup = "Network name: " + wifiP2pGroup.getNetworkName();
strWifiP2pGroup += "\nIs group owner: " + wifiP2pGroup.isGroupOwner();
if (wifiP2pGroup.getOwner() != null) {
strWifiP2pGroup += "\nGroup owner: ";
strWifiP2pGroup += "\n" + p2pDeviceToString(wifiP2pGroup.getOwner());
}
if (wifiP2pGroup.getClientList() != null && !wifiP2pGroup.getClientList().isEmpty()) {
for (WifiP2pDevice client : wifiP2pGroup.getClientList()) {
strWifiP2pGroup += "\nClient: ";
strWifiP2pGroup += "\n" + p2pDeviceToString(client);
}
}
return strWifiP2pGroup;
} else {
Log.e(TAG, "WifiP2pGroup is null");
return "";
}
}
/**
* Translates a device status code to a readable String status
* @param status
* @return A readable String device status
*/
public String deviceStatusToString(int status) {
if (status == WifiP2pDevice.AVAILABLE) {
return "Available";
} else if (status == WifiP2pDevice.INVITED) {
return "Invited";
} else if (status == WifiP2pDevice.CONNECTED) {
return "Connected";
} else if (status == WifiP2pDevice.FAILED) {
return "Failed";
} else if (status == WifiP2pDevice.UNAVAILABLE) {
return "Unavailable";
} else {
return "Unknown";
}
}
public String getThisDeviceInfo() {
if (thisDevice == null) {
return "No Device Info";
} else {
if (thisDevice.deviceName.equals("")) {
thisDevice.deviceName = "Android Device";
}
return p2pDeviceToString(thisDevice);
}
}
public boolean isGroupOwner() {
return this.isGroupOwner;
}
public boolean isGroupFormed() {
return this.groupFormed;
}
public boolean isDiscovering() {
return this.isDiscovering;
}
public WifiP2pDevice getThisDevice() {
return this.thisDevice;
}
public WifiP2pServiceInfo getWifiP2pServiceInfo() {
return this.wifiP2pServiceInfo;
}
public List<ScanResult> getWifiScanResults() {
return wifiScanResults;
}
}
| Adds test logging
| wifibuddy/src/main/java/edu/rit/se/wifibuddy/WifiDirectHandler.java | Adds test logging | <ide><path>ifibuddy/src/main/java/edu/rit/se/wifibuddy/WifiDirectHandler.java
<ide> unregisterP2pReceiver();
<ide> unregisterP2p();
<ide> }
<add> Log.e(TAG, "TESTTTT");
<ide> localBroadcastManager.sendBroadcast(new Intent(Action.WIFI_STATE_CHANGED));
<ide> }
<ide> |
|
JavaScript | mit | b0fe6a480a31ea8b29c5e988085d37493ce3e70f | 0 | NabaviLab/CNV-Visualizer,igvteam/igv.js,NabaviLab/CNV-Visualizer,NabaviLab/CNV-Visualizer,NabaviLab/CNV-Visualizer,igvteam/igv.js,NabaviLab/CNV-Visualizer | var igv = (function (igv) {
igv.createCursorBrowser = function () {
var browser = new igv.Browser("CURSOR"),
contentHeader = $('<div class="row"></div>')[0],
contentHeaderDiv = $('<div id="igvHeaderDiv" class="col-md-12" style="font-size:16px;"><span id="igvHeaderRegionDisplaySpan"></span></div>')[0],
trackContainer = $('<div id="igvTrackContainerDiv" class="igv-track-container-div">')[0];
browser.startup = function () {
browser.genome = null;
browser.referenceFrame = null;
browser.controlPanelWidth = 50;
browser.trackContainerDiv = trackContainer;
browser.trackPanels = [];
initCursor();
window.onresize = throttle(function () {
if (browser.ideoPanel) browser.ideoPanel.resize();
browser.trackPanels.forEach(function (panel) {
panel.resize();
})
}, 10);
function initCursor() {
var regionDisplayJQueryObject = $('#igvHeaderRegionDisplaySpan');
browser.cursorModel = new cursor.CursorModel(browser, regionDisplayJQueryObject);
browser.referenceFrame = new igv.ReferenceFrame("", 0, 1 / browser.cursorModel.framePixelWidth);
browser.setFrameWidth = function (frameWidthString) {
var frameWidth = parseFloat(frameWidthString);
if (frameWidth > 0) {
browser.cursorModel.framePixelWidth = frameWidth;
$( "input[id='frameWidthInput']" ).val( browser.cursorModel.framePixelWidth );
browser.referenceFrame.bpPerPixel = 1 / frameWidth;
browser.update();
}
};
browser.setRegionSize = function (regionSizeString) {
var regionSize = parseFloat(regionSizeString);
if (regionSize > 0) {
browser.cursorModel.regionWidth = regionSize;
browser.update();
}
};
browser.zoomIn = function () {
browser.cursorModel.framePixelWidth *= 2;
$( "input[id='frameWidthInput']" ).val( browser.cursorModel.framePixelWidth );
browser.update();
};
browser.zoomOut = function () {
browser.cursorModel.framePixelWidth /= 2;
$( "input[id='frameWidthInput']" ).val( browser.cursorModel.framePixelWidth );
browser.update();
};
browser.fitToScreen = function () {
var regionCount, frameWidth;
if (!(browser.cursorModel && browser.cursorModel.regions)) return;
regionCount = browser.cursorModel.getRegionList().length;
if (regionCount > 0) {
frameWidth = (browser.trackContainerDiv.clientWidth - browser.controlPanelWidth) / regionCount;
browser.referenceFrame.start = 0;
browser.setFrameWidth(frameWidth);
$('frameWidthBox').value = frameWidth;
}
};
var tssUrl = "test/data/cursor/hg19.tss.bed.gz";
var peakURL = "test/data/cursor/wgEncodeBroadHistoneH1hescH3k4me3StdPk.broadPeak.gz";
var peak2URL = "test/data/cursor/wgEncodeBroadHistoneH1hescH3k27me3StdPk.broadPeak.gz";
var peakDataSource = new igv.BedFeatureSource(peakURL);
var peak2DataSource = new igv.BedFeatureSource(peak2URL);
var tssDataSource = new igv.BedFeatureSource(tssUrl);
var tssTrack = new cursor.CursorTrack(tssDataSource, browser.cursorModel, browser.referenceFrame, "TSS", 40);
var track1 = new cursor.CursorTrack(peakDataSource, browser.cursorModel, browser.referenceFrame, "H3k4me3 H1hesc", browser.trackHeight);
track1.color = "rgb(0,150,0)";
var track2 = new cursor.CursorTrack(peak2DataSource, browser.cursorModel, browser.referenceFrame, "H3k27me3 H1hesc", browser.trackHeight);
track2.color = "rgb(150,0,0)";
// Set the TSS track as the inital "selected" track (i.e. defines the regions)
tssDataSource.allFeatures(function (featureList) {
browser.cursorModel.setRegions(featureList);
browser.addTrack(tssTrack);
browser.addTrack(track1);
browser.addTrack(track2);
tssTrack.labelButton.className = "btn btn-xs btn-cursor-selected";
});
}
};
browser.div = $('<div id="igvRootDiv" class="igv-root-div">')[0];
$(browser.div).append(contentHeader);
$(contentHeader).append(contentHeaderDiv);
$(browser.div).append(trackContainer);
document.getElementById('igvContainerDiv').appendChild(browser.div);
// Append event handlers to DOM elements
document.getElementById('zoomOut').onclick = function (e) {
browser.zoomOut()
};
document.getElementById('zoomIn').onclick = function () {
browser.zoomIn()
};
document.getElementById('fitToScreen').onclick = function () {
browser.fitToScreen();
};
document.getElementById('frameWidthInput').onchange = function (e) {
var value = $("#frameWidthInput").val();
if (!igv.isNumber(value)) {
console.log("bogus " + value);
return;
}
browser.setFrameWidth(parseFloat(value, 10));
};
document.getElementById('regionSizeInput').onchange = function (e) {
var value = $("#regionSizeInput").val();
if (!igv.isNumber(value)) {
console.log("bogus " + value);
return;
}
browser.setRegionSize(parseFloat(value, 10));
};
document.getElementById('trackHeightInput').onchange = function (e) {
var value = $("#trackHeightInput").val();
if (!igv.isNumber(value)) {
console.log("bogus " + value);
return;
}
browser.setTrackHeight( Math.round(parseFloat(value, 10)) );
};
var fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', function(e) {
var localFile,
localFiles = fileInput.files,
featureSource,
cursorTrack;
for (var i=0; i < localFiles.length; i++) {
localFile = localFiles[ i ];
featureSource = new igv.BedFeatureSource(localFile);
cursorTrack = new cursor.CursorTrack(featureSource, browser.cursorModel,browser.referenceFrame, localFile.name, browser.trackHeight);
browser.addTrack(cursorTrack);
}
});
// Load ENCODE DataTables data and build markup for modal dialog.
encode.createEncodeDataTablesDataSet("test/data/cursor/encode/peaks.hg19.txt", function (dataSet) {
var encodeModalTable = $('#encodeModalTable'),
myDataTable = encodeModalTable.dataTable( {
"data": dataSet,
"scrollY": "400px",
"scrollCollapse": true,
"paging": false,
"columns": [
{ "title": "cell" },
{ "title": "dataType" },
{ "title": "antibody" },
{ "title": "view" },
{ "title": "replicate" },
{ "title": "type" },
{ "title": "lab" },
{ "title": "path" }
]
} );
encodeModalTable.find('tbody').on( 'click', 'tr', function () {
if ( $(this).hasClass('selected') ) {
$(this).removeClass('selected');
}
else {
// Commenting this out enables multi-selection
// myDataTable.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
}
} );
$('#encodeModalTopCloseButton').on( 'click', function () {
myDataTable.$('tr.selected').removeClass('selected');
} );
$('#encodeModalBottomCloseButton').on( 'click', function () {
myDataTable.$('tr.selected').removeClass('selected');
} );
$('#encodeModalGoButton').on( 'click', function () {
var featureSource,
cursorTrack,
tableRow,
tableRows,
tableCell,
tableCells,
record = {};
tableRows = myDataTable.$('tr.selected');
if (0 < tableRows.length) {
tableRows.removeClass('selected');
for (var i= 0; i < tableRows.length; i++) {
tableRow = tableRows[ i ];
tableCells = $('td', tableRow);
tableCells.each (function() {
tableCell = $(this)[0];
record[ encode.dataTableRowLabels[ tableCell.cellIndex ] ] = tableCell.innerText;
});
featureSource = new igv.BedFeatureSource(record.path);
cursorTrack = new cursor.CursorTrack(featureSource, browser.cursorModel, browser.referenceFrame, encode.encodeTrackLabel(record), browser.trackHeight);
cursorTrack.color = encode.encodeAntibodyColor(record.antibody);
browser.addTrack(cursorTrack);
}
}
});
});
// Append resultant ENCODE DataTables markup
$('#encodeModalBody').html( '<table cellpadding="0" cellspacing="0" border="0" class="display" id="encodeModalTable"></table>' );
return browser;
};
function throttle(fn, threshhold, scope) {
threshhold || (threshhold = 100);
var last, deferTimer;
return function () {
var context = scope || this;
var now = +new Date,
args = arguments;
if (last && now < last + threshhold) {
// hold on to it
clearTimeout(deferTimer);
deferTimer = setTimeout(function () {
last = now;
fn.apply(context, args);
}, threshhold);
} else {
last = now;
fn.apply(context, args);
}
}
}
return igv;
})(igv || {}); | js/cursor/igv-cursor.js | var igv = (function (igv) {
igv.createCursorBrowser = function () {
var browser = new igv.Browser("CURSOR"),
contentHeader = $('<div class="row"></div>')[0],
contentHeaderDiv = $('<div id="igvHeaderDiv" class="col-md-12" style="font-size:16px;"><span id="igvHeaderRegionDisplaySpan"></span></div>')[0],
trackContainer = $('<div id="igvTrackContainerDiv" class="igv-track-container-div">')[0];
browser.startup = function () {
browser.genome = null;
browser.referenceFrame = null;
browser.controlPanelWidth = 50;
browser.trackContainerDiv = trackContainer;
browser.trackPanels = [];
initCursor();
window.onresize = throttle(function () {
if (browser.ideoPanel) browser.ideoPanel.resize();
browser.trackPanels.forEach(function (panel) {
panel.resize();
})
}, 10);
function initCursor() {
var regionDisplayJQueryObject = $('#igvHeaderRegionDisplaySpan');
browser.cursorModel = new cursor.CursorModel(browser, regionDisplayJQueryObject);
browser.referenceFrame = new igv.ReferenceFrame("", 0, 1 / browser.cursorModel.framePixelWidth);
browser.setFrameWidth = function (frameWidthString) {
var frameWidth = parseFloat(frameWidthString);
if (frameWidth > 0) {
browser.cursorModel.framePixelWidth = frameWidth;
browser.referenceFrame.bpPerPixel = 1 / frameWidth;
browser.update();
}
};
browser.setRegionSize = function (regionSizeString) {
var regionSize = parseFloat(regionSizeString);
if (regionSize > 0) {
browser.cursorModel.regionWidth = regionSize;
browser.update();
}
};
browser.zoomIn = function () {
browser.cursorModel.framePixelWidth *= 2;
browser.update();
};
browser.zoomOut = function () {
browser.cursorModel.framePixelWidth /= 2;
browser.update();
};
browser.fitToScreen = function () {
var regionCount, frameWidth;
if (!(browser.cursorModel && browser.cursorModel.regions)) return;
regionCount = browser.cursorModel.getRegionList().length;
if (regionCount > 0) {
frameWidth = (browser.trackContainerDiv.clientWidth - browser.controlPanelWidth) / regionCount;
browser.referenceFrame.start = 0;
browser.setFrameWidth(frameWidth);
$('frameWidthBox').value = frameWidth;
}
};
var tssUrl = "test/data/cursor/hg19.tss.bed.gz";
var peakURL = "test/data/cursor/wgEncodeBroadHistoneH1hescH3k4me3StdPk.broadPeak.gz";
var peak2URL = "test/data/cursor/wgEncodeBroadHistoneH1hescH3k27me3StdPk.broadPeak.gz";
var peakDataSource = new igv.BedFeatureSource(peakURL);
var peak2DataSource = new igv.BedFeatureSource(peak2URL);
var tssDataSource = new igv.BedFeatureSource(tssUrl);
var tssTrack = new cursor.CursorTrack(tssDataSource, browser.cursorModel, browser.referenceFrame, "TSS", 40);
var track1 = new cursor.CursorTrack(peakDataSource, browser.cursorModel, browser.referenceFrame, "H3k4me3 H1hesc", browser.trackHeight);
track1.color = "rgb(0,150,0)";
var track2 = new cursor.CursorTrack(peak2DataSource, browser.cursorModel, browser.referenceFrame, "H3k27me3 H1hesc", browser.trackHeight);
track2.color = "rgb(150,0,0)";
// Set the TSS track as the inital "selected" track (i.e. defines the regions)
tssDataSource.allFeatures(function (featureList) {
browser.cursorModel.setRegions(featureList);
browser.addTrack(tssTrack);
browser.addTrack(track1);
browser.addTrack(track2);
tssTrack.labelButton.className = "btn btn-xs btn-cursor-selected";
});
}
};
browser.div = $('<div id="igvRootDiv" class="igv-root-div">')[0];
$(browser.div).append(contentHeader);
$(contentHeader).append(contentHeaderDiv);
$(browser.div).append(trackContainer);
document.getElementById('igvContainerDiv').appendChild(browser.div);
// Append event handlers to DOM elements
document.getElementById('zoomOut').onclick = function (e) {
browser.zoomOut()
};
document.getElementById('zoomIn').onclick = function () {
browser.zoomIn()
};
document.getElementById('fitToScreen').onclick = function () {
browser.fitToScreen();
};
document.getElementById('frameWidthInput').onchange = function (e) {
var value = $("#frameWidthInput").val();
if (!igv.isNumber(value)) {
console.log("bogus " + value);
return;
}
browser.setFrameWidth(parseFloat(value, 10));
};
document.getElementById('regionSizeInput').onchange = function (e) {
var value = $("#regionSizeInput").val();
if (!igv.isNumber(value)) {
console.log("bogus " + value);
return;
}
browser.setRegionSize(parseFloat(value, 10));
};
document.getElementById('trackHeightInput').onchange = function (e) {
var value = $("#trackHeightInput").val();
if (!igv.isNumber(value)) {
console.log("bogus " + value);
return;
}
browser.setTrackHeight( Math.round(parseFloat(value, 10)) );
};
var fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', function(e) {
var localFile,
localFiles = fileInput.files,
featureSource,
cursorTrack;
for (var i=0; i < localFiles.length; i++) {
localFile = localFiles[ i ];
featureSource = new igv.BedFeatureSource(localFile);
cursorTrack = new cursor.CursorTrack(featureSource, browser.cursorModel,browser.referenceFrame, localFile.name, browser.trackHeight);
browser.addTrack(cursorTrack);
}
});
// Load ENCODE DataTables data and build markup for modal dialog.
encode.createEncodeDataTablesDataSet("test/data/cursor/encode/peaks.hg19.txt", function (dataSet) {
var encodeModalTable = $('#encodeModalTable'),
myDataTable = encodeModalTable.dataTable( {
"data": dataSet,
"scrollY": "400px",
"scrollCollapse": true,
"paging": false,
"columns": [
{ "title": "cell" },
{ "title": "dataType" },
{ "title": "antibody" },
{ "title": "view" },
{ "title": "replicate" },
{ "title": "type" },
{ "title": "lab" },
{ "title": "path" }
]
} );
encodeModalTable.find('tbody').on( 'click', 'tr', function () {
if ( $(this).hasClass('selected') ) {
$(this).removeClass('selected');
}
else {
// Commenting this out enables multi-selection
// myDataTable.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
}
} );
$('#encodeModalTopCloseButton').on( 'click', function () {
myDataTable.$('tr.selected').removeClass('selected');
} );
$('#encodeModalBottomCloseButton').on( 'click', function () {
myDataTable.$('tr.selected').removeClass('selected');
} );
$('#encodeModalGoButton').on( 'click', function () {
var featureSource,
cursorTrack,
tableRow,
tableRows,
tableCell,
tableCells,
record = {};
tableRows = myDataTable.$('tr.selected');
if (0 < tableRows.length) {
tableRows.removeClass('selected');
for (var i= 0; i < tableRows.length; i++) {
tableRow = tableRows[ i ];
tableCells = $('td', tableRow);
tableCells.each (function() {
tableCell = $(this)[0];
record[ encode.dataTableRowLabels[ tableCell.cellIndex ] ] = tableCell.innerText;
});
featureSource = new igv.BedFeatureSource(record.path);
cursorTrack = new cursor.CursorTrack(featureSource, browser.cursorModel, browser.referenceFrame, encode.encodeTrackLabel(record), browser.trackHeight);
cursorTrack.color = encode.encodeAntibodyColor(record.antibody);
browser.addTrack(cursorTrack);
}
}
});
});
// Append resultant ENCODE DataTables markup
$('#encodeModalBody').html( '<table cellpadding="0" cellspacing="0" border="0" class="display" id="encodeModalTable"></table>' );
return browser;
};
function throttle(fn, threshhold, scope) {
threshhold || (threshhold = 100);
var last, deferTimer;
return function () {
var context = scope || this;
var now = +new Date,
args = arguments;
if (last && now < last + threshhold) {
// hold on to it
clearTimeout(deferTimer);
deferTimer = setTimeout(function () {
last = now;
fn.apply(context, args);
}, threshhold);
} else {
last = now;
fn.apply(context, args);
}
}
}
return igv;
})(igv || {}); | Update frameWidth display in realtime.
| js/cursor/igv-cursor.js | Update frameWidth display in realtime. | <ide><path>s/cursor/igv-cursor.js
<ide> if (frameWidth > 0) {
<ide>
<ide> browser.cursorModel.framePixelWidth = frameWidth;
<add> $( "input[id='frameWidthInput']" ).val( browser.cursorModel.framePixelWidth );
<add>
<ide> browser.referenceFrame.bpPerPixel = 1 / frameWidth;
<ide> browser.update();
<ide> }
<ide> browser.zoomIn = function () {
<ide>
<ide> browser.cursorModel.framePixelWidth *= 2;
<add> $( "input[id='frameWidthInput']" ).val( browser.cursorModel.framePixelWidth );
<add>
<ide> browser.update();
<ide> };
<ide>
<ide> browser.zoomOut = function () {
<ide>
<ide> browser.cursorModel.framePixelWidth /= 2;
<add> $( "input[id='frameWidthInput']" ).val( browser.cursorModel.framePixelWidth );
<add>
<ide> browser.update();
<ide> };
<ide> |
|
Java | lgpl-2.1 | 754d1bc8eb963f26c95f15b72558d7550da9c243 | 0 | CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine | /*
* jETeL/Clover - Java based ETL application framework.
* Created on Apr 25, 2003
* Copyright (C) 2003, 2002 David Pavlis, Wes Maciorowski
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.jetel.exception;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import org.jetel.data.DataRecord;
import org.jetel.data.parser.DelimitedDataParser;
import org.jetel.metadata.DataRecordMetadata;
import org.jetel.metadata.DataRecordMetadataXMLReaderWriter;
import org.jetel.test.CloverTestCase;
/**
* @author maciorowski
*
*/
public class BadDataFormatExceptionHandler_DelimitedDataParserNIO_Test extends CloverTestCase {
private DelimitedDataParser aParser = null;
private DelimitedDataParser aParser2 = null;
private DataRecord record;
private FileInputStream in = null;
private FileInputStream in2 = null;
private DataRecordMetadata metadata = null;
@Override
protected void setUp() throws FileNotFoundException {
initEngine();
DataRecordMetadataXMLReaderWriter xmlReader = new DataRecordMetadataXMLReaderWriter();
metadata = xmlReader.read(new FileInputStream("config/test/rec_def/DL_null_def_rec.xml"));
in = new FileInputStream("data/in/good/DL28_NL.txt");
in2 = new FileInputStream("data/in/bad/DL_NL_nulls.txt");
aParser2 = new DelimitedDataParser(metadata);
aParser = new DelimitedDataParser(metadata);
record = new DataRecord(metadata);
record.init();
}
@Override
protected void tearDown() {
aParser.close();
aParser = null;
aParser2.close();
aParser2 = null;
record = null;
metadata = null;
in = null;
in2 = null;
}
/**
* Test for @link for a well formatted data source.
* No handler
*/
public void test_goodFile() throws ComponentNotReadyException, JetelException {
// test no handler ------------------------------------
aParser.init();
aParser.setDataSource(in);
while((record=aParser.getNext(record))!=null){}
aParser.close();
}
/**
* Test for @link for a well formatted data source.
* strict handler
*/
public void test_strict_goodFile() throws ComponentNotReadyException, JetelException {
IParserExceptionHandler aHandler = null;
// test strict handler ------------------------------------
aParser.init();
aParser.setDataSource(in);
aHandler = ParserExceptionHandlerFactory.getHandler(PolicyType.STRICT);
aParser.setExceptionHandler(aHandler);
while((record=aParser.getNext(record))!=null){}
aParser.close();
}
/**
* Test for @link for a well formatted data source.
* controlled handler
*/
public void test_controlled_goodFile() throws ComponentNotReadyException, JetelException {
IParserExceptionHandler aHandler = null;
// test controlled handler ------------------------------------
aParser.init();
aParser.setDataSource(in);
aHandler = ParserExceptionHandlerFactory.getHandler(PolicyType.CONTROLLED);
aParser.setExceptionHandler(aHandler);
// 1.0Stone 101 01/11/93
// -15.5 Brook 112 11/03/02
// -0.7Bone Broo 9901/01/03
int recCount = 0;
while ((record = aParser.getNext(record)) != null) {
if (recCount == 0) {
assertEquals(record.getField(0).toString(), "1.0");
assertEquals(record.getField(1).toString(), "Stone");
assertEquals(record.getField(2).toString(), "101");
assertEquals(record.getField(3).toString(), "01/11/93");
} else if (recCount == 1) {
assertEquals(record.getField(0).toString(), "-15.5");
assertEquals(record.getField(1).toString(), "Brook");
assertEquals(record.getField(2).toString(), "112");
assertEquals(record.getField(3).toString(), "11/03/02");
} else if (recCount == 2) {
assertEquals(record.getField(0).toString(), "-0.7");
assertEquals(record.getField(1).toString(), "Bone Broo");
assertEquals(record.getField(2).toString(), "99");
assertEquals(record.getField(3).toString(), "01/01/03");
}
recCount++;
}
assertEquals(3, recCount);
aParser.close();
}
/**
* Test for @link for a well formatted data source.
* lenient handler
*/
public void test_lenient_goodFile() throws JetelException, ComponentNotReadyException {
IParserExceptionHandler aHandler = null;
// test lenient handler ------------------------------------
aParser.init();
aParser.setDataSource(in);
aHandler = ParserExceptionHandlerFactory.getHandler(PolicyType.LENIENT);
aParser.setExceptionHandler(aHandler);
// 1.0Stone 101 01/11/93
// -15.5 Brook 112 11/03/02
// -0.7Bone Broo 9901/01/03
int recCount = 0;
while ((record = aParser.getNext(record)) != null) {
if (recCount == 0) {
assertEquals(record.getField(0).toString(), "1.0");
assertEquals(record.getField(1).toString(), "Stone");
assertEquals(record.getField(2).toString(), "101");
assertEquals(record.getField(3).toString(), "01/11/93");
} else if (recCount == 1) {
assertEquals(record.getField(0).toString(), "-15.5");
assertEquals(record.getField(1).toString(), "Brook");
assertEquals(record.getField(2).toString(), "112");
assertEquals(record.getField(3).toString(), "11/03/02");
} else if (recCount == 2) {
assertEquals(record.getField(0).toString(), "-0.7");
assertEquals(record.getField(1).toString(), "Bone Broo");
assertEquals(record.getField(2).toString(), "99");
assertEquals(record.getField(3).toString(), "01/01/03");
}
recCount++;
}
assertEquals(3, recCount);
}
/**
* Test for a data source with poorly formatted fields.
* No handler.
* @throws JetelException
*/
public void test_badFile() throws ComponentNotReadyException, JetelException {
boolean failed = false;
// test no handler ------------------------------------
aParser2.init();
aParser2.setDataSource(in2);
try{
while((record=aParser2.getNext(record))!=null){
fail("Should throw BadDataFormatException");
}
} catch (BadDataFormatException e){
failed = true;
}
aParser2.close();
if(!failed)
fail("Should raise an RuntimeException");
}
/**
* Test for a data source with poorly formatted fields.
* No handler.
*/
public void test_strict_badFile() throws ComponentNotReadyException, JetelException {
IParserExceptionHandler aHandler = null;
boolean failed = false;
// test strict handler ------------------------------------
aParser2.init();
aParser2.setDataSource(in2);
aHandler = ParserExceptionHandlerFactory.getHandler(PolicyType.STRICT);
aParser2.setExceptionHandler(aHandler);
int recCount = 0;
try{
while((record=aParser2.getNext(record))!=null){
recCount++;
}
}catch (BadDataFormatException e) {
failed = true;
}
if(!failed)
fail("Should raise an BadDataFormatException");
assertEquals(0,recCount);
aParser2.close();
}
/**
* Test for a data source with poorly formatted fields.
* controlled handler.
*/
public void test_controlled_badFile() throws JetelException, ComponentNotReadyException {
IParserExceptionHandler aHandler = null;
// test controlled handler ------------------------------------
aParser2.init();
aParser2.setDataSource(in2);
aHandler = ParserExceptionHandlerFactory.getHandler(PolicyType.CONTROLLED);
aParser2.setExceptionHandler(aHandler);
int recCount = 0;
while((record != null)){
try {
record = aParser2.getNext(record);
recCount++;
} catch (BadDataFormatException e) {
for (BadDataFormatException exception : e) {
System.out.println(exception.getMessage());
}
System.out.println("Message from handler:");
System.out.println(aHandler.getErrorMessage());
}
}
assertEquals(3,recCount); //may need to be revised
//depending how we implement nullable property
aParser2.close();
}
/**
* Test for a data source with poorly formatted fields.
* lenient handler.
*/
public void test_lenient_badFile() throws ComponentNotReadyException, JetelException {
IParserExceptionHandler aHandler = null;
// test lenient handler ------------------------------------
aParser2.init();
aParser2.setDataSource(in2);
aHandler = ParserExceptionHandlerFactory.getHandler(PolicyType.LENIENT);
aParser2.setExceptionHandler(aHandler);
int recCount = 0;
// the content of the test file
// N/AStone 01/11/93
// -15.5 112 11/03/02
// -0.7Bone Broo 99
while ((record = aParser2.getNext(record)) != null) {
if (recCount == 0) {
assertEquals("-15.5", record.getField(0).toString());
assertEquals("", record.getField(1).toString());
assertEquals(null, record.getField(1).getValue());
} else if (recCount == 1) {
assertEquals("", record.getField(3).toString());
assertNull(record.getField(3).getValue());
}
recCount++;
}
assertEquals(2, recCount);
}
} | cloveretl.engine/test/org/jetel/exception/BadDataFormatExceptionHandler_DelimitedDataParserNIO_Test.java | /*
* jETeL/Clover - Java based ETL application framework.
* Created on Apr 25, 2003
* Copyright (C) 2003, 2002 David Pavlis, Wes Maciorowski
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.jetel.exception;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import org.jetel.data.DataRecord;
import org.jetel.data.parser.DelimitedDataParser;
import org.jetel.metadata.DataRecordMetadata;
import org.jetel.metadata.DataRecordMetadataXMLReaderWriter;
import org.jetel.test.CloverTestCase;
import de.schlichtherle.io.File;
/**
* @author maciorowski
*
*/
public class BadDataFormatExceptionHandler_DelimitedDataParserNIO_Test extends CloverTestCase {
private DelimitedDataParser aParser = null;
private DelimitedDataParser aParser2 = null;
private DataRecord record;
private FileInputStream in = null;
private FileInputStream in2 = null;
private DataRecordMetadata metadata = null;
@Override
protected void setUp() throws FileNotFoundException {
initEngine();
DataRecordMetadataXMLReaderWriter xmlReader = new DataRecordMetadataXMLReaderWriter();
metadata = xmlReader.read(new FileInputStream("config/test/rec_def/DL_null_def_rec.xml"));
File testFile = new File("data/in/good/DL28_NL.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(testFile)));
System.out.println("### CONTENT OF THE FILE " + testFile.getAbsolutePath());
String line = null;
try {
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
in = new FileInputStream("data/in/good/DL28_NL.txt");
in2 = new FileInputStream("data/in/bad/DL_NL_nulls.txt");
aParser2 = new DelimitedDataParser(metadata);
aParser = new DelimitedDataParser(metadata);
record = new DataRecord(metadata);
record.init();
}
@Override
protected void tearDown() {
aParser.close();
aParser = null;
aParser2.close();
aParser2 = null;
record = null;
metadata = null;
in = null;
in2 = null;
}
/**
* Test for @link for a well formatted data source.
* No handler
*/
public void test_goodFile() throws ComponentNotReadyException, JetelException {
// test no handler ------------------------------------
aParser.init();
aParser.setDataSource(in);
while((record=aParser.getNext(record))!=null){}
aParser.close();
}
/**
* Test for @link for a well formatted data source.
* strict handler
*/
public void test_strict_goodFile() throws ComponentNotReadyException, JetelException {
IParserExceptionHandler aHandler = null;
// test strict handler ------------------------------------
aParser.init();
aParser.setDataSource(in);
aHandler = ParserExceptionHandlerFactory.getHandler(PolicyType.STRICT);
aParser.setExceptionHandler(aHandler);
while((record=aParser.getNext(record))!=null){}
aParser.close();
}
/**
* Test for @link for a well formatted data source.
* controlled handler
*/
public void test_controlled_goodFile() throws ComponentNotReadyException, JetelException {
IParserExceptionHandler aHandler = null;
// test controlled handler ------------------------------------
aParser.init();
aParser.setDataSource(in);
aHandler = ParserExceptionHandlerFactory.getHandler(PolicyType.CONTROLLED);
aParser.setExceptionHandler(aHandler);
// 1.0Stone 101 01/11/93
// -15.5 Brook 112 11/03/02
// -0.7Bone Broo 9901/01/03
int recCount = 0;
while ((record = aParser.getNext(record)) != null) {
if (recCount == 0) {
assertEquals(record.getField(0).toString(), "1.0");
assertEquals(record.getField(1).toString(), "Stone");
assertEquals(record.getField(2).toString(), "101");
assertEquals(record.getField(3).toString(), "01/11/93");
} else if (recCount == 1) {
assertEquals(record.getField(0).toString(), "-15.5");
assertEquals(record.getField(1).toString(), "Brook");
assertEquals(record.getField(2).toString(), "112");
assertEquals(record.getField(3).toString(), "11/03/02");
} else if (recCount == 2) {
assertEquals(record.getField(0).toString(), "-0.7");
assertEquals(record.getField(1).toString(), "Bone Broo");
assertEquals(record.getField(2).toString(), "99");
assertEquals(record.getField(3).toString(), "01/01/03");
}
recCount++;
}
assertEquals(3, recCount);
aParser.close();
}
/**
* Test for @link for a well formatted data source.
* lenient handler
*/
public void test_lenient_goodFile() throws JetelException, ComponentNotReadyException {
IParserExceptionHandler aHandler = null;
// test lenient handler ------------------------------------
aParser.init();
aParser.setDataSource(in);
aHandler = ParserExceptionHandlerFactory.getHandler(PolicyType.LENIENT);
aParser.setExceptionHandler(aHandler);
// 1.0Stone 101 01/11/93
// -15.5 Brook 112 11/03/02
// -0.7Bone Broo 9901/01/03
int recCount = 0;
while ((record = aParser.getNext(record)) != null) {
if (recCount == 0) {
assertEquals(record.getField(0).toString(), "1.0");
assertEquals(record.getField(1).toString(), "Stone");
assertEquals(record.getField(2).toString(), "101");
assertEquals(record.getField(3).toString(), "01/11/93");
} else if (recCount == 1) {
assertEquals(record.getField(0).toString(), "-15.5");
assertEquals(record.getField(1).toString(), "Brook");
assertEquals(record.getField(2).toString(), "112");
assertEquals(record.getField(3).toString(), "11/03/02");
} else if (recCount == 2) {
assertEquals(record.getField(0).toString(), "-0.7");
assertEquals(record.getField(1).toString(), "Bone Broo");
assertEquals(record.getField(2).toString(), "99");
assertEquals(record.getField(3).toString(), "01/01/03");
}
recCount++;
}
assertEquals(3, recCount);
}
/**
* Test for a data source with poorly formatted fields.
* No handler.
* @throws JetelException
*/
public void test_badFile() throws ComponentNotReadyException, JetelException {
boolean failed = false;
// test no handler ------------------------------------
aParser2.init();
aParser2.setDataSource(in2);
try{
while((record=aParser2.getNext(record))!=null){
fail("Should throw BadDataFormatException");
}
} catch (BadDataFormatException e){
failed = true;
}
aParser2.close();
if(!failed)
fail("Should raise an RuntimeException");
}
/**
* Test for a data source with poorly formatted fields.
* No handler.
*/
public void test_strict_badFile() throws ComponentNotReadyException, JetelException {
IParserExceptionHandler aHandler = null;
boolean failed = false;
// test strict handler ------------------------------------
aParser2.init();
aParser2.setDataSource(in2);
aHandler = ParserExceptionHandlerFactory.getHandler(PolicyType.STRICT);
aParser2.setExceptionHandler(aHandler);
int recCount = 0;
try{
while((record=aParser2.getNext(record))!=null){
recCount++;
}
}catch (BadDataFormatException e) {
failed = true;
}
if(!failed)
fail("Should raise an BadDataFormatException");
assertEquals(0,recCount);
aParser2.close();
}
/**
* Test for a data source with poorly formatted fields.
* controlled handler.
*/
public void test_controlled_badFile() throws JetelException, ComponentNotReadyException {
IParserExceptionHandler aHandler = null;
// test controlled handler ------------------------------------
aParser2.init();
aParser2.setDataSource(in2);
aHandler = ParserExceptionHandlerFactory.getHandler(PolicyType.CONTROLLED);
aParser2.setExceptionHandler(aHandler);
int recCount = 0;
while((record != null)){
try {
record = aParser2.getNext(record);
recCount++;
} catch (BadDataFormatException e) {
for (BadDataFormatException exception : e) {
System.out.println(exception.getMessage());
}
System.out.println("Message from handler:");
System.out.println(aHandler.getErrorMessage());
}
}
assertEquals(3,recCount); //may need to be revised
//depending how we implement nullable property
aParser2.close();
}
/**
* Test for a data source with poorly formatted fields.
* lenient handler.
*/
public void test_lenient_badFile() throws ComponentNotReadyException, JetelException {
IParserExceptionHandler aHandler = null;
// test lenient handler ------------------------------------
aParser2.init();
aParser2.setDataSource(in2);
aHandler = ParserExceptionHandlerFactory.getHandler(PolicyType.LENIENT);
aParser2.setExceptionHandler(aHandler);
int recCount = 0;
// the content of the test file
// N/AStone 01/11/93
// -15.5 112 11/03/02
// -0.7Bone Broo 99
while ((record = aParser2.getNext(record)) != null) {
if (recCount == 0) {
assertEquals("-15.5", record.getField(0).toString());
assertEquals("", record.getField(1).toString());
assertEquals(null, record.getField(1).getValue());
} else if (recCount == 1) {
assertEquals("", record.getField(3).toString());
assertNull(record.getField(3).getValue());
}
recCount++;
}
assertEquals(2, recCount);
}
} | MINOR: test prints for debugging unit tests removed
git-svn-id: 0c3331f003cd65fce51c5a16c6c1f4b0bff1e9aa@11854 a09ad3ba-1a0f-0410-b1b9-c67202f10d70
| cloveretl.engine/test/org/jetel/exception/BadDataFormatExceptionHandler_DelimitedDataParserNIO_Test.java | MINOR: test prints for debugging unit tests removed | <ide><path>loveretl.engine/test/org/jetel/exception/BadDataFormatExceptionHandler_DelimitedDataParserNIO_Test.java
<ide>
<ide> package org.jetel.exception;
<ide>
<del>import java.io.BufferedReader;
<ide> import java.io.FileInputStream;
<ide> import java.io.FileNotFoundException;
<del>import java.io.IOException;
<del>import java.io.InputStreamReader;
<ide>
<ide> import org.jetel.data.DataRecord;
<ide> import org.jetel.data.parser.DelimitedDataParser;
<ide> import org.jetel.metadata.DataRecordMetadata;
<ide> import org.jetel.metadata.DataRecordMetadataXMLReaderWriter;
<ide> import org.jetel.test.CloverTestCase;
<del>
<del>import de.schlichtherle.io.File;
<ide>
<ide> /**
<ide> * @author maciorowski
<ide> DataRecordMetadataXMLReaderWriter xmlReader = new DataRecordMetadataXMLReaderWriter();
<ide>
<ide> metadata = xmlReader.read(new FileInputStream("config/test/rec_def/DL_null_def_rec.xml"));
<del>
<del> File testFile = new File("data/in/good/DL28_NL.txt");
<del> BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(testFile)));
<del> System.out.println("### CONTENT OF THE FILE " + testFile.getAbsolutePath());
<del> String line = null;
<del> try {
<del> while ((line = br.readLine()) != null) {
<del> System.out.println(line);
<del> }
<del>
<del> } catch (IOException e) {
<del> // TODO Auto-generated catch block
<del> e.printStackTrace();
<del> }
<del>
<ide> in = new FileInputStream("data/in/good/DL28_NL.txt");
<ide> in2 = new FileInputStream("data/in/bad/DL_NL_nulls.txt");
<ide> |
|
Java | mit | d9e1ccc98a36a10941237319628c86c6911f3bc9 | 0 | mwanji/toml4j,bruno-medeiros/toml4j | package com.moandjiezana.toml;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.parboiled.Parboiled;
import org.parboiled.parserunners.RecoveringParseRunner;
import org.parboiled.support.ParsingResult;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
/**
* <p>Provides access to the keys and tables in a TOML data source.</p>
*
* <p>All getters can fall back to default values if they have been provided.
* Getters for simple values (String, Date, etc.) will return null if no matching key exists.
* {@link #getList(String, Class)}, {@link #getTable(String)} and {@link #getTables(String)} return empty values if there is no matching key.</p>
*
* <p>Example usage:</p>
* <code><pre>
* Toml toml = new Toml().parse(getTomlFile());
* String name = toml.getString("name");
* Long port = toml.getLong("server.ip"); // compound key. Is equivalent to:
* Long port2 = toml.getTable("server").getLong("ip");
* MyConfig config = toml.to(MyConfig.class);
* </pre></code>
*
*/
public class Toml {
private static final Gson DEFAULT_GSON = new Gson();
private static final Pattern ARRAY_INDEX_PATTERN = Pattern.compile("(.*)\\[(\\d+)\\]");
private Map<String, Object> values = new HashMap<String, Object>();
private final Toml defaults;
/**
* Creates Toml instance with no defaults.
*/
public Toml() {
this(null);
}
/**
* @param defaults fallback values used when the requested key or table is not present.
*/
public Toml(Toml defaults) {
this(defaults, new HashMap<String, Object>());
}
/**
* Populates the current Toml instance with values from file.
*
* @param file
* @return this instance
* @throws IllegalStateException If file contains invalid TOML
*/
public Toml parse(File file) {
try {
return parse(new FileReader(file));
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
/**
* Populates the current Toml instance with values from inputStream.
*
* @param inputStream
* @return this instance
* @throws IllegalStateException If file contains invalid TOML
*/
public Toml parse(InputStream inputStream) {
return parse(new InputStreamReader(inputStream));
}
/**
* Populates the current Toml instance with values from reader.
*
* @param reader
* @return this instance
* @throws IllegalStateException If file contains invalid TOML
*/
public Toml parse(Reader reader) {
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(reader);
StringBuilder w = new StringBuilder();
String line = bufferedReader.readLine();
while (line != null) {
w.append(line).append('\n');
line = bufferedReader.readLine();
}
parse(w.toString());
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
bufferedReader.close();
} catch (IOException e) {}
}
return this;
}
/**
* Populates the current Toml instance with values from tomlString.
*
* @param tomlString
* @return this instance
* @throws IllegalStateException If tomlString is not valid TOML
*/
public Toml parse(String tomlString) throws IllegalStateException {
TomlParser parser = Parboiled.createParser(TomlParser.class);
ParsingResult<Object> result = new RecoveringParseRunner<Object>(parser.Toml()).run(tomlString);
// ParsingResult<Object> parsingResult = new ReportingParseRunner<Object>(parser.Toml()).run(tomlString);
// System.out.println(ParseTreeUtils.printNodeTree(parsingResult));
TomlParser.Results results = (TomlParser.Results) result.valueStack.peek(result.valueStack.size() - 1);
if (results.errors.length() > 0) {
throw new IllegalStateException(results.errors.toString());
}
this.values = results.values;
return this;
}
public String getString(String key) {
return (String) get(key);
}
public Long getLong(String key) {
return (Long) get(key);
}
@SuppressWarnings("unchecked")
public <T> List<T> getList(String key, Class<T> itemClass) {
List<T> list = (List<T>) get(key);
if (list == null) {
return Collections.emptyList();
}
return list;
}
public Boolean getBoolean(String key) {
return (Boolean) get(key);
}
public Date getDate(String key) {
return (Date) get(key);
}
public Double getDouble(String key) {
return (Double) get(key);
}
/**
* If no value is found for key, an empty Toml instance is returned.
*
* @param key
*/
@SuppressWarnings("unchecked")
public Toml getTable(String key) {
return new Toml(null, (Map<String, Object>) get(key));
}
/**
* If no value is found for key, an empty list is returned.
* @param key
*/
@SuppressWarnings("unchecked")
public List<Toml> getTables(String key) {
List<Map<String, Object>> tableArray = (List<Map<String, Object>>) get(key);
if (tableArray == null) {
return Collections.emptyList();
}
ArrayList<Toml> tables = new ArrayList<Toml>();
for (Map<String, Object> table : tableArray) {
tables.add(new Toml(null, table));
}
return tables;
}
/**
* <p>Populates an instance of targetClass with the values of this Toml instance.
* The target's field names must match keys or tables.
* Keys not present in targetClass will be ignored.</p>
*
* <p>Tables are recursively converted to custom classes or to {@link Map Map<String, Object>}.</p>
*
* <p>In addition to straight-forward conversion of TOML primitives, the following are also available:</p>
*
* <ul>
* <li>TOML string to {@link Character}, {@link URL} or enum</li>
* <li>TOML number to any primitive (or wrapper), {@link BigInteger} or {@link BigDecimal}</li>
* <li>TOML array to {@link Set}</li>
* </ul>
*
* @param targetClass
*/
public <T> T to(Class<T> targetClass) {
return to(targetClass, DEFAULT_GSON);
}
/*
* Should not be used directly, except for testing purposes
*/
<T> T to(Class<T> targetClass, Gson gson) {
HashMap<String, Object> valuesCopy = new HashMap<String, Object>(values);
if (defaults != null) {
for (Map.Entry<String, Object> entry : defaults.values.entrySet()) {
if (!valuesCopy.containsKey(entry.getKey())) {
valuesCopy.put(entry.getKey(), entry.getValue());
}
}
}
JsonElement json = gson.toJsonTree(valuesCopy);
if (targetClass == JsonElement.class) {
return targetClass.cast(json);
}
return gson.fromJson(json, targetClass);
}
@SuppressWarnings("unchecked")
private Object get(String key) {
String[] split = key.split("\\.");
Object current = new HashMap<String, Object>(values);
for (String splitKey : split) {
Matcher matcher = ARRAY_INDEX_PATTERN.matcher(splitKey);
int index = -1;
if (matcher.find()) {
splitKey = matcher.group(1);
index = Integer.parseInt(matcher.group(2), 10);
}
current = ((Map<String, Object>) current).get(splitKey);
if (index > -1 && current != null) {
current = ((List<?>) current).get(index);
}
if (current == null) {
return defaults != null ? defaults.get(key) : null;
}
}
return current;
}
private Toml(Toml defaults, Map<String, Object> values) {
this.values = values != null ? values : Collections.<String, Object>emptyMap();
this.defaults = defaults;
}
}
| src/main/java/com/moandjiezana/toml/Toml.java | package com.moandjiezana.toml;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.parboiled.Parboiled;
import org.parboiled.parserunners.RecoveringParseRunner;
import org.parboiled.support.ParsingResult;
import com.google.gson.Gson;
/**
* <p>Provides access to the keys and tables in a TOML data source.</p>
*
* <p>All getters can fall back to default values if they have been provided.
* Getters for simple values (String, Date, etc.) will return null if no matching key exists.
* {@link #getList(String, Class)}, {@link #getTable(String)} and {@link #getTables(String)} return empty values if there is no matching key.</p>
*
* <p>Example usage:</p>
* <code><pre>
* Toml toml = new Toml().parse(getTomlFile());
* String name = toml.getString("name");
* Long port = toml.getLong("server.ip"); // compound key. Is equivalent to:
* Long port2 = toml.getTable("server").getLong("ip");
* MyConfig config = toml.to(MyConfig.class);
* </pre></code>
*
*/
public class Toml {
private static Pattern ARRAY_INDEX_PATTERN = Pattern.compile("(.*)\\[(\\d+)\\]");
private Map<String, Object> values = new HashMap<String, Object>();
private final Toml defaults;
private final Gson gson = new Gson();
/**
* Creates Toml instance with no defaults.
*/
public Toml() {
this(null);
}
/**
* @param defaults fallback values used when the requested key or table is not present.
*/
public Toml(Toml defaults) {
this(defaults, new HashMap<String, Object>());
}
/**
* Populates the current Toml instance with values from file.
*
* @param file
* @return this instance
* @throws IllegalStateException If file contains invalid TOML
*/
public Toml parse(File file) {
try {
return parse(new FileReader(file));
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
/**
* Populates the current Toml instance with values from inputStream.
*
* @param inputStream
* @return this instance
* @throws IllegalStateException If file contains invalid TOML
*/
public Toml parse(InputStream inputStream) {
return parse(new InputStreamReader(inputStream));
}
/**
* Populates the current Toml instance with values from reader.
*
* @param reader
* @return this instance
* @throws IllegalStateException If file contains invalid TOML
*/
public Toml parse(Reader reader) {
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(reader);
StringBuilder w = new StringBuilder();
String line = bufferedReader.readLine();
while (line != null) {
w.append(line).append('\n');
line = bufferedReader.readLine();
}
parse(w.toString());
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
bufferedReader.close();
} catch (IOException e) {}
}
return this;
}
/**
* Populates the current Toml instance with values from tomlString.
*
* @param tomlString
* @return this instance
* @throws IllegalStateException If tomlString is not valid TOML
*/
public Toml parse(String tomlString) throws IllegalStateException {
TomlParser parser = Parboiled.createParser(TomlParser.class);
ParsingResult<Object> result = new RecoveringParseRunner<Object>(parser.Toml()).run(tomlString);
// ParsingResult<Object> parsingResult = new ReportingParseRunner<Object>(parser.Toml()).run(tomlString);
// System.out.println(ParseTreeUtils.printNodeTree(parsingResult));
TomlParser.Results results = (TomlParser.Results) result.valueStack.peek(result.valueStack.size() - 1);
if (results.errors.length() > 0) {
throw new IllegalStateException(results.errors.toString());
}
this.values = results.values;
return this;
}
public String getString(String key) {
return (String) get(key);
}
public Long getLong(String key) {
return (Long) get(key);
}
@SuppressWarnings("unchecked")
public <T> List<T> getList(String key, Class<T> itemClass) {
List<T> list = (List<T>) get(key);
if (list == null) {
return Collections.emptyList();
}
return list;
}
public Boolean getBoolean(String key) {
return (Boolean) get(key);
}
public Date getDate(String key) {
return (Date) get(key);
}
public Double getDouble(String key) {
return (Double) get(key);
}
/**
* If no value is found for key, an empty Toml instance is returned.
*
* @param key
*/
@SuppressWarnings("unchecked")
public Toml getTable(String key) {
return new Toml(null, (Map<String, Object>) get(key));
}
/**
* If no value is found for key, an empty list is returned.
* @param key
*/
@SuppressWarnings("unchecked")
public List<Toml> getTables(String key) {
List<Map<String, Object>> tableArray = (List<Map<String, Object>>) get(key);
if (tableArray == null) {
return Collections.emptyList();
}
ArrayList<Toml> tables = new ArrayList<Toml>();
for (Map<String, Object> table : tableArray) {
tables.add(new Toml(null, table));
}
return tables;
}
/**
* <p>Populates an instance of targetClass with the values of this Toml instance.
* The target's field names must match keys or tables.
* Keys not present in targetClass will be ignored.</p>
*
* <p>Tables are recursively converted to custom classes or to {@link Map Map<String, Object>}.</p>
*
* <p>In addition to straight-forward conversion of TOML primitives, the following are also available:</p>
*
* <ul>
* <li>TOML string to {@link Character}, {@link URL} or enum</li>
* <li>TOML number to any primitive (or wrapper), {@link BigInteger} or {@link BigDecimal}</li>
* <li>TOML array to {@link Set}</li>
* </ul>
*
* @param targetClass
*/
public <T> T to(Class<T> targetClass) {
HashMap<String, Object> valuesCopy = new HashMap<String, Object>(values);
if (defaults != null) {
for (Map.Entry<String, Object> entry : defaults.values.entrySet()) {
if (!valuesCopy.containsKey(entry.getKey())) {
valuesCopy.put(entry.getKey(), entry.getValue());
}
}
}
String json = gson.toJson(valuesCopy);
return gson.fromJson(json, targetClass);
}
@SuppressWarnings("unchecked")
private Object get(String key) {
String[] split = key.split("\\.");
Object current = new HashMap<String, Object>(values);
for (String splitKey : split) {
Matcher matcher = ARRAY_INDEX_PATTERN.matcher(splitKey);
int index = -1;
if (matcher.find()) {
splitKey = matcher.group(1);
index = Integer.parseInt(matcher.group(2), 10);
}
current = ((Map<String, Object>) current).get(splitKey);
if (index > -1 && current != null) {
current = ((List<?>) current).get(index);
}
if (current == null) {
return defaults != null ? defaults.get(key) : null;
}
}
return current;
}
private Toml(Toml defaults, Map<String, Object> values) {
this.values = values != null ? values : Collections.<String, Object>emptyMap();
this.defaults = defaults;
}
}
| Added Toml#to(Class, Gson) to allow for test output as specified by
BurntSushi/toml-test | src/main/java/com/moandjiezana/toml/Toml.java | Added Toml#to(Class, Gson) to allow for test output as specified by BurntSushi/toml-test | <ide><path>rc/main/java/com/moandjiezana/toml/Toml.java
<ide> import org.parboiled.support.ParsingResult;
<ide>
<ide> import com.google.gson.Gson;
<add>import com.google.gson.JsonElement;
<ide>
<ide> /**
<ide> * <p>Provides access to the keys and tables in a TOML data source.</p>
<ide> */
<ide> public class Toml {
<ide>
<del> private static Pattern ARRAY_INDEX_PATTERN = Pattern.compile("(.*)\\[(\\d+)\\]");
<add> private static final Gson DEFAULT_GSON = new Gson();
<add> private static final Pattern ARRAY_INDEX_PATTERN = Pattern.compile("(.*)\\[(\\d+)\\]");
<add>
<ide> private Map<String, Object> values = new HashMap<String, Object>();
<ide> private final Toml defaults;
<del> private final Gson gson = new Gson();
<ide>
<ide> /**
<ide> * Creates Toml instance with no defaults.
<ide> * @param targetClass
<ide> */
<ide> public <T> T to(Class<T> targetClass) {
<add> return to(targetClass, DEFAULT_GSON);
<add> }
<add>
<add> /*
<add> * Should not be used directly, except for testing purposes
<add> */
<add> <T> T to(Class<T> targetClass, Gson gson) {
<ide> HashMap<String, Object> valuesCopy = new HashMap<String, Object>(values);
<ide>
<ide> if (defaults != null) {
<ide> }
<ide> }
<ide>
<del> String json = gson.toJson(valuesCopy);
<add> JsonElement json = gson.toJsonTree(valuesCopy);
<add>
<add> if (targetClass == JsonElement.class) {
<add> return targetClass.cast(json);
<add> }
<add>
<ide> return gson.fromJson(json, targetClass);
<ide> }
<ide> |
|
Java | mpl-2.0 | f37bc7132c65c5225bc1e2696a4f6fadc4b25bb3 | 0 | etomica/etomica,ajschult/etomica,etomica/etomica,ajschult/etomica,etomica/etomica,ajschult/etomica | package etomica.statmech;
import etomica.util.Arrays;
/**
* Implementation of some semi-empirical equations of state for the
* Lennard-Jones model.
*
* Equations for the fcc solid phase and liquid-fcc saturation conditions are
* based on the empirical formulas proposed by van der Hoef:
*
* [1] M.A. van der Hoef, "Free energy of the Lennard-Jones solid", Journal of
* Chemical Physics, vol 113, page 8142 (2000).
*
* Equations for vapor-fcc saturation conditions are based on equations given in:
*
* [2] M.S. van der Hoef, "Gas-solid coexistence of the Lennard-Jones system",
* Journal of Chemical Physics, vol 117, page 5093 (2002).
*
* No fluid-phase equations are (yet) implemented here.
*
* This is a library class, containing only static methods, and thus is not
* intended to be instantiated.
*
* @author David Kofke
*
*/
public final class LennardJones {
private LennardJones() {
//private constructor prevents instantiation
}
/**
* Total Helmholtz free energy for the fcc solid. Does
* not include contributions from momentum degrees of freedom
* (alternatively, one might say that the mass is defined such that the
* deBroglie wavelength is unity). Based on Eq. 21 of van der Hoef [1].
*
* @param T
* the temperature, in units of epsilon/k (thus input is kT/epsilon)
* @param rho
* the number density, in units of 1/sigma^3 (thus input is rho*sigma^3)
* @return the Helmholtz free energy, in units of epsilon
*/
public static double aFcc(double T, double rho) {
double sum = T * (-1 + Math.log(rho)); // ideal part, excluding momentum contribution (deBroglie wavelength)
sum += uStaticFcc(rho) - 1.5 * T * Math.log(T);// harmonic contribution, static-lattice energy plus 3/2 ln(beta)
sum += T * Uah(T, rho); //anharmonic contribution
double rhon1 = rho;// rho^(n+1)
for (int n = 0; n <= 3; n++) {
sum += T * b[n] / (n + 1) * rhon1;
rhon1 *= rho;
}
sum -= 23.3450759 * T;
return sum;
}
/**
* Total ensemble-averaged internal potential energy for the fcc solid.
* Based on Eq. 19 of van der Hoef [1].
*
* @param T
* temperature, in units of epsilon/k
* @param rho
* number density, in units of 1/sigma^3
* @return internal potential energy, in units of epsilon (thus u/epsilon is returned)
*
*/
public static double uFcc(double T, double rho) {
return uStaticFcc(rho) + 1.5/T + uah(T, rho);
}
/**
* Compressibility factor, P/rho/kT for the fcc solid.
* Based on Eq. 20 of van der Hoef [1].
*
* @param T
* temperature, in units of epsilon/k
* @param rho
* number density, in units of 1/sigma^3
* @return compressibility factor (dimensionless)
*/
public static double ZFcc(double T, double rho) {
double sum = 1.0/rho;//ideal-gas value of betaP/rho^2
sum += rho * (2.0*cStat[0] + 4.0*cStat[1] * rho*rho) / T;// beta dUstatic/drho
sum += dUahDrho(T, rho);
double rhon = 1.0;
for(int n=0; n<=3; n++) {
sum += b[n] * rhon;
rhon *= rho;
}
return rho*sum;
}
/**
* Potential energy per atom of a static fcc lattice with a LJ particle at
* each site.
*
* @param rho
* number density, in units of 1/sigma^3
* @return the static-lattice energy, in units of epsilon
*/
public static double uStaticFcc(double rho) {
double rho2 = rho * rho;
return rho2 * (cStat[0] + cStat[1] * rho2);
}
/**
* Returns the densities of coexisting (saturated) liquid and fcc phases
* (i.e., melting and freezing densities). Uses Eqs. (25) and (26) of van
* der Hoef [1].
*
* @param T
* temperature, in units of epsilon/k
* @return coexistence densities, in units of 1/sigma^3; liquid is element
* 0, fcc solid is element 1
*/
public static double[] liquidFccCoexDensities(double T) {
double beta = 1.0/T;
double betaM14 = Math.pow(beta, -0.25);
double rhoLiq = 0.91070 + beta * (-0.25124 +
beta * (+0.85861 +
beta * (-1.08918 +
beta * (+0.63932 +
beta * (-0.14433)))));
double rhofcc = 0.92302 + beta * (-0.09218 +
beta * (+0.62381 +
beta * (-0.82672 +
beta * (+0.49124 +
beta * (-0.10847)))));
rhoLiq *= betaM14;
rhofcc *= betaM14;
return new double[] {rhoLiq, rhofcc};
}
/**
* Returns the saturation pressure for fluid-fcc coexistence (i.e., the
* melting or freezing pressure). Uses Eq. (24) of van der Hoef [1], which
* is based on a formula proposed by Agrawal and Kofke, referenced therein.
*
* @param T
* temperature, in units of epsilon/k
* @return saturation pressure, in units of epsilon/sigma^3 (thus p
* sigma^3/epsilon is returned)
*/
public static double liquidFccCoexPressure(double T) {
double beta = 1.0/T;
double betaM54 = Math.pow(beta,-1.25);
double A = -7.2866;//value recommended by van der Hoef
double B = -2.9895;//value recommended by van der Hoef
return betaM54 * Math.exp(-0.4759 * Math.sqrt(beta)) * (16.89 + A * beta + B * beta*beta);
}
/**
* Returns the densities of coexisting (saturated) vapor and fcc phases
* (sublimation densities). Uses Eqs. (2) and (3) of van der Hoef [2].
*
* @param T
* temperature, in units of epsilon/k
* @return coexistence densities, in units of 1/sigma^3; vapor is element
* 0, fcc solid is element 1
*/
public static double[] vaporFccCoexDensities(double T) {
double sum = -cStat[0]*cStat[0]/4.0/cStat[1]/T;
double Tn = 1.0;
for(int n=0; n<=5; n++) {
sum += bSub[n]*Tn;
Tn *= T;
}
double rhoVap = Math.exp(sum);
sum = Math.sqrt(-cStat[0]/2.0/cStat[1]);
Tn = T;
for(int n=1; n<=4; n++) {
sum += cSub[n-1]*Tn;
Tn *= T;
}
return new double[] {rhoVap, sum};
}
/**
* Returns the saturation pressure for vapor-fcc coexistence. Uses Eq. (1)
* of van der Hoef [2].
*
* @param T
* temperature, in units of epsilon/k
* @return saturation pressure, in units of epsilon/sigma^3 (thus p sigma^3/epsilon is returned)
*/
public static double vaporFccCoexPressure(double T) {
double sum = -cStat[0]*cStat[0]/4.0/cStat[1]/T;
double Tn= 1.0;
for(int n=0; n<=5; n++) {
sum += aSub[n]*Tn;
Tn *= T;
}
return T * Math.exp(sum);
}
/*
* Implementation of van der Hoef's [1] Eq. 12 for u^{ah}
*/
private static double uah(double T, double rho) {
double sum = 0.0;
double rhon = 1.0;
for (int n = 0; n <= 2; n++) {
double betamm = T*T; // beta^(-m) = T^(m), starting at m = 2 is T^2
for (int m = 2; m <= 5; m++) {
sum += a[n][m - 2] * rhon * betamm;
betamm *= T;
}
rhon *= rho;
}
return -sum;
}
/*
* Derivative of Uah wrt rho
*/
private static double dUahDrho(double T, double rho) {
double sum = 0.0;
double rhon1 = 1.0;
for (int n = 1; n <= 2; n++) {
double beta1m = T; // beta^(1-m) = T^(m-1), starting at m = 2 is T
for (int m = 2; m <= 5; m++) {
sum += n * a[n][m - 2] / (m - 1) * rhon1 * beta1m;
beta1m *= T;
}
rhon1 *= rho;
}
return -sum;
}
/*
* Implementation of van der Hoef's [1] Eq. (14) for U^{ah}
*/
private static double Uah(double T, double rho) {
double sum = 0.0;
double rhon = 1.0;
for (int n = 0; n <= 2; n++) {
double beta1m = T; // beta^(1-m) = T^(m-1), starting at m = 2 is T
for (int m = 2; m <= 5; m++) {
sum += a[n][m - 2] / (m - 1) * rhon * beta1m;
beta1m *= T;
}
rhon *= rho;
}
return -sum;
}
public static void main(String[] args) {
double T = 0.65;
double rho = 1.7;
double pSat = liquidFccCoexPressure(T);
double[] rhoSat = liquidFccCoexDensities(T);
System.out.println("Input T, rho: "+ T + " "+rho);
System.out.println("Helmholtz: " + aFcc(T, rho));
double betaAex = (aFcc(T, rho) - T * (-1 + Math.log(rho)))/T;
System.out.println("betaA_excess: " + betaAex);
System.out.println("Potential energy: " + uFcc(T, rho));
System.out.println("Compressibility factor: " + ZFcc(T, rho));
System.out.println("Liquid-fcc coexistence pressure: " + pSat);
System.out.println("fcc, liquid coexistence densities: "+ Arrays.toString(rhoSat));
double rhs = aFcc(T,rho)/T - uStaticFcc(rho)/T + 1.5*Math.log(T) - Uah(T,rho)
+ 1.5*Math.log(2*Math.PI);
System.out.println("rhs of Eq. 23: " + rhs);
double zfcc = pSat/rhoSat[1]/T;
System.out.println("Two routes to Z: "+zfcc+" "+ZFcc(T,rhoSat[1]));
double psub = vaporFccCoexPressure(T);
System.out.println("Sublimation pressure: " + psub);
double[] rhosub = vaporFccCoexDensities(T);
System.out.println("vapor, fcc coexistence densities: " + Arrays.toString(rhosub));
}
//Constants for van der Hoef's formulas
private static final double[][] a = new double[][] {
{ -8.2151768, 12.070686, -6.6594615, 1.3211582 },
{ 13.404069, -20.632066, 11.564825, -2.3064801 },
{ -5.5481261, 8.8465978, -5.0258631, 1.0070066 } };
private static final double[] b = new double[] { 69.833875, -132.86963,
97.438593, -25.848057 };
private static final double[] cStat = new double[] {-14.45392093, 6.065940096};
private static final double[] aSub = new double[] {10.48631, -16.81771, 35.10031, -48.76487, 36.39136, -10.90788};
private static final double[] bSub = new double[] {10.49107, -16.83818, 34.95754, -47.66412, 33.90821, -9.011857};
private static final double[] cSub = new double[] {-0.134343, -0.0950795, 0.137215, -0.161890};
}
| etomica/statmech/LennardJones.java | package etomica.statmech;
import etomica.util.Arrays;
/**
* Implementation of some semi-empirical equations of state for the
* Lennard-Jones model.
*
* Equations for the fcc solid phase and liquid-fcc saturation conditions are
* based on the empirical formulas proposed by van der Hoef ("Free energy of the
* Lennard-Jones solid", Journal of Chemical Physics, vol 113, page 8142
* (2000)).
*
* No fluid-phase equations are (yet) implemented here.
*
* This is a library class, containing only static methods, and thus is not
* intended to be instantiated.
*
* @author David Kofke
*
*/
public final class LennardJones {
private LennardJones() {
//private constructor prevents instantiation
}
/**
* Total Helmholtz free energy for the fcc solid. Does
* not include contributions from momentum degrees of freedom
* (alternatively, one might say that the mass is defined such that the
* deBroglie wavelength is unity). Based on Eq. 21 of van der Hoef.
*
* @param T
* the temperature, in units of epsilon/k (thus input is kT/epsilon)
* @param rho
* the number density, in units of 1/sigma^3 (thus input is rho*sigma^3)
* @return the Helmholtz free energy, in units of epsilon
*/
public static double aFcc(double T, double rho) {
double sum = T * (-1 + Math.log(rho)); // ideal part, excluding momentum contribution (deBroglie wavelength)
sum += uStaticFcc(rho) - 1.5 * T * Math.log(T);// harmonic contribution, static-lattice energy plus 3/2 ln(beta)
sum += T * Uah(T, rho); //anharmonic contribution
double rhon1 = rho;// rho^(n+1)
for (int n = 0; n <= 3; n++) {
sum += T * b[n] / (n + 1) * rhon1;
rhon1 *= rho;
}
sum -= 23.3450759 * T;
return sum;
}
/**
* Total ensemble-averaged internal potential energy for the fcc solid.
* Based on Eq. 19 of van der Hoef.
*
* @param T
* temperature, in units of epsilon/k
* @param rho
* number density, in units of 1/sigma^3
* @return internal potential energy, in units of epsilon (thus u/epsilon is returned)
*
*/
public static double uFcc(double T, double rho) {
return uStaticFcc(rho) + 1.5/T + uah(T, rho);
}
/**
* Compressibility factor, P/rho/kT for the fcc solid.
* Based on Eq. 20 of van der Hoef.
*
* @param T
* temperature, in units of epsilon/k
* @param rho
* number density, in units of 1/sigma^3
* @return compressibility factor (dimensionless)
*/
public static double ZFcc(double T, double rho) {
double sum = 1.0/rho;//ideal-gas value of betaP/rho^2
sum += rho * (2.0*cStat[0] + 4.0*cStat[1] * rho*rho) / T;// beta dUstatic/drho
sum += dUahDrho(T, rho);
double rhon = 1.0;
for(int n=0; n<=3; n++) {
sum += b[n] * rhon;
rhon *= rho;
}
return rho*sum;
}
/**
* Potential energy per atom of a static fcc lattice with a LJ particle at
* each site.
*
* @param rho
* number density, in units of 1/sigma^3
* @return the static-lattice energy, in units of epsilon
*/
public static double uStaticFcc(double rho) {
double rho2 = rho * rho;
return rho2 * (cStat[0] + cStat[1] * rho2);
}
/**
* Returns the densities of coexisting (saturated) liquid and fcc phases.
* Uses Eqs. (25) and (26) of van der Hoef.
*
* @param T
* temperature, in units of epsilon/k
* @return coexistence densities, in units of 1/sigma^3; liquid is element 0,
* fcc solid is element 1
*/
public static double[] liquidFccCoexDensities(double T) {
double beta = 1.0/T;
double betaM14 = Math.pow(beta, -0.25);
double rhoLiq = 0.91070 + beta * (-0.25124 +
beta * (+0.85861 +
beta * (-1.08918 +
beta * (+0.63932 +
beta * (-0.14433)))));
double rhofcc = 0.92302 + beta * (-0.09218 +
beta * (+0.62381 +
beta * (-0.82672 +
beta * (+0.49124 +
beta * (-0.10847)))));
rhoLiq *= betaM14;
rhofcc *= betaM14;
return new double[] {rhoLiq, rhofcc};
}
/**
* Returns the saturation pressure for fluid-fcc coexistence. Uses Eq. (24)
* of van der Hoef, which is based on a formula proposed by Agrawal and Kofke,
* referenced therein.
*
* @param T
* temperature, in units of epsilon/k
* @return saturation pressure, in units of epsilon/sigma^3 (thus p sigma^3/epsilon is returned)
*/
public static double liquidFccCoexPressure(double T) {
double beta = 1.0/T;
double betaM54 = Math.pow(beta,-1.25);
double A = -7.2866;//value recommended by van der Hoef
double B = -2.9895;//value recommended by van der Hoef
return betaM54 * Math.exp(-0.4759 * Math.sqrt(beta)) * (16.89 + A * beta + B * beta*beta);
}
/*
* Implementation of van der Hoef's Eq. 12 for u^{ah}
*/
private static double uah(double T, double rho) {
double sum = 0.0;
double rhon = 1.0;
for (int n = 0; n <= 2; n++) {
double betamm = T*T; // beta^(-m) = T^(m), starting at m = 2 is T^2
for (int m = 2; m <= 5; m++) {
sum += a[n][m - 2] * rhon * betamm;
betamm *= T;
}
rhon *= rho;
}
return -sum;
}
/*
* Derivative of Uah wrt rho
*/
private static double dUahDrho(double T, double rho) {
double sum = 0.0;
double rhon1 = 1.0;
for (int n = 1; n <= 2; n++) {
double beta1m = T; // beta^(1-m) = T^(m-1), starting at m = 2 is T
for (int m = 2; m <= 5; m++) {
sum += n * a[n][m - 2] / (m - 1) * rhon1 * beta1m;
beta1m *= T;
}
rhon1 *= rho;
}
return -sum;
}
/*
* Implementation of van der Hoef's Eq. (14) for U^{ah}
*/
private static double Uah(double T, double rho) {
double sum = 0.0;
double rhon = 1.0;
for (int n = 0; n <= 2; n++) {
double beta1m = T; // beta^(1-m) = T^(m-1), starting at m = 2 is T
for (int m = 2; m <= 5; m++) {
sum += a[n][m - 2] / (m - 1) * rhon * beta1m;
beta1m *= T;
}
rhon *= rho;
}
return -sum;
}
public static void main(String[] args) {
double T = 1.0;
double rho = 1.7;
double pSat = liquidFccCoexPressure(T);
double[] rhoSat = liquidFccCoexDensities(T);
System.out.println("Input T, rho: "+ T + " "+rho);
System.out.println("Helmholtz: " + aFcc(T, rho));
double betaAex = (aFcc(T, rho) - T * (-1 + Math.log(rho)))/T;
System.out.println("betaA_excess: " + betaAex);
System.out.println("Potential energy: " + uFcc(T, rho));
System.out.println("Compressibility factor: " + ZFcc(T, rho));
System.out.println("Liquid-fcc coexistence pressure: " + pSat);
System.out.println("fcc, liquid coexistence densities: "+ Arrays.toString(rhoSat));
double rhs = aFcc(T,rho)/T - uStaticFcc(rho)/T + 1.5*Math.log(T) - Uah(T,rho)
+ 1.5*Math.log(2*Math.PI);
System.out.println("rhs of Eq. 23: " + rhs);
double zfcc = pSat/rhoSat[1]/T;
System.out.println("Two routes to Z: "+zfcc+" "+ZFcc(T,rhoSat[1]));
}
//Constants for van der Hoef's formulas
private static final double[][] a = new double[][] {
{ -8.2151768, 12.070686, -6.6594615, 1.3211582 },
{ 13.404069, -20.632066, 11.564825, -2.3064801 },
{ -5.5481261, 8.8465978, -5.0258631, 1.0070066 } };
private static final double[] b = new double[] { 69.833875, -132.86963,
97.438593, -25.848057 };
private static final double[] cStat = new double[] {-14.45392093, 6.065940096};
}
| Add van der Hoef's vapor-fcc coexistence equations
| etomica/statmech/LennardJones.java | Add van der Hoef's vapor-fcc coexistence equations | <ide><path>tomica/statmech/LennardJones.java
<ide> * Lennard-Jones model.
<ide> *
<ide> * Equations for the fcc solid phase and liquid-fcc saturation conditions are
<del> * based on the empirical formulas proposed by van der Hoef ("Free energy of the
<del> * Lennard-Jones solid", Journal of Chemical Physics, vol 113, page 8142
<del> * (2000)).
<add> * based on the empirical formulas proposed by van der Hoef:
<add> *
<add> * [1] M.A. van der Hoef, "Free energy of the Lennard-Jones solid", Journal of
<add> * Chemical Physics, vol 113, page 8142 (2000).
<add> *
<add> * Equations for vapor-fcc saturation conditions are based on equations given in:
<add> *
<add> * [2] M.S. van der Hoef, "Gas-solid coexistence of the Lennard-Jones system",
<add> * Journal of Chemical Physics, vol 117, page 5093 (2002).
<ide> *
<ide> * No fluid-phase equations are (yet) implemented here.
<ide> *
<ide> * Total Helmholtz free energy for the fcc solid. Does
<ide> * not include contributions from momentum degrees of freedom
<ide> * (alternatively, one might say that the mass is defined such that the
<del> * deBroglie wavelength is unity). Based on Eq. 21 of van der Hoef.
<add> * deBroglie wavelength is unity). Based on Eq. 21 of van der Hoef [1].
<ide> *
<ide> * @param T
<ide> * the temperature, in units of epsilon/k (thus input is kT/epsilon)
<ide>
<ide> /**
<ide> * Total ensemble-averaged internal potential energy for the fcc solid.
<del> * Based on Eq. 19 of van der Hoef.
<add> * Based on Eq. 19 of van der Hoef [1].
<ide> *
<ide> * @param T
<ide> * temperature, in units of epsilon/k
<ide>
<ide> /**
<ide> * Compressibility factor, P/rho/kT for the fcc solid.
<del> * Based on Eq. 20 of van der Hoef.
<add> * Based on Eq. 20 of van der Hoef [1].
<ide> *
<ide> * @param T
<ide> * temperature, in units of epsilon/k
<ide> }
<ide>
<ide> /**
<del> * Returns the densities of coexisting (saturated) liquid and fcc phases.
<del> * Uses Eqs. (25) and (26) of van der Hoef.
<del> *
<del> * @param T
<del> * temperature, in units of epsilon/k
<del> * @return coexistence densities, in units of 1/sigma^3; liquid is element 0,
<del> * fcc solid is element 1
<add> * Returns the densities of coexisting (saturated) liquid and fcc phases
<add> * (i.e., melting and freezing densities). Uses Eqs. (25) and (26) of van
<add> * der Hoef [1].
<add> *
<add> * @param T
<add> * temperature, in units of epsilon/k
<add> * @return coexistence densities, in units of 1/sigma^3; liquid is element
<add> * 0, fcc solid is element 1
<ide> */
<ide> public static double[] liquidFccCoexDensities(double T) {
<ide> double beta = 1.0/T;
<ide> }
<ide>
<ide> /**
<del> * Returns the saturation pressure for fluid-fcc coexistence. Uses Eq. (24)
<del> * of van der Hoef, which is based on a formula proposed by Agrawal and Kofke,
<del> * referenced therein.
<del> *
<del> * @param T
<del> * temperature, in units of epsilon/k
<del> * @return saturation pressure, in units of epsilon/sigma^3 (thus p sigma^3/epsilon is returned)
<add> * Returns the saturation pressure for fluid-fcc coexistence (i.e., the
<add> * melting or freezing pressure). Uses Eq. (24) of van der Hoef [1], which
<add> * is based on a formula proposed by Agrawal and Kofke, referenced therein.
<add> *
<add> * @param T
<add> * temperature, in units of epsilon/k
<add> * @return saturation pressure, in units of epsilon/sigma^3 (thus p
<add> * sigma^3/epsilon is returned)
<ide> */
<ide> public static double liquidFccCoexPressure(double T) {
<ide> double beta = 1.0/T;
<ide> return betaM54 * Math.exp(-0.4759 * Math.sqrt(beta)) * (16.89 + A * beta + B * beta*beta);
<ide> }
<ide>
<del>
<add>
<add> /**
<add> * Returns the densities of coexisting (saturated) vapor and fcc phases
<add> * (sublimation densities). Uses Eqs. (2) and (3) of van der Hoef [2].
<add> *
<add> * @param T
<add> * temperature, in units of epsilon/k
<add> * @return coexistence densities, in units of 1/sigma^3; vapor is element
<add> * 0, fcc solid is element 1
<add> */
<add> public static double[] vaporFccCoexDensities(double T) {
<add> double sum = -cStat[0]*cStat[0]/4.0/cStat[1]/T;
<add> double Tn = 1.0;
<add> for(int n=0; n<=5; n++) {
<add> sum += bSub[n]*Tn;
<add> Tn *= T;
<add> }
<add> double rhoVap = Math.exp(sum);
<add> sum = Math.sqrt(-cStat[0]/2.0/cStat[1]);
<add> Tn = T;
<add> for(int n=1; n<=4; n++) {
<add> sum += cSub[n-1]*Tn;
<add> Tn *= T;
<add> }
<add> return new double[] {rhoVap, sum};
<add> }
<add>
<add> /**
<add> * Returns the saturation pressure for vapor-fcc coexistence. Uses Eq. (1)
<add> * of van der Hoef [2].
<add> *
<add> * @param T
<add> * temperature, in units of epsilon/k
<add> * @return saturation pressure, in units of epsilon/sigma^3 (thus p sigma^3/epsilon is returned)
<add> */
<add> public static double vaporFccCoexPressure(double T) {
<add> double sum = -cStat[0]*cStat[0]/4.0/cStat[1]/T;
<add> double Tn= 1.0;
<add> for(int n=0; n<=5; n++) {
<add> sum += aSub[n]*Tn;
<add> Tn *= T;
<add> }
<add> return T * Math.exp(sum);
<add> }
<add>
<ide> /*
<del> * Implementation of van der Hoef's Eq. 12 for u^{ah}
<add> * Implementation of van der Hoef's [1] Eq. 12 for u^{ah}
<ide> */
<ide> private static double uah(double T, double rho) {
<ide> double sum = 0.0;
<ide> }
<ide>
<ide> /*
<del> * Implementation of van der Hoef's Eq. (14) for U^{ah}
<add> * Implementation of van der Hoef's [1] Eq. (14) for U^{ah}
<ide> */
<ide> private static double Uah(double T, double rho) {
<ide> double sum = 0.0;
<ide> }
<ide>
<ide> public static void main(String[] args) {
<del> double T = 1.0;
<add> double T = 0.65;
<ide> double rho = 1.7;
<ide> double pSat = liquidFccCoexPressure(T);
<ide> double[] rhoSat = liquidFccCoexDensities(T);
<ide> System.out.println("rhs of Eq. 23: " + rhs);
<ide> double zfcc = pSat/rhoSat[1]/T;
<ide> System.out.println("Two routes to Z: "+zfcc+" "+ZFcc(T,rhoSat[1]));
<add> double psub = vaporFccCoexPressure(T);
<add> System.out.println("Sublimation pressure: " + psub);
<add> double[] rhosub = vaporFccCoexDensities(T);
<add> System.out.println("vapor, fcc coexistence densities: " + Arrays.toString(rhosub));
<ide>
<ide> }
<ide>
<ide> private static final double[] b = new double[] { 69.833875, -132.86963,
<ide> 97.438593, -25.848057 };
<ide> private static final double[] cStat = new double[] {-14.45392093, 6.065940096};
<add> private static final double[] aSub = new double[] {10.48631, -16.81771, 35.10031, -48.76487, 36.39136, -10.90788};
<add> private static final double[] bSub = new double[] {10.49107, -16.83818, 34.95754, -47.66412, 33.90821, -9.011857};
<add> private static final double[] cSub = new double[] {-0.134343, -0.0950795, 0.137215, -0.161890};
<ide>
<ide>
<ide> } |
|
Java | apache-2.0 | 10d2936a73e2699166ba74d32348dff28a69ff1e | 0 | jmrozanec/cron-utils,meincs/cron-utils | package com.cronutils.utils.descriptor;
import com.cronutils.descriptor.CronDescriptor;
import com.cronutils.model.CronType;
import com.cronutils.model.definition.CronDefinitionBuilder;
import com.cronutils.parser.CronParser;
import org.junit.Before;
import org.junit.Test;
import java.util.Locale;
import static org.junit.Assert.assertEquals;
public class CronDescriptorQuartzIntegrationTest {
private CronDescriptor descriptor;
private CronParser parser;
@Before
public void setUp() throws Exception {
descriptor = CronDescriptor.instance(Locale.UK);
parser = new CronParser(CronDefinitionBuilder.instanceDefinitionFor(CronType.QUARTZ));
}
@Test
public void testCronWithAndHours(){
assertExpression("* * 1,2,3,4 * * ? *", "at 1, 2, 3 and 4 hours");
}
@Test
public void testCronAndWithRangeHours(){
assertExpression("* * 1,2,3,4,6-9 * * ? *", "at 1, 2, 3 and 4 hours and every hour between 6 and 9");
}
@Test
public void testCronAndWithRangesAndEveryExpressions(){
assertExpression("0 2-59/3 1,9,22 11-26 1-6 ?", "every 3 minutes between 2 and 59 at 1, 9 " +
"and 22 hours every day between 11 and 26 every month between January and June");
}
@Test
public void testEverySecond() {
assertExpression("* * * * * ?", "every second");
}
@Test
public void testEvery45Seconds(){
assertExpression("*/45 * * * * ?", "every 45 seconds");
}
@Test
public void testEveryHour(){
assertExpression("0 0 * * * ?", "every hour");
assertExpression("0 0 0/1 * * ?", "every hour");
}
/* Examples exposed at cron documentations */
@Test
public void testEveryDayFireAtNoon() throws Exception {
assertExpression("0 0 12 * * ?", "at 12:00");
}
@Test
public void testEveryDayFireAtTenFifteen() throws Exception {
String description = "at 10:15";
assertExpression("0 15 10 ? * *", description);
assertExpression("0 15 10 * * ?", description);
assertExpression("0 15 10 * * ? *", description);
}
@Test
public void testEveryDayFireAtTenFifteenYear2005() throws Exception {
assertExpression("0 15 10 * * ? 2005", "at 10:15 at 2005 year");
}
@Test
public void testEveryMinuteBetween14and15EveryDay() throws Exception {
assertExpression("0 * 14 * * ?", "at 14 hour");
}
@Test
public void testEveryFiveMinutesBetween14and15EveryDay() throws Exception {
assertExpression("0 0/5 14 * * ?", "every 5 minutes at 14 hour");
}
@Test
public void testEveryFiveMinutesBetween14and15AndBetween18And19EveryDay() throws Exception {
assertExpression("0 0/5 14,18 * * ?", "every 5 minutes at 14 and 18 hours");
}
/**
* Issue #43: getting bad description for expression
* @throws Exception
*/
//TODO
public void testEveryDayEveryFourHoursFromHour2() throws Exception {
assertExpression("0 0 2/4 * * ?", "");
}
/*
* Issue #103
*/
@Test
public void testDescriptionDayOfWeek() {
assertExpression("* 0/1 * ? * TUE", "every minute at Tuesday day");
}
private void assertExpression(String cron, String description){
assertEquals(description, descriptor.describe(parser.parse(cron)));
}
}
| src/test/java/com/cronutils/utils/descriptor/CronDescriptorQuartzIntegrationTest.java | package com.cronutils.utils.descriptor;
import com.cronutils.descriptor.CronDescriptor;
import com.cronutils.model.CronType;
import com.cronutils.model.definition.CronDefinitionBuilder;
import com.cronutils.parser.CronParser;
import org.junit.Before;
import org.junit.Test;
import java.util.Locale;
import static org.junit.Assert.assertEquals;
/*
* Copyright 2015 jmrozanec
* 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.
*/
public class CronDescriptorQuartzIntegrationTest {
private CronDescriptor descriptor;
private CronParser parser;
@Before
public void setUp() throws Exception {
descriptor = CronDescriptor.instance(Locale.UK);
parser = new CronParser(CronDefinitionBuilder.instanceDefinitionFor(CronType.QUARTZ));
}
@Test
public void testCronWithAndHours(){
assertExpression("* * 1,2,3,4 * * ? *", "at 1, 2, 3 and 4 hours");
}
@Test
public void testCronAndWithRangeHours(){
assertExpression("* * 1,2,3,4,6-9 * * ? *", "at 1, 2, 3 and 4 hours and every hour between 6 and 9");
}
@Test
public void testCronAndWithRangesAndEveryExpressions(){
assertExpression("0 2-59/3 1,9,22 11-26 1-6 ?", "every 3 minutes between 2 and 59 at 1, 9 " +
"and 22 hours every day between 11 and 26 every month between January and June");
}
@Test
public void testEverySecond() {
assertExpression("* * * * * ?", "every second");
}
@Test
public void testEvery45Seconds(){
assertExpression("*/45 * * * * ?", "every 45 seconds");
}
@Test
public void testEveryHour(){
assertExpression("0 0 * * * ?", "every hour");
assertExpression("0 0 0/1 * * ?", "every hour");
}
/* Examples exposed at cron documentations */
@Test
public void testEveryDayFireAtNoon() throws Exception {
assertExpression("0 0 12 * * ?", "at 12:00");
}
@Test
public void testEveryDayFireAtTenFifteen() throws Exception {
String description = "at 10:15";
assertExpression("0 15 10 ? * *", description);
assertExpression("0 15 10 * * ?", description);
assertExpression("0 15 10 * * ? *", description);
}
@Test
public void testEveryDayFireAtTenFifteenYear2005() throws Exception {
assertExpression("0 15 10 * * ? 2005", "at 10:15 at 2005 year");
}
@Test
public void testEveryMinuteBetween14and15EveryDay() throws Exception {
assertExpression("0 * 14 * * ?", "at 14 hour");
}
@Test
public void testEveryFiveMinutesBetween14and15EveryDay() throws Exception {
assertExpression("0 0/5 14 * * ?", "every 5 minutes at 14 hour");
}
@Test
public void testEveryFiveMinutesBetween14and15AndBetween18And19EveryDay() throws Exception {
assertExpression("0 0/5 14,18 * * ?", "every 5 minutes at 14 and 18 hours");
}
/**
* Issue #43: getting bad description for expression
* @throws Exception
*/
//TODO
public void testEveryDayEveryFourHoursFromHour2() throws Exception {
assertExpression("0 0 2/4 * * ?", "");
}
private void assertExpression(String cron, String description){
assertEquals(description, descriptor.describe(parser.parse(cron)));
}
}
| Failing unit test for issue #103
| src/test/java/com/cronutils/utils/descriptor/CronDescriptorQuartzIntegrationTest.java | Failing unit test for issue #103 | <ide><path>rc/test/java/com/cronutils/utils/descriptor/CronDescriptorQuartzIntegrationTest.java
<ide> import java.util.Locale;
<ide>
<ide> import static org.junit.Assert.assertEquals;
<del>/*
<del> * Copyright 2015 jmrozanec
<del> * Licensed under the Apache License, Version 2.0 (the "License");
<del> * you may not use this file except in compliance with the License.
<del> * You may obtain a copy of the License at
<del> * http://www.apache.org/licenses/LICENSE-2.0
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS,
<del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del> * See the License for the specific language governing permissions and
<del> * limitations under the License.
<del> */
<ide> public class CronDescriptorQuartzIntegrationTest {
<ide>
<ide> private CronDescriptor descriptor;
<ide> public void testEveryDayEveryFourHoursFromHour2() throws Exception {
<ide> assertExpression("0 0 2/4 * * ?", "");
<ide> }
<add>
<add> /*
<add> * Issue #103
<add> */
<add> @Test
<add> public void testDescriptionDayOfWeek() {
<add> assertExpression("* 0/1 * ? * TUE", "every minute at Tuesday day");
<add> }
<ide>
<ide> private void assertExpression(String cron, String description){
<ide> assertEquals(description, descriptor.describe(parser.parse(cron))); |
|
Java | apache-2.0 | 0a1b72276ac28c0da50ac01bc99dd01da5f7aa67 | 0 | caot/intellij-community,kool79/intellij-community,kool79/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,signed/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,adedayo/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,allotria/intellij-community,semonte/intellij-community,holmes/intellij-community,ryano144/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,supersven/intellij-community,kool79/intellij-community,retomerz/intellij-community,signed/intellij-community,wreckJ/intellij-community,supersven/intellij-community,robovm/robovm-studio,dslomov/intellij-community,samthor/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,akosyakov/intellij-community,alphafoobar/intellij-community,signed/intellij-community,ibinti/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,semonte/intellij-community,ryano144/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,samthor/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,allotria/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,petteyg/intellij-community,ibinti/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,signed/intellij-community,ibinti/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,petteyg/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,fnouama/intellij-community,Lekanich/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,holmes/intellij-community,signed/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,asedunov/intellij-community,jagguli/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,caot/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,semonte/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,caot/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,clumsy/intellij-community,allotria/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,adedayo/intellij-community,supersven/intellij-community,akosyakov/intellij-community,signed/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,retomerz/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,semonte/intellij-community,xfournet/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,da1z/intellij-community,amith01994/intellij-community,kool79/intellij-community,allotria/intellij-community,semonte/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,izonder/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,supersven/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,fitermay/intellij-community,kool79/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,holmes/intellij-community,wreckJ/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,xfournet/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,clumsy/intellij-community,izonder/intellij-community,adedayo/intellij-community,adedayo/intellij-community,ryano144/intellij-community,holmes/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,ftomassetti/intellij-community,caot/intellij-community,vladmm/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,diorcety/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,hurricup/intellij-community,clumsy/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,adedayo/intellij-community,dslomov/intellij-community,da1z/intellij-community,supersven/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,amith01994/intellij-community,caot/intellij-community,da1z/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,caot/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,semonte/intellij-community,signed/intellij-community,supersven/intellij-community,Lekanich/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,adedayo/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,caot/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,xfournet/intellij-community,slisson/intellij-community,holmes/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,vladmm/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,kool79/intellij-community,supersven/intellij-community,allotria/intellij-community,hurricup/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,caot/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,robovm/robovm-studio,jagguli/intellij-community,kdwink/intellij-community,nicolargo/intellij-community,allotria/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,apixandru/intellij-community,retomerz/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,retomerz/intellij-community,izonder/intellij-community,asedunov/intellij-community,clumsy/intellij-community,retomerz/intellij-community,allotria/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,FHannes/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,vladmm/intellij-community,da1z/intellij-community,semonte/intellij-community,hurricup/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,da1z/intellij-community,jagguli/intellij-community,fnouama/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,caot/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,slisson/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,holmes/intellij-community,allotria/intellij-community,kdwink/intellij-community,signed/intellij-community,samthor/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,caot/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,holmes/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,kool79/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,supersven/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,ryano144/intellij-community,diorcety/intellij-community,slisson/intellij-community,ibinti/intellij-community,vladmm/intellij-community,kool79/intellij-community,blademainer/intellij-community,clumsy/intellij-community,asedunov/intellij-community,petteyg/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,petteyg/intellij-community,jagguli/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,samthor/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,holmes/intellij-community,da1z/intellij-community,asedunov/intellij-community,robovm/robovm-studio,slisson/intellij-community,vladmm/intellij-community,petteyg/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,ryano144/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,gnuhub/intellij-community,ahb0327/intellij-community,allotria/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,ol-loginov/intellij-community,vladmm/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,fitermay/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,apixandru/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,lucafavatella/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,amith01994/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,kdwink/intellij-community,semonte/intellij-community,clumsy/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,robovm/robovm-studio,slisson/intellij-community,kdwink/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,holmes/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,petteyg/intellij-community,samthor/intellij-community,blademainer/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,fitermay/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,xfournet/intellij-community,hurricup/intellij-community,dslomov/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,allotria/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,signed/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,allotria/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,kool79/intellij-community,slisson/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,michaelgallacher/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community,vladmm/intellij-community,signed/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,caot/intellij-community,kdwink/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,da1z/intellij-community,ibinti/intellij-community | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.unwrap;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.psi.*;
import com.intellij.util.IncorrectOperationException;
import java.util.List;
public class JavaMethodParameterUnwrapper extends JavaUnwrapper {
private static final Logger LOG = Logger.getInstance("#" + JavaMethodParameterUnwrapper.class.getName());
public JavaMethodParameterUnwrapper() {
super("");
}
private static PsiElement adjustElementToTheLeft(PsiElement element) {
if (element instanceof PsiJavaToken && ((PsiJavaToken)element).getTokenType() == JavaTokenType.RPARENTH) {
PsiElement prevSibling = element.getPrevSibling();
if (prevSibling != null) {
return prevSibling;
}
}
return element;
}
@Override
public String getDescription(PsiElement e) {
String text = adjustElementToTheLeft(e).getText();
if (text.length() > 20) text = text.substring(0, 17) + "...";
return CodeInsightBundle.message("unwrap.with.placeholder", text);
}
@Override
public boolean isApplicableTo(PsiElement e) {
e = adjustElementToTheLeft(e);
final PsiElement parent = e.getParent();
if (e instanceof PsiExpression){
if (parent instanceof PsiExpressionList) {
return true;
}
if (e instanceof PsiReferenceExpression && parent instanceof PsiCallExpression) {
final PsiExpressionList argumentList = ((PsiCall)parent).getArgumentList();
if (argumentList != null && argumentList.getExpressions().length == 1) {
return true;
}
}
} else if (e instanceof PsiJavaCodeReferenceElement) {
if (parent instanceof PsiCall) {
final PsiExpressionList argumentList = ((PsiCall)parent).getArgumentList();
if (argumentList != null && argumentList.getExpressions().length == 1) {
return true;
}
}
}
return false;
}
@Override
public PsiElement collectAffectedElements(PsiElement e, List<PsiElement> toExtract) {
e = adjustElementToTheLeft(e);
super.collectAffectedElements(e, toExtract);
return isTopLevelCall(e) ? e.getParent() : e.getParent().getParent();
}
private static boolean isTopLevelCall(PsiElement e) {
if (e instanceof PsiReferenceExpression && e.getParent() instanceof PsiCallExpression) return true;
return e instanceof PsiJavaCodeReferenceElement && !(e instanceof PsiExpression);
}
@Override
protected void doUnwrap(PsiElement element, Context context) throws IncorrectOperationException {
element = adjustElementToTheLeft(element);
PsiElement methodCall = isTopLevelCall(element) ? element.getParent() : element.getParent().getParent();
final PsiElement extractedElement = isTopLevelCall(element) ? getArg(element) : element;
context.extractElement(extractedElement, methodCall);
if (methodCall.getParent() instanceof PsiExpressionList) {
context.delete(methodCall);
}
else {
context.deleteExactly(methodCall);
}
}
private static PsiExpression getArg(PsiElement element) {
final PsiExpressionList argumentList = ((PsiCall)element.getParent()).getArgumentList();
LOG.assertTrue(argumentList != null);
final PsiExpression[] args = argumentList.getExpressions();
LOG.assertTrue(args.length == 1);
return args[0];
}
}
| java/java-impl/src/com/intellij/codeInsight/unwrap/JavaMethodParameterUnwrapper.java | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.unwrap;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.psi.*;
import com.intellij.util.IncorrectOperationException;
import java.util.List;
public class JavaMethodParameterUnwrapper extends JavaUnwrapper {
private static final Logger LOG = Logger.getInstance("#" + JavaMethodParameterUnwrapper.class.getName());
public JavaMethodParameterUnwrapper() {
super("");
}
private static PsiElement adjustElementToTheLeft(PsiElement element) {
if (element instanceof PsiJavaToken && ((PsiJavaToken)element).getTokenType() == JavaTokenType.RPARENTH) {
return element.getPrevSibling();
}
return element;
}
@Override
public String getDescription(PsiElement e) {
String text = adjustElementToTheLeft(e).getText();
if (text.length() > 20) text = text.substring(0, 17) + "...";
return CodeInsightBundle.message("unwrap.with.placeholder", text);
}
@Override
public boolean isApplicableTo(PsiElement e) {
e = adjustElementToTheLeft(e);
final PsiElement parent = e.getParent();
if (e instanceof PsiExpression){
if (parent instanceof PsiExpressionList) {
return true;
}
if (e instanceof PsiReferenceExpression && parent instanceof PsiCallExpression) {
final PsiExpressionList argumentList = ((PsiCall)parent).getArgumentList();
if (argumentList != null && argumentList.getExpressions().length == 1) {
return true;
}
}
} else if (e instanceof PsiJavaCodeReferenceElement) {
if (parent instanceof PsiCall) {
final PsiExpressionList argumentList = ((PsiCall)parent).getArgumentList();
if (argumentList != null && argumentList.getExpressions().length == 1) {
return true;
}
}
}
return false;
}
@Override
public PsiElement collectAffectedElements(PsiElement e, List<PsiElement> toExtract) {
e = adjustElementToTheLeft(e);
super.collectAffectedElements(e, toExtract);
return isTopLevelCall(e) ? e.getParent() : e.getParent().getParent();
}
private static boolean isTopLevelCall(PsiElement e) {
if (e instanceof PsiReferenceExpression && e.getParent() instanceof PsiCallExpression) return true;
return e instanceof PsiJavaCodeReferenceElement && !(e instanceof PsiExpression);
}
@Override
protected void doUnwrap(PsiElement element, Context context) throws IncorrectOperationException {
element = adjustElementToTheLeft(element);
PsiElement methodCall = isTopLevelCall(element) ? element.getParent() : element.getParent().getParent();
final PsiElement extractedElement = isTopLevelCall(element) ? getArg(element) : element;
context.extractElement(extractedElement, methodCall);
if (methodCall.getParent() instanceof PsiExpressionList) {
context.delete(methodCall);
}
else {
context.deleteExactly(methodCall);
}
}
private static PsiExpression getArg(PsiElement element) {
final PsiExpressionList argumentList = ((PsiCall)element.getParent()).getArgumentList();
LOG.assertTrue(argumentList != null);
final PsiExpression[] args = argumentList.getExpressions();
LOG.assertTrue(args.length == 1);
return args[0];
}
}
| EA-59683 - NPE: JavaMethodParameterUnwrapper.isApplicableTo
| java/java-impl/src/com/intellij/codeInsight/unwrap/JavaMethodParameterUnwrapper.java | EA-59683 - NPE: JavaMethodParameterUnwrapper.isApplicableTo | <ide><path>ava/java-impl/src/com/intellij/codeInsight/unwrap/JavaMethodParameterUnwrapper.java
<ide>
<ide> private static PsiElement adjustElementToTheLeft(PsiElement element) {
<ide> if (element instanceof PsiJavaToken && ((PsiJavaToken)element).getTokenType() == JavaTokenType.RPARENTH) {
<del> return element.getPrevSibling();
<add> PsiElement prevSibling = element.getPrevSibling();
<add> if (prevSibling != null) {
<add> return prevSibling;
<add> }
<ide> }
<ide> return element;
<ide> } |
|
Java | apache-2.0 | 19681a107fe8258984d20c86b3d140038d31f621 | 0 | facebook/litho,facebook/litho,facebook/litho,facebook/litho,facebook/litho,facebook/litho | /**
* Copyright (c) 2017-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.litho;
import java.util.ArrayDeque;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.res.Resources;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.util.SparseArrayCompat;
import android.util.SparseArray;
import com.facebook.litho.config.ComponentsConfiguration;
import com.facebook.litho.displaylist.DisplayList;
import com.facebook.infer.annotation.ThreadSafe;
import com.facebook.litho.internal.ArraySet;
import com.facebook.yoga.YogaConfig;
import com.facebook.yoga.YogaDirection;
import com.facebook.yoga.YogaExperimentalFeature;
import com.facebook.yoga.YogaNode;
import static android.support.v4.view.ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO;
/**
* Pools of recycled resources.
*
* FUTURE: Consider customizing the pool implementation such that we can match buffer sizes. Without
* this we will tend to expand all buffers to the largest size needed.
*/
public class ComponentsPools {
private static final int SCRAP_ARRAY_INITIAL_SIZE = 4;
private static YogaConfig sYogaConfig;
private ComponentsPools() {
}
// FUTURE: tune pool max sizes
private static final Object mountContentLock = new Object();
static final RecyclePool<LayoutState> sLayoutStatePool =
new RecyclePool<>("LayoutState", 64, true);
static final RecyclePool<InternalNode> sInternalNodePool =
new RecyclePool<>("InternalNode", 256, true);
static final RecyclePool<NodeInfo> sNodeInfoPool =
new RecyclePool<>("NodeInfo", 256, true);
static final RecyclePool<ViewNodeInfo> sViewNodeInfoPool =
new RecyclePool<>("ViewNodeInfo", 64, true);
static final RecyclePool<YogaNode> sYogaNodePool =
new RecyclePool<>("YogaNode", 256, true);
static final RecyclePool<MountItem> sMountItemPool =
new RecyclePool<>("MountItem", 256, true);
static final Map<Context, SparseArray<RecyclePool>> sMountContentPoolsByContext =
new ConcurrentHashMap<>(4);
static final RecyclePool<LayoutOutput> sLayoutOutputPool =
new RecyclePool<>("LayoutOutput", 256, true);
static final RecyclePool<VisibilityOutput> sVisibilityOutputPool =
new RecyclePool<>("VisibilityOutput", 64, true);
// These are lazily initialized as they are only needed when we're in a test environment.
static RecyclePool<TestOutput> sTestOutputPool = null;
static RecyclePool<TestItem> sTestItemPool = null;
static final RecyclePool<VisibilityItem> sVisibilityItemPool =
new RecyclePool<>("VisibilityItem", 64, true);
static final RecyclePool<Output<?>> sOutputPool =
new RecyclePool<>("Output", 20, true);
static final RecyclePool<DiffNode> sDiffNodePool =
new RecyclePool<>("DiffNode", 256, true);
static final RecyclePool<Diff<?>> sDiffPool =
new RecyclePool<>("Diff", 20, true);
static final RecyclePool<ComponentTree.Builder> sComponentTreeBuilderPool =
new RecyclePool<>("ComponentTree.Builder", 2, true);
static final RecyclePool<StateHandler> sStateHandlerPool =
new RecyclePool<>("StateHandler", 10, true);
static final RecyclePool<SparseArrayCompat<MountItem>> sMountItemScrapArrayPool =
new RecyclePool<>("MountItemScrapArray", 8, false);
static final RecyclePool<SparseArrayCompat<Touchable>> sTouchableScrapArrayPool =
new RecyclePool<>("TouchableScrapArray", 4, false);
static final RecyclePool<RectF> sRectFPool =
new RecyclePool<>("RectF", 4, true);
static final RecyclePool<Rect> sRectPool =
new RecyclePool<>("Rect", 30, true);
static final RecyclePool<Edges> sEdgesPool =
new RecyclePool<>("Edges", 30, true);
static final RecyclePool<TransitionContext> sTransitionContextPool =
new RecyclePool<>("TransitionContext", 2, true);
static final RecyclePool<DisplayListDrawable> sDisplayListDrawablePool =
new RecyclePool<>("DisplayListDrawable", 10, false);
static final RecyclePool<TreeProps> sTreePropsMapPool =
new RecyclePool<>("TreeProps", 10, true);
static final RecyclePool<ArraySet> sArraySetPool =
new RecyclePool<>("ArraySet", 10, true);
static final RecyclePool<ArrayDeque> sArrayDequePool =
new RecyclePool<>("ArrayDeque", 10, true);
static final RecyclePool<LogEvent> sLogEventPool =
new RecyclePool<>("LogEvent", 10, true);
// Lazily initialized when acquired first time, as this is not a common use case.
static RecyclePool<BorderColorDrawable> sBorderColorDrawablePool = null;
private static PoolsActivityCallback sActivityCallbacks;
/**
* To support Gingerbread (where the registerActivityLifecycleCallbacks API
* doesn't exist), we allow apps to explicitly invoke activity callbacks. If
* this is enabled we'll throw if we are passed a context for which we have
* no record.
*/
static boolean sIsManualCallbacks;
static LayoutState acquireLayoutState(ComponentContext context) {
LayoutState state = ComponentsConfiguration.usePooling ? sLayoutStatePool.acquire() : null;
if (state == null) {
state = new LayoutState();
}
state.init(context);
return state;
}
static synchronized YogaNode acquireYogaNode(ComponentContext c) {
if (sYogaConfig == null) {
sYogaConfig = new YogaConfig();
sYogaConfig.setUseWebDefaults(true);
sYogaConfig.setUseLegacyStretchBehaviour(true);
}
if (sYogaConfig.getLogger() != ComponentsConfiguration.YOGA_LOGGER) {
sYogaConfig.setLogger(ComponentsConfiguration.YOGA_LOGGER);
}
YogaNode node = ComponentsConfiguration.usePooling ? sYogaNodePool.acquire() : null;
if (node == null) {
node = new YogaNode(sYogaConfig);
}
return node;
}
static synchronized InternalNode acquireInternalNode(
ComponentContext componentContext,
Resources resources) {
InternalNode node = ComponentsConfiguration.usePooling ? sInternalNodePool.acquire() : null;
if (node == null) {
node = new InternalNode();
}
node.init(acquireYogaNode(componentContext), componentContext, resources);
return node;
}
static synchronized NodeInfo acquireNodeInfo() {
NodeInfo nodeInfo = ComponentsConfiguration.usePooling ? sNodeInfoPool.acquire() : null;
if (nodeInfo == null) {
nodeInfo = new NodeInfo();
}
return nodeInfo;
}
static synchronized ViewNodeInfo acquireViewNodeInfo() {
ViewNodeInfo viewNodeInfo =
ComponentsConfiguration.usePooling ? sViewNodeInfoPool.acquire() : null;
if (viewNodeInfo == null) {
viewNodeInfo = new ViewNodeInfo();
}
return viewNodeInfo;
}
static MountItem acquireRootHostMountItem(
Component<?> component,
ComponentHost host,
Object content) {
MountItem item = ComponentsConfiguration.usePooling ? sMountItemPool.acquire() : null;
if (item == null) {
item = new MountItem();
}
final ViewNodeInfo viewNodeInfo = ViewNodeInfo.acquire();
viewNodeInfo.setLayoutDirection(YogaDirection.INHERIT);
item.init(
component,
host,
content,
null,
viewNodeInfo,
null,
0,
IMPORTANT_FOR_ACCESSIBILITY_AUTO);
return item;
}
static MountItem acquireMountItem(
Component<?> component,
ComponentHost host,
Object content,
LayoutOutput layoutOutput) {
MountItem item = ComponentsConfiguration.usePooling ? sMountItemPool.acquire() : null;
if (item == null) {
item = new MountItem();
}
item.init(component, host, content, layoutOutput, null);
return item;
}
static Object acquireMountContent(Context context, int componentId) {
if (context instanceof ComponentContext) {
context = ((ComponentContext) context).getBaseContext();
if (context instanceof ComponentContext) {
throw new IllegalStateException("Double wrapped ComponentContext.");
}
}
final RecyclePool<Object> pool;
synchronized (mountContentLock) {
if (sActivityCallbacks == null && !sIsManualCallbacks) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
throw new RuntimeException(
"Activity callbacks must be invoked manually below ICS (API level 14)");
}
sActivityCallbacks = new PoolsActivityCallback();
((Application) context.getApplicationContext())
.registerActivityLifecycleCallbacks(sActivityCallbacks);
}
SparseArray<RecyclePool> poolsArray =
sMountContentPoolsByContext.get(context);
if (poolsArray == null) {
// The context is created here because we are sure the Activity is alive at this point in
// contrast of the release call where the Activity might by gone.
sMountContentPoolsByContext.put(context, new SparseArray<RecyclePool>());
return null;
}
pool = poolsArray.get(componentId);
if (pool == null) {
return null;
}
}
return pool.acquire();
}
static LayoutOutput acquireLayoutOutput() {
LayoutOutput output = ComponentsConfiguration.usePooling ? sLayoutOutputPool.acquire() : null;
if (output == null) {
output = new LayoutOutput();
}
return output;
}
static VisibilityOutput acquireVisibilityOutput() {
VisibilityOutput output =
ComponentsConfiguration.usePooling ? sVisibilityOutputPool.acquire() : null;
if (output == null) {
output = new VisibilityOutput();
}
return output;
}
static VisibilityItem acquireVisibilityItem(
EventHandler invisibleHandler,
EventHandler unfocusedHandler) {
VisibilityItem item = ComponentsConfiguration.usePooling ? sVisibilityItemPool.acquire() : null;
if (item == null) {
item = new VisibilityItem();
}
item.setInvisibleHandler(invisibleHandler);
item.setUnfocusedHandler(unfocusedHandler);
return item;
}
static TestOutput acquireTestOutput() {
if (sTestOutputPool == null) {
sTestOutputPool = new RecyclePool<>("TestOutput", 64, true);
}
TestOutput output = ComponentsConfiguration.usePooling ? sTestOutputPool.acquire() : null;
if (output == null) {
output = new TestOutput();
}
return output;
}
static TestItem acquireTestItem() {
if (sTestItemPool == null) {
sTestItemPool = new RecyclePool<>("TestItem", 64, true);
}
TestItem item = ComponentsConfiguration.usePooling ? sTestItemPool.acquire() : null;
if (item == null) {
item = new TestItem();
}
return item;
}
static Output acquireOutput() {
Output output = ComponentsConfiguration.usePooling ? sOutputPool.acquire() : null;
if (output == null) {
output = new Output();
}
return output;
}
static DiffNode acquireDiffNode() {
DiffNode node = ComponentsConfiguration.usePooling ? sDiffNodePool.acquire() : null;
if (node == null) {
node = new DiffNode();
}
return node;
}
public static <T> Diff acquireDiff(T previous, T next) {
Diff diff = ComponentsConfiguration.usePooling ? sDiffPool.acquire() : null;
if (diff == null) {
diff = new Diff();
}
diff.init(previous, next);
return diff;
}
static ComponentTree.Builder acquireComponentTreeBuilder(ComponentContext c, Component<?> root) {
ComponentTree.Builder componentTreeBuilder =
ComponentsConfiguration.usePooling ? sComponentTreeBuilderPool.acquire() : null;
if (componentTreeBuilder == null) {
componentTreeBuilder = new ComponentTree.Builder();
}
componentTreeBuilder.init(c, root);
return componentTreeBuilder;
}
static StateHandler acquireStateHandler(StateHandler fromStateHandler) {
StateHandler stateHandler =
ComponentsConfiguration.usePooling ? sStateHandlerPool.acquire() : null;
if (stateHandler == null) {
stateHandler = new StateHandler();
}
stateHandler.init(fromStateHandler);
return stateHandler;
}
static StateHandler acquireStateHandler() {
return acquireStateHandler(null);
}
static TransitionContext acquireTransitionContext() {
TransitionContext transitionContext =
ComponentsConfiguration.usePooling ? sTransitionContextPool.acquire() : null;
if (transitionContext == null) {
transitionContext = new TransitionContext();
}
return transitionContext;
}
public static TreeProps acquireTreeProps() {
TreeProps treeProps = ComponentsConfiguration.usePooling ? sTreePropsMapPool.acquire() : null;
if (treeProps == null) {
treeProps = new TreeProps();
}
return treeProps;
}
public static LogEvent acquireLogEvent(int eventId) {
LogEvent event = ComponentsConfiguration.usePooling ? sLogEventPool.acquire() : null;
if (event == null) {
event = new LogEvent();
}
event.setEventId(eventId);
return event;
}
//TODO t16407516 shb: change all "enableChecks = false" here to @TakesOwnership
@ThreadSafe(enableChecks = false)
public static void release(TreeProps treeProps) {
if (!ComponentsConfiguration.usePooling) {
return;
}
treeProps.reset();
sTreePropsMapPool.release(treeProps);
}
@ThreadSafe(enableChecks = false)
static void release(TransitionContext transitionContext) {
if (!ComponentsConfiguration.usePooling) {
return;
}
transitionContext.reset();
sTransitionContextPool.release(transitionContext);
}
@ThreadSafe(enableChecks = false)
static void release(ComponentTree.Builder componentTreeBuilder) {
if (!ComponentsConfiguration.usePooling) {
return;
}
componentTreeBuilder.release();
sComponentTreeBuilderPool.release(componentTreeBuilder);
}
@ThreadSafe(enableChecks = false)
static void release(StateHandler stateHandler) {
if (!ComponentsConfiguration.usePooling) {
return;
}
stateHandler.release();
sStateHandlerPool.release(stateHandler);
}
@ThreadSafe(enableChecks = false)
static void release(LayoutState state) {
if (!ComponentsConfiguration.usePooling) {
return;
}
sLayoutStatePool.release(state);
}
@ThreadSafe(enableChecks = false)
static void release(YogaNode node) {
if (!ComponentsConfiguration.usePooling) {
return;
}
node.reset();
sYogaNodePool.release(node);
}
@ThreadSafe(enableChecks = false)
static void release(InternalNode node) {
if (!ComponentsConfiguration.usePooling) {
return;
}
node.release();
sInternalNodePool.release(node);
}
@ThreadSafe(enableChecks = false)
static void release(NodeInfo nodeInfo) {
if (!ComponentsConfiguration.usePooling) {
return;
}
sNodeInfoPool.release(nodeInfo);
}
@ThreadSafe(enableChecks = false)
static void release(ViewNodeInfo viewNodeInfo) {
if (!ComponentsConfiguration.usePooling) {
return;
}
sViewNodeInfoPool.release(viewNodeInfo);
}
@ThreadSafe(enableChecks = false)
static void release(Context context, MountItem item) {
if (!ComponentsConfiguration.usePooling) {
return;
}
item.release(context);
sMountItemPool.release(item);
}
@ThreadSafe(enableChecks = false)
static void release(LayoutOutput output) {
if (!ComponentsConfiguration.usePooling) {
return;
}
output.release();
sLayoutOutputPool.release(output);
}
@ThreadSafe(enableChecks = false)
static void release(VisibilityOutput output) {
if (!ComponentsConfiguration.usePooling) {
return;
}
output.release();
sVisibilityOutputPool.release(output);
}
@ThreadSafe(enableChecks = false)
static void release(VisibilityItem item) {
if (!ComponentsConfiguration.usePooling) {
return;
}
item.release();
sVisibilityItemPool.release(item);
}
@ThreadSafe(enableChecks = false)
static void release(TestOutput testOutput) {
if (!ComponentsConfiguration.usePooling) {
return;
}
testOutput.release();
sTestOutputPool.release(testOutput);
}
@ThreadSafe(enableChecks = false)
static void release(TestItem testItem) {
if (!ComponentsConfiguration.usePooling) {
return;
}
testItem.release();
sTestItemPool.release(testItem);
}
@ThreadSafe(enableChecks = false)
static void release(DiffNode node) {
if (!ComponentsConfiguration.usePooling) {
return;
}
node.release();
sDiffNodePool.release(node);
}
@ThreadSafe(enableChecks = false)
static void release(Output output) {
if (!ComponentsConfiguration.usePooling) {
return;
}
output.release();
sOutputPool.release(output);
}
@ThreadSafe(enableChecks = false)
public static void release(Diff diff) {
if (!ComponentsConfiguration.usePooling) {
return;
}
diff.release();
sDiffPool.release(diff);
}
@ThreadSafe(enableChecks = false)
static void release(Context context, ComponentLifecycle lifecycle, Object mountContent) {
if (context instanceof ComponentContext) {
context = ((ComponentContext) context).getBaseContext();
if (context instanceof ComponentContext) {
throw new IllegalStateException("Double wrapped ComponentContext.");
}
}
RecyclePool pool = null;
synchronized (mountContentLock) {
SparseArray<RecyclePool> poolsArray =
sMountContentPoolsByContext.get(context);
if (poolsArray != null) {
pool = poolsArray.get(lifecycle.getId());
if (pool == null) {
pool = new RecyclePool(
"MountContent - " + lifecycle.getClass().getSimpleName(),
lifecycle.poolSize(),
true);
poolsArray.put(lifecycle.getId(), pool);
}
}
if (pool != null) {
pool.release(mountContent);
}
}
}
static boolean canAddMountContentToPool(Context context, ComponentLifecycle lifecycle) {
if (lifecycle.poolSize() == 0) {
return false;
}
final SparseArray<RecyclePool> poolsArray =
sMountContentPoolsByContext.get(context);
if (poolsArray == null) {
return true;
}
final RecyclePool pool = poolsArray.get(lifecycle.getId());
return pool == null || !pool.isFull();
}
static SparseArrayCompat<MountItem> acquireScrapMountItemsArray() {
SparseArrayCompat<MountItem> sparseArray =
ComponentsConfiguration.usePooling ? sMountItemScrapArrayPool.acquire() : null;
if (sparseArray == null) {
sparseArray = new SparseArrayCompat<>(SCRAP_ARRAY_INITIAL_SIZE);
}
return sparseArray;
}
@ThreadSafe(enableChecks = false)
static void releaseScrapMountItemsArray(SparseArrayCompat<MountItem> sparseArray) {
if (!ComponentsConfiguration.usePooling) {
return;
}
sMountItemScrapArrayPool.release(sparseArray);
}
static SparseArrayCompat<Touchable> acquireScrapTouchablesArray() {
SparseArrayCompat<Touchable> sparseArray =
ComponentsConfiguration.usePooling ? sTouchableScrapArrayPool.acquire() : null;
if (sparseArray == null) {
sparseArray = new SparseArrayCompat<>(SCRAP_ARRAY_INITIAL_SIZE);
}
return sparseArray;
}
@ThreadSafe(enableChecks = false)
static void releaseScrapTouchablesArray(SparseArrayCompat<Touchable> sparseArray) {
if (!ComponentsConfiguration.usePooling) {
return;
}
sTouchableScrapArrayPool.release(sparseArray);
}
static RectF acquireRectF() {
RectF rect = ComponentsConfiguration.usePooling ? sRectFPool.acquire() : null;
if (rect == null) {
rect = new RectF();
}
return rect;
}
@ThreadSafe(enableChecks = false)
static void releaseRectF(RectF rect) {
if (!ComponentsConfiguration.usePooling) {
return;
}
rect.setEmpty();
sRectFPool.release(rect);
}
static Rect acquireRect() {
Rect rect = ComponentsConfiguration.usePooling ? sRectPool.acquire() : null;
if (rect == null) {
rect = new Rect();
}
return rect;
}
@ThreadSafe(enableChecks = false)
static void release(Rect rect) {
if (!ComponentsConfiguration.usePooling) {
return;
}
rect.setEmpty();
sRectPool.release(rect);
}
static Edges acquireEdges() {
Edges spacing = ComponentsConfiguration.usePooling ? sEdgesPool.acquire() : null;
if (spacing == null) {
spacing = new Edges();
}
return spacing;
}
@ThreadSafe(enableChecks = false)
static void release(Edges edges) {
if (!ComponentsConfiguration.usePooling) {
return;
}
edges.reset();
sEdgesPool.release(edges);
}
/**
* Empty implementation of the {@link Application.ActivityLifecycleCallbacks} interface
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private static class PoolsActivityCallback
implements Application.ActivityLifecycleCallbacks {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
ComponentsPools.onContextCreated(activity);
}
@Override
public void onActivityStarted(Activity activity) {
// Do nothing.
}
@Override
public void onActivityResumed(Activity activity) {
// Do nothing.
}
@Override
public void onActivityPaused(Activity activity) {
// Do nothing.
}
@Override
public void onActivityStopped(Activity activity) {
// Do nothing.
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
// Do nothing.
}
@Override
public void onActivityDestroyed(Activity activity) {
ComponentsPools.onContextDestroyed(activity);
}
}
static void onContextCreated(Context context) {
if (sMountContentPoolsByContext.containsKey(context)) {
throw new IllegalStateException("The MountContentPools has a reference to an activity" +
"that has just been created");
}
}
static void onContextDestroyed(Context context) {
sMountContentPoolsByContext.remove(context);
// Clear any context wrappers holding a reference to this activity.
final Iterator<Map.Entry<Context, SparseArray<RecyclePool>>> it =
sMountContentPoolsByContext.entrySet().iterator();
while (it.hasNext()) {
final Context contextKey = it.next().getKey();
if (isContextWrapper(contextKey, context)) {
it.remove();
}
}
}
/**
* Call from tests to clear external references.
*/
public static void clearAll() {
sMountContentPoolsByContext.clear();
}
/**
* Check whether contextWrapper is a wrapper of baseContext
*/
private static boolean isContextWrapper(Context contextWrapper, Context baseContext) {
Context currentContext = contextWrapper;
while (currentContext instanceof ContextWrapper) {
currentContext = ((ContextWrapper) currentContext).getBaseContext();
if (currentContext == baseContext) {
return true;
}
}
return false;
}
public static DisplayListDrawable acquireDisplayListDrawable(
Drawable content,
DisplayList displayList) {
// When we are wrapping drawable with DisplayListDrawable we need to make sure that
// wrapped DisplayListDrawable has the same view callback as original one had for correct
// view invalidations.
final Drawable.Callback callback = content.getCallback();
DisplayListDrawable displayListDrawable =
ComponentsConfiguration.usePooling ? sDisplayListDrawablePool.acquire() : null;
if (displayListDrawable == null) {
displayListDrawable = new DisplayListDrawable(content, displayList);
} else {
displayListDrawable.setWrappedDrawable(content, displayList);
}
displayListDrawable.setCallback(callback);
return displayListDrawable;
}
@ThreadSafe(enableChecks = false)
public static void release(DisplayListDrawable displayListDrawable) {
if (!ComponentsConfiguration.usePooling) {
return;
}
displayListDrawable.release();
sDisplayListDrawablePool.release(displayListDrawable);
}
public static BorderColorDrawable acquireBorderColorDrawable() {
if (sBorderColorDrawablePool == null) {
sBorderColorDrawablePool = new RecyclePool<>("BorderColorDrawable", 10, true);
}
BorderColorDrawable drawable =
ComponentsConfiguration.usePooling ? sBorderColorDrawablePool.acquire() : null;
if (drawable == null) {
drawable = new BorderColorDrawable();
}
return drawable;
}
@ThreadSafe(enableChecks = false)
public static void release(BorderColorDrawable borderColorDrawable) {
if (!ComponentsConfiguration.usePooling) {
return;
}
sBorderColorDrawablePool.release(borderColorDrawable);
}
public static <E> ArraySet<E> acquireArraySet() {
ArraySet<E> set = ComponentsConfiguration.usePooling ? sArraySetPool.acquire() : null;
if (set == null) {
set = new ArraySet<>();
}
return set;
}
@ThreadSafe(enableChecks = false)
public static void release(ArraySet set) {
if (!ComponentsConfiguration.usePooling) {
return;
}
set.clear();
sArraySetPool.release(set);
}
public static <E> ArrayDeque<E> acquireArrayDeque() {
ArrayDeque<E> deque = ComponentsConfiguration.usePooling ? sArrayDequePool.acquire() : null;
if (deque == null) {
deque = new ArrayDeque<>();
}
return deque;
}
@ThreadSafe(enableChecks = false)
public static void release(ArrayDeque deque) {
if (!ComponentsConfiguration.usePooling) {
return;
}
deque.clear();
sArrayDequePool.release(deque);
}
@ThreadSafe(enableChecks = false)
public static void release(LogEvent event) {
if (!ComponentsConfiguration.usePooling) {
return;
}
event.reset();
sLogEventPool.release(event);
}
}
| litho-core/src/main/java/com/facebook/litho/ComponentsPools.java | /**
* Copyright (c) 2017-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.litho;
import java.util.ArrayDeque;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.res.Resources;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.util.SparseArrayCompat;
import android.util.SparseArray;
import com.facebook.litho.config.ComponentsConfiguration;
import com.facebook.litho.displaylist.DisplayList;
import com.facebook.infer.annotation.ThreadSafe;
import com.facebook.litho.internal.ArraySet;
import com.facebook.yoga.YogaConfig;
import com.facebook.yoga.YogaDirection;
import com.facebook.yoga.YogaExperimentalFeature;
import com.facebook.yoga.YogaNode;
import static android.support.v4.view.ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO;
/**
* Pools of recycled resources.
*
* FUTURE: Consider customizing the pool implementation such that we can match buffer sizes. Without
* this we will tend to expand all buffers to the largest size needed.
*/
public class ComponentsPools {
private static final int SCRAP_ARRAY_INITIAL_SIZE = 4;
private static YogaConfig sYogaConfig;
private ComponentsPools() {
}
// FUTURE: tune pool max sizes
private static final Object mountContentLock = new Object();
static final RecyclePool<LayoutState> sLayoutStatePool =
new RecyclePool<>("LayoutState", 64, true);
static final RecyclePool<InternalNode> sInternalNodePool =
new RecyclePool<>("InternalNode", 256, true);
static final RecyclePool<NodeInfo> sNodeInfoPool =
new RecyclePool<>("NodeInfo", 256, true);
static final RecyclePool<ViewNodeInfo> sViewNodeInfoPool =
new RecyclePool<>("ViewNodeInfo", 64, true);
static final RecyclePool<YogaNode> sYogaNodePool =
new RecyclePool<>("YogaNode", 256, true);
static final RecyclePool<MountItem> sMountItemPool =
new RecyclePool<>("MountItem", 256, true);
static final Map<Context, SparseArray<RecyclePool>> sMountContentPoolsByContext =
new ConcurrentHashMap<>(4);
static final RecyclePool<LayoutOutput> sLayoutOutputPool =
new RecyclePool<>("LayoutOutput", 256, true);
static final RecyclePool<VisibilityOutput> sVisibilityOutputPool =
new RecyclePool<>("VisibilityOutput", 64, true);
// These are lazily initialized as they are only needed when we're in a test environment.
static RecyclePool<TestOutput> sTestOutputPool = null;
static RecyclePool<TestItem> sTestItemPool = null;
static final RecyclePool<VisibilityItem> sVisibilityItemPool =
new RecyclePool<>("VisibilityItem", 64, true);
static final RecyclePool<Output<?>> sOutputPool =
new RecyclePool<>("Output", 20, true);
static final RecyclePool<DiffNode> sDiffNodePool =
new RecyclePool<>("DiffNode", 256, true);
static final RecyclePool<Diff<?>> sDiffPool =
new RecyclePool<>("Diff", 20, true);
static final RecyclePool<ComponentTree.Builder> sComponentTreeBuilderPool =
new RecyclePool<>("ComponentTree.Builder", 2, true);
static final RecyclePool<StateHandler> sStateHandlerPool =
new RecyclePool<>("StateHandler", 10, true);
static final RecyclePool<SparseArrayCompat<MountItem>> sMountItemScrapArrayPool =
new RecyclePool<>("MountItemScrapArray", 8, false);
static final RecyclePool<SparseArrayCompat<Touchable>> sTouchableScrapArrayPool =
new RecyclePool<>("TouchableScrapArray", 4, false);
static final RecyclePool<RectF> sRectFPool =
new RecyclePool<>("RectF", 4, true);
static final RecyclePool<Rect> sRectPool =
new RecyclePool<>("Rect", 30, true);
static final RecyclePool<Edges> sEdgesPool =
new RecyclePool<>("Edges", 30, true);
static final RecyclePool<TransitionContext> sTransitionContextPool =
new RecyclePool<>("TransitionContext", 2, true);
static final RecyclePool<DisplayListDrawable> sDisplayListDrawablePool =
new RecyclePool<>("DisplayListDrawable", 10, false);
static final RecyclePool<TreeProps> sTreePropsMapPool =
new RecyclePool<>("TreeProps", 10, true);
static final RecyclePool<ArraySet> sArraySetPool =
new RecyclePool<>("ArraySet", 10, true);
static final RecyclePool<ArrayDeque> sArrayDequePool =
new RecyclePool<>("ArrayDeque", 10, true);
static final RecyclePool<LogEvent> sLogEventPool =
new RecyclePool<>("LogEvent", 10, true);
// Lazily initialized when acquired first time, as this is not a common use case.
static RecyclePool<BorderColorDrawable> sBorderColorDrawablePool = null;
private static PoolsActivityCallback sActivityCallbacks;
/**
* To support Gingerbread (where the registerActivityLifecycleCallbacks API
* doesn't exist), we allow apps to explicitly invoke activity callbacks. If
* this is enabled we'll throw if we are passed a context for which we have
* no record.
*/
static boolean sIsManualCallbacks;
static LayoutState acquireLayoutState(ComponentContext context) {
LayoutState state = ComponentsConfiguration.usePooling ? sLayoutStatePool.acquire() : null;
if (state == null) {
state = new LayoutState();
}
state.init(context);
return state;
}
static synchronized YogaNode acquireYogaNode(ComponentContext c) {
if (sYogaConfig == null) {
sYogaConfig = new YogaConfig();
sYogaConfig.setUseWebDefaults(true);
sYogaConfig.setUseLegacyStretchBehaviour(true);
}
if (sYogaConfig.getLogger() != ComponentsConfiguration.YOGA_LOGGER) {
sYogaConfig.setLogger(ComponentsConfiguration.YOGA_LOGGER);
}
YogaNode node = ComponentsConfiguration.usePooling ? sYogaNodePool.acquire() : null;
if (node == null) {
node = new YogaNode(sYogaConfig);
}
return node;
}
static synchronized InternalNode acquireInternalNode(
ComponentContext componentContext,
Resources resources) {
InternalNode node = ComponentsConfiguration.usePooling ? sInternalNodePool.acquire() : null;
if (node == null) {
node = new InternalNode();
}
node.init(acquireYogaNode(componentContext), componentContext, resources);
return node;
}
static synchronized NodeInfo acquireNodeInfo() {
NodeInfo nodeInfo = ComponentsConfiguration.usePooling ? sNodeInfoPool.acquire() : null;
if (nodeInfo == null) {
nodeInfo = new NodeInfo();
}
return nodeInfo;
}
static synchronized ViewNodeInfo acquireViewNodeInfo() {
ViewNodeInfo viewNodeInfo =
ComponentsConfiguration.usePooling ? sViewNodeInfoPool.acquire() : null;
if (viewNodeInfo == null) {
viewNodeInfo = new ViewNodeInfo();
}
return viewNodeInfo;
}
static MountItem acquireRootHostMountItem(
Component<?> component,
ComponentHost host,
Object content) {
MountItem item = ComponentsConfiguration.usePooling ? sMountItemPool.acquire() : null;
if (item == null) {
item = new MountItem();
}
final ViewNodeInfo viewNodeInfo = ViewNodeInfo.acquire();
viewNodeInfo.setLayoutDirection(YogaDirection.INHERIT);
item.init(
component,
host,
content,
null,
viewNodeInfo,
null,
0,
IMPORTANT_FOR_ACCESSIBILITY_AUTO);
return item;
}
static MountItem acquireMountItem(
Component<?> component,
ComponentHost host,
Object content,
LayoutOutput layoutOutput) {
MountItem item = ComponentsConfiguration.usePooling ? sMountItemPool.acquire() : null;
if (item == null) {
item = new MountItem();
}
item.init(component, host, content, layoutOutput, null);
return item;
}
static Object acquireMountContent(Context context, int componentId) {
if (!ComponentsConfiguration.usePooling) {
return null;
}
if (context instanceof ComponentContext) {
context = ((ComponentContext) context).getBaseContext();
if (context instanceof ComponentContext) {
throw new IllegalStateException("Double wrapped ComponentContext.");
}
}
final RecyclePool<Object> pool;
synchronized (mountContentLock) {
if (sActivityCallbacks == null && !sIsManualCallbacks) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
throw new RuntimeException(
"Activity callbacks must be invoked manually below ICS (API level 14)");
}
sActivityCallbacks = new PoolsActivityCallback();
((Application) context.getApplicationContext())
.registerActivityLifecycleCallbacks(sActivityCallbacks);
}
SparseArray<RecyclePool> poolsArray =
sMountContentPoolsByContext.get(context);
if (poolsArray == null) {
// The context is created here because we are sure the Activity is alive at this point in
// contrast of the release call where the Activity might by gone.
sMountContentPoolsByContext.put(context, new SparseArray<RecyclePool>());
return null;
}
pool = poolsArray.get(componentId);
if (pool == null) {
return null;
}
}
return pool.acquire();
}
static LayoutOutput acquireLayoutOutput() {
LayoutOutput output = ComponentsConfiguration.usePooling ? sLayoutOutputPool.acquire() : null;
if (output == null) {
output = new LayoutOutput();
}
return output;
}
static VisibilityOutput acquireVisibilityOutput() {
VisibilityOutput output =
ComponentsConfiguration.usePooling ? sVisibilityOutputPool.acquire() : null;
if (output == null) {
output = new VisibilityOutput();
}
return output;
}
static VisibilityItem acquireVisibilityItem(
EventHandler invisibleHandler,
EventHandler unfocusedHandler) {
VisibilityItem item = ComponentsConfiguration.usePooling ? sVisibilityItemPool.acquire() : null;
if (item == null) {
item = new VisibilityItem();
}
item.setInvisibleHandler(invisibleHandler);
item.setUnfocusedHandler(unfocusedHandler);
return item;
}
static TestOutput acquireTestOutput() {
if (sTestOutputPool == null) {
sTestOutputPool = new RecyclePool<>("TestOutput", 64, true);
}
TestOutput output = ComponentsConfiguration.usePooling ? sTestOutputPool.acquire() : null;
if (output == null) {
output = new TestOutput();
}
return output;
}
static TestItem acquireTestItem() {
if (sTestItemPool == null) {
sTestItemPool = new RecyclePool<>("TestItem", 64, true);
}
TestItem item = ComponentsConfiguration.usePooling ? sTestItemPool.acquire() : null;
if (item == null) {
item = new TestItem();
}
return item;
}
static Output acquireOutput() {
Output output = ComponentsConfiguration.usePooling ? sOutputPool.acquire() : null;
if (output == null) {
output = new Output();
}
return output;
}
static DiffNode acquireDiffNode() {
DiffNode node = ComponentsConfiguration.usePooling ? sDiffNodePool.acquire() : null;
if (node == null) {
node = new DiffNode();
}
return node;
}
public static <T> Diff acquireDiff(T previous, T next) {
Diff diff = ComponentsConfiguration.usePooling ? sDiffPool.acquire() : null;
if (diff == null) {
diff = new Diff();
}
diff.init(previous, next);
return diff;
}
static ComponentTree.Builder acquireComponentTreeBuilder(ComponentContext c, Component<?> root) {
ComponentTree.Builder componentTreeBuilder =
ComponentsConfiguration.usePooling ? sComponentTreeBuilderPool.acquire() : null;
if (componentTreeBuilder == null) {
componentTreeBuilder = new ComponentTree.Builder();
}
componentTreeBuilder.init(c, root);
return componentTreeBuilder;
}
static StateHandler acquireStateHandler(StateHandler fromStateHandler) {
StateHandler stateHandler =
ComponentsConfiguration.usePooling ? sStateHandlerPool.acquire() : null;
if (stateHandler == null) {
stateHandler = new StateHandler();
}
stateHandler.init(fromStateHandler);
return stateHandler;
}
static StateHandler acquireStateHandler() {
return acquireStateHandler(null);
}
static TransitionContext acquireTransitionContext() {
TransitionContext transitionContext =
ComponentsConfiguration.usePooling ? sTransitionContextPool.acquire() : null;
if (transitionContext == null) {
transitionContext = new TransitionContext();
}
return transitionContext;
}
public static TreeProps acquireTreeProps() {
TreeProps treeProps = ComponentsConfiguration.usePooling ? sTreePropsMapPool.acquire() : null;
if (treeProps == null) {
treeProps = new TreeProps();
}
return treeProps;
}
public static LogEvent acquireLogEvent(int eventId) {
LogEvent event = ComponentsConfiguration.usePooling ? sLogEventPool.acquire() : null;
if (event == null) {
event = new LogEvent();
}
event.setEventId(eventId);
return event;
}
//TODO t16407516 shb: change all "enableChecks = false" here to @TakesOwnership
@ThreadSafe(enableChecks = false)
public static void release(TreeProps treeProps) {
if (!ComponentsConfiguration.usePooling) {
return;
}
treeProps.reset();
sTreePropsMapPool.release(treeProps);
}
@ThreadSafe(enableChecks = false)
static void release(TransitionContext transitionContext) {
if (!ComponentsConfiguration.usePooling) {
return;
}
transitionContext.reset();
sTransitionContextPool.release(transitionContext);
}
@ThreadSafe(enableChecks = false)
static void release(ComponentTree.Builder componentTreeBuilder) {
if (!ComponentsConfiguration.usePooling) {
return;
}
componentTreeBuilder.release();
sComponentTreeBuilderPool.release(componentTreeBuilder);
}
@ThreadSafe(enableChecks = false)
static void release(StateHandler stateHandler) {
if (!ComponentsConfiguration.usePooling) {
return;
}
stateHandler.release();
sStateHandlerPool.release(stateHandler);
}
@ThreadSafe(enableChecks = false)
static void release(LayoutState state) {
if (!ComponentsConfiguration.usePooling) {
return;
}
sLayoutStatePool.release(state);
}
@ThreadSafe(enableChecks = false)
static void release(YogaNode node) {
if (!ComponentsConfiguration.usePooling) {
return;
}
node.reset();
sYogaNodePool.release(node);
}
@ThreadSafe(enableChecks = false)
static void release(InternalNode node) {
if (!ComponentsConfiguration.usePooling) {
return;
}
node.release();
sInternalNodePool.release(node);
}
@ThreadSafe(enableChecks = false)
static void release(NodeInfo nodeInfo) {
if (!ComponentsConfiguration.usePooling) {
return;
}
sNodeInfoPool.release(nodeInfo);
}
@ThreadSafe(enableChecks = false)
static void release(ViewNodeInfo viewNodeInfo) {
if (!ComponentsConfiguration.usePooling) {
return;
}
sViewNodeInfoPool.release(viewNodeInfo);
}
@ThreadSafe(enableChecks = false)
static void release(Context context, MountItem item) {
if (!ComponentsConfiguration.usePooling) {
return;
}
item.release(context);
sMountItemPool.release(item);
}
@ThreadSafe(enableChecks = false)
static void release(LayoutOutput output) {
if (!ComponentsConfiguration.usePooling) {
return;
}
output.release();
sLayoutOutputPool.release(output);
}
@ThreadSafe(enableChecks = false)
static void release(VisibilityOutput output) {
if (!ComponentsConfiguration.usePooling) {
return;
}
output.release();
sVisibilityOutputPool.release(output);
}
@ThreadSafe(enableChecks = false)
static void release(VisibilityItem item) {
if (!ComponentsConfiguration.usePooling) {
return;
}
item.release();
sVisibilityItemPool.release(item);
}
@ThreadSafe(enableChecks = false)
static void release(TestOutput testOutput) {
if (!ComponentsConfiguration.usePooling) {
return;
}
testOutput.release();
sTestOutputPool.release(testOutput);
}
@ThreadSafe(enableChecks = false)
static void release(TestItem testItem) {
if (!ComponentsConfiguration.usePooling) {
return;
}
testItem.release();
sTestItemPool.release(testItem);
}
@ThreadSafe(enableChecks = false)
static void release(DiffNode node) {
if (!ComponentsConfiguration.usePooling) {
return;
}
node.release();
sDiffNodePool.release(node);
}
@ThreadSafe(enableChecks = false)
static void release(Output output) {
if (!ComponentsConfiguration.usePooling) {
return;
}
output.release();
sOutputPool.release(output);
}
@ThreadSafe(enableChecks = false)
public static void release(Diff diff) {
if (!ComponentsConfiguration.usePooling) {
return;
}
diff.release();
sDiffPool.release(diff);
}
@ThreadSafe(enableChecks = false)
static void release(Context context, ComponentLifecycle lifecycle, Object mountContent) {
if (!ComponentsConfiguration.usePooling) {
return;
}
if (context instanceof ComponentContext) {
context = ((ComponentContext) context).getBaseContext();
if (context instanceof ComponentContext) {
throw new IllegalStateException("Double wrapped ComponentContext.");
}
}
RecyclePool pool = null;
synchronized (mountContentLock) {
SparseArray<RecyclePool> poolsArray =
sMountContentPoolsByContext.get(context);
if (poolsArray != null) {
pool = poolsArray.get(lifecycle.getId());
if (pool == null) {
pool = new RecyclePool(
"MountContent - " + lifecycle.getClass().getSimpleName(),
lifecycle.poolSize(),
true);
poolsArray.put(lifecycle.getId(), pool);
}
}
if (pool != null) {
pool.release(mountContent);
}
}
}
static boolean canAddMountContentToPool(Context context, ComponentLifecycle lifecycle) {
if (!ComponentsConfiguration.usePooling) {
return false;
}
if (lifecycle.poolSize() == 0) {
return false;
}
final SparseArray<RecyclePool> poolsArray =
sMountContentPoolsByContext.get(context);
if (poolsArray == null) {
return true;
}
final RecyclePool pool = poolsArray.get(lifecycle.getId());
return pool == null || !pool.isFull();
}
static SparseArrayCompat<MountItem> acquireScrapMountItemsArray() {
SparseArrayCompat<MountItem> sparseArray =
ComponentsConfiguration.usePooling ? sMountItemScrapArrayPool.acquire() : null;
if (sparseArray == null) {
sparseArray = new SparseArrayCompat<>(SCRAP_ARRAY_INITIAL_SIZE);
}
return sparseArray;
}
@ThreadSafe(enableChecks = false)
static void releaseScrapMountItemsArray(SparseArrayCompat<MountItem> sparseArray) {
if (!ComponentsConfiguration.usePooling) {
return;
}
sMountItemScrapArrayPool.release(sparseArray);
}
static SparseArrayCompat<Touchable> acquireScrapTouchablesArray() {
SparseArrayCompat<Touchable> sparseArray =
ComponentsConfiguration.usePooling ? sTouchableScrapArrayPool.acquire() : null;
if (sparseArray == null) {
sparseArray = new SparseArrayCompat<>(SCRAP_ARRAY_INITIAL_SIZE);
}
return sparseArray;
}
@ThreadSafe(enableChecks = false)
static void releaseScrapTouchablesArray(SparseArrayCompat<Touchable> sparseArray) {
if (!ComponentsConfiguration.usePooling) {
return;
}
sTouchableScrapArrayPool.release(sparseArray);
}
static RectF acquireRectF() {
RectF rect = ComponentsConfiguration.usePooling ? sRectFPool.acquire() : null;
if (rect == null) {
rect = new RectF();
}
return rect;
}
@ThreadSafe(enableChecks = false)
static void releaseRectF(RectF rect) {
if (!ComponentsConfiguration.usePooling) {
return;
}
rect.setEmpty();
sRectFPool.release(rect);
}
static Rect acquireRect() {
Rect rect = ComponentsConfiguration.usePooling ? sRectPool.acquire() : null;
if (rect == null) {
rect = new Rect();
}
return rect;
}
@ThreadSafe(enableChecks = false)
static void release(Rect rect) {
if (!ComponentsConfiguration.usePooling) {
return;
}
rect.setEmpty();
sRectPool.release(rect);
}
static Edges acquireEdges() {
Edges spacing = ComponentsConfiguration.usePooling ? sEdgesPool.acquire() : null;
if (spacing == null) {
spacing = new Edges();
}
return spacing;
}
@ThreadSafe(enableChecks = false)
static void release(Edges edges) {
if (!ComponentsConfiguration.usePooling) {
return;
}
edges.reset();
sEdgesPool.release(edges);
}
/**
* Empty implementation of the {@link Application.ActivityLifecycleCallbacks} interface
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private static class PoolsActivityCallback
implements Application.ActivityLifecycleCallbacks {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
ComponentsPools.onContextCreated(activity);
}
@Override
public void onActivityStarted(Activity activity) {
// Do nothing.
}
@Override
public void onActivityResumed(Activity activity) {
// Do nothing.
}
@Override
public void onActivityPaused(Activity activity) {
// Do nothing.
}
@Override
public void onActivityStopped(Activity activity) {
// Do nothing.
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
// Do nothing.
}
@Override
public void onActivityDestroyed(Activity activity) {
ComponentsPools.onContextDestroyed(activity);
}
}
static void onContextCreated(Context context) {
if (sMountContentPoolsByContext.containsKey(context)) {
throw new IllegalStateException("The MountContentPools has a reference to an activity" +
"that has just been created");
}
}
static void onContextDestroyed(Context context) {
sMountContentPoolsByContext.remove(context);
// Clear any context wrappers holding a reference to this activity.
final Iterator<Map.Entry<Context, SparseArray<RecyclePool>>> it =
sMountContentPoolsByContext.entrySet().iterator();
while (it.hasNext()) {
final Context contextKey = it.next().getKey();
if (isContextWrapper(contextKey, context)) {
it.remove();
}
}
}
/**
* Call from tests to clear external references.
*/
public static void clearAll() {
sMountContentPoolsByContext.clear();
}
/**
* Check whether contextWrapper is a wrapper of baseContext
*/
private static boolean isContextWrapper(Context contextWrapper, Context baseContext) {
Context currentContext = contextWrapper;
while (currentContext instanceof ContextWrapper) {
currentContext = ((ContextWrapper) currentContext).getBaseContext();
if (currentContext == baseContext) {
return true;
}
}
return false;
}
public static DisplayListDrawable acquireDisplayListDrawable(
Drawable content,
DisplayList displayList) {
// When we are wrapping drawable with DisplayListDrawable we need to make sure that
// wrapped DisplayListDrawable has the same view callback as original one had for correct
// view invalidations.
final Drawable.Callback callback = content.getCallback();
DisplayListDrawable displayListDrawable =
ComponentsConfiguration.usePooling ? sDisplayListDrawablePool.acquire() : null;
if (displayListDrawable == null) {
displayListDrawable = new DisplayListDrawable(content, displayList);
} else {
displayListDrawable.setWrappedDrawable(content, displayList);
}
displayListDrawable.setCallback(callback);
return displayListDrawable;
}
@ThreadSafe(enableChecks = false)
public static void release(DisplayListDrawable displayListDrawable) {
if (!ComponentsConfiguration.usePooling) {
return;
}
displayListDrawable.release();
sDisplayListDrawablePool.release(displayListDrawable);
}
public static BorderColorDrawable acquireBorderColorDrawable() {
if (sBorderColorDrawablePool == null) {
sBorderColorDrawablePool = new RecyclePool<>("BorderColorDrawable", 10, true);
}
BorderColorDrawable drawable =
ComponentsConfiguration.usePooling ? sBorderColorDrawablePool.acquire() : null;
if (drawable == null) {
drawable = new BorderColorDrawable();
}
return drawable;
}
@ThreadSafe(enableChecks = false)
public static void release(BorderColorDrawable borderColorDrawable) {
if (!ComponentsConfiguration.usePooling) {
return;
}
sBorderColorDrawablePool.release(borderColorDrawable);
}
public static <E> ArraySet<E> acquireArraySet() {
ArraySet<E> set = ComponentsConfiguration.usePooling ? sArraySetPool.acquire() : null;
if (set == null) {
set = new ArraySet<>();
}
return set;
}
@ThreadSafe(enableChecks = false)
public static void release(ArraySet set) {
if (!ComponentsConfiguration.usePooling) {
return;
}
set.clear();
sArraySetPool.release(set);
}
public static <E> ArrayDeque<E> acquireArrayDeque() {
ArrayDeque<E> deque = ComponentsConfiguration.usePooling ? sArrayDequePool.acquire() : null;
if (deque == null) {
deque = new ArrayDeque<>();
}
return deque;
}
@ThreadSafe(enableChecks = false)
public static void release(ArrayDeque deque) {
if (!ComponentsConfiguration.usePooling) {
return;
}
deque.clear();
sArrayDequePool.release(deque);
}
@ThreadSafe(enableChecks = false)
public static void release(LogEvent event) {
if (!ComponentsConfiguration.usePooling) {
return;
}
event.reset();
sLogEventPool.release(event);
}
}
| Don't disable pooling MountContent in pooling experiment
Summary: The aim of the experiment is to test the effect of recycling internal objects, not mount content.
Reviewed By: pasqualeanatriello
Differential Revision: D5019680
fbshipit-source-id: 576f19123d07dd7a9ec5d0b83bd87d367819b696
| litho-core/src/main/java/com/facebook/litho/ComponentsPools.java | Don't disable pooling MountContent in pooling experiment | <ide><path>itho-core/src/main/java/com/facebook/litho/ComponentsPools.java
<ide> }
<ide>
<ide> static Object acquireMountContent(Context context, int componentId) {
<del> if (!ComponentsConfiguration.usePooling) {
<del> return null;
<del> }
<del>
<ide> if (context instanceof ComponentContext) {
<ide> context = ((ComponentContext) context).getBaseContext();
<ide>
<ide>
<ide> @ThreadSafe(enableChecks = false)
<ide> static void release(Context context, ComponentLifecycle lifecycle, Object mountContent) {
<del> if (!ComponentsConfiguration.usePooling) {
<del> return;
<del> }
<del>
<ide> if (context instanceof ComponentContext) {
<ide> context = ((ComponentContext) context).getBaseContext();
<ide>
<ide> }
<ide>
<ide> static boolean canAddMountContentToPool(Context context, ComponentLifecycle lifecycle) {
<del> if (!ComponentsConfiguration.usePooling) {
<del> return false;
<del> }
<ide> if (lifecycle.poolSize() == 0) {
<ide> return false;
<ide> } |
|
JavaScript | mit | 169c6616e17aa43ecfbd2beaccfc8646e3e61715 | 0 | jamiechong/ember-cli-unslider,jamiechong/ember-cli-unslider,jamiechong/ember-cli-unslider | /* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'dummy',
environment: environment,
baseURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
// For github pages
ENV.baseURL = '/ember-cli-nouislider';
//ENV.locationType = 'hash';
}
return ENV;
};
| tests/dummy/config/environment.js | /* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'dummy',
environment: environment,
baseURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
}
return ENV;
};
| dummy production build needs a diff baseUrl for gh pages
| tests/dummy/config/environment.js | dummy production build needs a diff baseUrl for gh pages | <ide><path>ests/dummy/config/environment.js
<ide> }
<ide>
<ide> if (environment === 'production') {
<del>
<add> // For github pages
<add> ENV.baseURL = '/ember-cli-nouislider';
<add> //ENV.locationType = 'hash';
<ide> }
<ide>
<ide> return ENV; |
|
Java | epl-1.0 | f87bde7088c470a7c1b83d742dc87053594eb3bf | 0 | ESSICS/cs-studio,ControlSystemStudio/cs-studio,ControlSystemStudio/cs-studio,ControlSystemStudio/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,ESSICS/cs-studio,ControlSystemStudio/cs-studio,css-iter/cs-studio,ControlSystemStudio/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,ControlSystemStudio/cs-studio,css-iter/cs-studio,css-iter/cs-studio | package org.csstudio.sds.components.ui.internal.figureparts;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.draw2d.geometry.Rectangle;
public class PolarPoint {
/**
* The radial coordinate
*/
public int r;
/**
* The angular coordinate in radians
*/
public double theta;
/**
* @param r The radial coordinate
* @param theta The angular coordinate in radians
*/
public PolarPoint(int r, double theta) {
this.r = r;
this.theta = theta;
}
@Override
public boolean equals(Object obj) {
if(obj instanceof PolarPoint) {
PolarPoint p = (PolarPoint)obj;
return p.r == r && p.theta == theta;
}
return false;
}
/**
* Transform the polar point to the {@link Point} in rectangular coordinates.
* The rectangular coordinates has the same origin as the polar coordinates.
* @return the point in rectangular coordinates
*/
public Point toPoint() {
int x = (int) (r * Math.cos(theta));
int y = (int) (-r * Math.sin(theta));
return new Point(x, y);
}
/**
* Transform the polar point to the {@link Point} in the absolute coordinate system.
* It is assumed that the origin of the polar coordinate system is the central point of
* the rectangle.
* @param rect the paint area of the figure
* @return the point in absolute coordinate system.
*/
public Point toAbsolutePoint(Rectangle rect) {
Point p = this.toPoint();
return p.translate(rect.width/2, rect.height/2).translate(
rect.x, rect.y);
}
/**Transform the polar point to the {@link Point} in the relative coordinate system,
* whose origin is (rect.x, rect.y).
* It is assumed that the origin of the polar coordinate system is the central point of
* the rectangle.
* @param rect the paint area of the figure
* @return the point in relative coordinate system.
*/
public Point toRelativePoint(Rectangle rect) {
Point p = this.toPoint();
return p.translate(rect.width/2, rect.height/2);
}
}
| applications/plugins/org.csstudio.sds.components.ui/src/org/csstudio/sds/components/ui/internal/figureparts/PolarPoint.java | package org.csstudio.sds.components.ui.internal.figureparts;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.draw2d.geometry.Rectangle;
public class PolarPoint {
/**
* The radial coordinate
*/
public int r;
/**
* The angular coordinate in radians
*/
public double theta;
/**
* @param r
* @param theta
*/
public PolarPoint(int r, double theta) {
this.r = r;
this.theta = theta;
}
@Override
public boolean equals(Object obj) {
if(obj instanceof PolarPoint) {
PolarPoint p = (PolarPoint)obj;
return p.r == r && p.theta == theta;
}
return false;
}
/**
* Transform the polar point to the {@link Point} in rectangular coordinates.
* The rectangular coordinates has the same origin as the polar coordinates.
* @return the point in rectangular coordinates
*/
public Point toPoint() {
int x = (int) (r * Math.cos(theta));
int y = (int) (-r * Math.sin(theta));
return new Point(x, y);
}
/**
* Transform the polar point to the {@link Point} in the absolute coordinate system.
* It is assumed that the origin of the polar coordinate system is the central point of
* the rectangle.
* @param rect the paint area of the figure
* @return the point in absolute coordinate system.
*/
public Point toAbsolutePoint(Rectangle rect) {
Point p = this.toPoint();
return p.translate(rect.width/2, rect.height/2).translate(
rect.x, rect.y);
}
/**Transform the polar point to the {@link Point} in the relative coordinate system,
* whose origin is (rect.x, rect.y).
* It is assumed that the origin of the polar coordinate system is the central point of
* the rectangle.
* @param rect the paint area of the figure
* @return the point in relative coordinate system.
*/
public Point toRelativePoint(Rectangle rect) {
Point p = this.toPoint();
return p.translate(rect.width/2, rect.height/2);
}
}
| add comments
| applications/plugins/org.csstudio.sds.components.ui/src/org/csstudio/sds/components/ui/internal/figureparts/PolarPoint.java | add comments | <ide><path>pplications/plugins/org.csstudio.sds.components.ui/src/org/csstudio/sds/components/ui/internal/figureparts/PolarPoint.java
<ide> public double theta;
<ide>
<ide> /**
<del> * @param r
<del> * @param theta
<add> * @param r The radial coordinate
<add> * @param theta The angular coordinate in radians
<ide> */
<ide> public PolarPoint(int r, double theta) {
<ide> this.r = r; |
|
Java | unlicense | 4c0766337c9e1a7bf5152a59ec8cd96e4be7d4aa | 0 | kwaled/ReROUTE,reecemartin/ReROUTE,kwaled/ReROUTE,aaangelaaa/ReROUTE,aaangelaaa/ReROUTE,reecemartin/ReROUTE | import java.awt.Button;
import javafx.application.Application;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class GUIObject extends Application implements EventHandler {
private double pos;
/**
* Creates a GUIObject object at position 0.*/
public GUIObject() {
pos = 0;
}
/**
* Create a GUIObject object at position pos
*
* @param pos the position to create the object at
*/
public GUIObject(double pos) {
setPos(pos);
}
/**
* Returns the position of this GUIObject.
*
* @return the position this object.
* */
public double getPos() {
return pos;
}
/**
* Sets the position of this GUIObject.
* Throws IllegalArgumentException if pos not between -30200 and 30200
*
* @param pos the position to set this object to. */
public void setPos(double pos) {
if (-30200 <= pos && pos <= 30200){
this.pos = pos;
}
else{
throw new IllegalArgumentException("Position must be between -30200 and 30200");
}
}
/**
* Returns the distance from this object to other.
*
* @param other the other GUIObject.
* @return the distance from this object to other.
*/
public double distanceTo(GUIObject other) {
return this.pos - other.pos;
}
/**
* Returns the horizontal coordinate of this object.
*
* @return the horizontal coordiante of this object.*/
public double getX(){return 0;}
/**
* Returns the vertical coordinate of this object.
*
* @return the vertical coordiante of this object.*/
public double getY(){return 0;}
@Override
public void start(Stage stage) throws Exception {
stage.setTitle("ReROUTE Simulator");
Button buttonLT = new Button("List Trains");
Button buttonLS = new Button("List Stations");
VBox vBox = new VBox(10);
vBox.setPadding(new Insets(0, 20, 10, 20));
//Returns error for some reason
vBox.getChildren().addAll(buttonLT, buttonLS);
Text vBoxTitle = new Text("Lists");
vBoxTitle.setFont(Font.font("Lato", FontWeight.BOLD, 14));
vBox.getChildren().add(vBoxTitle);
HBox header = new HBox();
header.setPadding(new Insets(15, 12, 15, 12));
header.setSpacing(10);
header.setStyle("-fx-background-color: ##19b585;");
Text headerTitle = new Text("ReROUTE Simulator");
headerTitle.setFont(Font.font("Lato", FontWeight.BOLD, 16));
header.getChildren().add(headerTitle);
Scene scene = new Scene(vBox, 900, 500);
stage.setScene(scene);
}
@Override
public void handle(Event arg0) {
// TODO Auto-generated method stub
}
}
| src/GUIObject.java | import java.awt.Button;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class GUIObject extends Application{
private double pos;
/**
* Creates a GUIObject object at position 0.*/
public GUIObject() {
pos = 0;
}
/**
* Create a GUIObject object at position pos
*
* @param pos the position to create the object at
*/
public GUIObject(double pos) {
setPos(pos);
}
/**
* Returns the position of this GUIObject.
*
* @return the position this object.
* */
public double getPos() {
return pos;
}
/**
* Sets the position of this GUIObject.
* Throws IllegalArgumentException if pos not between -30200 and 30200
*
* @param pos the position to set this object to. */
public void setPos(double pos) {
if (-30200 <= pos && pos <= 30200){
this.pos = pos;
}
else{
throw new IllegalArgumentException("Position must be between -30200 and 30200");
}
}
/**
* Returns the distance from this object to other.
*
* @param other the other GUIObject.
* @return the distance from this object to other.
*/
public double distanceTo(GUIObject other) {
return this.pos - other.pos;
}
/**
* Returns the horizontal coordinate of this object.
*
* @return the horizontal coordiante of this object.*/
public double getX(){return 0;}
/**
* Returns the vertical coordinate of this object.
*
* @return the vertical coordiante of this object.*/
public double getY(){return 0;}
@Override
public void start(Stage stage) throws Exception {
stage.setTitle("ReROUTE Simulator");
Button buttonLT = new Button("List Trains");
Button buttonLS = new Button("List Stations");
VBox vBox = new VBox(10);
vBox.setPadding(new Insets(0, 20, 10, 20));
vBox.getChildren().addAll(buttonLT, buttonLS);
Scene scene = new Scene(vBox, 900, 500);
stage.setScene(scene);
}
}
| Added EventHandler (blank) and header. | src/GUIObject.java | Added EventHandler (blank) and header. | <ide><path>rc/GUIObject.java
<ide> import java.awt.Button;
<ide>
<ide> import javafx.application.Application;
<add>import javafx.event.Event;
<add>import javafx.event.EventHandler;
<ide> import javafx.geometry.Insets;
<ide> import javafx.scene.Scene;
<add>import javafx.scene.layout.HBox;
<ide> import javafx.scene.layout.VBox;
<add>import javafx.scene.text.Font;
<add>import javafx.scene.text.FontWeight;
<add>import javafx.scene.text.Text;
<ide> import javafx.stage.Stage;
<ide>
<del>public class GUIObject extends Application{
<add>public class GUIObject extends Application implements EventHandler {
<ide> private double pos;
<ide>
<ide> /**
<ide>
<ide> VBox vBox = new VBox(10);
<ide> vBox.setPadding(new Insets(0, 20, 10, 20));
<add> //Returns error for some reason
<ide> vBox.getChildren().addAll(buttonLT, buttonLS);
<ide>
<del> Scene scene = new Scene(vBox, 900, 500);
<add> Text vBoxTitle = new Text("Lists");
<add> vBoxTitle.setFont(Font.font("Lato", FontWeight.BOLD, 14));
<add> vBox.getChildren().add(vBoxTitle);
<add>
<add> HBox header = new HBox();
<add> header.setPadding(new Insets(15, 12, 15, 12));
<add> header.setSpacing(10);
<add> header.setStyle("-fx-background-color: ##19b585;");
<add> Text headerTitle = new Text("ReROUTE Simulator");
<add> headerTitle.setFont(Font.font("Lato", FontWeight.BOLD, 16));
<add>
<add> header.getChildren().add(headerTitle);
<add> Scene scene = new Scene(vBox, 900, 500);
<ide>
<ide> stage.setScene(scene);
<ide> }
<add>
<add> @Override
<add> public void handle(Event arg0) {
<add> // TODO Auto-generated method stub
<add>
<add> }
<ide> } |
|
Java | mit | 04680c9d97ee72827ad0cd4adeb883e2b6335172 | 0 | dbcls/ConvRDF | /*
* This code is derived from arq.examples.riot.ExRIOT_6, which is
* distributed under the Apache License, Version 2.0.
* http://www.apache.org/licenses/LICENSE-2.0
*
* Database Center for Life Science (DBCLS) has developed this code
* and releases it under MIT style license.
*/
package jp.ac.rois.dbcls;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.jena.riot.RDFParser;
import org.apache.jena.riot.RDFParserBuilder;
import org.apache.jena.riot.RiotException;
import org.apache.jena.riot.Lang;
import org.apache.jena.riot.RDFDataMgr;
import org.apache.jena.riot.RDFFormat;
import org.apache.jena.riot.RiotNotFoundException;
import org.apache.jena.riot.RiotParseException;
import org.apache.jena.riot.lang.PipedRDFIterator;
import org.apache.jena.riot.lang.PipedRDFStream;
import org.apache.jena.riot.lang.PipedTriplesStream;
import org.apache.jena.riot.system.ErrorHandlerFactory;
import org.apache.jena.riot.RDFLanguages;
import org.apache.jena.graph.Triple;
import org.apache.jena.graph.Graph;
import org.apache.jena.graph.Factory;
import org.apache.jena.atlas.logging.LogCtl;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
import org.apache.commons.compress.compressors.xz.XZCompressorInputStream;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.input.CloseShieldInputStream;
public class ConvRDF {
static { LogCtl.setCmdLogging(); }
static boolean recursive;
static boolean checking;
static final Set<String>types = new HashSet<String>(
Arrays.asList("String","StringReader","XZCompressorInputStream","CloseShieldInputStream"));
private static void issuer(String file) {
System.err.println("File:" + file);
issuer(file, null);
}
private static void issuer(Object reader, Lang lang) {
if(reader.getClass() == StringReader.class && lang == null) return;
final String sn = reader.getClass().getSimpleName();
System.err.println(sn);
if(!types.contains(sn)) {
System.err.println("No parser for this content.");
return;
}
final int interval = 10000;
final int buffersize = 100000;
final int pollTimeout = 300; // Poll timeout in milliseconds
final int maxPolls = 1000; // Max poll attempts
PipedRDFIterator<Triple> iter = new PipedRDFIterator<Triple>(buffersize, false, pollTimeout, maxPolls);
final PipedRDFStream<Triple> inputStream = new PipedTriplesStream(iter);
ExecutorService executor = Executors.newSingleThreadExecutor();
Runnable parser = new Runnable() {
@Override
public void run() {
RDFParser parser_object = null;
switch(sn) {
case "String":
parser_object = RDFParserBuilder
.create()
.errorHandler(ErrorHandlerFactory.errorHandlerDetailed())
.source((String) reader)
.checking(checking)
.build();
break;
case "StringReader":
parser_object = RDFParserBuilder
.create()
.errorHandler(ErrorHandlerFactory.errorHandlerDetailed())
.source((StringReader) reader)
.checking(checking)
.lang(lang)
.build();
break;
case "XZCompressorInputStream":
parser_object = RDFParserBuilder
.create()
.errorHandler(ErrorHandlerFactory.errorHandlerDetailed())
.source((XZCompressorInputStream) reader)
.checking(checking)
.lang(lang)
.build();
break;
case "CloseShieldInputStream":
parser_object = RDFParserBuilder
.create()
.errorHandler(ErrorHandlerFactory.errorHandlerDetailed())
.source((CloseShieldInputStream) reader)
.checking(checking)
.lang(lang)
.build();
break;
}
try {
parser_object.parse(inputStream);
} catch (RiotParseException e){
String location = "";
if(e.getLine() >= 0 && e.getCol() >= 0)
location = " at the line: " + e.getLine() + " and the column: " + e.getCol();
System.err.println("Parse error"
+ location
+ " in \""
+ reader
+ "\", and cannot parse this file anymore. Reason: "
+ e.getMessage());
inputStream.finish();
} catch (RiotNotFoundException e){
System.err.println("Format error for the file \"" + reader + "\": " + e.getMessage());
inputStream.finish();
}
}
};
executor.submit(parser);
int i = 0;
Graph g = Factory.createDefaultGraph();
try{
while (iter.hasNext()) {
Triple next = iter.next();
g.add(next);
i++;
if(i % interval == 0){
RDFDataMgr.write(System.out, g, RDFFormat.NTRIPLES_UTF8);
g = Factory.createDefaultGraph();
}
}
if(i % interval > 0){
RDFDataMgr.write(System.out, g, RDFFormat.NTRIPLES_UTF8);
}
}
catch (RiotException e){
System.err.println("Riot Exception: " + e.getMessage());
}
executor.shutdown();
}
private static void dispatch(String filename){
InputStream is = null;
try {
FileInputStream fis = new FileInputStream(filename);
String fext = FilenameUtils.getExtension(filename);
switch (fext) {
case "gz":
is = new GzipCompressorInputStream(fis);
break;
case "bz2":
is = new BZip2CompressorInputStream(fis);
break;
case "xz":
is = new XZCompressorInputStream(fis);
break;
default:
fis.close();
issuer(filename);
return;
}
String fwoext = FilenameUtils.removeExtension(filename);
if(FilenameUtils.getExtension(fwoext).equals("tar")) {
procTar(is);
} else if (fext.equals("xz")) {
Lang lang = RDFLanguages.filenameToLang(fwoext);
issuer(is, lang);
} else {
issuer(filename);
}
} catch (FileNotFoundException e) {
System.err.println("File not found:" + e.getMessage());
} catch (IOException e) {
System.err.println("IO Exception:" + e.getMessage());
}
}
private static void procTar(InputStream ins) {
try {
TarArchiveInputStream tarInput = new TarArchiveInputStream(ins);
TarArchiveEntry currentEntry;
while ((currentEntry = tarInput.getNextTarEntry()) != null) {
String currentFile = currentEntry.getName();
Lang lang = RDFLanguages.filenameToLang(currentFile);
if(lang != null) {
InputStream tarIns = new CloseShieldInputStream(tarInput);
System.err.println("Tar:" + currentFile);
issuer(tarIns, lang);
}
}
tarInput.close();
} catch (IOException e) {
System.err.println("Something wrong in processing a tar file:" + e.getMessage());
}
}
private static void processRecursively(File file) throws FileNotFoundException, IOException {
File[] fileList = file.listFiles();
for (File f: fileList){
if (f.isFile()) {
if(f.getName().endsWith(".taz")) {
procTar(new GzipCompressorInputStream(new FileInputStream(f.getPath())));
} else {
dispatch(f.getPath());
}
} else if (f.isDirectory()) {
if(f.getName().startsWith("."))
continue;
if (recursive)
processRecursively(f);
}
}
}
public static void main(String[] args) {
int idx = 0;
recursive = false;
checking = false;
while (idx < args.length && args[idx].startsWith("-")) {
if(args[idx].equals("-r")) {
recursive = true;
} else if(args[idx].equals("-c")) {
checking = true;
}
idx++;
}
if(idx == args.length){
System.out.println("Please specify the filename to be converted.");
return;
}
File file = new File(args[idx]);
if(!file.exists() || !file.canRead()){
System.out.println("Can't read " + file);
return;
}
try {
if(file.isFile()){
if( file.getName().endsWith(".taz") ) {
procTar(new GzipCompressorInputStream(new FileInputStream(args[idx])));
} else {
dispatch(args[idx]);
}
} else if(file.isDirectory()){
processRecursively(file);
}
} catch (FileNotFoundException e) {
System.err.println("File not found:" + e.getMessage());
} catch (IOException e) {
System.err.println("IO Exception:" + e.getMessage());
}
}
} | src/jp/ac/rois/dbcls/ConvRDF.java | /*
* This code is derived from arq.examples.riot.ExRIOT_6, which is
* distributed under the Apache License, Version 2.0.
* http://www.apache.org/licenses/LICENSE-2.0
*
* Database Center for Life Science (DBCLS) has developed this code
* and releases it under MIT style license.
*/
package jp.ac.rois.dbcls;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.jena.riot.RDFParser;
import org.apache.jena.riot.RDFParserBuilder;
import org.apache.jena.riot.RiotException;
import org.apache.jena.riot.Lang;
import org.apache.jena.riot.RDFDataMgr;
import org.apache.jena.riot.RDFFormat;
import org.apache.jena.riot.RiotNotFoundException;
import org.apache.jena.riot.RiotParseException;
import org.apache.jena.riot.lang.PipedRDFIterator;
import org.apache.jena.riot.lang.PipedRDFStream;
import org.apache.jena.riot.lang.PipedTriplesStream;
import org.apache.jena.riot.system.ErrorHandlerFactory;
import org.apache.jena.graph.Triple;
import org.apache.jena.graph.Graph;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
import org.apache.commons.compress.compressors.xz.XZCompressorInputStream;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.input.CloseShieldInputStream;
import org.apache.jena.atlas.logging.LogCtl;
import org.apache.jena.graph.Factory;
import org.apache.jena.riot.RDFLanguages;
public class ConvRDF {
static { LogCtl.setCmdLogging(); }
static boolean recursive;
static boolean checking;
static final Set<String>types = new HashSet<String>(
Arrays.asList("String","StringReader","XZCompressorInputStream","CloseShieldInputStream"));
private static void issuer(String file) {
System.err.println("File:" + file);
issuer(file, null);
}
private static void issuer(Object reader, Lang lang) {
if(reader.getClass() == StringReader.class && lang == null) return;
final String sn = reader.getClass().getSimpleName();
System.err.println(sn);
if(!types.contains(sn)) {
System.err.println("No parser for this content.");
return;
}
final int interval = 10000;
final int buffersize = 100000;
final int pollTimeout = 300; // Poll timeout in milliseconds
final int maxPolls = 1000; // Max poll attempts
PipedRDFIterator<Triple> iter = new PipedRDFIterator<Triple>(buffersize, false, pollTimeout, maxPolls);
final PipedRDFStream<Triple> inputStream = new PipedTriplesStream(iter);
ExecutorService executor = Executors.newSingleThreadExecutor();
Runnable parser = new Runnable() {
@Override
public void run() {
RDFParser parser_object = null;
switch(sn) {
case "String":
parser_object = RDFParserBuilder
.create()
.errorHandler(ErrorHandlerFactory.errorHandlerDetailed())
.source((String) reader)
.checking(checking)
.build();
break;
case "StringReader":
parser_object = RDFParserBuilder
.create()
.errorHandler(ErrorHandlerFactory.errorHandlerDetailed())
.source((StringReader) reader)
.checking(checking)
.lang(lang)
.build();
break;
case "XZCompressorInputStream":
parser_object = RDFParserBuilder
.create()
.errorHandler(ErrorHandlerFactory.errorHandlerDetailed())
.source((XZCompressorInputStream) reader)
.checking(checking)
.lang(lang)
.build();
break;
case "CloseShieldInputStream":
parser_object = RDFParserBuilder
.create()
.errorHandler(ErrorHandlerFactory.errorHandlerDetailed())
.source((CloseShieldInputStream) reader)
.checking(checking)
.lang(lang)
.build();
break;
}
try {
parser_object.parse(inputStream);
} catch (RiotParseException e){
String location = "";
if(e.getLine() >= 0 && e.getCol() >= 0)
location = " at the line: " + e.getLine() + " and the column: " + e.getCol();
System.err.println("Parse error"
+ location
+ " in \""
+ reader
+ "\", and cannot parse this file anymore. Reason: "
+ e.getMessage());
inputStream.finish();
} catch (RiotNotFoundException e){
System.err.println("Format error for the file \"" + reader + "\": " + e.getMessage());
inputStream.finish();
}
}
};
executor.submit(parser);
int i = 0;
Graph g = Factory.createDefaultGraph();
try{
while (iter.hasNext()) {
Triple next = iter.next();
g.add(next);
i++;
if(i % interval == 0){
RDFDataMgr.write(System.out, g, RDFFormat.NTRIPLES_UTF8);
g = Factory.createDefaultGraph();
}
}
if(i % interval > 0){
RDFDataMgr.write(System.out, g, RDFFormat.NTRIPLES_UTF8);
}
}
catch (RiotException e){
System.err.println("Riot Exception: " + e.getMessage());
}
executor.shutdown();
}
private static void dispatch(String filename){
InputStream is = null;
try {
FileInputStream fis = new FileInputStream(filename);
String fext = FilenameUtils.getExtension(filename);
switch (fext) {
case "gz":
is = new GzipCompressorInputStream(fis);
break;
case "bz2":
is = new BZip2CompressorInputStream(fis);
break;
case "xz":
is = new XZCompressorInputStream(fis);
break;
default:
fis.close();
issuer(filename);
return;
}
String fwoext = FilenameUtils.removeExtension(filename);
if(FilenameUtils.getExtension(fwoext).equals("tar")) {
procTar(is);
} else if (fext.equals("xz")) {
Lang lang = RDFLanguages.filenameToLang(fwoext);
issuer(is, lang);
} else {
issuer(filename);
}
} catch (FileNotFoundException e) {
System.err.println("File not found:" + e.getMessage());
} catch (IOException e) {
System.err.println("IO Exception:" + e.getMessage());
}
}
private static void procTar(InputStream ins) {
try {
TarArchiveInputStream tarInput = new TarArchiveInputStream(ins);
TarArchiveEntry currentEntry;
while ((currentEntry = tarInput.getNextTarEntry()) != null) {
String currentFile = currentEntry.getName();
Lang lang = RDFLanguages.filenameToLang(currentFile);
if(lang != null) {
InputStream tarIns = new CloseShieldInputStream(tarInput);
System.err.println("Tar:" + currentFile);
issuer(tarIns, lang);
}
}
tarInput.close();
} catch (IOException e) {
System.err.println("Something wrong in processing a tar file:" + e.getMessage());
}
}
private static void processRecursively(File file) throws FileNotFoundException, IOException {
File[] fileList = file.listFiles();
for (File f: fileList){
if (f.isFile()) {
if(f.getName().endsWith(".taz")) {
procTar(new GzipCompressorInputStream(new FileInputStream(f.getPath())));
} else {
dispatch(f.getPath());
}
} else if (f.isDirectory()) {
if(f.getName().startsWith("."))
continue;
if (recursive)
processRecursively(f);
}
}
}
public static void main(String[] args) {
int idx = 0;
recursive = false;
checking = false;
while (idx < args.length && args[idx].startsWith("-")) {
if(args[idx].equals("-r")) {
recursive = true;
} else if(args[idx].equals("-c")) {
checking = true;
}
idx++;
}
if(idx == args.length){
System.out.println("Please specify the filename to be converted.");
return;
}
File file = new File(args[idx]);
if(!file.exists() || !file.canRead()){
System.out.println("Can't read " + file);
return;
}
try {
if(file.isFile()){
if( file.getName().endsWith(".taz") ) {
procTar(new GzipCompressorInputStream(new FileInputStream(args[idx])));
} else {
dispatch(args[idx]);
}
} else if(file.isDirectory()){
processRecursively(file);
}
} catch (FileNotFoundException e) {
System.err.println("File not found:" + e.getMessage());
} catch (IOException e) {
System.err.println("IO Exception:" + e.getMessage());
}
}
} | Reorder imported libraries listed at the top for improving readability. | src/jp/ac/rois/dbcls/ConvRDF.java | Reorder imported libraries listed at the top for improving readability. | <ide><path>rc/jp/ac/rois/dbcls/ConvRDF.java
<ide> import org.apache.jena.riot.lang.PipedRDFStream;
<ide> import org.apache.jena.riot.lang.PipedTriplesStream;
<ide> import org.apache.jena.riot.system.ErrorHandlerFactory;
<add>import org.apache.jena.riot.RDFLanguages;
<ide> import org.apache.jena.graph.Triple;
<ide> import org.apache.jena.graph.Graph;
<add>import org.apache.jena.graph.Factory;
<add>import org.apache.jena.atlas.logging.LogCtl;
<ide> import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
<ide> import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
<ide> import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream;
<ide> import org.apache.commons.compress.compressors.xz.XZCompressorInputStream;
<ide> import org.apache.commons.io.FilenameUtils;
<ide> import org.apache.commons.io.input.CloseShieldInputStream;
<del>import org.apache.jena.atlas.logging.LogCtl;
<del>import org.apache.jena.graph.Factory;
<del>import org.apache.jena.riot.RDFLanguages;
<ide>
<ide> public class ConvRDF {
<ide> |
|
Java | agpl-3.0 | 399376959a13541878c64eac076a36eceab3c145 | 0 | genepi/imputationserver | package genepi.imputationserver.steps;
import genepi.hadoop.HdfsUtil;
import genepi.hadoop.PreferenceStore;
import genepi.hadoop.common.WorkflowContext;
import genepi.hadoop.common.WorkflowStep;
import genepi.hadoop.importer.IImporter;
import genepi.hadoop.importer.ImporterFactory;
import genepi.imputationserver.steps.converter.VCFBuilder;
import genepi.imputationserver.steps.vcf.VcfFile;
import genepi.imputationserver.steps.vcf.VcfFileUtil;
import genepi.imputationserver.util.GeneticMap;
import genepi.imputationserver.util.MapList;
import genepi.imputationserver.util.RefPanel;
import genepi.imputationserver.util.RefPanelList;
import genepi.io.FileUtil;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.List;
import java.util.Vector;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
import com.esotericsoftware.yamlbeans.YamlException;
public class InputValidation extends WorkflowStep {
@Override
public boolean run(WorkflowContext context) {
URLClassLoader cl = (URLClassLoader) InputValidation.class
.getClassLoader();
try {
URL url = cl.findResource("META-INF/MANIFEST.MF");
Manifest manifest = new Manifest(url.openStream());
Attributes attr = manifest.getMainAttributes();
String buildVesion = attr.getValue("Version");
String buildTime = attr.getValue("Build-Time");
String builtBy = attr.getValue("Built-By");
context.println("Version: " + buildVesion + " (Built by " + builtBy
+ " on " + buildTime + ")");
} catch (IOException E) {
// handle
}
if (!importVcfFiles(context)) {
return false;
}
return checkVcfFiles(context);
}
private boolean checkVcfFiles(WorkflowContext context) {
String folder = getFolder(InputValidation.class);
//String tester;
// inputs
String inputFiles = context.get("files");
String reference = context.get("refpanel");
String population = context.get("population");
String phasing = context.get("phasing");
int sampleLimit = Integer.valueOf(context.get("sample-limit"));
int chunkSize = Integer.parseInt(context.get("chunksize"));
VcfFileUtil.setBinaries(FileUtil.path(folder, "bin"));
String files = FileUtil.path(context.getLocalTemp(), "input");
PreferenceStore store = new PreferenceStore(new File(
FileUtil.path(folder, "job.config")));
// exports files from hdfs
try {
//tester = loadChrXTesterFromFile(FileUtil.path(folder,
// "chrX-tester.txt"));
HdfsUtil.getFolder(inputFiles, files);
} catch (Exception e) {
context.error("Downloading files: " + e.getMessage());
return false;
}
List<VcfFile> validVcfFiles = new Vector<VcfFile>();
context.beginTask("Analyze files ");
List<String> chromosomes = new Vector<String>();
int chunks = 0;
int noSnps = 0;
int noSamples = 0;
boolean phased = true;
try {
String[] genome = FileUtil.getFiles(files, "*.txt$|*.zip");
if (genome.length == 1) {
context.updateTask("Check for valid 23andMe data",
WorkflowContext.RUNNING);
VCFBuilder builder = new VCFBuilder(genome[0]);
builder.setReference(store.getString("ref.fasta"));
builder.setOutDirectory(files);
builder.setExcludeList("MT,X,Y");
builder.build();
HdfsUtil.delete(inputFiles);
for (String vcf : FileUtil.getFiles(files, "*.vcf.gz$|*.vcf$")) {
HdfsUtil.put(vcf, inputFiles);
}
context.incCounter("23andme-input", 1);
} else if (genome.length > 1) {
context.endTask(
"Please upload your 23andMe data as a single txt or zip file",
WorkflowContext.ERROR);
return false;
}
} catch (Exception e1) {
// TODO Auto-generated catch block
context.endTask("Converter task failed! \n" + e1.getMessage(),
WorkflowContext.ERROR);
return false;
}
String[] vcfFiles = FileUtil.getFiles(files, "*.vcf.gz$|*.vcf$");
if (vcfFiles.length == 0) {
context.endTask(
"The provided files are not VCF files (see <a href=\"/start.html#!pages/help\">Help</a>).",
WorkflowContext.ERROR);
return false;
}
String infos = null;
for (String filename : vcfFiles) {
if (infos == null) {
// first files, no infos available
context.updateTask(
"Analyze file " + FileUtil.getFilename(filename)
+ "...", WorkflowContext.RUNNING);
} else {
context.updateTask(
"Analyze file " + FileUtil.getFilename(filename)
+ "...\n\n" + infos, WorkflowContext.RUNNING);
}
try {
VcfFile vcfFile = VcfFileUtil.load(filename, chunkSize, true);
String mail = null;
if(store.getString("minimac.sendmail") != null && store.getString("minimac.sendmail").equals("yes")){
mail = context.getData("cloudgene.user.mail").toString();
}
if (VcfFileUtil.isValidChromosome(vcfFile.getChromosome())) {
if (VcfFileUtil.isChrX(vcfFile.getChromosome())) {
/*if (mail != null && !tester.contains(mail.toLowerCase())) {
context.endTask(
"Chromosome X imputation is currently under preperation. Please contact us to become a beta tester.",
WorkflowContext.ERROR);
return false;
}*/
if(!phasing.equals("shapeit") && !vcfFile.isPhased()){
context.endTask(
"Please select shapeit for phasing chromosome X. Eagle2 is under prepartion.",
WorkflowContext.ERROR);
return false;
}
}
validVcfFiles.add(vcfFile);
chromosomes.add(vcfFile.getChromosome());
String chromosomeString = "";
for (String chr : chromosomes) {
chromosomeString += " " + chr;
}
// check if all files have same amount of samples
if (noSamples != 0 && noSamples != vcfFile.getNoSamples()) {
context.endTask(
"Please double check, if all uploaded VCF files include the same amount of samples ("
+ vcfFile.getNoSamples()
+ " vs "
+ noSamples + ")",
WorkflowContext.ERROR);
return false;
}
noSamples = vcfFile.getNoSamples();
noSnps += vcfFile.getNoSnps();
chunks += vcfFile.getChunks().size();
phased = phased && vcfFile.isPhased();
// check reference panel
if (vcfFile.isPhasedAutodetect() && !vcfFile.isPhased()) {
context.endTask(
"File should be phased, but also includes unphased and/or missing genotypes! Please double-check!",
WorkflowContext.ERROR);
return false;
}
RefPanelList panels = null;
try {
panels = RefPanelList.loadFromFile(FileUtil.path(
folder, "panels.txt"));
} catch (Exception e) {
context.endTask("panels.txt not found.",
WorkflowContext.ERROR);
return false;
}
RefPanel panel = panels.getById(reference);
if (panel == null) {
StringBuilder report = new StringBuilder();
report.append("Reference '" + reference
+ "' not found.\n");
report.append("Available reference IDs:");
for (RefPanel p : panels.getPanels()) {
report.append("\n - " + p.getId());
}
context.error(report.toString());
return false;
}
if (!panel.existsReference()) {
context.endTask("Reference File '" + panel.getHdfs()
+ "' not found.",WorkflowContext.ERROR);
return false;
}
if (!panel.existsLegend()) {
context.endTask("Reference File '" + panel.getLegend()
+ "' not found.",WorkflowContext.ERROR);
return false;
}
// load maps
MapList maps = null;
try {
maps = MapList.loadFromFile(FileUtil.path(folder,
"genetic-maps.txt"));
} catch (Exception e) {
context.error("genetic-maps.txt not found." + e);
return false;
}
// check map; hapmap2 map for all files used!
GeneticMap map = maps.getById("hapmap2");
if (map == null) {
context.error("genetic map file not found.");
return false;
}
if (map.getMapHapiUR()!=null && !map.checkHapiUR()) {
context.endTask("Map HapiUR '" + map.getMapHapiUR()
+ "' not found.",WorkflowContext.ERROR);
return false;
}
if (map.getMapShapeIT()!=null && !map.checkShapeIT()) {
context.endTask("Map ShapeIT '" + map.getMapShapeIT()
+ "' not found.",WorkflowContext.ERROR);
return false;
}
if (map.getMapEagle()!=null && !map.checkEagle()) {
context.error("Eagle reference files not found.");
return false;
}
if ((panel.getId().equals("hrc") && !population
.equals("eur"))) {
context.endTask(
"Please select the EUR population for the HRC panel",
WorkflowContext.ERROR);
return false;
}
if ((panel.getId().equals("caapa") && !population
.equals("AA"))) {
context.endTask(
"Please select the AA population for the CAAPA panel",
WorkflowContext.ERROR);
return false;
}
if ((panel.getId().equals("hapmap2") && !population
.equals("eur"))) {
context.endTask(
"Please select the EUR population for the HapMap reference panel",
WorkflowContext.ERROR);
return false;
}
if ((panel.getId().equals("phase1") && population
.equals("sas"))
|| (panel.getId().equals("phase1") && population
.equals("eas"))) {
context.endTask(
"The selected population (SAS, EAS) is not allowed for this panel",
WorkflowContext.ERROR);
return false;
}
if ((panel.getId().equals("phase3") && population
.equals("asn"))) {
context.endTask(
"The selected population (ASN) is not allowed for the 1000G Phase3 reference panel",
WorkflowContext.ERROR);
return false;
}
if (!phased && noSamples < 50 && !phasing.equals("eagle")) {
context.endTask(
"At least 50 samples must be included for pre-phasing using "
+ phasing + ". Please select eagle.",
WorkflowContext.ERROR);
return false;
}
if (noSamples > sampleLimit && sampleLimit != 0) {
context.endTask(
"The maximum number of samples is "
+ sampleLimit
+ ". Please contact Christian Fuchsberger (<a href=\"mailto:[email protected]\">[email protected]</a>) to discuss this large imputation.",
WorkflowContext.ERROR);
return false;
}
infos = "Samples: " + noSamples + "\n" + "Chromosomes:"
+ chromosomeString + "\n" + "SNPs: " + noSnps
+ "\n" + "Chunks: " + chunks + "\n" + "Datatype: "
+ (phased ? "phased" : "unphased") + "\n"
+ "Reference Panel: " + panel.getId() + "\n"
+ "Phasing: " + phasing;
} else {
context.endTask("No valid chromosomes found!",
WorkflowContext.ERROR);
return false;
}
} catch (IOException e) {
context.endTask(
e.getMessage()
+ " (see <a href=\"/start.html#!pages/help\">Help</a>).",
WorkflowContext.ERROR);
return false;
}
}
if (validVcfFiles.size() > 0) {
context.endTask(validVcfFiles.size()
+ " valid VCF file(s) found.\n\n" + infos,
WorkflowContext.OK);
// init counters
context.incCounter("samples", noSamples);
context.incCounter("genotypes", noSamples * noSnps);
context.incCounter("chromosomes", noSamples * chromosomes.size());
context.incCounter("runs", 1);
context.incCounter("refpanel_" + reference, 1);
context.incCounter("phasing_" + phasing, 1);
return true;
} else {
context.endTask(
"The provided files are not VCF files (see <a href=\"/start.html#!pages/help\">Help</a>). Chromosome X is currently in Beta.",
WorkflowContext.ERROR);
return false;
}
}
private boolean importVcfFiles(WorkflowContext context) {
for (String input : context.getInputs()) {
if (ImporterFactory.needsImport(context.get(input))) {
context.beginTask("Importing files...");
String[] urlList = context.get(input).split(";")[0]
.split("\\s+");
String username = "";
if (context.get(input).split(";").length > 1) {
username = context.get(input).split(";")[1];
}
String password = "";
if (context.get(input).split(";").length > 2) {
password = context.get(input).split(";")[2];
}
for (String url2 : urlList) {
String url = url2 + ";" + username + ";" + password;
String target = HdfsUtil.path(context.getHdfsTemp(),
"importer", input);
try {
context.updateTask("Import " + url2 + "...",
WorkflowContext.RUNNING);
IImporter importer = ImporterFactory.createImporter(
url, target);
if (importer != null) {
boolean successful = importer.importFiles("vcf.gz");
if (successful) {
context.setInput(input, target);
} else {
context.updateTask(
"Import " + url2 + " failed: "
+ importer.getErrorMessage(),
WorkflowContext.ERROR);
return false;
}
} else {
context.updateTask("Import " + url2
+ " failed: Protocol not supported",
WorkflowContext.ERROR);
return false;
}
} catch (Exception e) {
context.updateTask("Import File(s) " + url2
+ " failed: " + e.toString(),
WorkflowContext.ERROR);
return false;
}
}
context.updateTask("File Import successful. ",
WorkflowContext.OK);
}
}
return true;
}
public static String loadChrXTesterFromFile(String filename)
throws YamlException, FileNotFoundException {
return FileUtil.readFileAsString(filename);
}
}
| src/main/java/genepi/imputationserver/steps/InputValidation.java | package genepi.imputationserver.steps;
import genepi.hadoop.HdfsUtil;
import genepi.hadoop.PreferenceStore;
import genepi.hadoop.common.WorkflowContext;
import genepi.hadoop.common.WorkflowStep;
import genepi.hadoop.importer.IImporter;
import genepi.hadoop.importer.ImporterFactory;
import genepi.imputationserver.steps.converter.VCFBuilder;
import genepi.imputationserver.steps.vcf.VcfFile;
import genepi.imputationserver.steps.vcf.VcfFileUtil;
import genepi.imputationserver.util.GeneticMap;
import genepi.imputationserver.util.MapList;
import genepi.imputationserver.util.RefPanel;
import genepi.imputationserver.util.RefPanelList;
import genepi.io.FileUtil;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.List;
import java.util.Vector;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
import com.esotericsoftware.yamlbeans.YamlException;
public class InputValidation extends WorkflowStep {
@Override
public boolean run(WorkflowContext context) {
URLClassLoader cl = (URLClassLoader) InputValidation.class
.getClassLoader();
try {
URL url = cl.findResource("META-INF/MANIFEST.MF");
Manifest manifest = new Manifest(url.openStream());
Attributes attr = manifest.getMainAttributes();
String buildVesion = attr.getValue("Version");
String buildTime = attr.getValue("Build-Time");
String builtBy = attr.getValue("Built-By");
context.println("Version: " + buildVesion + " (Built by " + builtBy
+ " on " + buildTime + ")");
} catch (IOException E) {
// handle
}
if (!importVcfFiles(context)) {
return false;
}
return checkVcfFiles(context);
}
private boolean checkVcfFiles(WorkflowContext context) {
String folder = getFolder(InputValidation.class);
String tester;
// inputs
String inputFiles = context.get("files");
String reference = context.get("refpanel");
String population = context.get("population");
String phasing = context.get("phasing");
int sampleLimit = Integer.valueOf(context.get("sample-limit"));
int chunkSize = Integer.parseInt(context.get("chunksize"));
VcfFileUtil.setBinaries(FileUtil.path(folder, "bin"));
String files = FileUtil.path(context.getLocalTemp(), "input");
PreferenceStore store = new PreferenceStore(new File(
FileUtil.path(folder, "job.config")));
// exports files from hdfs
try {
tester = loadChrXTesterFromFile(FileUtil.path(folder,
"chrX-tester.txt"));
HdfsUtil.getFolder(inputFiles, files);
} catch (Exception e) {
context.error("Downloading files: " + e.getMessage());
return false;
}
List<VcfFile> validVcfFiles = new Vector<VcfFile>();
context.beginTask("Analyze files ");
List<String> chromosomes = new Vector<String>();
int chunks = 0;
int noSnps = 0;
int noSamples = 0;
boolean phased = true;
try {
String[] genome = FileUtil.getFiles(files, "*.txt$|*.zip");
if (genome.length == 1) {
context.updateTask("Check for valid 23andMe data",
WorkflowContext.RUNNING);
VCFBuilder builder = new VCFBuilder(genome[0]);
builder.setReference(store.getString("ref.fasta"));
builder.setOutDirectory(files);
builder.setExcludeList("MT,X,Y");
builder.build();
HdfsUtil.delete(inputFiles);
for (String vcf : FileUtil.getFiles(files, "*.vcf.gz$|*.vcf$")) {
HdfsUtil.put(vcf, inputFiles);
}
context.incCounter("23andme-input", 1);
} else if (genome.length > 1) {
context.endTask(
"Please upload your 23andMe data as a single txt or zip file",
WorkflowContext.ERROR);
return false;
}
} catch (Exception e1) {
// TODO Auto-generated catch block
context.endTask("Converter task failed! \n" + e1.getMessage(),
WorkflowContext.ERROR);
return false;
}
String[] vcfFiles = FileUtil.getFiles(files, "*.vcf.gz$|*.vcf$");
if (vcfFiles.length == 0) {
context.endTask(
"The provided files are not VCF files (see <a href=\"/start.html#!pages/help\">Help</a>).",
WorkflowContext.ERROR);
return false;
}
String infos = null;
for (String filename : vcfFiles) {
if (infos == null) {
// first files, no infos available
context.updateTask(
"Analyze file " + FileUtil.getFilename(filename)
+ "...", WorkflowContext.RUNNING);
} else {
context.updateTask(
"Analyze file " + FileUtil.getFilename(filename)
+ "...\n\n" + infos, WorkflowContext.RUNNING);
}
try {
VcfFile vcfFile = VcfFileUtil.load(filename, chunkSize, true);
String mail = null;
if(store.getString("minimac.sendmail") != null && store.getString("minimac.sendmail").equals("yes")){
mail = context.getData("cloudgene.user.mail").toString();
}
if (VcfFileUtil.isValidChromosome(vcfFile.getChromosome())) {
if (VcfFileUtil.isChrX(vcfFile.getChromosome())) {
/*if (mail != null && !tester.contains(mail.toLowerCase())) {
context.endTask(
"Chromosome X imputation is currently under preperation. Please contact us to become a beta tester.",
WorkflowContext.ERROR);
return false;
}*/
if(!phasing.equals("shapeit") && !vcfFile.isPhased()){
context.endTask(
"Please select shapeit for phasing chromosome X. Eagle2 is under prepartion.",
WorkflowContext.ERROR);
return false;
}
}
validVcfFiles.add(vcfFile);
chromosomes.add(vcfFile.getChromosome());
String chromosomeString = "";
for (String chr : chromosomes) {
chromosomeString += " " + chr;
}
// check if all files have same amount of samples
if (noSamples != 0 && noSamples != vcfFile.getNoSamples()) {
context.endTask(
"Please double check, if all uploaded VCF files include the same amount of samples ("
+ vcfFile.getNoSamples()
+ " vs "
+ noSamples + ")",
WorkflowContext.ERROR);
return false;
}
noSamples = vcfFile.getNoSamples();
noSnps += vcfFile.getNoSnps();
chunks += vcfFile.getChunks().size();
phased = phased && vcfFile.isPhased();
// check reference panel
if (vcfFile.isPhasedAutodetect() && !vcfFile.isPhased()) {
context.endTask(
"File should be phased, but also includes unphased and/or missing genotypes! Please double-check!",
WorkflowContext.ERROR);
return false;
}
RefPanelList panels = null;
try {
panels = RefPanelList.loadFromFile(FileUtil.path(
folder, "panels.txt"));
} catch (Exception e) {
context.endTask("panels.txt not found.",
WorkflowContext.ERROR);
return false;
}
RefPanel panel = panels.getById(reference);
if (panel == null) {
StringBuilder report = new StringBuilder();
report.append("Reference '" + reference
+ "' not found.\n");
report.append("Available reference IDs:");
for (RefPanel p : panels.getPanels()) {
report.append("\n - " + p.getId());
}
context.error(report.toString());
return false;
}
if (!panel.existsReference()) {
context.endTask("Reference File '" + panel.getHdfs()
+ "' not found.",WorkflowContext.ERROR);
return false;
}
if (!panel.existsLegend()) {
context.endTask("Reference File '" + panel.getLegend()
+ "' not found.",WorkflowContext.ERROR);
return false;
}
// load maps
MapList maps = null;
try {
maps = MapList.loadFromFile(FileUtil.path(folder,
"genetic-maps.txt"));
} catch (Exception e) {
context.error("genetic-maps.txt not found." + e);
return false;
}
// check map; hapmap2 map for all files used!
GeneticMap map = maps.getById("hapmap2");
if (map == null) {
context.error("genetic map file not found.");
return false;
}
if (map.getMapHapiUR()!=null && !map.checkHapiUR()) {
context.endTask("Map HapiUR '" + map.getMapHapiUR()
+ "' not found.",WorkflowContext.ERROR);
return false;
}
if (map.getMapShapeIT()!=null && !map.checkShapeIT()) {
context.endTask("Map ShapeIT '" + map.getMapShapeIT()
+ "' not found.",WorkflowContext.ERROR);
return false;
}
if (map.getMapEagle()!=null && !map.checkEagle()) {
context.error("Eagle reference files not found.");
return false;
}
if ((panel.getId().equals("hrc") && !population
.equals("eur"))) {
context.endTask(
"Please select the EUR population for the HRC panel",
WorkflowContext.ERROR);
return false;
}
if ((panel.getId().equals("caapa") && !population
.equals("AA"))) {
context.endTask(
"Please select the AA population for the CAAPA panel",
WorkflowContext.ERROR);
return false;
}
if ((panel.getId().equals("hapmap2") && !population
.equals("eur"))) {
context.endTask(
"Please select the EUR population for the HapMap reference panel",
WorkflowContext.ERROR);
return false;
}
if ((panel.getId().equals("phase1") && population
.equals("sas"))
|| (panel.getId().equals("phase1") && population
.equals("eas"))) {
context.endTask(
"The selected population (SAS, EAS) is not allowed for this panel",
WorkflowContext.ERROR);
return false;
}
if ((panel.getId().equals("phase3") && population
.equals("asn"))) {
context.endTask(
"The selected population (ASN) is not allowed for the 1000G Phase3 reference panel",
WorkflowContext.ERROR);
return false;
}
if (!phased && noSamples < 50 && !phasing.equals("eagle")) {
context.endTask(
"At least 50 samples must be included for pre-phasing using "
+ phasing + ". Please select eagle.",
WorkflowContext.ERROR);
return false;
}
if (noSamples > sampleLimit && sampleLimit != 0) {
context.endTask(
"The maximum number of samples is "
+ sampleLimit
+ ". Please contact Christian Fuchsberger (<a href=\"mailto:[email protected]\">[email protected]</a>) to discuss this large imputation.",
WorkflowContext.ERROR);
return false;
}
infos = "Samples: " + noSamples + "\n" + "Chromosomes:"
+ chromosomeString + "\n" + "SNPs: " + noSnps
+ "\n" + "Chunks: " + chunks + "\n" + "Datatype: "
+ (phased ? "phased" : "unphased") + "\n"
+ "Reference Panel: " + panel.getId() + "\n"
+ "Phasing: " + phasing;
} else {
context.endTask("No valid chromosomes found!",
WorkflowContext.ERROR);
return false;
}
} catch (IOException e) {
context.endTask(
e.getMessage()
+ " (see <a href=\"/start.html#!pages/help\">Help</a>).",
WorkflowContext.ERROR);
return false;
}
}
if (validVcfFiles.size() > 0) {
context.endTask(validVcfFiles.size()
+ " valid VCF file(s) found.\n\n" + infos,
WorkflowContext.OK);
// init counters
context.incCounter("samples", noSamples);
context.incCounter("genotypes", noSamples * noSnps);
context.incCounter("chromosomes", noSamples * chromosomes.size());
context.incCounter("runs", 1);
context.incCounter("refpanel_" + reference, 1);
context.incCounter("phasing_" + phasing, 1);
return true;
} else {
context.endTask(
"The provided files are not VCF files (see <a href=\"/start.html#!pages/help\">Help</a>). Chromosome X is currently in Beta.",
WorkflowContext.ERROR);
return false;
}
}
private boolean importVcfFiles(WorkflowContext context) {
for (String input : context.getInputs()) {
if (ImporterFactory.needsImport(context.get(input))) {
context.beginTask("Importing files...");
String[] urlList = context.get(input).split(";")[0]
.split("\\s+");
String username = "";
if (context.get(input).split(";").length > 1) {
username = context.get(input).split(";")[1];
}
String password = "";
if (context.get(input).split(";").length > 2) {
password = context.get(input).split(";")[2];
}
for (String url2 : urlList) {
String url = url2 + ";" + username + ";" + password;
String target = HdfsUtil.path(context.getHdfsTemp(),
"importer", input);
try {
context.updateTask("Import " + url2 + "...",
WorkflowContext.RUNNING);
IImporter importer = ImporterFactory.createImporter(
url, target);
if (importer != null) {
boolean successful = importer.importFiles("vcf.gz");
if (successful) {
context.setInput(input, target);
} else {
context.updateTask(
"Import " + url2 + " failed: "
+ importer.getErrorMessage(),
WorkflowContext.ERROR);
return false;
}
} else {
context.updateTask("Import " + url2
+ " failed: Protocol not supported",
WorkflowContext.ERROR);
return false;
}
} catch (Exception e) {
context.updateTask("Import File(s) " + url2
+ " failed: " + e.toString(),
WorkflowContext.ERROR);
return false;
}
}
context.updateTask("File Import successful. ",
WorkflowContext.OK);
}
}
return true;
}
public static String loadChrXTesterFromFile(String filename)
throws YamlException, FileNotFoundException {
return FileUtil.readFileAsString(filename);
}
}
| removing unused load of chrX tester | src/main/java/genepi/imputationserver/steps/InputValidation.java | removing unused load of chrX tester | <ide><path>rc/main/java/genepi/imputationserver/steps/InputValidation.java
<ide>
<ide> private boolean checkVcfFiles(WorkflowContext context) {
<ide> String folder = getFolder(InputValidation.class);
<del> String tester;
<add> //String tester;
<ide> // inputs
<ide> String inputFiles = context.get("files");
<ide> String reference = context.get("refpanel");
<ide>
<ide> // exports files from hdfs
<ide> try {
<del> tester = loadChrXTesterFromFile(FileUtil.path(folder,
<del> "chrX-tester.txt"));
<add> //tester = loadChrXTesterFromFile(FileUtil.path(folder,
<add> // "chrX-tester.txt"));
<ide> HdfsUtil.getFolder(inputFiles, files);
<ide>
<ide> } catch (Exception e) { |
|
Java | mit | 5eca609c44ad56847857daac349e12a64fb306b3 | 0 | dashteacup/PassMan | package cs242.pcurry2.pm;
import java.io.File;
import javax.swing.filechooser.FileFilter;
/**
* Custom file filter to restrict the openable files to .PMAN files
*/
public class PmanFileFilter extends FileFilter {
/**
* Determines if a file should be displayed as selectable in the file
* chooser.
*/
@Override
public boolean accept(File f) {
if (f.isDirectory()) {
return true;
}
String filename = f.getName();
int extIndex = filename.lastIndexOf('.');
// I don't want to worry about the case of the extension
String extension = filename.substring(extIndex + 1).toLowerCase();
return extension.equals("pman");
}
/**
* Description of the file type displayed in the file chooser.
*/
@Override
public String getDescription() {
return "PMAN file";
}
}
| src/cs242/pcurry2/pm/PmanFileFilter.java | package cs242.pcurry2.pm;
import java.io.File;
import javax.swing.filechooser.FileFilter;
/**
* Custom file filter to restrict the openable files to .PMAN files
*/
public class PmanFileFilter extends FileFilter {
@Override
public boolean accept(File f) {
if (f.isDirectory()) {
return true;
}
String filename = f.getName();
int extIndex = filename.lastIndexOf('.');
String extension = filename.substring(extIndex + 1);
if (extension.equals("pman") || extension.equals("PMAN")) {
return true;
}
return false;
}
@Override
public String getDescription() {
return "PMAN file";
}
}
| Cleaned up code and comments for file chooser filter.
| src/cs242/pcurry2/pm/PmanFileFilter.java | Cleaned up code and comments for file chooser filter. | <ide><path>rc/cs242/pcurry2/pm/PmanFileFilter.java
<ide> */
<ide> public class PmanFileFilter extends FileFilter {
<ide>
<add> /**
<add> * Determines if a file should be displayed as selectable in the file
<add> * chooser.
<add> */
<ide> @Override
<ide> public boolean accept(File f) {
<ide> if (f.isDirectory()) {
<ide> }
<ide> String filename = f.getName();
<ide> int extIndex = filename.lastIndexOf('.');
<del> String extension = filename.substring(extIndex + 1);
<del> if (extension.equals("pman") || extension.equals("PMAN")) {
<del> return true;
<del> }
<del> return false;
<add> // I don't want to worry about the case of the extension
<add> String extension = filename.substring(extIndex + 1).toLowerCase();
<add> return extension.equals("pman");
<ide> }
<ide>
<add> /**
<add> * Description of the file type displayed in the file chooser.
<add> */
<ide> @Override
<ide> public String getDescription() {
<ide> return "PMAN file"; |
|
Java | apache-2.0 | 603ee688cb5cb1e75a1fa86bb7b4bd604ac82f68 | 0 | smartnews/presto,smartnews/presto,smartnews/presto,smartnews/presto,smartnews/presto | /*
* 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.trino.plugin.hive.metastore.cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.SetMultimap;
import com.google.common.util.concurrent.UncheckedExecutionException;
import io.airlift.jmx.CacheStatsMBean;
import io.airlift.units.Duration;
import io.trino.plugin.hive.HivePartition;
import io.trino.plugin.hive.HiveType;
import io.trino.plugin.hive.PartitionNotFoundException;
import io.trino.plugin.hive.PartitionStatistics;
import io.trino.plugin.hive.acid.AcidOperation;
import io.trino.plugin.hive.acid.AcidTransaction;
import io.trino.plugin.hive.authentication.HiveIdentity;
import io.trino.plugin.hive.metastore.Database;
import io.trino.plugin.hive.metastore.HiveMetastore;
import io.trino.plugin.hive.metastore.HivePartitionName;
import io.trino.plugin.hive.metastore.HivePrincipal;
import io.trino.plugin.hive.metastore.HivePrivilegeInfo;
import io.trino.plugin.hive.metastore.HivePrivilegeInfo.HivePrivilege;
import io.trino.plugin.hive.metastore.HiveTableName;
import io.trino.plugin.hive.metastore.Partition;
import io.trino.plugin.hive.metastore.PartitionFilter;
import io.trino.plugin.hive.metastore.PartitionWithStatistics;
import io.trino.plugin.hive.metastore.PrincipalPrivileges;
import io.trino.plugin.hive.metastore.Table;
import io.trino.plugin.hive.metastore.TablesWithParameterCacheKey;
import io.trino.plugin.hive.metastore.UserTableKey;
import io.trino.spi.TrinoException;
import io.trino.spi.connector.SchemaTableName;
import io.trino.spi.connector.TableNotFoundException;
import io.trino.spi.predicate.TupleDomain;
import io.trino.spi.security.RoleGrant;
import io.trino.spi.statistics.ColumnStatisticType;
import io.trino.spi.type.Type;
import org.apache.hadoop.hive.metastore.api.DataOperationType;
import org.weakref.jmx.Managed;
import org.weakref.jmx.Nested;
import javax.annotation.concurrent.ThreadSafe;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.OptionalLong;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.function.Function;
import java.util.function.Predicate;
import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Throwables.throwIfInstanceOf;
import static com.google.common.base.Throwables.throwIfUnchecked;
import static com.google.common.cache.CacheLoader.asyncReloading;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableMap.toImmutableMap;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.collect.ImmutableSetMultimap.toImmutableSetMultimap;
import static com.google.common.collect.Maps.immutableEntry;
import static com.google.common.collect.Streams.stream;
import static com.google.common.util.concurrent.MoreExecutors.newDirectExecutorService;
import static io.trino.plugin.hive.HivePartitionManager.extractPartitionValues;
import static io.trino.plugin.hive.metastore.HivePartitionName.hivePartitionName;
import static io.trino.plugin.hive.metastore.HiveTableName.hiveTableName;
import static io.trino.plugin.hive.metastore.MetastoreUtil.makePartitionName;
import static io.trino.plugin.hive.metastore.PartitionFilter.partitionFilter;
import static io.trino.plugin.hive.metastore.cache.CachingHiveMetastoreConfig.isCacheEnabled;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.apache.hadoop.hive.common.FileUtils.makePartName;
/**
* Hive Metastore Cache
*/
@ThreadSafe
public class CachingHiveMetastore
implements HiveMetastore
{
public enum StatsRecording
{
ENABLED,
DISABLED
}
protected final HiveMetastore delegate;
private final LoadingCache<String, Optional<Database>> databaseCache;
private final LoadingCache<String, List<String>> databaseNamesCache;
private final LoadingCache<WithIdentity<HiveTableName>, Optional<Table>> tableCache;
private final LoadingCache<String, List<String>> tableNamesCache;
private final LoadingCache<TablesWithParameterCacheKey, List<String>> tablesWithParameterCache;
private final LoadingCache<WithIdentity<HiveTableName>, PartitionStatistics> tableStatisticsCache;
private final LoadingCache<WithIdentity<HivePartitionName>, PartitionStatistics> partitionStatisticsCache;
private final LoadingCache<String, List<String>> viewNamesCache;
private final LoadingCache<WithIdentity<HivePartitionName>, Optional<Partition>> partitionCache;
private final LoadingCache<WithIdentity<PartitionFilter>, Optional<List<String>>> partitionFilterCache;
private final LoadingCache<UserTableKey, Set<HivePrivilegeInfo>> tablePrivilegesCache;
private final LoadingCache<String, Set<String>> rolesCache;
private final LoadingCache<HivePrincipal, Set<RoleGrant>> roleGrantsCache;
private final LoadingCache<String, Set<RoleGrant>> grantedPrincipalsCache;
private final LoadingCache<String, Optional<String>> configValuesCache;
public static CachingHiveMetastore cachingHiveMetastore(HiveMetastore delegate, Executor executor, CachingHiveMetastoreConfig config)
{
return cachingHiveMetastore(
delegate,
executor,
config.getMetastoreCacheTtl(),
config.getMetastoreRefreshInterval(),
config.getMetastoreCacheMaximumSize());
}
public static CachingHiveMetastore cachingHiveMetastore(HiveMetastore delegate, Executor executor, Duration cacheTtl, Optional<Duration> refreshInterval, long maximumSize)
{
checkState(
isCacheEnabled(cacheTtl, maximumSize),
format("Invalid cache parameters (cacheTtl: %s, maxSize: %s)", cacheTtl, maximumSize));
return new CachingHiveMetastore(
delegate,
executor,
OptionalLong.of(cacheTtl.toMillis()),
refreshInterval
.map(Duration::toMillis)
.map(OptionalLong::of)
.orElseGet(OptionalLong::empty),
maximumSize,
StatsRecording.ENABLED);
}
public static CachingHiveMetastore memoizeMetastore(HiveMetastore delegate, long maximumSize)
{
return new CachingHiveMetastore(
delegate,
newDirectExecutorService(),
OptionalLong.empty(),
OptionalLong.empty(),
maximumSize,
StatsRecording.DISABLED);
}
protected CachingHiveMetastore(HiveMetastore delegate, Executor executor, OptionalLong expiresAfterWriteMillis, OptionalLong refreshMills, long maximumSize, StatsRecording statsRecording)
{
this.delegate = requireNonNull(delegate, "delegate is null");
requireNonNull(executor, "executor is null");
databaseNamesCache = newCacheBuilder(expiresAfterWriteMillis, refreshMills, maximumSize, statsRecording)
.build(asyncReloading(CacheLoader.from(this::loadAllDatabases), executor));
databaseCache = newCacheBuilder(expiresAfterWriteMillis, refreshMills, maximumSize, statsRecording)
.build(asyncReloading(CacheLoader.from(this::loadDatabase), executor));
tableNamesCache = newCacheBuilder(expiresAfterWriteMillis, refreshMills, maximumSize, statsRecording)
.build(asyncReloading(CacheLoader.from(this::loadAllTables), executor));
tablesWithParameterCache = newCacheBuilder(expiresAfterWriteMillis, refreshMills, maximumSize, statsRecording)
.build(asyncReloading(CacheLoader.from(this::loadTablesMatchingParameter), executor));
tableStatisticsCache = newCacheBuilder(expiresAfterWriteMillis, refreshMills, maximumSize, statsRecording)
.build(asyncReloading(CacheLoader.from(this::loadTableColumnStatistics), executor));
// disable refresh since it can't use the bulk loading and causes too many requests
partitionStatisticsCache = newCacheBuilder(expiresAfterWriteMillis, OptionalLong.empty(), maximumSize, statsRecording)
.build(new CacheLoader<>()
{
@Override
public PartitionStatistics load(WithIdentity<HivePartitionName> key)
{
return loadPartitionColumnStatistics(key);
}
@Override
public Map<WithIdentity<HivePartitionName>, PartitionStatistics> loadAll(Iterable<? extends WithIdentity<HivePartitionName>> keys)
{
return loadPartitionColumnStatistics(keys);
}
});
tableCache = newCacheBuilder(expiresAfterWriteMillis, refreshMills, maximumSize, statsRecording)
.build(asyncReloading(CacheLoader.from(this::loadTable), executor));
viewNamesCache = newCacheBuilder(expiresAfterWriteMillis, refreshMills, maximumSize, statsRecording)
.build(asyncReloading(CacheLoader.from(this::loadAllViews), executor));
partitionFilterCache = newCacheBuilder(expiresAfterWriteMillis, refreshMills, maximumSize, statsRecording)
.build(asyncReloading(CacheLoader.from(this::loadPartitionNamesByFilter), executor));
// disable refresh since it can't use the bulk loading and causes too many requests
partitionCache = newCacheBuilder(expiresAfterWriteMillis, OptionalLong.empty(), maximumSize, statsRecording)
.build(new CacheLoader<>()
{
@Override
public Optional<Partition> load(WithIdentity<HivePartitionName> partitionName)
{
return loadPartitionByName(partitionName);
}
@Override
public Map<WithIdentity<HivePartitionName>, Optional<Partition>> loadAll(Iterable<? extends WithIdentity<HivePartitionName>> partitionNames)
{
return loadPartitionsByNames(partitionNames);
}
});
tablePrivilegesCache = newCacheBuilder(expiresAfterWriteMillis, refreshMills, maximumSize, statsRecording)
.build(asyncReloading(CacheLoader.from(key -> loadTablePrivileges(key.getDatabase(), key.getTable(), key.getOwner(), key.getPrincipal())), executor));
rolesCache = newCacheBuilder(expiresAfterWriteMillis, refreshMills, maximumSize, statsRecording)
.build(asyncReloading(CacheLoader.from(this::loadRoles), executor));
roleGrantsCache = newCacheBuilder(expiresAfterWriteMillis, refreshMills, maximumSize, statsRecording)
.build(asyncReloading(CacheLoader.from(this::loadRoleGrants), executor));
grantedPrincipalsCache = newCacheBuilder(expiresAfterWriteMillis, refreshMills, maximumSize, statsRecording)
.build(asyncReloading(CacheLoader.from(this::loadPrincipals), executor));
configValuesCache = newCacheBuilder(expiresAfterWriteMillis, refreshMills, maximumSize, statsRecording)
.build(asyncReloading(CacheLoader.from(this::loadConfigValue), executor));
}
@Managed
public void flushCache()
{
databaseNamesCache.invalidateAll();
tableNamesCache.invalidateAll();
viewNamesCache.invalidateAll();
databaseCache.invalidateAll();
tableCache.invalidateAll();
partitionCache.invalidateAll();
partitionFilterCache.invalidateAll();
tablePrivilegesCache.invalidateAll();
tableStatisticsCache.invalidateAll();
partitionStatisticsCache.invalidateAll();
rolesCache.invalidateAll();
}
public void flushPartitionCache(String schemaName, String tableName, List<String> partitionColumns, List<String> partitionValues)
{
requireNonNull(schemaName, "schemaName is null");
requireNonNull(tableName, "tableName is null");
requireNonNull(partitionColumns, "partitionColumns is null");
requireNonNull(partitionValues, "partitionValues is null");
String providedPartitionName = makePartName(partitionColumns, partitionValues);
invalidatePartitionCache(schemaName, tableName, partitionNameToCheck -> partitionNameToCheck.map(value -> value.equals(providedPartitionName)).orElse(false));
}
private static <K, V> V get(LoadingCache<K, V> cache, K key)
{
try {
return cache.getUnchecked(key);
}
catch (UncheckedExecutionException e) {
throwIfInstanceOf(e.getCause(), TrinoException.class);
throw e;
}
}
private static <K, V> Map<K, V> getAll(LoadingCache<K, V> cache, Iterable<K> keys)
{
try {
return cache.getAll(keys);
}
catch (ExecutionException | UncheckedExecutionException e) {
throwIfInstanceOf(e.getCause(), TrinoException.class);
throwIfUnchecked(e);
throw new UncheckedExecutionException(e);
}
}
@Override
public Optional<Database> getDatabase(String databaseName)
{
return get(databaseCache, databaseName);
}
private Optional<Database> loadDatabase(String databaseName)
{
return delegate.getDatabase(databaseName);
}
@Override
public List<String> getAllDatabases()
{
return get(databaseNamesCache, "");
}
private List<String> loadAllDatabases()
{
return delegate.getAllDatabases();
}
private Table getExistingTable(HiveIdentity identity, String databaseName, String tableName)
{
return getTable(identity, databaseName, tableName)
.orElseThrow(() -> new TableNotFoundException(new SchemaTableName(databaseName, tableName)));
}
@Override
public Optional<Table> getTable(HiveIdentity identity, String databaseName, String tableName)
{
identity = updateIdentity(identity);
return get(tableCache, new WithIdentity<>(identity, hiveTableName(databaseName, tableName)));
}
@Override
public Set<ColumnStatisticType> getSupportedColumnStatistics(Type type)
{
return delegate.getSupportedColumnStatistics(type);
}
private Optional<Table> loadTable(WithIdentity<HiveTableName> hiveTableName)
{
return delegate.getTable(hiveTableName.getIdentity(), hiveTableName.key.getDatabaseName(), hiveTableName.key.getTableName());
}
@Override
public PartitionStatistics getTableStatistics(HiveIdentity identity, Table table)
{
return get(tableStatisticsCache, new WithIdentity<>(updateIdentity(identity), hiveTableName(table.getDatabaseName(), table.getTableName())));
}
private PartitionStatistics loadTableColumnStatistics(WithIdentity<HiveTableName> hiveTableName)
{
HiveTableName tableName = hiveTableName.getKey();
Table table = getExistingTable(hiveTableName.getIdentity(), tableName.getDatabaseName(), tableName.getTableName());
return delegate.getTableStatistics(hiveTableName.getIdentity(), table);
}
@Override
public Map<String, PartitionStatistics> getPartitionStatistics(HiveIdentity identity, Table table, List<Partition> partitions)
{
HiveTableName hiveTableName = hiveTableName(table.getDatabaseName(), table.getTableName());
List<WithIdentity<HivePartitionName>> partitionNames = partitions.stream()
.map(partition -> new WithIdentity<>(updateIdentity(identity), hivePartitionName(hiveTableName, makePartitionName(table, partition))))
.collect(toImmutableList());
Map<WithIdentity<HivePartitionName>, PartitionStatistics> statistics = getAll(partitionStatisticsCache, partitionNames);
return statistics.entrySet()
.stream()
.collect(toImmutableMap(entry -> entry.getKey().getKey().getPartitionName().get(), Entry::getValue));
}
private PartitionStatistics loadPartitionColumnStatistics(WithIdentity<HivePartitionName> partition)
{
HiveTableName tableName = partition.getKey().getHiveTableName();
String partitionName = partition.getKey().getPartitionName().get();
Table table = getExistingTable(partition.getIdentity(), tableName.getDatabaseName(), tableName.getTableName());
Map<String, PartitionStatistics> partitionStatistics = delegate.getPartitionStatistics(
partition.getIdentity(),
table,
ImmutableList.of(getExistingPartition(partition.getIdentity(), table, partition.getKey().getPartitionValues())));
return partitionStatistics.get(partitionName);
}
private Map<WithIdentity<HivePartitionName>, PartitionStatistics> loadPartitionColumnStatistics(Iterable<? extends WithIdentity<HivePartitionName>> keys)
{
SetMultimap<WithIdentity<HiveTableName>, WithIdentity<HivePartitionName>> tablePartitions = stream(keys)
.collect(toImmutableSetMultimap(value -> new WithIdentity<>(value.getIdentity(), value.getKey().getHiveTableName()), Function.identity()));
ImmutableMap.Builder<WithIdentity<HivePartitionName>, PartitionStatistics> result = ImmutableMap.builder();
tablePartitions.keySet().forEach(tableName -> {
Set<WithIdentity<HivePartitionName>> partitionNames = tablePartitions.get(tableName);
Set<String> partitionNameStrings = partitionNames.stream()
.map(partitionName -> partitionName.getKey().getPartitionName().get())
.collect(toImmutableSet());
Table table = getExistingTable(tableName.getIdentity(), tableName.getKey().getDatabaseName(), tableName.getKey().getTableName());
List<Partition> partitions = getExistingPartitionsByNames(tableName.getIdentity(), table, ImmutableList.copyOf(partitionNameStrings));
Map<String, PartitionStatistics> statisticsByPartitionName = delegate.getPartitionStatistics(tableName.getIdentity(), table, partitions);
for (WithIdentity<HivePartitionName> partitionName : partitionNames) {
String stringNameForPartition = partitionName.getKey().getPartitionName().get();
result.put(partitionName, statisticsByPartitionName.get(stringNameForPartition));
}
});
return result.buildOrThrow();
}
@Override
public void updateTableStatistics(HiveIdentity identity, String databaseName, String tableName, AcidTransaction transaction, Function<PartitionStatistics, PartitionStatistics> update)
{
identity = updateIdentity(identity);
try {
delegate.updateTableStatistics(identity, databaseName, tableName, transaction, update);
}
finally {
HiveTableName hiveTableName = hiveTableName(databaseName, tableName);
tableStatisticsCache.invalidate(new WithIdentity<>(identity, hiveTableName));
// basic stats are stored as table properties
tableCache.invalidate(new WithIdentity<>(identity, hiveTableName));
}
}
@Override
public void updatePartitionStatistics(HiveIdentity identity, Table table, String partitionName, Function<PartitionStatistics, PartitionStatistics> update)
{
identity = updateIdentity(identity);
try {
delegate.updatePartitionStatistics(identity, table, partitionName, update);
}
finally {
HivePartitionName hivePartitionName = hivePartitionName(hiveTableName(table.getDatabaseName(), table.getTableName()), partitionName);
partitionStatisticsCache.invalidate(new WithIdentity<>(identity, hivePartitionName));
// basic stats are stored as partition properties
partitionCache.invalidate(new WithIdentity<>(identity, hivePartitionName));
}
}
@Override
public void updatePartitionStatistics(HiveIdentity identity, Table table, Map<String, Function<PartitionStatistics, PartitionStatistics>> updates)
{
try {
delegate.updatePartitionStatistics(updateIdentity(identity), table, updates);
}
finally {
HiveIdentity hiveIdentity = updateIdentity(identity);
updates.forEach((partitionName, update) -> {
HivePartitionName hivePartitionName = hivePartitionName(hiveTableName(table.getDatabaseName(), table.getTableName()), partitionName);
partitionStatisticsCache.invalidate(new WithIdentity<>(hiveIdentity, hivePartitionName));
// basic stats are stored as partition properties
partitionCache.invalidate(new WithIdentity<>(hiveIdentity, hivePartitionName));
});
}
}
@Override
public List<String> getAllTables(String databaseName)
{
return get(tableNamesCache, databaseName);
}
private List<String> loadAllTables(String databaseName)
{
return delegate.getAllTables(databaseName);
}
@Override
public List<String> getTablesWithParameter(String databaseName, String parameterKey, String parameterValue)
{
TablesWithParameterCacheKey key = new TablesWithParameterCacheKey(databaseName, parameterKey, parameterValue);
return get(tablesWithParameterCache, key);
}
private List<String> loadTablesMatchingParameter(TablesWithParameterCacheKey key)
{
return delegate.getTablesWithParameter(key.getDatabaseName(), key.getParameterKey(), key.getParameterValue());
}
@Override
public List<String> getAllViews(String databaseName)
{
return get(viewNamesCache, databaseName);
}
private List<String> loadAllViews(String databaseName)
{
return delegate.getAllViews(databaseName);
}
@Override
public void createDatabase(HiveIdentity identity, Database database)
{
identity = updateIdentity(identity);
try {
delegate.createDatabase(identity, database);
}
finally {
invalidateDatabase(database.getDatabaseName());
}
}
@Override
public void dropDatabase(HiveIdentity identity, String databaseName, boolean deleteData)
{
identity = updateIdentity(identity);
try {
delegate.dropDatabase(identity, databaseName, deleteData);
}
finally {
invalidateDatabase(databaseName);
}
}
@Override
public void renameDatabase(HiveIdentity identity, String databaseName, String newDatabaseName)
{
identity = updateIdentity(identity);
try {
delegate.renameDatabase(identity, databaseName, newDatabaseName);
}
finally {
invalidateDatabase(databaseName);
invalidateDatabase(newDatabaseName);
}
}
@Override
public void setDatabaseOwner(HiveIdentity identity, String databaseName, HivePrincipal principal)
{
identity = updateIdentity(identity);
try {
delegate.setDatabaseOwner(identity, databaseName, principal);
}
finally {
invalidateDatabase(databaseName);
}
}
protected void invalidateDatabase(String databaseName)
{
databaseCache.invalidate(databaseName);
databaseNamesCache.invalidateAll();
}
@Override
public void createTable(HiveIdentity identity, Table table, PrincipalPrivileges principalPrivileges)
{
identity = updateIdentity(identity);
try {
delegate.createTable(identity, table, principalPrivileges);
}
finally {
invalidateTable(table.getDatabaseName(), table.getTableName());
}
}
@Override
public void dropTable(HiveIdentity identity, String databaseName, String tableName, boolean deleteData)
{
identity = updateIdentity(identity);
try {
delegate.dropTable(identity, databaseName, tableName, deleteData);
}
finally {
invalidateTable(databaseName, tableName);
}
}
@Override
public void replaceTable(HiveIdentity identity, String databaseName, String tableName, Table newTable, PrincipalPrivileges principalPrivileges)
{
identity = updateIdentity(identity);
try {
delegate.replaceTable(identity, databaseName, tableName, newTable, principalPrivileges);
}
finally {
invalidateTable(databaseName, tableName);
invalidateTable(newTable.getDatabaseName(), newTable.getTableName());
}
}
@Override
public void renameTable(HiveIdentity identity, String databaseName, String tableName, String newDatabaseName, String newTableName)
{
identity = updateIdentity(identity);
try {
delegate.renameTable(identity, databaseName, tableName, newDatabaseName, newTableName);
}
finally {
invalidateTable(databaseName, tableName);
invalidateTable(newDatabaseName, newTableName);
}
}
@Override
public void commentTable(HiveIdentity identity, String databaseName, String tableName, Optional<String> comment)
{
identity = updateIdentity(identity);
try {
delegate.commentTable(identity, databaseName, tableName, comment);
}
finally {
invalidateTable(databaseName, tableName);
}
}
@Override
public void setTableOwner(HiveIdentity identity, String databaseName, String tableName, HivePrincipal principal)
{
identity = updateIdentity(identity);
try {
delegate.setTableOwner(identity, databaseName, tableName, principal);
}
finally {
invalidateTable(databaseName, tableName);
}
}
@Override
public void commentColumn(HiveIdentity identity, String databaseName, String tableName, String columnName, Optional<String> comment)
{
identity = updateIdentity(identity);
try {
delegate.commentColumn(identity, databaseName, tableName, columnName, comment);
}
finally {
invalidateTable(databaseName, tableName);
}
}
@Override
public void addColumn(HiveIdentity identity, String databaseName, String tableName, String columnName, HiveType columnType, String columnComment)
{
identity = updateIdentity(identity);
try {
delegate.addColumn(identity, databaseName, tableName, columnName, columnType, columnComment);
}
finally {
invalidateTable(databaseName, tableName);
}
}
@Override
public void renameColumn(HiveIdentity identity, String databaseName, String tableName, String oldColumnName, String newColumnName)
{
identity = updateIdentity(identity);
try {
delegate.renameColumn(identity, databaseName, tableName, oldColumnName, newColumnName);
}
finally {
invalidateTable(databaseName, tableName);
}
}
@Override
public void dropColumn(HiveIdentity identity, String databaseName, String tableName, String columnName)
{
identity = updateIdentity(identity);
try {
delegate.dropColumn(identity, databaseName, tableName, columnName);
}
finally {
invalidateTable(databaseName, tableName);
}
}
protected void invalidateTable(String databaseName, String tableName)
{
invalidateTableCache(databaseName, tableName);
tableNamesCache.invalidate(databaseName);
viewNamesCache.invalidate(databaseName);
tablePrivilegesCache.asMap().keySet().stream()
.filter(userTableKey -> userTableKey.matches(databaseName, tableName))
.forEach(tablePrivilegesCache::invalidate);
invalidateTableStatisticsCache(databaseName, tableName);
invalidatePartitionCache(databaseName, tableName);
}
private void invalidateTableCache(String databaseName, String tableName)
{
tableCache.asMap().keySet().stream()
.filter(table -> table.getKey().getDatabaseName().equals(databaseName) && table.getKey().getTableName().equals(tableName))
.forEach(tableCache::invalidate);
}
private void invalidateTableStatisticsCache(String databaseName, String tableName)
{
tableStatisticsCache.asMap().keySet().stream()
.filter(table -> table.getKey().getDatabaseName().equals(databaseName) && table.getKey().getTableName().equals(tableName))
.forEach(tableCache::invalidate);
}
private Partition getExistingPartition(HiveIdentity identity, Table table, List<String> partitionValues)
{
return getPartition(identity, table, partitionValues)
.orElseThrow(() -> new PartitionNotFoundException(table.getSchemaTableName(), partitionValues));
}
private List<Partition> getExistingPartitionsByNames(HiveIdentity identity, Table table, List<String> partitionNames)
{
Map<String, Partition> partitions = getPartitionsByNames(identity, table, partitionNames).entrySet().stream()
.map(entry -> immutableEntry(entry.getKey(), entry.getValue().orElseThrow(() ->
new PartitionNotFoundException(table.getSchemaTableName(), extractPartitionValues(entry.getKey())))))
.collect(toImmutableMap(Map.Entry::getKey, Map.Entry::getValue));
return partitionNames.stream()
.map(partitions::get)
.collect(toImmutableList());
}
@Override
public Optional<Partition> getPartition(HiveIdentity identity, Table table, List<String> partitionValues)
{
return get(partitionCache, new WithIdentity<>(updateIdentity(identity), hivePartitionName(hiveTableName(table.getDatabaseName(), table.getTableName()), partitionValues)));
}
@Override
public Optional<List<String>> getPartitionNamesByFilter(HiveIdentity identity, String databaseName, String tableName, List<String> columnNames, TupleDomain<String> partitionKeysFilter)
{
return get(partitionFilterCache, new WithIdentity<>(updateIdentity(identity), partitionFilter(databaseName, tableName, columnNames, partitionKeysFilter)));
}
private Optional<List<String>> loadPartitionNamesByFilter(WithIdentity<PartitionFilter> partitionFilter)
{
return delegate.getPartitionNamesByFilter(
partitionFilter.getIdentity(),
partitionFilter.getKey().getHiveTableName().getDatabaseName(),
partitionFilter.getKey().getHiveTableName().getTableName(),
partitionFilter.getKey().getPartitionColumnNames(),
partitionFilter.getKey().getPartitionKeysFilter());
}
@Override
public Map<String, Optional<Partition>> getPartitionsByNames(HiveIdentity identity, Table table, List<String> partitionNames)
{
List<WithIdentity<HivePartitionName>> names = partitionNames.stream()
.map(name -> new WithIdentity<>(updateIdentity(identity), hivePartitionName(hiveTableName(table.getDatabaseName(), table.getTableName()), name)))
.collect(toImmutableList());
Map<WithIdentity<HivePartitionName>, Optional<Partition>> all = getAll(partitionCache, names);
ImmutableMap.Builder<String, Optional<Partition>> partitionsByName = ImmutableMap.builder();
for (Entry<WithIdentity<HivePartitionName>, Optional<Partition>> entry : all.entrySet()) {
partitionsByName.put(entry.getKey().getKey().getPartitionName().get(), entry.getValue());
}
return partitionsByName.buildOrThrow();
}
private Optional<Partition> loadPartitionByName(WithIdentity<HivePartitionName> partitionName)
{
HiveTableName hiveTableName = partitionName.getKey().getHiveTableName();
return getTable(partitionName.getIdentity(), hiveTableName.getDatabaseName(), hiveTableName.getTableName())
.flatMap(table -> delegate.getPartition(partitionName.getIdentity(), table, partitionName.getKey().getPartitionValues()));
}
private Map<WithIdentity<HivePartitionName>, Optional<Partition>> loadPartitionsByNames(Iterable<? extends WithIdentity<HivePartitionName>> partitionNames)
{
requireNonNull(partitionNames, "partitionNames is null");
checkArgument(!Iterables.isEmpty(partitionNames), "partitionNames is empty");
WithIdentity<HivePartitionName> firstPartition = Iterables.get(partitionNames, 0);
HiveTableName hiveTableName = firstPartition.getKey().getHiveTableName();
HiveIdentity identity = updateIdentity(firstPartition.getIdentity());
Optional<Table> table = getTable(identity, hiveTableName.getDatabaseName(), hiveTableName.getTableName());
if (table.isEmpty()) {
return stream(partitionNames)
.collect(toImmutableMap(name -> name, name -> Optional.empty()));
}
List<String> partitionsToFetch = new ArrayList<>();
for (WithIdentity<HivePartitionName> partitionName : partitionNames) {
checkArgument(partitionName.getKey().getHiveTableName().equals(hiveTableName), "Expected table name %s but got %s", hiveTableName, partitionName.getKey().getHiveTableName());
checkArgument(identity.equals(partitionName.getIdentity()), "Expected identity %s but got %s", identity, partitionName.getIdentity());
partitionsToFetch.add(partitionName.getKey().getPartitionName().get());
}
ImmutableMap.Builder<WithIdentity<HivePartitionName>, Optional<Partition>> partitions = ImmutableMap.builder();
Map<String, Optional<Partition>> partitionsByNames = delegate.getPartitionsByNames(identity, table.get(), partitionsToFetch);
for (WithIdentity<HivePartitionName> partitionName : partitionNames) {
partitions.put(partitionName, partitionsByNames.getOrDefault(partitionName.getKey().getPartitionName().get(), Optional.empty()));
}
return partitions.buildOrThrow();
}
@Override
public void addPartitions(HiveIdentity identity, String databaseName, String tableName, List<PartitionWithStatistics> partitions)
{
identity = updateIdentity(identity);
try {
delegate.addPartitions(identity, databaseName, tableName, partitions);
}
finally {
// todo do we need to invalidate all partitions?
invalidatePartitionCache(databaseName, tableName);
}
}
@Override
public void dropPartition(HiveIdentity identity, String databaseName, String tableName, List<String> parts, boolean deleteData)
{
identity = updateIdentity(identity);
try {
delegate.dropPartition(identity, databaseName, tableName, parts, deleteData);
}
finally {
invalidatePartitionCache(databaseName, tableName);
}
}
@Override
public void alterPartition(HiveIdentity identity, String databaseName, String tableName, PartitionWithStatistics partition)
{
identity = updateIdentity(identity);
try {
delegate.alterPartition(identity, databaseName, tableName, partition);
}
finally {
invalidatePartitionCache(databaseName, tableName);
}
}
@Override
public void createRole(String role, String grantor)
{
try {
delegate.createRole(role, grantor);
}
finally {
rolesCache.invalidateAll();
}
}
@Override
public void dropRole(String role)
{
try {
delegate.dropRole(role);
}
finally {
rolesCache.invalidateAll();
roleGrantsCache.invalidateAll();
}
}
@Override
public Set<String> listRoles()
{
return get(rolesCache, "");
}
private Set<String> loadRoles()
{
return delegate.listRoles();
}
@Override
public void grantRoles(Set<String> roles, Set<HivePrincipal> grantees, boolean adminOption, HivePrincipal grantor)
{
try {
delegate.grantRoles(roles, grantees, adminOption, grantor);
}
finally {
roleGrantsCache.invalidateAll();
}
}
@Override
public void revokeRoles(Set<String> roles, Set<HivePrincipal> grantees, boolean adminOption, HivePrincipal grantor)
{
try {
delegate.revokeRoles(roles, grantees, adminOption, grantor);
}
finally {
roleGrantsCache.invalidateAll();
}
}
@Override
public Set<RoleGrant> listGrantedPrincipals(String role)
{
return get(grantedPrincipalsCache, role);
}
@Override
public Set<RoleGrant> listRoleGrants(HivePrincipal principal)
{
return get(roleGrantsCache, principal);
}
private Set<RoleGrant> loadRoleGrants(HivePrincipal principal)
{
return delegate.listRoleGrants(principal);
}
private Set<RoleGrant> loadPrincipals(String role)
{
return delegate.listGrantedPrincipals(role);
}
private void invalidatePartitionCache(String databaseName, String tableName)
{
invalidatePartitionCache(databaseName, tableName, partitionName -> true);
}
private void invalidatePartitionCache(String databaseName, String tableName, Predicate<Optional<String>> partitionPredicate)
{
HiveTableName hiveTableName = hiveTableName(databaseName, tableName);
Predicate<WithIdentity<HivePartitionName>> hivePartitionPredicate =
partitionName -> partitionName.getKey().getHiveTableName().equals(hiveTableName) &&
partitionPredicate.test(partitionName.getKey().getPartitionName());
partitionCache.asMap().keySet().stream()
.filter(hivePartitionPredicate)
.forEach(partitionCache::invalidate);
partitionFilterCache.asMap().keySet().stream()
.filter(partitionFilter -> partitionFilter.getKey().getHiveTableName().equals(hiveTableName))
.forEach(partitionFilterCache::invalidate);
partitionStatisticsCache.asMap().keySet().stream()
.filter(hivePartitionPredicate)
.forEach(partitionStatisticsCache::invalidate);
}
@Override
public void grantTablePrivileges(String databaseName, String tableName, String tableOwner, HivePrincipal grantee, HivePrincipal grantor, Set<HivePrivilege> privileges, boolean grantOption)
{
try {
delegate.grantTablePrivileges(databaseName, tableName, tableOwner, grantee, grantor, privileges, grantOption);
}
finally {
invalidateTablePrivilegeCacheEntries(databaseName, tableName, tableOwner, grantee);
}
}
@Override
public void revokeTablePrivileges(String databaseName, String tableName, String tableOwner, HivePrincipal grantee, HivePrincipal grantor, Set<HivePrivilege> privileges, boolean grantOption)
{
try {
delegate.revokeTablePrivileges(databaseName, tableName, tableOwner, grantee, grantor, privileges, grantOption);
}
finally {
invalidateTablePrivilegeCacheEntries(databaseName, tableName, tableOwner, grantee);
}
}
private void invalidateTablePrivilegeCacheEntries(String databaseName, String tableName, String tableOwner, HivePrincipal grantee)
{
// some callers of xxxxTablePrivileges use Optional.of(grantee), some Optional.empty() (to get all privileges), so have to invalidate them both
tablePrivilegesCache.invalidate(new UserTableKey(Optional.of(grantee), databaseName, tableName, Optional.of(tableOwner)));
tablePrivilegesCache.invalidate(new UserTableKey(Optional.empty(), databaseName, tableName, Optional.of(tableOwner)));
}
@Override
public Set<HivePrivilegeInfo> listTablePrivileges(String databaseName, String tableName, Optional<String> tableOwner, Optional<HivePrincipal> principal)
{
return get(tablePrivilegesCache, new UserTableKey(principal, databaseName, tableName, tableOwner));
}
@Override
public Optional<String> getConfigValue(String name)
{
return get(configValuesCache, name);
}
private Optional<String> loadConfigValue(String name)
{
return delegate.getConfigValue(name);
}
@Override
public long openTransaction(HiveIdentity identity)
{
return delegate.openTransaction(identity);
}
@Override
public void commitTransaction(HiveIdentity identity, long transactionId)
{
delegate.commitTransaction(identity, transactionId);
}
@Override
public void abortTransaction(HiveIdentity identity, long transactionId)
{
delegate.abortTransaction(identity, transactionId);
}
@Override
public void sendTransactionHeartbeat(HiveIdentity identity, long transactionId)
{
delegate.sendTransactionHeartbeat(identity, transactionId);
}
@Override
public void acquireSharedReadLock(HiveIdentity identity, String queryId, long transactionId, List<SchemaTableName> fullTables, List<HivePartition> partitions)
{
delegate.acquireSharedReadLock(identity, queryId, transactionId, fullTables, partitions);
}
@Override
public String getValidWriteIds(HiveIdentity identity, List<SchemaTableName> tables, long currentTransactionId)
{
return delegate.getValidWriteIds(identity, tables, currentTransactionId);
}
@Override
public boolean isImpersonationEnabled()
{
return delegate.isImpersonationEnabled();
}
private Set<HivePrivilegeInfo> loadTablePrivileges(String databaseName, String tableName, Optional<String> tableOwner, Optional<HivePrincipal> principal)
{
return delegate.listTablePrivileges(databaseName, tableName, tableOwner, principal);
}
@Override
public long allocateWriteId(HiveIdentity identity, String dbName, String tableName, long transactionId)
{
return delegate.allocateWriteId(identity, dbName, tableName, transactionId);
}
@Override
public void acquireTableWriteLock(HiveIdentity identity, String queryId, long transactionId, String dbName, String tableName, DataOperationType operation, boolean isDynamicPartitionWrite)
{
delegate.acquireTableWriteLock(identity, queryId, transactionId, dbName, tableName, operation, isDynamicPartitionWrite);
}
@Override
public void updateTableWriteId(HiveIdentity identity, String dbName, String tableName, long transactionId, long writeId, OptionalLong rowCountChange)
{
try {
delegate.updateTableWriteId(identity, dbName, tableName, transactionId, writeId, rowCountChange);
}
finally {
invalidateTable(dbName, tableName);
}
}
@Override
public void alterPartitions(HiveIdentity identity, String dbName, String tableName, List<Partition> partitions, long writeId)
{
identity = updateIdentity(identity);
try {
delegate.alterPartitions(identity, dbName, tableName, partitions, writeId);
}
finally {
invalidatePartitionCache(dbName, tableName);
}
}
@Override
public void addDynamicPartitions(HiveIdentity identity, String dbName, String tableName, List<String> partitionNames, long transactionId, long writeId, AcidOperation operation)
{
identity = updateIdentity(identity);
try {
delegate.addDynamicPartitions(identity, dbName, tableName, partitionNames, transactionId, writeId, operation);
}
finally {
invalidatePartitionCache(dbName, tableName);
}
}
@Override
public void alterTransactionalTable(HiveIdentity identity, Table table, long transactionId, long writeId, PrincipalPrivileges principalPrivileges)
{
try {
delegate.alterTransactionalTable(identity, table, transactionId, writeId, principalPrivileges);
}
finally {
invalidateTable(table.getDatabaseName(), table.getTableName());
}
}
private static CacheBuilder<Object, Object> newCacheBuilder(OptionalLong expiresAfterWriteMillis, OptionalLong refreshMillis, long maximumSize, StatsRecording statsRecording)
{
CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder();
if (expiresAfterWriteMillis.isPresent()) {
cacheBuilder = cacheBuilder.expireAfterWrite(expiresAfterWriteMillis.getAsLong(), MILLISECONDS);
}
if (refreshMillis.isPresent() && (expiresAfterWriteMillis.isEmpty() || expiresAfterWriteMillis.getAsLong() > refreshMillis.getAsLong())) {
cacheBuilder = cacheBuilder.refreshAfterWrite(refreshMillis.getAsLong(), MILLISECONDS);
}
cacheBuilder = cacheBuilder.maximumSize(maximumSize);
if (statsRecording == StatsRecording.ENABLED) {
cacheBuilder = cacheBuilder.recordStats();
}
return cacheBuilder;
}
private static class WithIdentity<T>
{
private final HiveIdentity identity;
private final T key;
private final int hashCode;
public WithIdentity(HiveIdentity identity, T key)
{
this.identity = requireNonNull(identity, "identity is null");
this.key = requireNonNull(key, "key is null");
this.hashCode = Objects.hash(identity, key);
}
public HiveIdentity getIdentity()
{
return identity;
}
public T getKey()
{
return key;
}
@Override
public boolean equals(Object o)
{
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
WithIdentity<?> other = (WithIdentity<?>) o;
return hashCode == other.hashCode &&
Objects.equals(identity, other.identity) &&
Objects.equals(key, other.key);
}
@Override
public int hashCode()
{
return hashCode;
}
@Override
public String toString()
{
return toStringHelper(this)
.add("identity", identity)
.add("key", key)
.toString();
}
}
private HiveIdentity updateIdentity(HiveIdentity identity)
{
// remove identity if not doing impersonation
return delegate.isImpersonationEnabled() ? identity : HiveIdentity.none();
}
@Managed
@Nested
public CacheStatsMBean getDatabaseStats()
{
return new CacheStatsMBean(databaseCache);
}
@Managed
@Nested
public CacheStatsMBean getDatabaseNamesStats()
{
return new CacheStatsMBean(databaseNamesCache);
}
@Managed
@Nested
public CacheStatsMBean getTableStats()
{
return new CacheStatsMBean(tableCache);
}
@Managed
@Nested
public CacheStatsMBean getTableNamesStats()
{
return new CacheStatsMBean(tableNamesCache);
}
@Managed
@Nested
public CacheStatsMBean getTableWithParameterStats()
{
return new CacheStatsMBean(tablesWithParameterCache);
}
@Managed
@Nested
public CacheStatsMBean getTableStatisticsStats()
{
return new CacheStatsMBean(tableStatisticsCache);
}
@Managed
@Nested
public CacheStatsMBean getPartitionStatisticsStats()
{
return new CacheStatsMBean(partitionStatisticsCache);
}
@Managed
@Nested
public CacheStatsMBean getViewNamesStats()
{
return new CacheStatsMBean(viewNamesCache);
}
@Managed
@Nested
public CacheStatsMBean getPartitionStats()
{
return new CacheStatsMBean(partitionCache);
}
@Managed
@Nested
public CacheStatsMBean getPartitionFilterStats()
{
return new CacheStatsMBean(partitionFilterCache);
}
@Managed
@Nested
public CacheStatsMBean getTablePrivilegesStats()
{
return new CacheStatsMBean(tablePrivilegesCache);
}
@Managed
@Nested
public CacheStatsMBean getRolesStats()
{
return new CacheStatsMBean(rolesCache);
}
@Managed
@Nested
public CacheStatsMBean getRoleGrantsStats()
{
return new CacheStatsMBean(roleGrantsCache);
}
@Managed
@Nested
public CacheStatsMBean getGrantedPrincipalsStats()
{
return new CacheStatsMBean(grantedPrincipalsCache);
}
@Managed
@Nested
public CacheStatsMBean getConfigValuesStats()
{
return new CacheStatsMBean(configValuesCache);
}
}
| plugin/trino-hive/src/main/java/io/trino/plugin/hive/metastore/cache/CachingHiveMetastore.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.trino.plugin.hive.metastore.cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.SetMultimap;
import com.google.common.util.concurrent.UncheckedExecutionException;
import io.airlift.jmx.CacheStatsMBean;
import io.airlift.units.Duration;
import io.trino.plugin.hive.HivePartition;
import io.trino.plugin.hive.HiveType;
import io.trino.plugin.hive.PartitionNotFoundException;
import io.trino.plugin.hive.PartitionStatistics;
import io.trino.plugin.hive.acid.AcidOperation;
import io.trino.plugin.hive.acid.AcidTransaction;
import io.trino.plugin.hive.authentication.HiveIdentity;
import io.trino.plugin.hive.metastore.Database;
import io.trino.plugin.hive.metastore.HiveMetastore;
import io.trino.plugin.hive.metastore.HivePartitionName;
import io.trino.plugin.hive.metastore.HivePrincipal;
import io.trino.plugin.hive.metastore.HivePrivilegeInfo;
import io.trino.plugin.hive.metastore.HivePrivilegeInfo.HivePrivilege;
import io.trino.plugin.hive.metastore.HiveTableName;
import io.trino.plugin.hive.metastore.Partition;
import io.trino.plugin.hive.metastore.PartitionFilter;
import io.trino.plugin.hive.metastore.PartitionWithStatistics;
import io.trino.plugin.hive.metastore.PrincipalPrivileges;
import io.trino.plugin.hive.metastore.Table;
import io.trino.plugin.hive.metastore.TablesWithParameterCacheKey;
import io.trino.plugin.hive.metastore.UserTableKey;
import io.trino.spi.TrinoException;
import io.trino.spi.connector.SchemaTableName;
import io.trino.spi.connector.TableNotFoundException;
import io.trino.spi.predicate.TupleDomain;
import io.trino.spi.security.RoleGrant;
import io.trino.spi.statistics.ColumnStatisticType;
import io.trino.spi.type.Type;
import org.apache.hadoop.hive.metastore.api.DataOperationType;
import org.weakref.jmx.Managed;
import org.weakref.jmx.Nested;
import javax.annotation.concurrent.ThreadSafe;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.OptionalLong;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.function.Function;
import java.util.function.Predicate;
import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Throwables.throwIfInstanceOf;
import static com.google.common.base.Throwables.throwIfUnchecked;
import static com.google.common.cache.CacheLoader.asyncReloading;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableMap.toImmutableMap;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.collect.ImmutableSetMultimap.toImmutableSetMultimap;
import static com.google.common.collect.Maps.immutableEntry;
import static com.google.common.collect.Streams.stream;
import static com.google.common.util.concurrent.MoreExecutors.newDirectExecutorService;
import static io.trino.plugin.hive.HivePartitionManager.extractPartitionValues;
import static io.trino.plugin.hive.metastore.HivePartitionName.hivePartitionName;
import static io.trino.plugin.hive.metastore.HiveTableName.hiveTableName;
import static io.trino.plugin.hive.metastore.MetastoreUtil.makePartitionName;
import static io.trino.plugin.hive.metastore.PartitionFilter.partitionFilter;
import static io.trino.plugin.hive.metastore.cache.CachingHiveMetastoreConfig.isCacheEnabled;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.apache.hadoop.hive.common.FileUtils.makePartName;
/**
* Hive Metastore Cache
*/
@ThreadSafe
public class CachingHiveMetastore
implements HiveMetastore
{
public enum StatsRecording
{
ENABLED,
DISABLED
}
protected final HiveMetastore delegate;
private final LoadingCache<String, Optional<Database>> databaseCache;
private final LoadingCache<String, List<String>> databaseNamesCache;
private final LoadingCache<WithIdentity<HiveTableName>, Optional<Table>> tableCache;
private final LoadingCache<String, List<String>> tableNamesCache;
private final LoadingCache<TablesWithParameterCacheKey, List<String>> tablesWithParameterCache;
private final LoadingCache<WithIdentity<HiveTableName>, PartitionStatistics> tableStatisticsCache;
private final LoadingCache<WithIdentity<HivePartitionName>, PartitionStatistics> partitionStatisticsCache;
private final LoadingCache<String, List<String>> viewNamesCache;
private final LoadingCache<WithIdentity<HivePartitionName>, Optional<Partition>> partitionCache;
private final LoadingCache<WithIdentity<PartitionFilter>, Optional<List<String>>> partitionFilterCache;
private final LoadingCache<UserTableKey, Set<HivePrivilegeInfo>> tablePrivilegesCache;
private final LoadingCache<String, Set<String>> rolesCache;
private final LoadingCache<HivePrincipal, Set<RoleGrant>> roleGrantsCache;
private final LoadingCache<String, Set<RoleGrant>> grantedPrincipalsCache;
private final LoadingCache<String, Optional<String>> configValuesCache;
public static CachingHiveMetastore cachingHiveMetastore(HiveMetastore delegate, Executor executor, CachingHiveMetastoreConfig config)
{
return cachingHiveMetastore(
delegate,
executor,
config.getMetastoreCacheTtl(),
config.getMetastoreRefreshInterval(),
config.getMetastoreCacheMaximumSize());
}
public static CachingHiveMetastore cachingHiveMetastore(HiveMetastore delegate, Executor executor, Duration cacheTtl, Optional<Duration> refreshInterval, long maximumSize)
{
checkState(
isCacheEnabled(cacheTtl, maximumSize),
format("Invalid cache parameters (cacheTtl: %s, maxSize: %s)", cacheTtl, maximumSize));
return new CachingHiveMetastore(
delegate,
executor,
OptionalLong.of(cacheTtl.toMillis()),
refreshInterval
.map(Duration::toMillis)
.map(OptionalLong::of)
.orElseGet(OptionalLong::empty),
maximumSize,
StatsRecording.ENABLED);
}
public static CachingHiveMetastore memoizeMetastore(HiveMetastore delegate, long maximumSize)
{
return new CachingHiveMetastore(
delegate,
newDirectExecutorService(),
OptionalLong.empty(),
OptionalLong.empty(),
maximumSize,
StatsRecording.DISABLED);
}
protected CachingHiveMetastore(HiveMetastore delegate, Executor executor, OptionalLong expiresAfterWriteMillis, OptionalLong refreshMills, long maximumSize, StatsRecording statsRecording)
{
this.delegate = requireNonNull(delegate, "delegate is null");
requireNonNull(executor, "executor is null");
databaseNamesCache = newCacheBuilder(expiresAfterWriteMillis, refreshMills, maximumSize, statsRecording)
.build(asyncReloading(CacheLoader.from(this::loadAllDatabases), executor));
databaseCache = newCacheBuilder(expiresAfterWriteMillis, refreshMills, maximumSize, statsRecording)
.build(asyncReloading(CacheLoader.from(this::loadDatabase), executor));
tableNamesCache = newCacheBuilder(expiresAfterWriteMillis, refreshMills, maximumSize, statsRecording)
.build(asyncReloading(CacheLoader.from(this::loadAllTables), executor));
tablesWithParameterCache = newCacheBuilder(expiresAfterWriteMillis, refreshMills, maximumSize, statsRecording)
.build(asyncReloading(CacheLoader.from(this::loadTablesMatchingParameter), executor));
tableStatisticsCache = newCacheBuilder(expiresAfterWriteMillis, refreshMills, maximumSize, statsRecording)
.build(asyncReloading(CacheLoader.from(this::loadTableColumnStatistics), executor));
// disable refresh since it can't use the bulk loading and causes too many requests
partitionStatisticsCache = newCacheBuilder(expiresAfterWriteMillis, OptionalLong.empty(), maximumSize, statsRecording)
.build(asyncReloading(new CacheLoader<>()
{
@Override
public PartitionStatistics load(WithIdentity<HivePartitionName> key)
{
return loadPartitionColumnStatistics(key);
}
@Override
public Map<WithIdentity<HivePartitionName>, PartitionStatistics> loadAll(Iterable<? extends WithIdentity<HivePartitionName>> keys)
{
return loadPartitionColumnStatistics(keys);
}
}, executor));
tableCache = newCacheBuilder(expiresAfterWriteMillis, refreshMills, maximumSize, statsRecording)
.build(asyncReloading(CacheLoader.from(this::loadTable), executor));
viewNamesCache = newCacheBuilder(expiresAfterWriteMillis, refreshMills, maximumSize, statsRecording)
.build(asyncReloading(CacheLoader.from(this::loadAllViews), executor));
partitionFilterCache = newCacheBuilder(expiresAfterWriteMillis, refreshMills, maximumSize, statsRecording)
.build(asyncReloading(CacheLoader.from(this::loadPartitionNamesByFilter), executor));
// disable refresh since it can't use the bulk loading and causes too many requests
partitionCache = newCacheBuilder(expiresAfterWriteMillis, OptionalLong.empty(), maximumSize, statsRecording)
.build(asyncReloading(new CacheLoader<>()
{
@Override
public Optional<Partition> load(WithIdentity<HivePartitionName> partitionName)
{
return loadPartitionByName(partitionName);
}
@Override
public Map<WithIdentity<HivePartitionName>, Optional<Partition>> loadAll(Iterable<? extends WithIdentity<HivePartitionName>> partitionNames)
{
return loadPartitionsByNames(partitionNames);
}
}, executor));
tablePrivilegesCache = newCacheBuilder(expiresAfterWriteMillis, refreshMills, maximumSize, statsRecording)
.build(asyncReloading(CacheLoader.from(key -> loadTablePrivileges(key.getDatabase(), key.getTable(), key.getOwner(), key.getPrincipal())), executor));
rolesCache = newCacheBuilder(expiresAfterWriteMillis, refreshMills, maximumSize, statsRecording)
.build(asyncReloading(CacheLoader.from(this::loadRoles), executor));
roleGrantsCache = newCacheBuilder(expiresAfterWriteMillis, refreshMills, maximumSize, statsRecording)
.build(asyncReloading(CacheLoader.from(this::loadRoleGrants), executor));
grantedPrincipalsCache = newCacheBuilder(expiresAfterWriteMillis, refreshMills, maximumSize, statsRecording)
.build(asyncReloading(CacheLoader.from(this::loadPrincipals), executor));
configValuesCache = newCacheBuilder(expiresAfterWriteMillis, refreshMills, maximumSize, statsRecording)
.build(asyncReloading(CacheLoader.from(this::loadConfigValue), executor));
}
@Managed
public void flushCache()
{
databaseNamesCache.invalidateAll();
tableNamesCache.invalidateAll();
viewNamesCache.invalidateAll();
databaseCache.invalidateAll();
tableCache.invalidateAll();
partitionCache.invalidateAll();
partitionFilterCache.invalidateAll();
tablePrivilegesCache.invalidateAll();
tableStatisticsCache.invalidateAll();
partitionStatisticsCache.invalidateAll();
rolesCache.invalidateAll();
}
public void flushPartitionCache(String schemaName, String tableName, List<String> partitionColumns, List<String> partitionValues)
{
requireNonNull(schemaName, "schemaName is null");
requireNonNull(tableName, "tableName is null");
requireNonNull(partitionColumns, "partitionColumns is null");
requireNonNull(partitionValues, "partitionValues is null");
String providedPartitionName = makePartName(partitionColumns, partitionValues);
invalidatePartitionCache(schemaName, tableName, partitionNameToCheck -> partitionNameToCheck.map(value -> value.equals(providedPartitionName)).orElse(false));
}
private static <K, V> V get(LoadingCache<K, V> cache, K key)
{
try {
return cache.getUnchecked(key);
}
catch (UncheckedExecutionException e) {
throwIfInstanceOf(e.getCause(), TrinoException.class);
throw e;
}
}
private static <K, V> Map<K, V> getAll(LoadingCache<K, V> cache, Iterable<K> keys)
{
try {
return cache.getAll(keys);
}
catch (ExecutionException | UncheckedExecutionException e) {
throwIfInstanceOf(e.getCause(), TrinoException.class);
throwIfUnchecked(e);
throw new UncheckedExecutionException(e);
}
}
@Override
public Optional<Database> getDatabase(String databaseName)
{
return get(databaseCache, databaseName);
}
private Optional<Database> loadDatabase(String databaseName)
{
return delegate.getDatabase(databaseName);
}
@Override
public List<String> getAllDatabases()
{
return get(databaseNamesCache, "");
}
private List<String> loadAllDatabases()
{
return delegate.getAllDatabases();
}
private Table getExistingTable(HiveIdentity identity, String databaseName, String tableName)
{
return getTable(identity, databaseName, tableName)
.orElseThrow(() -> new TableNotFoundException(new SchemaTableName(databaseName, tableName)));
}
@Override
public Optional<Table> getTable(HiveIdentity identity, String databaseName, String tableName)
{
identity = updateIdentity(identity);
return get(tableCache, new WithIdentity<>(identity, hiveTableName(databaseName, tableName)));
}
@Override
public Set<ColumnStatisticType> getSupportedColumnStatistics(Type type)
{
return delegate.getSupportedColumnStatistics(type);
}
private Optional<Table> loadTable(WithIdentity<HiveTableName> hiveTableName)
{
return delegate.getTable(hiveTableName.getIdentity(), hiveTableName.key.getDatabaseName(), hiveTableName.key.getTableName());
}
@Override
public PartitionStatistics getTableStatistics(HiveIdentity identity, Table table)
{
return get(tableStatisticsCache, new WithIdentity<>(updateIdentity(identity), hiveTableName(table.getDatabaseName(), table.getTableName())));
}
private PartitionStatistics loadTableColumnStatistics(WithIdentity<HiveTableName> hiveTableName)
{
HiveTableName tableName = hiveTableName.getKey();
Table table = getExistingTable(hiveTableName.getIdentity(), tableName.getDatabaseName(), tableName.getTableName());
return delegate.getTableStatistics(hiveTableName.getIdentity(), table);
}
@Override
public Map<String, PartitionStatistics> getPartitionStatistics(HiveIdentity identity, Table table, List<Partition> partitions)
{
HiveTableName hiveTableName = hiveTableName(table.getDatabaseName(), table.getTableName());
List<WithIdentity<HivePartitionName>> partitionNames = partitions.stream()
.map(partition -> new WithIdentity<>(updateIdentity(identity), hivePartitionName(hiveTableName, makePartitionName(table, partition))))
.collect(toImmutableList());
Map<WithIdentity<HivePartitionName>, PartitionStatistics> statistics = getAll(partitionStatisticsCache, partitionNames);
return statistics.entrySet()
.stream()
.collect(toImmutableMap(entry -> entry.getKey().getKey().getPartitionName().get(), Entry::getValue));
}
private PartitionStatistics loadPartitionColumnStatistics(WithIdentity<HivePartitionName> partition)
{
HiveTableName tableName = partition.getKey().getHiveTableName();
String partitionName = partition.getKey().getPartitionName().get();
Table table = getExistingTable(partition.getIdentity(), tableName.getDatabaseName(), tableName.getTableName());
Map<String, PartitionStatistics> partitionStatistics = delegate.getPartitionStatistics(
partition.getIdentity(),
table,
ImmutableList.of(getExistingPartition(partition.getIdentity(), table, partition.getKey().getPartitionValues())));
return partitionStatistics.get(partitionName);
}
private Map<WithIdentity<HivePartitionName>, PartitionStatistics> loadPartitionColumnStatistics(Iterable<? extends WithIdentity<HivePartitionName>> keys)
{
SetMultimap<WithIdentity<HiveTableName>, WithIdentity<HivePartitionName>> tablePartitions = stream(keys)
.collect(toImmutableSetMultimap(value -> new WithIdentity<>(value.getIdentity(), value.getKey().getHiveTableName()), Function.identity()));
ImmutableMap.Builder<WithIdentity<HivePartitionName>, PartitionStatistics> result = ImmutableMap.builder();
tablePartitions.keySet().forEach(tableName -> {
Set<WithIdentity<HivePartitionName>> partitionNames = tablePartitions.get(tableName);
Set<String> partitionNameStrings = partitionNames.stream()
.map(partitionName -> partitionName.getKey().getPartitionName().get())
.collect(toImmutableSet());
Table table = getExistingTable(tableName.getIdentity(), tableName.getKey().getDatabaseName(), tableName.getKey().getTableName());
List<Partition> partitions = getExistingPartitionsByNames(tableName.getIdentity(), table, ImmutableList.copyOf(partitionNameStrings));
Map<String, PartitionStatistics> statisticsByPartitionName = delegate.getPartitionStatistics(tableName.getIdentity(), table, partitions);
for (WithIdentity<HivePartitionName> partitionName : partitionNames) {
String stringNameForPartition = partitionName.getKey().getPartitionName().get();
result.put(partitionName, statisticsByPartitionName.get(stringNameForPartition));
}
});
return result.buildOrThrow();
}
@Override
public void updateTableStatistics(HiveIdentity identity, String databaseName, String tableName, AcidTransaction transaction, Function<PartitionStatistics, PartitionStatistics> update)
{
identity = updateIdentity(identity);
try {
delegate.updateTableStatistics(identity, databaseName, tableName, transaction, update);
}
finally {
HiveTableName hiveTableName = hiveTableName(databaseName, tableName);
tableStatisticsCache.invalidate(new WithIdentity<>(identity, hiveTableName));
// basic stats are stored as table properties
tableCache.invalidate(new WithIdentity<>(identity, hiveTableName));
}
}
@Override
public void updatePartitionStatistics(HiveIdentity identity, Table table, String partitionName, Function<PartitionStatistics, PartitionStatistics> update)
{
identity = updateIdentity(identity);
try {
delegate.updatePartitionStatistics(identity, table, partitionName, update);
}
finally {
HivePartitionName hivePartitionName = hivePartitionName(hiveTableName(table.getDatabaseName(), table.getTableName()), partitionName);
partitionStatisticsCache.invalidate(new WithIdentity<>(identity, hivePartitionName));
// basic stats are stored as partition properties
partitionCache.invalidate(new WithIdentity<>(identity, hivePartitionName));
}
}
@Override
public void updatePartitionStatistics(HiveIdentity identity, Table table, Map<String, Function<PartitionStatistics, PartitionStatistics>> updates)
{
try {
delegate.updatePartitionStatistics(updateIdentity(identity), table, updates);
}
finally {
HiveIdentity hiveIdentity = updateIdentity(identity);
updates.forEach((partitionName, update) -> {
HivePartitionName hivePartitionName = hivePartitionName(hiveTableName(table.getDatabaseName(), table.getTableName()), partitionName);
partitionStatisticsCache.invalidate(new WithIdentity<>(hiveIdentity, hivePartitionName));
// basic stats are stored as partition properties
partitionCache.invalidate(new WithIdentity<>(hiveIdentity, hivePartitionName));
});
}
}
@Override
public List<String> getAllTables(String databaseName)
{
return get(tableNamesCache, databaseName);
}
private List<String> loadAllTables(String databaseName)
{
return delegate.getAllTables(databaseName);
}
@Override
public List<String> getTablesWithParameter(String databaseName, String parameterKey, String parameterValue)
{
TablesWithParameterCacheKey key = new TablesWithParameterCacheKey(databaseName, parameterKey, parameterValue);
return get(tablesWithParameterCache, key);
}
private List<String> loadTablesMatchingParameter(TablesWithParameterCacheKey key)
{
return delegate.getTablesWithParameter(key.getDatabaseName(), key.getParameterKey(), key.getParameterValue());
}
@Override
public List<String> getAllViews(String databaseName)
{
return get(viewNamesCache, databaseName);
}
private List<String> loadAllViews(String databaseName)
{
return delegate.getAllViews(databaseName);
}
@Override
public void createDatabase(HiveIdentity identity, Database database)
{
identity = updateIdentity(identity);
try {
delegate.createDatabase(identity, database);
}
finally {
invalidateDatabase(database.getDatabaseName());
}
}
@Override
public void dropDatabase(HiveIdentity identity, String databaseName, boolean deleteData)
{
identity = updateIdentity(identity);
try {
delegate.dropDatabase(identity, databaseName, deleteData);
}
finally {
invalidateDatabase(databaseName);
}
}
@Override
public void renameDatabase(HiveIdentity identity, String databaseName, String newDatabaseName)
{
identity = updateIdentity(identity);
try {
delegate.renameDatabase(identity, databaseName, newDatabaseName);
}
finally {
invalidateDatabase(databaseName);
invalidateDatabase(newDatabaseName);
}
}
@Override
public void setDatabaseOwner(HiveIdentity identity, String databaseName, HivePrincipal principal)
{
identity = updateIdentity(identity);
try {
delegate.setDatabaseOwner(identity, databaseName, principal);
}
finally {
invalidateDatabase(databaseName);
}
}
protected void invalidateDatabase(String databaseName)
{
databaseCache.invalidate(databaseName);
databaseNamesCache.invalidateAll();
}
@Override
public void createTable(HiveIdentity identity, Table table, PrincipalPrivileges principalPrivileges)
{
identity = updateIdentity(identity);
try {
delegate.createTable(identity, table, principalPrivileges);
}
finally {
invalidateTable(table.getDatabaseName(), table.getTableName());
}
}
@Override
public void dropTable(HiveIdentity identity, String databaseName, String tableName, boolean deleteData)
{
identity = updateIdentity(identity);
try {
delegate.dropTable(identity, databaseName, tableName, deleteData);
}
finally {
invalidateTable(databaseName, tableName);
}
}
@Override
public void replaceTable(HiveIdentity identity, String databaseName, String tableName, Table newTable, PrincipalPrivileges principalPrivileges)
{
identity = updateIdentity(identity);
try {
delegate.replaceTable(identity, databaseName, tableName, newTable, principalPrivileges);
}
finally {
invalidateTable(databaseName, tableName);
invalidateTable(newTable.getDatabaseName(), newTable.getTableName());
}
}
@Override
public void renameTable(HiveIdentity identity, String databaseName, String tableName, String newDatabaseName, String newTableName)
{
identity = updateIdentity(identity);
try {
delegate.renameTable(identity, databaseName, tableName, newDatabaseName, newTableName);
}
finally {
invalidateTable(databaseName, tableName);
invalidateTable(newDatabaseName, newTableName);
}
}
@Override
public void commentTable(HiveIdentity identity, String databaseName, String tableName, Optional<String> comment)
{
identity = updateIdentity(identity);
try {
delegate.commentTable(identity, databaseName, tableName, comment);
}
finally {
invalidateTable(databaseName, tableName);
}
}
@Override
public void setTableOwner(HiveIdentity identity, String databaseName, String tableName, HivePrincipal principal)
{
identity = updateIdentity(identity);
try {
delegate.setTableOwner(identity, databaseName, tableName, principal);
}
finally {
invalidateTable(databaseName, tableName);
}
}
@Override
public void commentColumn(HiveIdentity identity, String databaseName, String tableName, String columnName, Optional<String> comment)
{
identity = updateIdentity(identity);
try {
delegate.commentColumn(identity, databaseName, tableName, columnName, comment);
}
finally {
invalidateTable(databaseName, tableName);
}
}
@Override
public void addColumn(HiveIdentity identity, String databaseName, String tableName, String columnName, HiveType columnType, String columnComment)
{
identity = updateIdentity(identity);
try {
delegate.addColumn(identity, databaseName, tableName, columnName, columnType, columnComment);
}
finally {
invalidateTable(databaseName, tableName);
}
}
@Override
public void renameColumn(HiveIdentity identity, String databaseName, String tableName, String oldColumnName, String newColumnName)
{
identity = updateIdentity(identity);
try {
delegate.renameColumn(identity, databaseName, tableName, oldColumnName, newColumnName);
}
finally {
invalidateTable(databaseName, tableName);
}
}
@Override
public void dropColumn(HiveIdentity identity, String databaseName, String tableName, String columnName)
{
identity = updateIdentity(identity);
try {
delegate.dropColumn(identity, databaseName, tableName, columnName);
}
finally {
invalidateTable(databaseName, tableName);
}
}
protected void invalidateTable(String databaseName, String tableName)
{
invalidateTableCache(databaseName, tableName);
tableNamesCache.invalidate(databaseName);
viewNamesCache.invalidate(databaseName);
tablePrivilegesCache.asMap().keySet().stream()
.filter(userTableKey -> userTableKey.matches(databaseName, tableName))
.forEach(tablePrivilegesCache::invalidate);
invalidateTableStatisticsCache(databaseName, tableName);
invalidatePartitionCache(databaseName, tableName);
}
private void invalidateTableCache(String databaseName, String tableName)
{
tableCache.asMap().keySet().stream()
.filter(table -> table.getKey().getDatabaseName().equals(databaseName) && table.getKey().getTableName().equals(tableName))
.forEach(tableCache::invalidate);
}
private void invalidateTableStatisticsCache(String databaseName, String tableName)
{
tableStatisticsCache.asMap().keySet().stream()
.filter(table -> table.getKey().getDatabaseName().equals(databaseName) && table.getKey().getTableName().equals(tableName))
.forEach(tableCache::invalidate);
}
private Partition getExistingPartition(HiveIdentity identity, Table table, List<String> partitionValues)
{
return getPartition(identity, table, partitionValues)
.orElseThrow(() -> new PartitionNotFoundException(table.getSchemaTableName(), partitionValues));
}
private List<Partition> getExistingPartitionsByNames(HiveIdentity identity, Table table, List<String> partitionNames)
{
Map<String, Partition> partitions = getPartitionsByNames(identity, table, partitionNames).entrySet().stream()
.map(entry -> immutableEntry(entry.getKey(), entry.getValue().orElseThrow(() ->
new PartitionNotFoundException(table.getSchemaTableName(), extractPartitionValues(entry.getKey())))))
.collect(toImmutableMap(Map.Entry::getKey, Map.Entry::getValue));
return partitionNames.stream()
.map(partitions::get)
.collect(toImmutableList());
}
@Override
public Optional<Partition> getPartition(HiveIdentity identity, Table table, List<String> partitionValues)
{
return get(partitionCache, new WithIdentity<>(updateIdentity(identity), hivePartitionName(hiveTableName(table.getDatabaseName(), table.getTableName()), partitionValues)));
}
@Override
public Optional<List<String>> getPartitionNamesByFilter(HiveIdentity identity, String databaseName, String tableName, List<String> columnNames, TupleDomain<String> partitionKeysFilter)
{
return get(partitionFilterCache, new WithIdentity<>(updateIdentity(identity), partitionFilter(databaseName, tableName, columnNames, partitionKeysFilter)));
}
private Optional<List<String>> loadPartitionNamesByFilter(WithIdentity<PartitionFilter> partitionFilter)
{
return delegate.getPartitionNamesByFilter(
partitionFilter.getIdentity(),
partitionFilter.getKey().getHiveTableName().getDatabaseName(),
partitionFilter.getKey().getHiveTableName().getTableName(),
partitionFilter.getKey().getPartitionColumnNames(),
partitionFilter.getKey().getPartitionKeysFilter());
}
@Override
public Map<String, Optional<Partition>> getPartitionsByNames(HiveIdentity identity, Table table, List<String> partitionNames)
{
List<WithIdentity<HivePartitionName>> names = partitionNames.stream()
.map(name -> new WithIdentity<>(updateIdentity(identity), hivePartitionName(hiveTableName(table.getDatabaseName(), table.getTableName()), name)))
.collect(toImmutableList());
Map<WithIdentity<HivePartitionName>, Optional<Partition>> all = getAll(partitionCache, names);
ImmutableMap.Builder<String, Optional<Partition>> partitionsByName = ImmutableMap.builder();
for (Entry<WithIdentity<HivePartitionName>, Optional<Partition>> entry : all.entrySet()) {
partitionsByName.put(entry.getKey().getKey().getPartitionName().get(), entry.getValue());
}
return partitionsByName.buildOrThrow();
}
private Optional<Partition> loadPartitionByName(WithIdentity<HivePartitionName> partitionName)
{
HiveTableName hiveTableName = partitionName.getKey().getHiveTableName();
return getTable(partitionName.getIdentity(), hiveTableName.getDatabaseName(), hiveTableName.getTableName())
.flatMap(table -> delegate.getPartition(partitionName.getIdentity(), table, partitionName.getKey().getPartitionValues()));
}
private Map<WithIdentity<HivePartitionName>, Optional<Partition>> loadPartitionsByNames(Iterable<? extends WithIdentity<HivePartitionName>> partitionNames)
{
requireNonNull(partitionNames, "partitionNames is null");
checkArgument(!Iterables.isEmpty(partitionNames), "partitionNames is empty");
WithIdentity<HivePartitionName> firstPartition = Iterables.get(partitionNames, 0);
HiveTableName hiveTableName = firstPartition.getKey().getHiveTableName();
HiveIdentity identity = updateIdentity(firstPartition.getIdentity());
Optional<Table> table = getTable(identity, hiveTableName.getDatabaseName(), hiveTableName.getTableName());
if (table.isEmpty()) {
return stream(partitionNames)
.collect(toImmutableMap(name -> name, name -> Optional.empty()));
}
List<String> partitionsToFetch = new ArrayList<>();
for (WithIdentity<HivePartitionName> partitionName : partitionNames) {
checkArgument(partitionName.getKey().getHiveTableName().equals(hiveTableName), "Expected table name %s but got %s", hiveTableName, partitionName.getKey().getHiveTableName());
checkArgument(identity.equals(partitionName.getIdentity()), "Expected identity %s but got %s", identity, partitionName.getIdentity());
partitionsToFetch.add(partitionName.getKey().getPartitionName().get());
}
ImmutableMap.Builder<WithIdentity<HivePartitionName>, Optional<Partition>> partitions = ImmutableMap.builder();
Map<String, Optional<Partition>> partitionsByNames = delegate.getPartitionsByNames(identity, table.get(), partitionsToFetch);
for (WithIdentity<HivePartitionName> partitionName : partitionNames) {
partitions.put(partitionName, partitionsByNames.getOrDefault(partitionName.getKey().getPartitionName().get(), Optional.empty()));
}
return partitions.buildOrThrow();
}
@Override
public void addPartitions(HiveIdentity identity, String databaseName, String tableName, List<PartitionWithStatistics> partitions)
{
identity = updateIdentity(identity);
try {
delegate.addPartitions(identity, databaseName, tableName, partitions);
}
finally {
// todo do we need to invalidate all partitions?
invalidatePartitionCache(databaseName, tableName);
}
}
@Override
public void dropPartition(HiveIdentity identity, String databaseName, String tableName, List<String> parts, boolean deleteData)
{
identity = updateIdentity(identity);
try {
delegate.dropPartition(identity, databaseName, tableName, parts, deleteData);
}
finally {
invalidatePartitionCache(databaseName, tableName);
}
}
@Override
public void alterPartition(HiveIdentity identity, String databaseName, String tableName, PartitionWithStatistics partition)
{
identity = updateIdentity(identity);
try {
delegate.alterPartition(identity, databaseName, tableName, partition);
}
finally {
invalidatePartitionCache(databaseName, tableName);
}
}
@Override
public void createRole(String role, String grantor)
{
try {
delegate.createRole(role, grantor);
}
finally {
rolesCache.invalidateAll();
}
}
@Override
public void dropRole(String role)
{
try {
delegate.dropRole(role);
}
finally {
rolesCache.invalidateAll();
roleGrantsCache.invalidateAll();
}
}
@Override
public Set<String> listRoles()
{
return get(rolesCache, "");
}
private Set<String> loadRoles()
{
return delegate.listRoles();
}
@Override
public void grantRoles(Set<String> roles, Set<HivePrincipal> grantees, boolean adminOption, HivePrincipal grantor)
{
try {
delegate.grantRoles(roles, grantees, adminOption, grantor);
}
finally {
roleGrantsCache.invalidateAll();
}
}
@Override
public void revokeRoles(Set<String> roles, Set<HivePrincipal> grantees, boolean adminOption, HivePrincipal grantor)
{
try {
delegate.revokeRoles(roles, grantees, adminOption, grantor);
}
finally {
roleGrantsCache.invalidateAll();
}
}
@Override
public Set<RoleGrant> listGrantedPrincipals(String role)
{
return get(grantedPrincipalsCache, role);
}
@Override
public Set<RoleGrant> listRoleGrants(HivePrincipal principal)
{
return get(roleGrantsCache, principal);
}
private Set<RoleGrant> loadRoleGrants(HivePrincipal principal)
{
return delegate.listRoleGrants(principal);
}
private Set<RoleGrant> loadPrincipals(String role)
{
return delegate.listGrantedPrincipals(role);
}
private void invalidatePartitionCache(String databaseName, String tableName)
{
invalidatePartitionCache(databaseName, tableName, partitionName -> true);
}
private void invalidatePartitionCache(String databaseName, String tableName, Predicate<Optional<String>> partitionPredicate)
{
HiveTableName hiveTableName = hiveTableName(databaseName, tableName);
Predicate<WithIdentity<HivePartitionName>> hivePartitionPredicate =
partitionName -> partitionName.getKey().getHiveTableName().equals(hiveTableName) &&
partitionPredicate.test(partitionName.getKey().getPartitionName());
partitionCache.asMap().keySet().stream()
.filter(hivePartitionPredicate)
.forEach(partitionCache::invalidate);
partitionFilterCache.asMap().keySet().stream()
.filter(partitionFilter -> partitionFilter.getKey().getHiveTableName().equals(hiveTableName))
.forEach(partitionFilterCache::invalidate);
partitionStatisticsCache.asMap().keySet().stream()
.filter(hivePartitionPredicate)
.forEach(partitionStatisticsCache::invalidate);
}
@Override
public void grantTablePrivileges(String databaseName, String tableName, String tableOwner, HivePrincipal grantee, HivePrincipal grantor, Set<HivePrivilege> privileges, boolean grantOption)
{
try {
delegate.grantTablePrivileges(databaseName, tableName, tableOwner, grantee, grantor, privileges, grantOption);
}
finally {
invalidateTablePrivilegeCacheEntries(databaseName, tableName, tableOwner, grantee);
}
}
@Override
public void revokeTablePrivileges(String databaseName, String tableName, String tableOwner, HivePrincipal grantee, HivePrincipal grantor, Set<HivePrivilege> privileges, boolean grantOption)
{
try {
delegate.revokeTablePrivileges(databaseName, tableName, tableOwner, grantee, grantor, privileges, grantOption);
}
finally {
invalidateTablePrivilegeCacheEntries(databaseName, tableName, tableOwner, grantee);
}
}
private void invalidateTablePrivilegeCacheEntries(String databaseName, String tableName, String tableOwner, HivePrincipal grantee)
{
// some callers of xxxxTablePrivileges use Optional.of(grantee), some Optional.empty() (to get all privileges), so have to invalidate them both
tablePrivilegesCache.invalidate(new UserTableKey(Optional.of(grantee), databaseName, tableName, Optional.of(tableOwner)));
tablePrivilegesCache.invalidate(new UserTableKey(Optional.empty(), databaseName, tableName, Optional.of(tableOwner)));
}
@Override
public Set<HivePrivilegeInfo> listTablePrivileges(String databaseName, String tableName, Optional<String> tableOwner, Optional<HivePrincipal> principal)
{
return get(tablePrivilegesCache, new UserTableKey(principal, databaseName, tableName, tableOwner));
}
@Override
public Optional<String> getConfigValue(String name)
{
return get(configValuesCache, name);
}
private Optional<String> loadConfigValue(String name)
{
return delegate.getConfigValue(name);
}
@Override
public long openTransaction(HiveIdentity identity)
{
return delegate.openTransaction(identity);
}
@Override
public void commitTransaction(HiveIdentity identity, long transactionId)
{
delegate.commitTransaction(identity, transactionId);
}
@Override
public void abortTransaction(HiveIdentity identity, long transactionId)
{
delegate.abortTransaction(identity, transactionId);
}
@Override
public void sendTransactionHeartbeat(HiveIdentity identity, long transactionId)
{
delegate.sendTransactionHeartbeat(identity, transactionId);
}
@Override
public void acquireSharedReadLock(HiveIdentity identity, String queryId, long transactionId, List<SchemaTableName> fullTables, List<HivePartition> partitions)
{
delegate.acquireSharedReadLock(identity, queryId, transactionId, fullTables, partitions);
}
@Override
public String getValidWriteIds(HiveIdentity identity, List<SchemaTableName> tables, long currentTransactionId)
{
return delegate.getValidWriteIds(identity, tables, currentTransactionId);
}
@Override
public boolean isImpersonationEnabled()
{
return delegate.isImpersonationEnabled();
}
private Set<HivePrivilegeInfo> loadTablePrivileges(String databaseName, String tableName, Optional<String> tableOwner, Optional<HivePrincipal> principal)
{
return delegate.listTablePrivileges(databaseName, tableName, tableOwner, principal);
}
@Override
public long allocateWriteId(HiveIdentity identity, String dbName, String tableName, long transactionId)
{
return delegate.allocateWriteId(identity, dbName, tableName, transactionId);
}
@Override
public void acquireTableWriteLock(HiveIdentity identity, String queryId, long transactionId, String dbName, String tableName, DataOperationType operation, boolean isDynamicPartitionWrite)
{
delegate.acquireTableWriteLock(identity, queryId, transactionId, dbName, tableName, operation, isDynamicPartitionWrite);
}
@Override
public void updateTableWriteId(HiveIdentity identity, String dbName, String tableName, long transactionId, long writeId, OptionalLong rowCountChange)
{
try {
delegate.updateTableWriteId(identity, dbName, tableName, transactionId, writeId, rowCountChange);
}
finally {
invalidateTable(dbName, tableName);
}
}
@Override
public void alterPartitions(HiveIdentity identity, String dbName, String tableName, List<Partition> partitions, long writeId)
{
identity = updateIdentity(identity);
try {
delegate.alterPartitions(identity, dbName, tableName, partitions, writeId);
}
finally {
invalidatePartitionCache(dbName, tableName);
}
}
@Override
public void addDynamicPartitions(HiveIdentity identity, String dbName, String tableName, List<String> partitionNames, long transactionId, long writeId, AcidOperation operation)
{
identity = updateIdentity(identity);
try {
delegate.addDynamicPartitions(identity, dbName, tableName, partitionNames, transactionId, writeId, operation);
}
finally {
invalidatePartitionCache(dbName, tableName);
}
}
@Override
public void alterTransactionalTable(HiveIdentity identity, Table table, long transactionId, long writeId, PrincipalPrivileges principalPrivileges)
{
try {
delegate.alterTransactionalTable(identity, table, transactionId, writeId, principalPrivileges);
}
finally {
invalidateTable(table.getDatabaseName(), table.getTableName());
}
}
private static CacheBuilder<Object, Object> newCacheBuilder(OptionalLong expiresAfterWriteMillis, OptionalLong refreshMillis, long maximumSize, StatsRecording statsRecording)
{
CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder();
if (expiresAfterWriteMillis.isPresent()) {
cacheBuilder = cacheBuilder.expireAfterWrite(expiresAfterWriteMillis.getAsLong(), MILLISECONDS);
}
if (refreshMillis.isPresent() && (expiresAfterWriteMillis.isEmpty() || expiresAfterWriteMillis.getAsLong() > refreshMillis.getAsLong())) {
cacheBuilder = cacheBuilder.refreshAfterWrite(refreshMillis.getAsLong(), MILLISECONDS);
}
cacheBuilder = cacheBuilder.maximumSize(maximumSize);
if (statsRecording == StatsRecording.ENABLED) {
cacheBuilder = cacheBuilder.recordStats();
}
return cacheBuilder;
}
private static class WithIdentity<T>
{
private final HiveIdentity identity;
private final T key;
private final int hashCode;
public WithIdentity(HiveIdentity identity, T key)
{
this.identity = requireNonNull(identity, "identity is null");
this.key = requireNonNull(key, "key is null");
this.hashCode = Objects.hash(identity, key);
}
public HiveIdentity getIdentity()
{
return identity;
}
public T getKey()
{
return key;
}
@Override
public boolean equals(Object o)
{
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
WithIdentity<?> other = (WithIdentity<?>) o;
return hashCode == other.hashCode &&
Objects.equals(identity, other.identity) &&
Objects.equals(key, other.key);
}
@Override
public int hashCode()
{
return hashCode;
}
@Override
public String toString()
{
return toStringHelper(this)
.add("identity", identity)
.add("key", key)
.toString();
}
}
private HiveIdentity updateIdentity(HiveIdentity identity)
{
// remove identity if not doing impersonation
return delegate.isImpersonationEnabled() ? identity : HiveIdentity.none();
}
@Managed
@Nested
public CacheStatsMBean getDatabaseStats()
{
return new CacheStatsMBean(databaseCache);
}
@Managed
@Nested
public CacheStatsMBean getDatabaseNamesStats()
{
return new CacheStatsMBean(databaseNamesCache);
}
@Managed
@Nested
public CacheStatsMBean getTableStats()
{
return new CacheStatsMBean(tableCache);
}
@Managed
@Nested
public CacheStatsMBean getTableNamesStats()
{
return new CacheStatsMBean(tableNamesCache);
}
@Managed
@Nested
public CacheStatsMBean getTableWithParameterStats()
{
return new CacheStatsMBean(tablesWithParameterCache);
}
@Managed
@Nested
public CacheStatsMBean getTableStatisticsStats()
{
return new CacheStatsMBean(tableStatisticsCache);
}
@Managed
@Nested
public CacheStatsMBean getPartitionStatisticsStats()
{
return new CacheStatsMBean(partitionStatisticsCache);
}
@Managed
@Nested
public CacheStatsMBean getViewNamesStats()
{
return new CacheStatsMBean(viewNamesCache);
}
@Managed
@Nested
public CacheStatsMBean getPartitionStats()
{
return new CacheStatsMBean(partitionCache);
}
@Managed
@Nested
public CacheStatsMBean getPartitionFilterStats()
{
return new CacheStatsMBean(partitionFilterCache);
}
@Managed
@Nested
public CacheStatsMBean getTablePrivilegesStats()
{
return new CacheStatsMBean(tablePrivilegesCache);
}
@Managed
@Nested
public CacheStatsMBean getRolesStats()
{
return new CacheStatsMBean(rolesCache);
}
@Managed
@Nested
public CacheStatsMBean getRoleGrantsStats()
{
return new CacheStatsMBean(roleGrantsCache);
}
@Managed
@Nested
public CacheStatsMBean getGrantedPrincipalsStats()
{
return new CacheStatsMBean(grantedPrincipalsCache);
}
@Managed
@Nested
public CacheStatsMBean getConfigValuesStats()
{
return new CacheStatsMBean(configValuesCache);
}
}
| Remove redundant asyncReloading CacheLoader wrapper
The changed caches do not set `cacheBuilder.refreshAfterWrite` (since
3a1bf59d7ca5008419d3efacf00fe1e99fa1d91c), so the `asyncReloading`,
which changes `CacheLoader.reload`, and delegates the reset), was
redundant.
| plugin/trino-hive/src/main/java/io/trino/plugin/hive/metastore/cache/CachingHiveMetastore.java | Remove redundant asyncReloading CacheLoader wrapper | <ide><path>lugin/trino-hive/src/main/java/io/trino/plugin/hive/metastore/cache/CachingHiveMetastore.java
<ide>
<ide> // disable refresh since it can't use the bulk loading and causes too many requests
<ide> partitionStatisticsCache = newCacheBuilder(expiresAfterWriteMillis, OptionalLong.empty(), maximumSize, statsRecording)
<del> .build(asyncReloading(new CacheLoader<>()
<add> .build(new CacheLoader<>()
<ide> {
<ide> @Override
<ide> public PartitionStatistics load(WithIdentity<HivePartitionName> key)
<ide> {
<ide> return loadPartitionColumnStatistics(keys);
<ide> }
<del> }, executor));
<add> });
<ide>
<ide> tableCache = newCacheBuilder(expiresAfterWriteMillis, refreshMills, maximumSize, statsRecording)
<ide> .build(asyncReloading(CacheLoader.from(this::loadTable), executor));
<ide>
<ide> // disable refresh since it can't use the bulk loading and causes too many requests
<ide> partitionCache = newCacheBuilder(expiresAfterWriteMillis, OptionalLong.empty(), maximumSize, statsRecording)
<del> .build(asyncReloading(new CacheLoader<>()
<add> .build(new CacheLoader<>()
<ide> {
<ide> @Override
<ide> public Optional<Partition> load(WithIdentity<HivePartitionName> partitionName)
<ide> {
<ide> return loadPartitionsByNames(partitionNames);
<ide> }
<del> }, executor));
<add> });
<ide>
<ide> tablePrivilegesCache = newCacheBuilder(expiresAfterWriteMillis, refreshMills, maximumSize, statsRecording)
<ide> .build(asyncReloading(CacheLoader.from(key -> loadTablePrivileges(key.getDatabase(), key.getTable(), key.getOwner(), key.getPrincipal())), executor)); |
|
JavaScript | mit | d0a435bf8d3ad7a5817c5cdc88de5736ee8000e2 | 0 | Codewest/prente,Codewest/prente | var menuOpen = false;
var addEventListeners = function () {
$(".hamburger").on('click', toggleMenu);
$(".menu-item").on('click', togglePage);
};
var toggleMenu = function() {
toggleButtonIcon($(".hamburger i"), "menu", "close");
$(".menu").slideToggle();
};
var togglePage = function() {
$();
};
var toggleButtonIcon = function(button, openIcon, closeIcon) {
if (menuOpen) {
button.html(openIcon);
menuOpen = false;
} else {
button.html(closeIcon);
menuOpen = true;
}
};
var xStart;
var yStart;
var determinePosition = function determinePosition() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(setPosition, showError);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
};
function setPosition(position) {
xStart = position.coords.latitude;
yStart = position.coords.longitude;
}
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation.";
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable.";
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out.";
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred.";
break;
}
}
var openRoute = function openRoute() {
var xDestination = 51.2079017; //end x-position here (open data)
var yDestination = 3.2221577; //end x-position here
var xCenter = (xStart + xDestination)/2;
var yCenter = (yStart + yDestination)/2;
var zoom = 18.75;
window.open("https://www.google.be/maps/dir/" + xStart + "," + yStart + "/" + xDestination + "," + yDestination + "/@" + xCenter + "," + yCenter + "," + zoom +"z");
};
/**
* Created by Sam on 14/10/2016.
*/
var drawBruges = function drawBruges(map) {
map.addSource('Brugge', {
'type': 'geojson',
'data': {
'type': 'Feature',
'properties': {
'name': 'Brugge'
},
'geometry': {
"type":"Polygon",
"coordinates":[[[3.15476744892041,51.3234140989248], [3.15506341515048,51.3228446746481], [3.15509453886165,51.3227858937051], [3.15530870478349,51.3223743889867], [3.15550350210443,51.3219962912782], [3.1556728415599,51.3216723970495], [3.1557062956764,51.3215950987342], [3.15579462817575,51.3213990039186], [3.15667203395984,51.3194507381225], [3.15754181947154,51.3196404030739], [3.15936367627512,51.3200564762843], [3.16098086871382,51.3203788898685], [3.16280916017925,51.3208343745895], [3.1639966232684,51.3211848211612], [3.16581496034153,51.3215984403175], [3.1679131357432,51.322134223545], [3.17003122134468,51.3226168650105], [3.17215099137294,51.3231075967475], [3.1735858682092,51.3216063460196], [3.17534803942473,51.319742188738], [3.1755286376775,51.3195504851308], [3.17655272712307,51.3185560988896], [3.17667795093217,51.3184322065145], [3.17689604796177,51.3182200192837], [3.17643625233827,51.3178329878349], [3.17598776458789,51.317437956553], [3.17555253013673,51.317103315077], [3.1754232009453,51.3170266904507], [3.17495142289077,51.3167473017668], [3.17415243826047,51.3161760697269], [3.17384941664817,51.31595052351], [3.17378162517701,51.3157099657644], [3.17384524300519,51.315536785022], [3.1739658014535,51.3152343910321], [3.17386972526281,51.3147270209669], [3.17369656974869,51.3141250096725], [3.17344305499472,51.3138443380735], [3.1733010998701,51.313827841938],[3.17310261201315,51.3137806462312],[3.17300844905228,51.3137032146231],[3.17274571090371,51.3130620569122],[3.17257729447908,51.3126362311054],[3.17261172601702,51.3125195382153],[3.17279162303132,51.3123544840438],[3.1729937606348,51.3121873363361],[3.17310430759215,51.3120586641588],[3.17302123170565,51.3118376511757],[3.17274417576029,51.3114663525244],[3.17230308267652,51.3110030097627],[3.17183835940585,51.3106680551923],[3.17175261320081,51.3106231542561],[3.17153735397104,51.3105097337894],[3.17142203038306,51.310320840576],[3.17146427126183,51.3100443100593],[3.17160676908104,51.3095358699468],[3.17176083620998,51.3092245453577],[3.17196541003335,51.3091060942116],[3.17223118594125,51.3089083021928],[3.17238268400109,51.3086247624568],[3.17309483079302,51.3071718386796],[3.17342459272994,51.306425409748],[3.17350320541069,51.3059557223854],[3.17339838360704,51.3053578736634],[3.17328107773318,51.3043102769377],[3.17306295074933,51.3041655416366],[3.17298549325438,51.3039422668002],[3.17293607642181,51.3029150539165],[3.17300393770085,51.3026480512373],[3.17323352696092,51.301625970483],[3.17342342212013,51.300925640765],[3.17368341293928,51.3005910461307],[3.17390468514671,51.3003244309611],[3.1739320583753,51.3000500663797],[3.17385601077089,51.29991603515],[3.17355679710755,51.299762370887],[3.1731685230655,51.2996217131672],[3.17252012625811,51.2994610461976],[3.17130277628762,51.2988542751669],[3.1698713635903,51.2980912021006],[3.16866141603943,51.2974867954066],[3.16791522580564,51.2971060944108],[3.16747416265353,51.2967203705594],[3.16696365838436,51.2963756583304],[3.16618658079379,51.2961186269363],[3.16627627649647,51.2956513719237],[3.16641722529727,51.2952750252394],[3.16665689086227,51.2947977032766],[3.16701528461745,51.2943748910211],[3.16739036185694,51.2939499291836],[3.1678529909035,51.2935698889541],[3.16841581349436,51.293102791269],[3.16875438456576,51.2928026084682],[3.16893711641016,51.2924533348103],[3.16933916629921,51.2918409101042],[3.16957291458633,51.2913044219949],[3.1696306777941,51.290927229207],[3.16953928432454,51.2906006738722],[3.16951627874094,51.2905610408977],[3.1694340004465,51.2904547547911],[3.17036310933272,51.2901871968778],[3.17104525016302,51.2900364944476],[3.17180177053004,51.2899398456262],[3.17249144240489,51.2897834168881],[3.17300096348158,51.2895892424313],[3.17346356730454,51.2892787098291],[3.17375108312653,51.2888771798559],[3.17386765980232,51.288439160413],[3.17396641754741,51.2880473141665],[3.17418639373682,51.2876126547226],[3.17449535670166,51.2873109982228],[3.17491816336889,51.2871819946244],[3.17509876978688,51.2871293496488],[3.17534454403696,51.2870576608446],[3.17577305062904,51.2867780641417],[3.17652015851627,51.2860358242474],[3.17691658967854,51.2855646941437],[3.17721463378567,51.2851829616662],[3.1775603133584,51.2849616256263],[3.1779900492843,51.2845603564639],[3.17832776780491,51.2839994016976],[3.17861685890206,51.2833162804446],[3.17861429841675,51.2829825122503],[3.17856268800088,51.2826158039971],[3.17849900536076,51.2822153683288],[3.17844302124944,51.2818752690015],[3.17855891708002,51.2818231274318],[3.17879070796253,51.2817188439488],[3.17880812004049,51.2811094749196],[3.17892753307715,51.2804130593557],[3.17917807743073,51.2799358204691],[3.17934967237653,51.2795110944196],[3.17933617139826,51.2791714217604],[3.17932987941229,51.2789836281538],[3.17937192661097,51.2787117253581],[3.17959080289983,51.2783164443348],[3.18001623406276,51.2777911294661],[3.18038873916675,51.2773846415663],[3.18063448043445,51.2770220753429],[3.18078243853979,51.2766538925369],[3.1808144695859,51.2762671643712],[3.18093124600716,51.2759624042453],[3.18106532667062,51.2757760182642],[3.18142234598583,51.2757587389273],[3.18151764807326,51.2754989573376],[3.18107300180526,51.2753299452897],[3.18113626249181,51.2747326227254],[3.18132743485327,51.2739731872523],[3.18163319019993,51.2732844298128],[3.18195822671354,51.2724185633684],[3.18230651226599,51.2716549060325],[3.18265392037281,51.2709978513779],[3.1834743958537,51.2711335376099],[3.18466099047839,51.2714015096768],[3.18638593131092,51.2717130871141],[3.18648525394389,51.2717303023342],[3.18624585994951,51.2725008527338],[3.18608980034422,51.2729720974863],[3.18591850256472,51.2733157183932],[3.18631493480889,51.2732733238407],[3.18668180995784,51.2733036392951],[3.18735572005088,51.27346564695],[3.18796173346831,51.2736825976427],[3.18855561568957,51.2738681358619],[3.18929368815432,51.2739774654944],[3.1901356654401,51.2739962770258],[3.19022373738851,51.2740933362992],[3.19037285076704,51.2742605326133],[3.19188815549819,51.274392641296],[3.19333851924778,51.2762206102699],[3.19356308201557,51.2759609435921],[3.19386071032224,51.275441265043],[3.19407500285814,51.2748558648186],[3.19416487428079,51.2743688894703],[3.19410171837205,51.2740159792625],[3.19392950424769,51.2733722799932],[3.19377277176541,51.2727009219535],[3.19361341432848,51.2721338320898],[3.19365774476845,51.2718410880757],[3.19373346587326,51.271475649195],[3.19374264520968,51.2711848739744],[3.19347971060157,51.2708427276876],[3.19302839238965,51.270425704295],[3.19253799645677,51.2698738665334],[3.19249847680538,51.2698294384346],[3.19190410756553,51.269152570054],[3.19098837398796,51.2681816357666],[3.19041418765281,51.2675849191986],[3.1903341017376,51.2675377689613],[3.18964261994679,51.2671241354377],[3.18957402647269,51.2670608754344],[3.18867019334018,51.2662070821886],[3.18839729649675,51.2659691190229],[3.18816324167019,51.2657292247756],[3.18807319639021,51.2656379379321],[3.18778407028973,51.2653117400157],[3.18736205426909,51.2648358847215],[3.18713434347436,51.2645647629779],[3.18680718584883,51.2642092119995],[3.18627003418217,51.2636128430185],[3.18539301071746,51.2626538359435],[3.18495700643584,51.2621488603634],[3.18498561683436,51.2621132224796],[3.18662214568783,51.2599984725565],[3.18708265161254,51.2593912036094],[3.18732906454668,51.259069188313],[3.18739211079214,51.2589863811315],[3.18746090160483,51.258895519372],[3.18749153067166,51.2588529479923],[3.18760053434173,51.2587057043326],[3.18782384400576,51.258420540294],[3.18803771355747,51.2581433935464],[3.18871347992763,51.2572752086099],[3.18915148250257,51.2566792955609],[3.18977008909538,51.2558789063955],[3.19028367350119,51.2552142114717],[3.19038876229293,51.2550750380978],[3.19050343317817,51.2549220539368],[3.19106165521029,51.2541708869607],[3.19122042118425,51.2538804389526],[3.19136626169414,51.2535898621652],[3.19146905556161,51.2533950407213],[3.19148065942712,51.2533742970205],[3.19144082712144,51.2531965985392],[3.19141716907053,51.2529634366154],[3.19159430270969,51.2526766472186],[3.19167379874787,51.2525267886076],[3.19176267134607,51.2523712289709],[3.19184582938995,51.2522225654857],[3.19192895765747,51.2520750604818],[3.19200056986169,51.2519448235297],[3.19205281372772,51.2518503180283],[3.19274755719349,51.2511016586289],[3.19282942276874,51.2505647702811],[3.19040385790865,51.2502405101886],[3.18902815094746,51.2500228516158],[3.1884625825561,51.2498978530311],[3.18811195226993,51.2497437069861],[3.18782965758167,51.2495890827954],[3.1874477109931,51.2493592975772],[3.18644012945233,51.2488254412522],[3.18605110582305,51.2485839922112],[3.18571327451568,51.2483627538113],[3.18509281755604,51.2480007861936],[3.18491294765785,51.2478854207523],[3.18477664662316,51.2477994619143],[3.18427123464052,51.2474884707341],[3.18378962070431,51.2471858274421],[3.18332017857371,51.2468404267696],[3.18258562968245,51.2463196998524],[3.18156171218044,51.2455619793378],[3.18046960449738,51.2447282398427],[3.17973755746178,51.2441843423463],[3.1793757196188,51.2438933128902],[3.17923419857496,51.2437957063894],[3.17889670041859,51.2435640211575],[3.17853203361012,51.2433842097928],[3.17820866924296,51.2432500077673],[3.17785782698995,51.2431074164183],[3.17744735934116,51.2429862419388],[3.17604868558225,51.2425943707237],[3.1755474805233,51.2424120149908],[3.17514086480678,51.2422850769468],[3.17373871814952,51.2418861897848],[3.17341404150049,51.2418041092711],[3.17327236106815,51.2417134468498],[3.1726726564114,51.2412693426051],[3.17231395514231,51.2410745067335],[3.17219743516672,51.2410107508484],[3.17140160363229,51.2407280545288],[3.17045586460807,51.2404600588521],[3.16977689513978,51.2402283651251],[3.1686905175879,51.2399739952191],[3.16795752878095,51.2398332922808],[3.16697470021115,51.2396448526925],[3.16612494510392,51.2394508041295],[3.1642653146394,51.2387585983636],[3.16411368499205,51.2386967946361],[3.16386885767695,51.2385981174249],[3.1615650617554,51.2376660978426],[3.15977063136067,51.2368852528256],[3.16056103547473,51.236303468496],[3.16142106691819,51.2355983919284],[3.16193056151533,51.23517017752],[3.1625970601727,51.2347377671284],[3.16251972067673,51.2344449473676],[3.16251676872727,51.2341308675907],[3.1626409109293,51.2338273541459],[3.1629539237286,51.233429580379],[3.16342841906664,51.232925677277],[3.16379000628593,51.2326477581864],[3.16429668368435,51.232183580428],[3.16480985045857,51.2321111596832],[3.1655902999614,51.2319811943918],[3.16569206296321,51.2319717994182],[3.16580823009951,51.2319764570606],[3.16667408545004,51.2323282776934],[3.16685691966085,51.2323961897117],[3.16706065045767,51.2324411365724],[3.16722429098667,51.2324659754612],[3.16806726543866,51.232488438668],[3.16877687021645,51.2324573949494],[3.16916139179771,51.2324346402451],[3.16934899339294,51.2324608779541],[3.1695475796303,51.2324188543054],[3.16973217832339,51.2322747094351],[3.17000898753736,51.2318464203948],[3.17023266533426,51.2312588294725],[3.17042943104327,51.2309282311965],[3.17063181928014,51.2307379109113],[3.17076298317812,51.2304460488109],[3.17079765579506,51.2302459180128],[3.17088212069154,51.2300474501576],[3.17106042557112,51.2298603618694],[3.17146756653924,51.2294588833202],[3.17194710628696,51.228897054891],[3.17271191177279,51.2280066760235],[3.17292468482061,51.227626404528],[3.17303475282089,51.2272926077604],[3.17326109420155,51.2264547247409],[3.17339189866841,51.2261037542367],[3.1734896215101,51.225963361136],[3.17321484439758,51.2258829414102],[3.17242161798612,51.2256524225742],[3.17129065677243,51.2252782586969],[3.1716994801652,51.2248095823769],[3.17200128703221,51.2244835203978],[3.17226202075837,51.2241037348279],[3.17319173242259,51.222896333989],[3.17222771671291,51.2226351154729],[3.17141131053525,51.2224472322553],[3.17081853864202,51.2223183921842],[3.17084859443146,51.2224415355107],[3.17091885465746,51.222795698679],[3.17103410984322,51.2231225047082],[3.1710102147763,51.2231906353988],[3.17084267677296,51.223175032746],[3.17013613339196,51.2229488520414],[3.16918499114134,51.2226182074816],[3.16903751217592,51.222612076508],[3.16892210790607,51.2227221565273],[3.1684241749974,51.2232826283],[3.16834700938247,51.2233409471067],[3.16783192489975,51.2233484668666],[3.16761838160563,51.2233277571815],[3.16696665658208,51.2228367352819],[3.16677836046466,51.2226957591779],[3.1665524544525,51.2228684513975],[3.16592643076616,51.2232421937254],[3.16539809317134,51.2236204030554],[3.16505054708635,51.2238579100408],[3.16465438692609,51.2239767176058],[3.16419880459066,51.224038134742],[3.16375631585807,51.2240927303458],[3.16328089616985,51.2240647097354],[3.16287449193554,51.2240084192234],[3.16258928595885,51.223832841646],[3.1623891925301,51.2236488604192],[3.16220705423451,51.2234129132502],[3.16215073713538,51.2231643428129],[3.16212039638933,51.2227677031609],[3.16213481478206,51.2223529782078],[3.16218888398309,51.2221889714978],[3.16221622453893,51.2220594579677],[3.16239232916945,51.2218862660053],[3.16281554642514,51.2216483792292],[3.16329143520679,51.2213716264439],[3.16114615895228,51.2206938306548],[3.16145770306628,51.2204212016149],[3.16098112199367,51.2202969739487],[3.1603139367672,51.2201221251345],[3.1594449752533,51.2199718637248],[3.15838363143359,51.2197686375962],[3.15726071521583,51.2195207344505],[3.15659040722091,51.2193249727945],[3.15626929836493,51.2191837771015],[3.15593264970845,51.2190725516328],[3.15506378215516,51.218919940853],[3.15427195026105,51.2187854975393],[3.15397066697613,51.2187337315582],[3.15372448741642,51.2186918017397],[3.15363998802598,51.2186770273822],[3.15329264619962,51.2186224687841],[3.15169010591714,51.2183707415913],[3.15029371441681,51.218210348806],[3.14870372751195,51.2179030845295],[3.14820471874578,51.218074084138],[3.14751708229628,51.2182605173493],[3.14683670442193,51.2183809662146],[3.14613521769995,51.2184617915615],[3.14542696530309,51.2184486746127],[3.14497360890956,51.2183559112697],[3.14532492766166,51.2181880331774],[3.14575231317975,51.2179340255621],[3.14614458993749,51.2176112804075],[3.14532940131019,51.2174545167469],[3.14426649374618,51.2171746610493],[3.14361035151667,51.2170751573731],[3.1430304553259,51.2169532627981],[3.14247757612462,51.2167864495855],[3.14172938443848,51.2163985816684],[3.14117939679204,51.216052167587],[3.14125028496683,51.2156021033211],[3.14206922690941,51.2140704625183],[3.14292036760192,51.2124348511282],[3.14367776657581,51.2114159400615],[3.14373898137794,51.2113331354811],[3.14376768334576,51.2112940311834],[3.14612063819804,51.2114840971717],[3.14619682464889,51.2113226430088],[3.1462261316596,51.2112603669987],[3.14629181996211,51.2111474767729],[3.14644043350726,51.2108975380909],[3.14654950506344,51.2105370979547],[3.14661904540372,51.2102770708685],[3.14657300738866,51.2101328952407],[3.14646175240936,51.2099428496417],[3.14731162983383,51.2087695826597],[3.14800371386751,51.2077731468262],[3.148314165655,51.2074008769874],[3.14877283032309,51.2069339491466],[3.14900629290736,51.2065423412809],[3.14925541441923,51.2061161282841],[3.14926118958171,51.2061069168708],[3.14951019630222,51.205331881866],[3.15173454883397,51.2030857248544],[3.15194741243182,51.2028457112612],[3.15223052996081,51.2024580844688],[3.15245620442545,51.2021509871768],[3.15265324761795,51.2018806788992],[3.15284454481464,51.2016184233077],[3.15332851834747,51.2008840385377],[3.15393770232886,51.2002992739097],[3.15395472131134,51.2002832245474],[3.15442883125395,51.1998558351274],[3.1546871480608,51.199427387149],[3.15504380200221,51.1986928467433],[3.15557945590749,51.1978836563395],[3.15601882157019,51.1971592324723],[3.15652159802386,51.1964783354031],[3.15694915954925,51.1958522912088],[3.15697796123383,51.1958085492086],[3.15763479485401,51.1958709054196],[3.15857309828867,51.1936137562932],[3.1596805232248,51.1922286434938],[3.15927518113725,51.1921422171521],[3.159451955535,51.1917256717344],[3.15967555715399,51.1912099416968],[3.1598371112066,51.1907399316966],[3.1598811291493,51.1903220278293],[3.16006321229482,51.1899136477493],[3.16030311982143,51.1895510546383],[3.16042073111318,51.1888546136439],[3.16061653477046,51.1882006910969],[3.16082880537118,51.1874090300901],[3.16122545376731,51.1866180933022],[3.16141908125472,51.1861901278472],[3.16188193901989,51.185333808948],[3.16129705453919,51.1852756862577],[3.16094013544376,51.1852442266879],[3.16077231736415,51.1852448295329],[3.16051622136734,51.1852364176758],[3.15988414250638,51.1852206840149],[3.15915879633096,51.1851750206306],[3.15829165301397,51.1851221063842],[3.15776183986885,51.1850738010934],[3.15741873092387,51.1850077059764],[3.15694082916283,51.1848776485785],[3.15643001828892,51.1847368217787],[3.15605085682745,51.1846390631285],[3.15501217571307,51.1843757663466],[3.15390035010763,51.1842310731361],[3.15324736526839,51.1840273503884],[3.15278275134848,51.1838835059847],[3.15150630161256,51.1834763482097],[3.15057407598905,51.1832338090208],[3.15013634306435,51.1831203619522],[3.14919766864119,51.1827722870204],[3.14833589297231,51.1823044747654],[3.14793284843889,51.1819932086749],[3.14759489717925,51.1817312867346],[3.14728704381369,51.1815171890003],[3.14535146380146,51.1810776540258],[3.14528184248192,51.1810607089845],[3.14413802019681,51.1808043385378],[3.14430700746982,51.180758575134],[3.14430895199837,51.1806844267252],[3.1443117776304,51.180576679815],[3.14347876316515,51.1801404186491],[3.14340473905991,51.1800805481157],[3.14294978212464,51.1797119406533],[3.14261612214057,51.1793584964017],[3.14231098101985,51.1789022062991],[3.14132154002559,51.1785268855466],[3.13995547704437,51.1781012855534],[3.13869017337865,51.1777010548208],[3.13776266074199,51.1773564791328],[3.13746970802188,51.1772792585607],[3.13732025834042,51.1772834958341],[3.13719388369683,51.1773215811088],[3.13696393367295,51.1774420266009],[3.13661192209416,51.1777164899753],[3.13644417854881,51.1778549663142],[3.13636914439857,51.1779735492474],[3.13629823277975,51.1781454839192],[3.13626451294873,51.1782355254448],[3.13628295339714,51.1783052509608],[3.13628148551224,51.1783608622184],[3.13627064307386,51.178631928638],[3.13616236188772,51.1789622409459],[3.13600315580255,51.1791263011966],[3.13583210890377,51.1791801434931],[3.13565991466269,51.179137785989],[3.13559748180377,51.1790583302846],[3.13555733705706,51.1788330873832],[3.13554088804953,51.1784087631594],[3.13559669126925,51.1779712861452],[3.13571411387684,51.1775043208942],[3.1358565813528,51.1771361221809],[3.13621806502032,51.1764329713964],[3.13636578790515,51.1761447900604],[3.13643181754465,51.1760180009671],[3.1367122758827,51.1755202856559],[3.1369964849467,51.175089824248],[3.13732510736984,51.1742333540956],[3.13731186004033,51.1741764305221],[3.13728389892103,51.1741181947263],[3.13727308506845,51.1741088109281],[3.13724451295314,51.1740737465213],[3.13723790463334,51.1740447054437],[3.13724041987284,51.1740192361107],[3.13723992122079,51.173968239823],[3.13722929073917,51.1739519046001],[3.13722652129742,51.1739171090845],[3.13725382098475,51.1738606080495],[3.13729365521295,51.1738181442922],[3.13732907005475,51.1738034477928],[3.13739765948469,51.1737890969691],[3.13746047538266,51.1737839570563],[3.13759870291817,51.173785397243],[3.13770523237318,51.1738004137192],[3.13784085344835,51.1738307986781],[3.13794713879151,51.1738550834978],[3.13917719980078,51.1736291577367],[3.13929223013954,51.1736013823742],[3.1388551216907,51.1726986953583],[3.13853085892186,51.1718516489089],[3.13811550247705,51.1711740092579],[3.13785201065671,51.1706798956078],[3.13742296035101,51.1696834155551],[3.13731889509582,51.1694354874222],[3.1370482144941,51.1687952763139],[3.13681138426444,51.1681299216891],[3.13668722038421,51.1677357629264],[3.13662132452824,51.1673688660972],[3.13661487037272,51.1673340320475],[3.13643710597592,51.1661072295077],[3.13642733350621,51.1660584541129],[3.1364223555708,51.1660375421347],[3.13627850876899,51.1653418652208],[3.13604773886254,51.1645178028048],[3.1358925256416,51.1639738213291],[3.13579977408849,51.1636472044236],[3.1355837079484,51.1628951452614],[3.1355252952621,51.1628736754535],[3.13522741243909,51.1629169214051],[3.13516715728643,51.1628954321816],[3.13513407558747,51.1628220764451],[3.1348681890236,51.1621425056949],[3.1345418180685,51.1615202469524],[3.13438655709948,51.1611883398481],[3.13411428025064,51.1606118416678],[3.13444218064093,51.1605480521505],[3.13480582847655,51.1605263553374],[3.13550478197887,51.1605093170769],[3.13560271022988,51.160499909269],[3.1370343820298,51.1603734596875],[3.13826775806018,51.1602182730187],[3.13919255786768,51.1601630038526],[3.14044209161316,51.1600937208935],[3.14172979661522,51.1600445224077],[3.14258273171996,51.15998848032],[3.1448309246864,51.1598576608314],[3.14586009428476,51.1598277575882],[3.14599441382087,51.1598361012826],[3.14607790033514,51.1592517246916],[3.14658500227379,51.1592407475348],[3.14719072405325,51.1591937034612],[3.14756486498551,51.1591929360782],[3.14760177479951,51.1591909998344],[3.1481240089826,51.1591651069019],[3.14882339109226,51.1591306111093],[3.15021025348323,51.1589525485508],[3.15149604324419,51.1588336907373],[3.15282773396556,51.1586503935419],[3.15444540818116,51.1583831046251],[3.15497167564353,51.1583433163022],[3.15629754890709,51.1582410427803],[3.15710944942652,51.1582018584312],[3.1578377787148,51.1581873074785],[3.15930351071553,51.1582347717204],[3.15953263170783,51.1582116216767],[3.16027712088482,51.1583559889394],[3.16053494180391,51.1583632616617],[3.16097657175074,51.1583179454062],[3.16175828589613,51.1582343827129],[3.1623589906063,51.1581663498427],[3.16243482162383,51.1583699297602],[3.16213478185001,51.1586415221714],[3.16212208119594,51.1587051313263],[3.16230174349077,51.1587417329299],[3.16425665403464,51.158901906775],[3.16445188533408,51.1589780660111],[3.1646783404709,51.1591298708763],[3.16483130720362,51.1592728141733],[3.16542324436004,51.1598316344472],[3.16560854512011,51.1600073548406],[3.1658629304455,51.1602915548593],[3.16590025084052,51.1603452436546],[3.16604228250874,51.1605552893436],[3.16607914201068,51.1607700586524],[3.16606593208362,51.1609252150022],[3.16601597646267,51.1612190636565],[3.16596910866997,51.1615361214309],[3.16596259648165,51.1615742983857],[3.16603953853578,51.1618787099375],[3.16624256951015,51.1622968167973],[3.16648376211891,51.1627361714984],[3.16665331158961,51.1630948335549],[3.16682664994178,51.1633063553809],[3.16696059012575,51.1634015876258],[3.1675281581312,51.1637642962274],[3.16808450411615,51.1640619903684],[3.16843546351889,51.1642475013282],[3.16892241391835,51.1648075530796],[3.16945903658608,51.1655152850515],[3.16961191840327,51.1657347069205],[3.16988392320708,51.1661245343247],[3.16996440542066,51.166435931685],[3.16997569331848,51.16692973048],[3.17003183640648,51.1671122447248],[3.17005570257579,51.1671878142468],[3.17015158628158,51.1672583199244],[3.170249223877,51.1673323199583],[3.17045210939762,51.1673274244159],[3.17178301407825,51.1670372871579],[3.17259243411364,51.1668843994479],[3.17322221047834,51.166764455164],[3.1754580399198,51.1663327749456],[3.1777351954974,51.1658690206439],[3.18037483500903,51.165355560681],[3.18269641309674,51.1648805695068],[3.18469997458168,51.1644429073117],[3.18715369560793,51.1639865366654],[3.18861172012409,51.1636905293629],[3.18913763856518,51.1635926410653],[3.19014132618699,51.1634056482242],[3.19234674343197,51.1629976839807],[3.19302844754669,51.1628607687875],[3.19308217528127,51.1628497146469],[3.19401388163645,51.162665449491],[3.19406208106153,51.1626543399399],[3.19593184230918,51.1622522425413],[3.19698944979105,51.1619706991638],[3.1981474149169,51.1616553744688],[3.19883770047272,51.1614686792935],[3.19920415534081,51.1615545878761],[3.19947347689218,51.1616186742092],[3.20035655731957,51.1618290555183],[3.20609394486985,51.1633840826829],[3.21213743961183,51.1650229444754],[3.21243222413384,51.1651023154087],[3.2135624405744,51.1653115381778],[3.21496234765221,51.1655720565006],[3.21603020343665,51.1658443844035],[3.21635745471201,51.1659530339389],[3.21645619008504,51.1661347809126],[3.21651365567714,51.1664204238122],[3.21660613367437,51.1668559025002],[3.21671381399295,51.1671234928825],[3.21685148082273,51.1672963480036],[3.21733504392192,51.167868907958],[3.21764475813162,51.1681662787409],[3.2180758353342,51.1685505869585],[3.21845534768363,51.1689332326515],[3.21910758812225,51.1696940045669],[3.21950723757193,51.1701579633208],[3.22013049936721,51.1707492521865],[3.22084518505847,51.1713715561849],[3.22185050132222,51.172170506755],[3.22252990671093,51.1727298785336],[3.22290859408499,51.1729236052329],[3.22326727106847,51.17303138053],[3.22331309126599,51.1730422544654],[3.22368869837745,51.1731362861501],[3.22424248104955,51.1734070312626],[3.22463736924357,51.1736924596209],[3.22507051537213,51.1738461460463],[3.22550474216333,51.1739558043775],[3.22586975623583,51.1740311846429],[3.22652955122161,51.1741140487194],[3.22780553999224,51.1743291760317],[3.22831778188843,51.1744152408781],[3.22877899404908,51.1746282864466],[3.22948623228505,51.1749584297495],[3.22971731885059,51.1751588230996],[3.22972063772643,51.1751739203303],[3.22976014723722,51.1752925053288],[3.22952862097257,51.1756390920459],[3.22860533864664,51.1769084161846],[3.22871859835433,51.1769512278684],[3.22915524836883,51.1771142034157],[3.22981479474925,51.1773604459852],[3.23003040076095,51.1774401673972],[3.23042503300444,51.1775876680634],[3.23053466606619,51.1776281253056],[3.2317861873114,51.1780956047584],[3.23292760567291,51.1784669858427],[3.23371851084879,51.1788477375775],[3.23385702260072,51.1789139639588],[3.23394995964128,51.1789588930824],[3.23400639732054,51.1789884065021],[3.23415568806165,51.1790663246299],[3.23425946019376,51.1791206284102],[3.23428855863905,51.1791371317828],[3.23428104294186,51.1794464757921],[3.23426248282854,51.1795274179751],[3.23436518716596,51.17947393724],[3.23468910049829,51.1793460942439],[3.23507691161787,51.1795479800172],[3.23628346409731,51.1797449645514],[3.23617663562099,51.1801205708379],[3.2360693557435,51.1805147144412],[3.23689450774186,51.1804739469092],[3.23956389147273,51.1804137233986],[3.23984245032695,51.1813226127798],[3.24051053056773,51.1813730283724],[3.24083609823491,51.1821687953493],[3.24117028304618,51.182226450173],[3.24201391916441,51.1823376334996],[3.2431752136506,51.182427500067],[3.24327484214771,51.1825014568224],[3.24463867160446,51.1844416151997],[3.2449477744332,51.1846995028437],[3.2453634665348,51.184895824367],[3.24608368256649,51.1851576152002],[3.24642134341164,51.1849951051098],[3.24655742408971,51.1849338187964],[3.24711294343993,51.1846829839548],[3.24786249692298,51.1844142860477],[3.24851943147902,51.1842397319617],[3.24905514544282,51.1841219688876],[3.24967215357758,51.1839203765522],[3.25008581946503,51.1837400339493],[3.25015865858803,51.1837013221448],[3.2503790742005,51.1835828867127],[3.25178938142356,51.1837480317535],[3.25467324849805,51.1841333333654],[3.25741377929769,51.1845774770002],[3.25972344517225,51.1849978144476],[3.26087314800229,51.1851916940441],[3.26103403012258,51.1851723423863],[3.26228343504842,51.1854389912608],[3.26357852565621,51.1856457935735],[3.26497640147033,51.1858732418242],[3.26573005409764,51.1860517865045],[3.26643503013524,51.1861835183657],[3.2668389210321,51.1862591326707],[3.26771106822598,51.1864179097176],[3.26775046653106,51.1863893053917],[3.26788472108451,51.1862480170449],[3.26827505307102,51.1858819779143],[3.26836385772602,51.1857912553558],[3.26847576763166,51.1856590291478],[3.26857645180529,51.1855336514645],[3.26865910948207,51.1853907231701],[3.26878553280247,51.1851902595045],[3.26972503938455,51.1835835591356],[3.27066704157381,51.1821031889924],[3.27107787438535,51.1814116934901],[3.27149802871131,51.1806368456332],[3.27181481905532,51.1800232763568],[3.27188533568655,51.179925428275],[3.27193313340955,51.1798528640945],[3.27198591669185,51.1798035232142],[3.27204013500934,51.1797715784195],[3.27287130594302,51.1794721916779],[3.27312711318206,51.1795707479508],[3.27374036239269,51.1796795687652],[3.27596240527847,51.1794278033011],[3.27823321924906,51.1792181648915],[3.27986618477013,51.1790837280982],[3.28081089066999,51.1789730658029],[3.28179868895494,51.1788326621571],[3.28211865641006,51.1787892501827],[3.28256461350341,51.1787191828079],[3.28270689673843,51.1787054252125],[3.28286025079018,51.1787705710183],[3.2837465966288,51.1794253493856],[3.28534708119952,51.1806904292723],[3.28585131433134,51.181049657788],[3.28613105772403,51.1812306830825],[3.28656696401256,51.181356353918],[3.28702457255507,51.1814208027436],[3.28865573478817,51.1814461486683],[3.28997798448511,51.1814350465837],[3.2900061532291,51.1818119292594],[3.28978193262197,51.1838552486298],[3.28969807844003,51.1846911706663],[3.28966606095153,51.1848797704082],[3.28958905690905,51.1849404863289],[3.28853104137084,51.1854812750962],[3.28744428226214,51.1859881850348],[3.28690849197604,51.1862718357662],[3.28647787980265,51.1863930496802],[3.28383738702026,51.1867860311313],[3.28430318698206,51.1870556809942],[3.28583742529901,51.1878496488084],[3.28612626647429,51.1880377096859],[3.28634759288968,51.1881950216926],[3.28650557419066,51.1883007641696],[3.28665106078289,51.1887864934398],[3.28708056717118,51.1887139402023],[3.28766804585962,51.1885883643766],[3.28784597766389,51.1885494317692],[3.28794304871678,51.1885781315499],[3.28801640646048,51.1887549466749],[3.28806887415235,51.1888782639003],[3.28817484293034,51.1892396333635],[3.28807344567444,51.1894774286034],[3.2876897940323,51.1900382785011],[3.28743406587304,51.1904102466752],[3.28691914261391,51.1912236802602],[3.28666928231779,51.1915806354424],[3.28646881724832,51.1917955044162],[3.28615373848689,51.1920220709038],[3.28592094036175,51.192199559867],[3.28540857493169,51.1927418406502],[3.2844269050718,51.194035382348],[3.28582465556794,51.1944421995223],[3.28380174749298,51.1953820179001],[3.28251757470339,51.1959589198714],[3.28202079504661,51.1962243655606],[3.2817015450998,51.1964694234213],[3.28132779889332,51.1968368166422],[3.28097693097251,51.1971719715466],[3.28061193441404,51.1975591433324],[3.28166314909717,51.1981181039363],[3.28511157542403,51.1992599269871],[3.28789937144429,51.2001823842664],[3.28933146427403,51.2006288714819],[3.28947688004622,51.2007217470989],[3.28958995451164,51.200857204453],[3.28960606979215,51.2008782106301],[3.28961965874236,51.2011680445067],[3.28954336496818,51.2014361989898],[3.28941211503149,51.2017675879754],[3.28936030289073,51.2020139478009],[3.28941805375608,51.202148900243],[3.28968607670781,51.2022046527996],[3.28980025736405,51.2022126476546],[3.28989730817914,51.2021637030189],[3.28999837207501,51.2020209289602],[3.29005664039578,51.2019739480849],[3.29029210986051,51.2020015901923],[3.29071448238016,51.202163043427],[3.29113215443119,51.2022885282872],[3.29188940634617,51.2024866346876],[3.2924422484666,51.2026701287071],[3.29287289280056,51.2027934076964],[3.2932577002713,51.2029046798602],[3.29443562900864,51.203259561322],[3.29549594182642,51.2035959809293],[3.29628250237633,51.2038047542342],[3.29714984628008,51.204030477963],[3.29800906689857,51.2042086094018],[3.29840199292674,51.2042886494714],[3.2987468887055,51.2043717301741],[3.29916006384178,51.2045342282398],[3.29981086692352,51.2047116200869],[3.30080326135097,51.2049558293617],[3.30111412023556,51.2050756784106],[3.30162030141834,51.2053664791098],[3.30197884393571,51.2055794628428],[3.30254370410615,51.2062091683248],[3.30349267101916,51.2070648271801],[3.30414228159615,51.2077010817871],[3.30455047514913,51.2082459303992],[3.30502011878234,51.208928072317],[3.3050289186688,51.2089466927796],[3.30544621373532,51.2097407685896],[3.30628179813766,51.2112060875038],[3.3070457842365,51.2126580094372],[3.30777266061379,51.2141211806333],[3.30836525312096,51.2153247236414],[3.30867653173119,51.2159984753457],[3.30920021059666,51.216744817107],[3.30946495861039,51.2171933368287],[3.30961406583946,51.2176153263357],[3.30975795678342,51.218023362938],[3.31001644009649,51.2198056345734],[3.31021706015834,51.2215363981925],[3.3101967154244,51.2220263993429],[3.31007431861134,51.2221342337368],[3.3059634700077,51.2232388204694],[3.30407578770905,51.2237155083867],[3.3031687844653,51.2239159316648],[3.30194735735441,51.2242270783551],[3.30055112129194,51.2245957345571],[3.29929693732217,51.2249656585106],[3.29822022790458,51.2252409926082],[3.2973158132596,51.2254066299877],[3.29690625468883,51.225480561854],[3.29513532191381,51.225848077299],[3.29449150132662,51.2259163984501],[3.29419157207236,51.2259577103132],[3.29405824035377,51.2259773582132],[3.29393782462928,51.2259971232947],[3.29369889143444,51.2260343526855],[3.29336839650483,51.2261205790096],[3.292753478764,51.2262957655579],[3.29163105131149,51.2266297245765],[3.29154820367037,51.2267807767384],[3.29137446048006,51.2268719010178],[3.29087455144428,51.2267016356425],[3.28865051329625,51.2259895335372],[3.28651620170796,51.2253106567663],[3.28539283359238,51.2249689507097],[3.28524448264525,51.2249200802117],[3.28438553475163,51.2246364094468],[3.28455497620128,51.2248894283756],[3.28525819810285,51.2275078711622],[3.28504796620513,51.2275801108615],[3.2845907023619,51.2275608571336],[3.28255127564625,51.2269279730763],[3.28231287468318,51.226783248236],[3.27974066700605,51.2268395608049],[3.2786278331317,51.2263634631899],[3.27855269967751,51.226419553618],[3.27794543685456,51.226817229685],[3.27700212424535,51.2274574744346],[3.27625188405496,51.2279697055904],[3.27527881067579,51.2286177737546],[3.27441263084588,51.2291926575279],[3.27479066091895,51.2294429839794],[3.27406535952846,51.2299125552377],[3.27349277477769,51.2303232766084],[3.27363539983374,51.2304590209441],[3.27478373014609,51.2315485131499],[3.27484152974694,51.2316811539988],[3.27458590549869,51.2320345510964],[3.27320260469986,51.2335618357406],[3.27220015104459,51.234746144114],[3.27181437029264,51.2352165294788],[3.27140535310209,51.2356542509248],[3.27082877411093,51.2362306346805],[3.26984528093524,51.2372320040839],[3.26938077729609,51.2376726797635],[3.26876161673891,51.2382521343654],[3.26803025205498,51.2388919600639],[3.26738221165927,51.2394421681929],[3.26692255855669,51.2398318910023],[3.2667208527415,51.2400084723577],[3.26666810522797,51.2400531754431],[3.26654933395653,51.2401575226553],[3.26647766345686,51.240221749486],[3.26641185854361,51.2402721249823],[3.26616183144784,51.2404621612389],[3.26606217274592,51.2405388741718],[3.26600223287971,51.2405753981632],[3.26595245310118,51.2405726166795],[3.265951631146,51.2406073738285],[3.26558821579856,51.2408299582776],[3.26510609357354,51.2410757701172],[3.2645461153863,51.2413347596],[3.26444325450093,51.2413905824253],[3.26439088736803,51.2414190644782],[3.26420196856472,51.2415227547995],[3.26414023510034,51.2415569434659],[3.26292813586562,51.2422223797558],[3.26170933685505,51.242935253009],[3.26108234860728,51.2433709000143],[3.2607529381435,51.2434813818121],[3.26045749477726,51.2435608924404],[3.26011626269093,51.2437025501139],[3.2594758328369,51.2440812802928],[3.25845830232333,51.2447114121862],[3.25784795920015,51.2450660805132],[3.25720517219477,51.245542117862],[3.25613421260968,51.2461647752796],[3.25522405273903,51.2467020239206],[3.2548076611936,51.2469739068062],[3.25480649866097,51.2470225665814],[3.2550690882482,51.24762415068],[3.25523444205725,51.2480452013205],[3.25528342790536,51.2486227573797],[3.25521351956155,51.2486893116633],[3.25471098953633,51.248624324363],[3.25467726392975,51.2488766309778],[3.25447489069633,51.2488457555296],[3.25270702326185,51.2485706827818],[3.2525640249744,51.2489135058837],[3.25245841176485,51.2489287335414],[3.25221333093091,51.2489078809],[3.25096461302798,51.2486979366727],[3.25027912478278,51.248562831907],[3.24971904230697,51.2485111854349],[3.24898433940358,51.2484265962362],[3.24863431746463,51.2483931551053],[3.24858621044027,51.2481667285268],[3.24824327690069,51.2482225830142],[3.24820152281565,51.2482696996913],[3.24809644338484,51.24857000007],[3.24785923485293,51.2489130846977],[3.24754464196929,51.2494026069524],[3.24715608750881,51.2498960628935],[3.24670834372443,51.2504700744066],[3.24640426974333,51.2509052283845],[3.24618630725918,51.2512148860647],[3.24625559581712,51.2512514667168],[3.24633375259066,51.2513031961565],[3.24642581409559,51.2513909809909],[3.24705644556514,51.2521189068497],[3.24721601707416,51.2523174191251],[3.24750349299221,51.2526492487832],[3.24783461348694,51.2530093027253],[3.24817863482751,51.2533706365789],[3.24828295920472,51.253486347699],[3.24865088641084,51.2539290240348],[3.24878465116876,51.2541261309334],[3.24885613570468,51.2542253072629],[3.24893276971823,51.2543407557945],[3.24905792738506,51.2545887691886],[3.24913241014266,51.2547169442848],[3.24929843862679,51.254954914462],[3.25114652364404,51.2572853859941],[3.25304994968528,51.2595491345959],[3.25491295565734,51.2618889506453],[3.25526758795801,51.2623523373725],[3.25546369091625,51.2625708804951],[3.2556550029367,51.2627580901067],[3.25584507847331,51.2629197937436],[3.25602823907233,51.2630617321526],[3.25614208663528,51.2631670956247],[3.25624080225407,51.263287381452],[3.25651435589089,51.2635889264233],[3.25998964483234,51.2679728747149],[3.26019527615158,51.2682587095714],[3.26033376142336,51.2684164458958],[3.26071727428689,51.2688348906164],[3.26093264387055,51.2690999564614],[3.2610171052535,51.2691992457752],[3.2610924979071,51.2692914973134],[3.26132785928408,51.269648295675],[3.26155660741223,51.2699725848574],[3.26199365616087,51.2705491241359],[3.26233075323189,51.2709787173281],[3.26263527147913,51.2713801936389],[3.26318146071906,51.2720295936182],[3.2634553363419,51.2723994935275],[3.26387483372983,51.2728611386423],[3.26498667289461,51.2741218634762],[3.26517515351057,51.2743542232742],[3.26548112654258,51.2747742458082],[3.2656719900105,51.2750622498242],[3.2663203480465,51.2760822455022],[3.26654447065414,51.2763705574121],[3.26711366310789,51.2770676621169],[3.26730922634662,51.2773139896127],[3.26740816509859,51.2774273141024],[3.26757606548435,51.2775934260445],[3.26767147535011,51.2776997646282],[3.26773641401449,51.277766420385],[3.26779499002104,51.2778677812358],[3.26796152484799,51.2780918203276],[3.26810230964377,51.2783109846482],[3.26832810971051,51.2786074199628],[3.26862657150391,51.2789566760241],[3.26874237571789,51.2791385255824],[3.26902437048823,51.2795594736799],[3.26913374562362,51.2797007048195],[3.26927243189256,51.2798526371773],[3.26941087304577,51.2800149963489],[3.269480019941,51.2801384716602],[3.26954050469004,51.2802375315838],[3.26960554768791,51.2803783508342],[3.2696561132308,51.2805062888289],[3.26971930963901,51.2806470908611],[3.26979603885454,51.2807625246361],[3.2698714676203,51.2808547701458],[3.26999185037356,51.2809995788984],[3.27009449815115,51.2811129352414],[3.2701440653583,51.2812049406957],[3.27019200395636,51.2812876605657],[3.27025495720616,51.281438889248],[3.27030147589511,51.2815818538444],[3.27035660345637,51.2817515507878],[3.27040769148064,51.2818574758765],[3.27045394771746,51.2819332271701],[3.27053100858093,51.2820347577689],[3.27074541220138,51.2822673477113],[3.27082630552906,51.2823631195843],[3.27088576765603,51.282427405014],[3.27104201359748,51.2826188971413],[3.27116875699479,51.2828077980811],[3.27162193540852,51.2834157337479],[3.27172073393982,51.2835360056663],[3.27180204065149,51.2836143985309],[3.27186023110148,51.283654336723],[3.27197164274324,51.283709832099],[3.27198954295642,51.2840483689484],[3.27261780591238,51.2848340593713],[3.27284396614458,51.2851177412029],[3.27303785499938,51.2853594071212],[3.27325146915058,51.2856267487714],[3.27331069361624,51.2857014598663],[3.26947825339915,51.2891412147653],[3.26507142245641,51.2931641688082],[3.26360966231093,51.2944808492888],[3.26212327360781,51.2958192990123],[3.26200322807461,51.2961264191208],[3.26092601418833,51.2968881151386],[3.26002898511676,51.297688569081],[3.25655103208617,51.3009087330749],[3.25349882891109,51.3036994110719],[3.25015333921334,51.3067549256548],[3.2476057897016,51.3090565654202],[3.24514026730049,51.311166567622],[3.24492693869535,51.3113487941918],[3.24342813042563,51.3126973214647],[3.24304443790033,51.3130424765381],[3.2415360502617,51.3144766400073],[3.24122535270763,51.314784242961],[3.24044615696666,51.315501077561],[3.23927130837709,51.3165953823389],[3.23777810758468,51.3179276685976],[3.23652576606209,51.3190096189672],[3.23581748510873,51.3196181735765],[3.23529423980725,51.3200697380374],[3.23525456731047,51.3201041226351],[3.2351826458368,51.3201718039736],[3.23388449515895,51.3213830737211],[3.23247253914456,51.3227079594307],[3.23093008815965,51.3241474556722],[3.22947761875285,51.3253826897573],[3.2285639684844,51.3262128751954],[3.22855357691846,51.3265615725213],[3.22855176056551,51.3266357179194],[3.22862168542054,51.327103384517],[3.22873744816656,51.3276630364123],[3.22888516062254,51.3282021368755],[3.22904287815936,51.3285594025624],[3.2293201788342,51.329018632121],[3.22975451284536,51.3296369651788],[3.23014563102167,51.3301320494165],[3.23058498059136,51.3306218011504],[3.2309891659728,51.3310370510036],[3.2309661529871,51.3310704351716],[3.23007611786321,51.3322172077824],[3.22979718191221,51.3325795484868],[3.22573221804906,51.3378152555655],[3.22522978129227,51.3384616522167],[3.22515334889196,51.3385605711823],[3.22747104921302,51.3388783872471],[3.2274448730904,51.3389650445342],[3.22727575020518,51.3395242707783],[3.22722971271969,51.3396663587077],[3.22745801707917,51.3397114309477],[3.2275997578448,51.3397406056767],[3.22786121456216,51.3397917900351],[3.22784451091577,51.3397939469382],[3.22783879153279,51.3398008446528],[3.22783660100735,51.3398147290424],[3.22776572712211,51.3400643455529],[3.2255081864251,51.3466326298399],[3.22544719411212,51.3468556876201],[3.22543956533575,51.3470155264824],[3.22545541633537,51.347198767334],[3.22554136625435,51.3473907952263],[3.22573455713698,51.3477368159994],[3.22670223267465,51.3493985622742],[3.22684847688458,51.3496977774715],[3.22692501807329,51.3499719871237],[3.22695223580988,51.3502955496693],[3.22691091570952,51.3506219288705],[3.22681375101539,51.3509616758955],[3.22668897552671,51.3512953630989],[3.22440461814136,51.3574206890789],[3.22420567688452,51.3578336136034],[3.22402560656818,51.3582316556712],[3.22382606612746,51.3585182666823],[3.22352155995463,51.3588583269616],[3.22321443276038,51.3591543275152],[3.22287610124873,51.3594395969223],[3.22254668051337,51.3596635361191],[3.22213324397056,51.3599167908612],[3.22125648794883,51.360344016675],[3.22059917624503,51.3605786846034],[3.21977030690474,51.3607896710772],[3.21933471767987,51.3608897427416],[3.21835908716027,51.361047152651],[3.19759416135762,51.3632960133711],[3.19529139914045,51.3632257542061],[3.19242751717216,51.3632391157376],[3.18985426067919,51.3632518193733],[3.18976525724935,51.3632578878444],[3.1874205015423,51.3632380451104],[3.18333864913803,51.3615078267032],[3.18291694497937,51.3612776493972],[3.18256415583542,51.3610307776258],[3.18020457702949,51.359494945795],[3.1716592230376,51.3538062728347],[3.17104674831482,51.3533713369903],[3.17061019847251,51.3530760713161],[3.17029176480587,51.3527935851549],[3.16978471610057,51.3522183341348],[3.16949980601742,51.3518562274549],[3.16929890126046,51.351465999433],[3.16915601383337,51.350907173248],[3.16913687596762,51.3502858642926],[3.16922279919264,51.3497525273829],[3.16947301721461,51.349019220501],[3.16994116774013,51.348086484596],[3.17527281863511,51.3396983931535],[3.17585917044731,51.3388375085579],[3.17637103152289,51.3381392631325],[3.18204559201075,51.3310834506336],[3.18095387026815,51.3305904576172],[3.18003049666395,51.3303146796724],[3.17935404162295,51.3302209861327],[3.17821655858082,51.3299279815646],[3.1774189023669,51.3296557626636],[3.17629235369172,51.3292979560047],[3.17539944489124,51.3289181550632],[3.17469067249223,51.3286433354267],[3.17375598217178,51.3283789817197],[3.17185785533873,51.327962365994],[3.16971955623492,51.3273926458596],[3.16742682651428,51.3267170290433],[3.16509920222562,51.3261059061679],[3.16387545330165,51.3257945035818],[3.16341344886429,51.3256368447034],[3.1624442915752,51.3253511911794],[3.1611874178658,51.3250347880807],[3.15937001110033,51.3245817093228],[3.15736601157256,51.3241220606594],[3.15627195449986,51.3238767968612],[3.15520485182358,51.3235912402159],[3.15476744892041,51.3234140989248]]]
}
}
});
map.addLayer({
'id': 'route',
'type': 'fill',
'source': 'Brugge',
'layout': {},
'paint': {
'fill-color': '#088',
'fill-opacity': 0.4
}
});
};
var getCoordinatenGeneric = function getCoordinaten(url){
var list = [];
$.when($.getJSON(url).done(function (json) {
for (var i = 0; i < json.length; i++) {
var item = json[i];
var geo = item.json_geometry;
var coords = {
lat: geo.coordinates[1],
long: geo.coordinates[0]
};
list.push(coords);
}
}));
return list;
};
function getCoordinatenMusea(){
var list = [];
$.when($.getJSON("data/musea.json").done(function (json) {
for (var i = 0; i < json.length; i++) {
var item = json[i];
var address = item.Ligging.split(" ");
$.getJSON("https://maps.googleapis.com/maps/api/geocode/json?address="+address[0]+"+"+address[1]+"&key=AIzaSyAM6FLYxpA8usOS4sBeYwo3wwzifUMPEfE").done(function(json){
var geo = json.results[0].geometry.location;
var object;
object = {
lat:geo.lat,
long:geo.lng
};
list.push(object);
});
}
}));
return list;
}
function getCoordinatenZitBanken(){
var list = [];
$.when($.getJSON("data/zitbanken.json").done(function (json) {
for (var i = 0; i < json.length; i++) {
var item = json[i];
var geo = item.json_geometry;
if(!Array.isArray(geo.coordinates[0])){
var object;
object = {
lat:geo.coordinates[1],
long:geo.coordinates[0]
};
list.push(object);
}
else{
for(var j = 0; j<geo.coordinates.length;j++){
var object;
object = {
lat:geo.coordinates[j][1],
long:geo.coordinates[j][0]
};
list.push(object);
}}}
}));
return list;
}
var getCoordinatenParken = function getCoordinatenParken(){
var list = [];
$.when($.getJSON("data/groen.json").done(function (json) {
for (var i = 0; i < json.length; i++) {
var item = json[i];
//console.log(item.BEHEERSOBJECT);
if(item.BEHEERSOBJECT == "parken"){
if(item.PUBLIEK_TOEGANKELIJK == "J"){
console.log(item);
var geo = item.json_geometry;
var glat = 0;
var glong = 0;
for(var j=0; j<geo.coordinates.length; j++){
glat += geo.coordinates[0][j][1];
glong += geo.coordinates[0][j][0];
}
glat = glat/geo.coordinates.length;
glong = glong/geo.coordinates.length;
var object = {
lat:glat,
long:glong
};
list.push(object);
}
}
}
}));
return list;
};
function getCoordinatenBib(){
return getCoordinatenGeneric("/data/bibliotheken.json");
}
function getCoordinatenLokalen(){
return getCoordinatenGeneric("/data/jeugdlokalen.json");
}
function getCoordinatenSport(){
return getCoordinatenGeneric("/data/sport.json");
}
function getCoordinatenZwembaden(){
return getCoordinatenGeneric("/data/zwembaden.json");
}
var data = {
libPoints: getCoordinatenBib,
museumPoints: getCoordinatenMusea,
sportPoints: getCoordinatenSport,
swimmingPoints: getCoordinatenZwembaden,
youthPoints: getCoordinatenLokalen,
museaPoints: getCoordinatenMusea,
benchPoints: getCoordinatenZitBanken,
parkPoints: getCoordinatenParken
};
(function() {
var map;
var list = [];
$(function () {
makeMap();
addEventListeners();
$("#route").on('click', openRoute);
setInterval(determinePosition, 5000);
console.log(data.benchPoints());
});
var makeMap = function makeMap() {
mapboxgl.accessToken = 'pk.eyJ1Ijoicm9vdHNhbSIsImEiOiJjaXU5a2V4aGcwMDFlMnRtazRibjZiZGN3In0.Q1K1wv1ugX49a4e1pCLMZw';
map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/light-v9',
center: [3.227180, 51.210358],
zoom: 13.7
});
map.on('load', function () {
drawBruges(map);
});
};
})();
| public/js/app.min.js | var menuOpen = false;
var addEventListeners = function () {
$(".hamburger").on('click', toggleMenu);
$(".menu-item").on('click', togglePage);
};
var toggleMenu = function() {
toggleButtonIcon($(".hamburger i"), "menu", "close");
$(".menu").slideToggle();
};
var togglePage = function() {
$();
};
var toggleButtonIcon = function(button, openIcon, closeIcon) {
if (menuOpen) {
button.html(openIcon);
menuOpen = false;
} else {
button.html(closeIcon);
menuOpen = true;
}
};
var xStart;
var yStart;
var determinePosition = function determinePosition() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(setPosition, showError);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
};
function setPosition(position) {
xStart = position.coords.latitude;
yStart = position.coords.longitude;
}
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation.";
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable.";
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out.";
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred.";
break;
}
}
var openRoute = function openRoute() {
var xDestination = 51.2079017; //end x-position here (open data)
var yDestination = 3.2221577; //end x-position here
var xCenter = (xStart + xDestination)/2;
var yCenter = (yStart + yDestination)/2;
var zoom = 18.75;
window.open("https://www.google.be/maps/dir/" + xStart + "," + yStart + "/" + xDestination + "," + yDestination + "/@" + xCenter + "," + yCenter + "," + zoom +"z");
};
<<<<<<< HEAD
/**
* Created by Sam on 14/10/2016.
*/
var drawBruges = function drawBruges(map) {
map.addSource('Brugge', {
'type': 'geojson',
'data': {
'type': 'Feature',
'properties': {
'name': 'Brugge'
},
'geometry': {
"type":"Polygon",
"coordinates":[[[3.15476744892041,51.3234140989248], [3.15506341515048,51.3228446746481], [3.15509453886165,51.3227858937051], [3.15530870478349,51.3223743889867], [3.15550350210443,51.3219962912782], [3.1556728415599,51.3216723970495], [3.1557062956764,51.3215950987342], [3.15579462817575,51.3213990039186], [3.15667203395984,51.3194507381225], [3.15754181947154,51.3196404030739], [3.15936367627512,51.3200564762843], [3.16098086871382,51.3203788898685], [3.16280916017925,51.3208343745895], [3.1639966232684,51.3211848211612], [3.16581496034153,51.3215984403175], [3.1679131357432,51.322134223545], [3.17003122134468,51.3226168650105], [3.17215099137294,51.3231075967475], [3.1735858682092,51.3216063460196], [3.17534803942473,51.319742188738], [3.1755286376775,51.3195504851308], [3.17655272712307,51.3185560988896], [3.17667795093217,51.3184322065145], [3.17689604796177,51.3182200192837], [3.17643625233827,51.3178329878349], [3.17598776458789,51.317437956553], [3.17555253013673,51.317103315077], [3.1754232009453,51.3170266904507], [3.17495142289077,51.3167473017668], [3.17415243826047,51.3161760697269], [3.17384941664817,51.31595052351], [3.17378162517701,51.3157099657644], [3.17384524300519,51.315536785022], [3.1739658014535,51.3152343910321], [3.17386972526281,51.3147270209669], [3.17369656974869,51.3141250096725], [3.17344305499472,51.3138443380735], [3.1733010998701,51.313827841938],[3.17310261201315,51.3137806462312],[3.17300844905228,51.3137032146231],[3.17274571090371,51.3130620569122],[3.17257729447908,51.3126362311054],[3.17261172601702,51.3125195382153],[3.17279162303132,51.3123544840438],[3.1729937606348,51.3121873363361],[3.17310430759215,51.3120586641588],[3.17302123170565,51.3118376511757],[3.17274417576029,51.3114663525244],[3.17230308267652,51.3110030097627],[3.17183835940585,51.3106680551923],[3.17175261320081,51.3106231542561],[3.17153735397104,51.3105097337894],[3.17142203038306,51.310320840576],[3.17146427126183,51.3100443100593],[3.17160676908104,51.3095358699468],[3.17176083620998,51.3092245453577],[3.17196541003335,51.3091060942116],[3.17223118594125,51.3089083021928],[3.17238268400109,51.3086247624568],[3.17309483079302,51.3071718386796],[3.17342459272994,51.306425409748],[3.17350320541069,51.3059557223854],[3.17339838360704,51.3053578736634],[3.17328107773318,51.3043102769377],[3.17306295074933,51.3041655416366],[3.17298549325438,51.3039422668002],[3.17293607642181,51.3029150539165],[3.17300393770085,51.3026480512373],[3.17323352696092,51.301625970483],[3.17342342212013,51.300925640765],[3.17368341293928,51.3005910461307],[3.17390468514671,51.3003244309611],[3.1739320583753,51.3000500663797],[3.17385601077089,51.29991603515],[3.17355679710755,51.299762370887],[3.1731685230655,51.2996217131672],[3.17252012625811,51.2994610461976],[3.17130277628762,51.2988542751669],[3.1698713635903,51.2980912021006],[3.16866141603943,51.2974867954066],[3.16791522580564,51.2971060944108],[3.16747416265353,51.2967203705594],[3.16696365838436,51.2963756583304],[3.16618658079379,51.2961186269363],[3.16627627649647,51.2956513719237],[3.16641722529727,51.2952750252394],[3.16665689086227,51.2947977032766],[3.16701528461745,51.2943748910211],[3.16739036185694,51.2939499291836],[3.1678529909035,51.2935698889541],[3.16841581349436,51.293102791269],[3.16875438456576,51.2928026084682],[3.16893711641016,51.2924533348103],[3.16933916629921,51.2918409101042],[3.16957291458633,51.2913044219949],[3.1696306777941,51.290927229207],[3.16953928432454,51.2906006738722],[3.16951627874094,51.2905610408977],[3.1694340004465,51.2904547547911],[3.17036310933272,51.2901871968778],[3.17104525016302,51.2900364944476],[3.17180177053004,51.2899398456262],[3.17249144240489,51.2897834168881],[3.17300096348158,51.2895892424313],[3.17346356730454,51.2892787098291],[3.17375108312653,51.2888771798559],[3.17386765980232,51.288439160413],[3.17396641754741,51.2880473141665],[3.17418639373682,51.2876126547226],[3.17449535670166,51.2873109982228],[3.17491816336889,51.2871819946244],[3.17509876978688,51.2871293496488],[3.17534454403696,51.2870576608446],[3.17577305062904,51.2867780641417],[3.17652015851627,51.2860358242474],[3.17691658967854,51.2855646941437],[3.17721463378567,51.2851829616662],[3.1775603133584,51.2849616256263],[3.1779900492843,51.2845603564639],[3.17832776780491,51.2839994016976],[3.17861685890206,51.2833162804446],[3.17861429841675,51.2829825122503],[3.17856268800088,51.2826158039971],[3.17849900536076,51.2822153683288],[3.17844302124944,51.2818752690015],[3.17855891708002,51.2818231274318],[3.17879070796253,51.2817188439488],[3.17880812004049,51.2811094749196],[3.17892753307715,51.2804130593557],[3.17917807743073,51.2799358204691],[3.17934967237653,51.2795110944196],[3.17933617139826,51.2791714217604],[3.17932987941229,51.2789836281538],[3.17937192661097,51.2787117253581],[3.17959080289983,51.2783164443348],[3.18001623406276,51.2777911294661],[3.18038873916675,51.2773846415663],[3.18063448043445,51.2770220753429],[3.18078243853979,51.2766538925369],[3.1808144695859,51.2762671643712],[3.18093124600716,51.2759624042453],[3.18106532667062,51.2757760182642],[3.18142234598583,51.2757587389273],[3.18151764807326,51.2754989573376],[3.18107300180526,51.2753299452897],[3.18113626249181,51.2747326227254],[3.18132743485327,51.2739731872523],[3.18163319019993,51.2732844298128],[3.18195822671354,51.2724185633684],[3.18230651226599,51.2716549060325],[3.18265392037281,51.2709978513779],[3.1834743958537,51.2711335376099],[3.18466099047839,51.2714015096768],[3.18638593131092,51.2717130871141],[3.18648525394389,51.2717303023342],[3.18624585994951,51.2725008527338],[3.18608980034422,51.2729720974863],[3.18591850256472,51.2733157183932],[3.18631493480889,51.2732733238407],[3.18668180995784,51.2733036392951],[3.18735572005088,51.27346564695],[3.18796173346831,51.2736825976427],[3.18855561568957,51.2738681358619],[3.18929368815432,51.2739774654944],[3.1901356654401,51.2739962770258],[3.19022373738851,51.2740933362992],[3.19037285076704,51.2742605326133],[3.19188815549819,51.274392641296],[3.19333851924778,51.2762206102699],[3.19356308201557,51.2759609435921],[3.19386071032224,51.275441265043],[3.19407500285814,51.2748558648186],[3.19416487428079,51.2743688894703],[3.19410171837205,51.2740159792625],[3.19392950424769,51.2733722799932],[3.19377277176541,51.2727009219535],[3.19361341432848,51.2721338320898],[3.19365774476845,51.2718410880757],[3.19373346587326,51.271475649195],[3.19374264520968,51.2711848739744],[3.19347971060157,51.2708427276876],[3.19302839238965,51.270425704295],[3.19253799645677,51.2698738665334],[3.19249847680538,51.2698294384346],[3.19190410756553,51.269152570054],[3.19098837398796,51.2681816357666],[3.19041418765281,51.2675849191986],[3.1903341017376,51.2675377689613],[3.18964261994679,51.2671241354377],[3.18957402647269,51.2670608754344],[3.18867019334018,51.2662070821886],[3.18839729649675,51.2659691190229],[3.18816324167019,51.2657292247756],[3.18807319639021,51.2656379379321],[3.18778407028973,51.2653117400157],[3.18736205426909,51.2648358847215],[3.18713434347436,51.2645647629779],[3.18680718584883,51.2642092119995],[3.18627003418217,51.2636128430185],[3.18539301071746,51.2626538359435],[3.18495700643584,51.2621488603634],[3.18498561683436,51.2621132224796],[3.18662214568783,51.2599984725565],[3.18708265161254,51.2593912036094],[3.18732906454668,51.259069188313],[3.18739211079214,51.2589863811315],[3.18746090160483,51.258895519372],[3.18749153067166,51.2588529479923],[3.18760053434173,51.2587057043326],[3.18782384400576,51.258420540294],[3.18803771355747,51.2581433935464],[3.18871347992763,51.2572752086099],[3.18915148250257,51.2566792955609],[3.18977008909538,51.2558789063955],[3.19028367350119,51.2552142114717],[3.19038876229293,51.2550750380978],[3.19050343317817,51.2549220539368],[3.19106165521029,51.2541708869607],[3.19122042118425,51.2538804389526],[3.19136626169414,51.2535898621652],[3.19146905556161,51.2533950407213],[3.19148065942712,51.2533742970205],[3.19144082712144,51.2531965985392],[3.19141716907053,51.2529634366154],[3.19159430270969,51.2526766472186],[3.19167379874787,51.2525267886076],[3.19176267134607,51.2523712289709],[3.19184582938995,51.2522225654857],[3.19192895765747,51.2520750604818],[3.19200056986169,51.2519448235297],[3.19205281372772,51.2518503180283],[3.19274755719349,51.2511016586289],[3.19282942276874,51.2505647702811],[3.19040385790865,51.2502405101886],[3.18902815094746,51.2500228516158],[3.1884625825561,51.2498978530311],[3.18811195226993,51.2497437069861],[3.18782965758167,51.2495890827954],[3.1874477109931,51.2493592975772],[3.18644012945233,51.2488254412522],[3.18605110582305,51.2485839922112],[3.18571327451568,51.2483627538113],[3.18509281755604,51.2480007861936],[3.18491294765785,51.2478854207523],[3.18477664662316,51.2477994619143],[3.18427123464052,51.2474884707341],[3.18378962070431,51.2471858274421],[3.18332017857371,51.2468404267696],[3.18258562968245,51.2463196998524],[3.18156171218044,51.2455619793378],[3.18046960449738,51.2447282398427],[3.17973755746178,51.2441843423463],[3.1793757196188,51.2438933128902],[3.17923419857496,51.2437957063894],[3.17889670041859,51.2435640211575],[3.17853203361012,51.2433842097928],[3.17820866924296,51.2432500077673],[3.17785782698995,51.2431074164183],[3.17744735934116,51.2429862419388],[3.17604868558225,51.2425943707237],[3.1755474805233,51.2424120149908],[3.17514086480678,51.2422850769468],[3.17373871814952,51.2418861897848],[3.17341404150049,51.2418041092711],[3.17327236106815,51.2417134468498],[3.1726726564114,51.2412693426051],[3.17231395514231,51.2410745067335],[3.17219743516672,51.2410107508484],[3.17140160363229,51.2407280545288],[3.17045586460807,51.2404600588521],[3.16977689513978,51.2402283651251],[3.1686905175879,51.2399739952191],[3.16795752878095,51.2398332922808],[3.16697470021115,51.2396448526925],[3.16612494510392,51.2394508041295],[3.1642653146394,51.2387585983636],[3.16411368499205,51.2386967946361],[3.16386885767695,51.2385981174249],[3.1615650617554,51.2376660978426],[3.15977063136067,51.2368852528256],[3.16056103547473,51.236303468496],[3.16142106691819,51.2355983919284],[3.16193056151533,51.23517017752],[3.1625970601727,51.2347377671284],[3.16251972067673,51.2344449473676],[3.16251676872727,51.2341308675907],[3.1626409109293,51.2338273541459],[3.1629539237286,51.233429580379],[3.16342841906664,51.232925677277],[3.16379000628593,51.2326477581864],[3.16429668368435,51.232183580428],[3.16480985045857,51.2321111596832],[3.1655902999614,51.2319811943918],[3.16569206296321,51.2319717994182],[3.16580823009951,51.2319764570606],[3.16667408545004,51.2323282776934],[3.16685691966085,51.2323961897117],[3.16706065045767,51.2324411365724],[3.16722429098667,51.2324659754612],[3.16806726543866,51.232488438668],[3.16877687021645,51.2324573949494],[3.16916139179771,51.2324346402451],[3.16934899339294,51.2324608779541],[3.1695475796303,51.2324188543054],[3.16973217832339,51.2322747094351],[3.17000898753736,51.2318464203948],[3.17023266533426,51.2312588294725],[3.17042943104327,51.2309282311965],[3.17063181928014,51.2307379109113],[3.17076298317812,51.2304460488109],[3.17079765579506,51.2302459180128],[3.17088212069154,51.2300474501576],[3.17106042557112,51.2298603618694],[3.17146756653924,51.2294588833202],[3.17194710628696,51.228897054891],[3.17271191177279,51.2280066760235],[3.17292468482061,51.227626404528],[3.17303475282089,51.2272926077604],[3.17326109420155,51.2264547247409],[3.17339189866841,51.2261037542367],[3.1734896215101,51.225963361136],[3.17321484439758,51.2258829414102],[3.17242161798612,51.2256524225742],[3.17129065677243,51.2252782586969],[3.1716994801652,51.2248095823769],[3.17200128703221,51.2244835203978],[3.17226202075837,51.2241037348279],[3.17319173242259,51.222896333989],[3.17222771671291,51.2226351154729],[3.17141131053525,51.2224472322553],[3.17081853864202,51.2223183921842],[3.17084859443146,51.2224415355107],[3.17091885465746,51.222795698679],[3.17103410984322,51.2231225047082],[3.1710102147763,51.2231906353988],[3.17084267677296,51.223175032746],[3.17013613339196,51.2229488520414],[3.16918499114134,51.2226182074816],[3.16903751217592,51.222612076508],[3.16892210790607,51.2227221565273],[3.1684241749974,51.2232826283],[3.16834700938247,51.2233409471067],[3.16783192489975,51.2233484668666],[3.16761838160563,51.2233277571815],[3.16696665658208,51.2228367352819],[3.16677836046466,51.2226957591779],[3.1665524544525,51.2228684513975],[3.16592643076616,51.2232421937254],[3.16539809317134,51.2236204030554],[3.16505054708635,51.2238579100408],[3.16465438692609,51.2239767176058],[3.16419880459066,51.224038134742],[3.16375631585807,51.2240927303458],[3.16328089616985,51.2240647097354],[3.16287449193554,51.2240084192234],[3.16258928595885,51.223832841646],[3.1623891925301,51.2236488604192],[3.16220705423451,51.2234129132502],[3.16215073713538,51.2231643428129],[3.16212039638933,51.2227677031609],[3.16213481478206,51.2223529782078],[3.16218888398309,51.2221889714978],[3.16221622453893,51.2220594579677],[3.16239232916945,51.2218862660053],[3.16281554642514,51.2216483792292],[3.16329143520679,51.2213716264439],[3.16114615895228,51.2206938306548],[3.16145770306628,51.2204212016149],[3.16098112199367,51.2202969739487],[3.1603139367672,51.2201221251345],[3.1594449752533,51.2199718637248],[3.15838363143359,51.2197686375962],[3.15726071521583,51.2195207344505],[3.15659040722091,51.2193249727945],[3.15626929836493,51.2191837771015],[3.15593264970845,51.2190725516328],[3.15506378215516,51.218919940853],[3.15427195026105,51.2187854975393],[3.15397066697613,51.2187337315582],[3.15372448741642,51.2186918017397],[3.15363998802598,51.2186770273822],[3.15329264619962,51.2186224687841],[3.15169010591714,51.2183707415913],[3.15029371441681,51.218210348806],[3.14870372751195,51.2179030845295],[3.14820471874578,51.218074084138],[3.14751708229628,51.2182605173493],[3.14683670442193,51.2183809662146],[3.14613521769995,51.2184617915615],[3.14542696530309,51.2184486746127],[3.14497360890956,51.2183559112697],[3.14532492766166,51.2181880331774],[3.14575231317975,51.2179340255621],[3.14614458993749,51.2176112804075],[3.14532940131019,51.2174545167469],[3.14426649374618,51.2171746610493],[3.14361035151667,51.2170751573731],[3.1430304553259,51.2169532627981],[3.14247757612462,51.2167864495855],[3.14172938443848,51.2163985816684],[3.14117939679204,51.216052167587],[3.14125028496683,51.2156021033211],[3.14206922690941,51.2140704625183],[3.14292036760192,51.2124348511282],[3.14367776657581,51.2114159400615],[3.14373898137794,51.2113331354811],[3.14376768334576,51.2112940311834],[3.14612063819804,51.2114840971717],[3.14619682464889,51.2113226430088],[3.1462261316596,51.2112603669987],[3.14629181996211,51.2111474767729],[3.14644043350726,51.2108975380909],[3.14654950506344,51.2105370979547],[3.14661904540372,51.2102770708685],[3.14657300738866,51.2101328952407],[3.14646175240936,51.2099428496417],[3.14731162983383,51.2087695826597],[3.14800371386751,51.2077731468262],[3.148314165655,51.2074008769874],[3.14877283032309,51.2069339491466],[3.14900629290736,51.2065423412809],[3.14925541441923,51.2061161282841],[3.14926118958171,51.2061069168708],[3.14951019630222,51.205331881866],[3.15173454883397,51.2030857248544],[3.15194741243182,51.2028457112612],[3.15223052996081,51.2024580844688],[3.15245620442545,51.2021509871768],[3.15265324761795,51.2018806788992],[3.15284454481464,51.2016184233077],[3.15332851834747,51.2008840385377],[3.15393770232886,51.2002992739097],[3.15395472131134,51.2002832245474],[3.15442883125395,51.1998558351274],[3.1546871480608,51.199427387149],[3.15504380200221,51.1986928467433],[3.15557945590749,51.1978836563395],[3.15601882157019,51.1971592324723],[3.15652159802386,51.1964783354031],[3.15694915954925,51.1958522912088],[3.15697796123383,51.1958085492086],[3.15763479485401,51.1958709054196],[3.15857309828867,51.1936137562932],[3.1596805232248,51.1922286434938],[3.15927518113725,51.1921422171521],[3.159451955535,51.1917256717344],[3.15967555715399,51.1912099416968],[3.1598371112066,51.1907399316966],[3.1598811291493,51.1903220278293],[3.16006321229482,51.1899136477493],[3.16030311982143,51.1895510546383],[3.16042073111318,51.1888546136439],[3.16061653477046,51.1882006910969],[3.16082880537118,51.1874090300901],[3.16122545376731,51.1866180933022],[3.16141908125472,51.1861901278472],[3.16188193901989,51.185333808948],[3.16129705453919,51.1852756862577],[3.16094013544376,51.1852442266879],[3.16077231736415,51.1852448295329],[3.16051622136734,51.1852364176758],[3.15988414250638,51.1852206840149],[3.15915879633096,51.1851750206306],[3.15829165301397,51.1851221063842],[3.15776183986885,51.1850738010934],[3.15741873092387,51.1850077059764],[3.15694082916283,51.1848776485785],[3.15643001828892,51.1847368217787],[3.15605085682745,51.1846390631285],[3.15501217571307,51.1843757663466],[3.15390035010763,51.1842310731361],[3.15324736526839,51.1840273503884],[3.15278275134848,51.1838835059847],[3.15150630161256,51.1834763482097],[3.15057407598905,51.1832338090208],[3.15013634306435,51.1831203619522],[3.14919766864119,51.1827722870204],[3.14833589297231,51.1823044747654],[3.14793284843889,51.1819932086749],[3.14759489717925,51.1817312867346],[3.14728704381369,51.1815171890003],[3.14535146380146,51.1810776540258],[3.14528184248192,51.1810607089845],[3.14413802019681,51.1808043385378],[3.14430700746982,51.180758575134],[3.14430895199837,51.1806844267252],[3.1443117776304,51.180576679815],[3.14347876316515,51.1801404186491],[3.14340473905991,51.1800805481157],[3.14294978212464,51.1797119406533],[3.14261612214057,51.1793584964017],[3.14231098101985,51.1789022062991],[3.14132154002559,51.1785268855466],[3.13995547704437,51.1781012855534],[3.13869017337865,51.1777010548208],[3.13776266074199,51.1773564791328],[3.13746970802188,51.1772792585607],[3.13732025834042,51.1772834958341],[3.13719388369683,51.1773215811088],[3.13696393367295,51.1774420266009],[3.13661192209416,51.1777164899753],[3.13644417854881,51.1778549663142],[3.13636914439857,51.1779735492474],[3.13629823277975,51.1781454839192],[3.13626451294873,51.1782355254448],[3.13628295339714,51.1783052509608],[3.13628148551224,51.1783608622184],[3.13627064307386,51.178631928638],[3.13616236188772,51.1789622409459],[3.13600315580255,51.1791263011966],[3.13583210890377,51.1791801434931],[3.13565991466269,51.179137785989],[3.13559748180377,51.1790583302846],[3.13555733705706,51.1788330873832],[3.13554088804953,51.1784087631594],[3.13559669126925,51.1779712861452],[3.13571411387684,51.1775043208942],[3.1358565813528,51.1771361221809],[3.13621806502032,51.1764329713964],[3.13636578790515,51.1761447900604],[3.13643181754465,51.1760180009671],[3.1367122758827,51.1755202856559],[3.1369964849467,51.175089824248],[3.13732510736984,51.1742333540956],[3.13731186004033,51.1741764305221],[3.13728389892103,51.1741181947263],[3.13727308506845,51.1741088109281],[3.13724451295314,51.1740737465213],[3.13723790463334,51.1740447054437],[3.13724041987284,51.1740192361107],[3.13723992122079,51.173968239823],[3.13722929073917,51.1739519046001],[3.13722652129742,51.1739171090845],[3.13725382098475,51.1738606080495],[3.13729365521295,51.1738181442922],[3.13732907005475,51.1738034477928],[3.13739765948469,51.1737890969691],[3.13746047538266,51.1737839570563],[3.13759870291817,51.173785397243],[3.13770523237318,51.1738004137192],[3.13784085344835,51.1738307986781],[3.13794713879151,51.1738550834978],[3.13917719980078,51.1736291577367],[3.13929223013954,51.1736013823742],[3.1388551216907,51.1726986953583],[3.13853085892186,51.1718516489089],[3.13811550247705,51.1711740092579],[3.13785201065671,51.1706798956078],[3.13742296035101,51.1696834155551],[3.13731889509582,51.1694354874222],[3.1370482144941,51.1687952763139],[3.13681138426444,51.1681299216891],[3.13668722038421,51.1677357629264],[3.13662132452824,51.1673688660972],[3.13661487037272,51.1673340320475],[3.13643710597592,51.1661072295077],[3.13642733350621,51.1660584541129],[3.1364223555708,51.1660375421347],[3.13627850876899,51.1653418652208],[3.13604773886254,51.1645178028048],[3.1358925256416,51.1639738213291],[3.13579977408849,51.1636472044236],[3.1355837079484,51.1628951452614],[3.1355252952621,51.1628736754535],[3.13522741243909,51.1629169214051],[3.13516715728643,51.1628954321816],[3.13513407558747,51.1628220764451],[3.1348681890236,51.1621425056949],[3.1345418180685,51.1615202469524],[3.13438655709948,51.1611883398481],[3.13411428025064,51.1606118416678],[3.13444218064093,51.1605480521505],[3.13480582847655,51.1605263553374],[3.13550478197887,51.1605093170769],[3.13560271022988,51.160499909269],[3.1370343820298,51.1603734596875],[3.13826775806018,51.1602182730187],[3.13919255786768,51.1601630038526],[3.14044209161316,51.1600937208935],[3.14172979661522,51.1600445224077],[3.14258273171996,51.15998848032],[3.1448309246864,51.1598576608314],[3.14586009428476,51.1598277575882],[3.14599441382087,51.1598361012826],[3.14607790033514,51.1592517246916],[3.14658500227379,51.1592407475348],[3.14719072405325,51.1591937034612],[3.14756486498551,51.1591929360782],[3.14760177479951,51.1591909998344],[3.1481240089826,51.1591651069019],[3.14882339109226,51.1591306111093],[3.15021025348323,51.1589525485508],[3.15149604324419,51.1588336907373],[3.15282773396556,51.1586503935419],[3.15444540818116,51.1583831046251],[3.15497167564353,51.1583433163022],[3.15629754890709,51.1582410427803],[3.15710944942652,51.1582018584312],[3.1578377787148,51.1581873074785],[3.15930351071553,51.1582347717204],[3.15953263170783,51.1582116216767],[3.16027712088482,51.1583559889394],[3.16053494180391,51.1583632616617],[3.16097657175074,51.1583179454062],[3.16175828589613,51.1582343827129],[3.1623589906063,51.1581663498427],[3.16243482162383,51.1583699297602],[3.16213478185001,51.1586415221714],[3.16212208119594,51.1587051313263],[3.16230174349077,51.1587417329299],[3.16425665403464,51.158901906775],[3.16445188533408,51.1589780660111],[3.1646783404709,51.1591298708763],[3.16483130720362,51.1592728141733],[3.16542324436004,51.1598316344472],[3.16560854512011,51.1600073548406],[3.1658629304455,51.1602915548593],[3.16590025084052,51.1603452436546],[3.16604228250874,51.1605552893436],[3.16607914201068,51.1607700586524],[3.16606593208362,51.1609252150022],[3.16601597646267,51.1612190636565],[3.16596910866997,51.1615361214309],[3.16596259648165,51.1615742983857],[3.16603953853578,51.1618787099375],[3.16624256951015,51.1622968167973],[3.16648376211891,51.1627361714984],[3.16665331158961,51.1630948335549],[3.16682664994178,51.1633063553809],[3.16696059012575,51.1634015876258],[3.1675281581312,51.1637642962274],[3.16808450411615,51.1640619903684],[3.16843546351889,51.1642475013282],[3.16892241391835,51.1648075530796],[3.16945903658608,51.1655152850515],[3.16961191840327,51.1657347069205],[3.16988392320708,51.1661245343247],[3.16996440542066,51.166435931685],[3.16997569331848,51.16692973048],[3.17003183640648,51.1671122447248],[3.17005570257579,51.1671878142468],[3.17015158628158,51.1672583199244],[3.170249223877,51.1673323199583],[3.17045210939762,51.1673274244159],[3.17178301407825,51.1670372871579],[3.17259243411364,51.1668843994479],[3.17322221047834,51.166764455164],[3.1754580399198,51.1663327749456],[3.1777351954974,51.1658690206439],[3.18037483500903,51.165355560681],[3.18269641309674,51.1648805695068],[3.18469997458168,51.1644429073117],[3.18715369560793,51.1639865366654],[3.18861172012409,51.1636905293629],[3.18913763856518,51.1635926410653],[3.19014132618699,51.1634056482242],[3.19234674343197,51.1629976839807],[3.19302844754669,51.1628607687875],[3.19308217528127,51.1628497146469],[3.19401388163645,51.162665449491],[3.19406208106153,51.1626543399399],[3.19593184230918,51.1622522425413],[3.19698944979105,51.1619706991638],[3.1981474149169,51.1616553744688],[3.19883770047272,51.1614686792935],[3.19920415534081,51.1615545878761],[3.19947347689218,51.1616186742092],[3.20035655731957,51.1618290555183],[3.20609394486985,51.1633840826829],[3.21213743961183,51.1650229444754],[3.21243222413384,51.1651023154087],[3.2135624405744,51.1653115381778],[3.21496234765221,51.1655720565006],[3.21603020343665,51.1658443844035],[3.21635745471201,51.1659530339389],[3.21645619008504,51.1661347809126],[3.21651365567714,51.1664204238122],[3.21660613367437,51.1668559025002],[3.21671381399295,51.1671234928825],[3.21685148082273,51.1672963480036],[3.21733504392192,51.167868907958],[3.21764475813162,51.1681662787409],[3.2180758353342,51.1685505869585],[3.21845534768363,51.1689332326515],[3.21910758812225,51.1696940045669],[3.21950723757193,51.1701579633208],[3.22013049936721,51.1707492521865],[3.22084518505847,51.1713715561849],[3.22185050132222,51.172170506755],[3.22252990671093,51.1727298785336],[3.22290859408499,51.1729236052329],[3.22326727106847,51.17303138053],[3.22331309126599,51.1730422544654],[3.22368869837745,51.1731362861501],[3.22424248104955,51.1734070312626],[3.22463736924357,51.1736924596209],[3.22507051537213,51.1738461460463],[3.22550474216333,51.1739558043775],[3.22586975623583,51.1740311846429],[3.22652955122161,51.1741140487194],[3.22780553999224,51.1743291760317],[3.22831778188843,51.1744152408781],[3.22877899404908,51.1746282864466],[3.22948623228505,51.1749584297495],[3.22971731885059,51.1751588230996],[3.22972063772643,51.1751739203303],[3.22976014723722,51.1752925053288],[3.22952862097257,51.1756390920459],[3.22860533864664,51.1769084161846],[3.22871859835433,51.1769512278684],[3.22915524836883,51.1771142034157],[3.22981479474925,51.1773604459852],[3.23003040076095,51.1774401673972],[3.23042503300444,51.1775876680634],[3.23053466606619,51.1776281253056],[3.2317861873114,51.1780956047584],[3.23292760567291,51.1784669858427],[3.23371851084879,51.1788477375775],[3.23385702260072,51.1789139639588],[3.23394995964128,51.1789588930824],[3.23400639732054,51.1789884065021],[3.23415568806165,51.1790663246299],[3.23425946019376,51.1791206284102],[3.23428855863905,51.1791371317828],[3.23428104294186,51.1794464757921],[3.23426248282854,51.1795274179751],[3.23436518716596,51.17947393724],[3.23468910049829,51.1793460942439],[3.23507691161787,51.1795479800172],[3.23628346409731,51.1797449645514],[3.23617663562099,51.1801205708379],[3.2360693557435,51.1805147144412],[3.23689450774186,51.1804739469092],[3.23956389147273,51.1804137233986],[3.23984245032695,51.1813226127798],[3.24051053056773,51.1813730283724],[3.24083609823491,51.1821687953493],[3.24117028304618,51.182226450173],[3.24201391916441,51.1823376334996],[3.2431752136506,51.182427500067],[3.24327484214771,51.1825014568224],[3.24463867160446,51.1844416151997],[3.2449477744332,51.1846995028437],[3.2453634665348,51.184895824367],[3.24608368256649,51.1851576152002],[3.24642134341164,51.1849951051098],[3.24655742408971,51.1849338187964],[3.24711294343993,51.1846829839548],[3.24786249692298,51.1844142860477],[3.24851943147902,51.1842397319617],[3.24905514544282,51.1841219688876],[3.24967215357758,51.1839203765522],[3.25008581946503,51.1837400339493],[3.25015865858803,51.1837013221448],[3.2503790742005,51.1835828867127],[3.25178938142356,51.1837480317535],[3.25467324849805,51.1841333333654],[3.25741377929769,51.1845774770002],[3.25972344517225,51.1849978144476],[3.26087314800229,51.1851916940441],[3.26103403012258,51.1851723423863],[3.26228343504842,51.1854389912608],[3.26357852565621,51.1856457935735],[3.26497640147033,51.1858732418242],[3.26573005409764,51.1860517865045],[3.26643503013524,51.1861835183657],[3.2668389210321,51.1862591326707],[3.26771106822598,51.1864179097176],[3.26775046653106,51.1863893053917],[3.26788472108451,51.1862480170449],[3.26827505307102,51.1858819779143],[3.26836385772602,51.1857912553558],[3.26847576763166,51.1856590291478],[3.26857645180529,51.1855336514645],[3.26865910948207,51.1853907231701],[3.26878553280247,51.1851902595045],[3.26972503938455,51.1835835591356],[3.27066704157381,51.1821031889924],[3.27107787438535,51.1814116934901],[3.27149802871131,51.1806368456332],[3.27181481905532,51.1800232763568],[3.27188533568655,51.179925428275],[3.27193313340955,51.1798528640945],[3.27198591669185,51.1798035232142],[3.27204013500934,51.1797715784195],[3.27287130594302,51.1794721916779],[3.27312711318206,51.1795707479508],[3.27374036239269,51.1796795687652],[3.27596240527847,51.1794278033011],[3.27823321924906,51.1792181648915],[3.27986618477013,51.1790837280982],[3.28081089066999,51.1789730658029],[3.28179868895494,51.1788326621571],[3.28211865641006,51.1787892501827],[3.28256461350341,51.1787191828079],[3.28270689673843,51.1787054252125],[3.28286025079018,51.1787705710183],[3.2837465966288,51.1794253493856],[3.28534708119952,51.1806904292723],[3.28585131433134,51.181049657788],[3.28613105772403,51.1812306830825],[3.28656696401256,51.181356353918],[3.28702457255507,51.1814208027436],[3.28865573478817,51.1814461486683],[3.28997798448511,51.1814350465837],[3.2900061532291,51.1818119292594],[3.28978193262197,51.1838552486298],[3.28969807844003,51.1846911706663],[3.28966606095153,51.1848797704082],[3.28958905690905,51.1849404863289],[3.28853104137084,51.1854812750962],[3.28744428226214,51.1859881850348],[3.28690849197604,51.1862718357662],[3.28647787980265,51.1863930496802],[3.28383738702026,51.1867860311313],[3.28430318698206,51.1870556809942],[3.28583742529901,51.1878496488084],[3.28612626647429,51.1880377096859],[3.28634759288968,51.1881950216926],[3.28650557419066,51.1883007641696],[3.28665106078289,51.1887864934398],[3.28708056717118,51.1887139402023],[3.28766804585962,51.1885883643766],[3.28784597766389,51.1885494317692],[3.28794304871678,51.1885781315499],[3.28801640646048,51.1887549466749],[3.28806887415235,51.1888782639003],[3.28817484293034,51.1892396333635],[3.28807344567444,51.1894774286034],[3.2876897940323,51.1900382785011],[3.28743406587304,51.1904102466752],[3.28691914261391,51.1912236802602],[3.28666928231779,51.1915806354424],[3.28646881724832,51.1917955044162],[3.28615373848689,51.1920220709038],[3.28592094036175,51.192199559867],[3.28540857493169,51.1927418406502],[3.2844269050718,51.194035382348],[3.28582465556794,51.1944421995223],[3.28380174749298,51.1953820179001],[3.28251757470339,51.1959589198714],[3.28202079504661,51.1962243655606],[3.2817015450998,51.1964694234213],[3.28132779889332,51.1968368166422],[3.28097693097251,51.1971719715466],[3.28061193441404,51.1975591433324],[3.28166314909717,51.1981181039363],[3.28511157542403,51.1992599269871],[3.28789937144429,51.2001823842664],[3.28933146427403,51.2006288714819],[3.28947688004622,51.2007217470989],[3.28958995451164,51.200857204453],[3.28960606979215,51.2008782106301],[3.28961965874236,51.2011680445067],[3.28954336496818,51.2014361989898],[3.28941211503149,51.2017675879754],[3.28936030289073,51.2020139478009],[3.28941805375608,51.202148900243],[3.28968607670781,51.2022046527996],[3.28980025736405,51.2022126476546],[3.28989730817914,51.2021637030189],[3.28999837207501,51.2020209289602],[3.29005664039578,51.2019739480849],[3.29029210986051,51.2020015901923],[3.29071448238016,51.202163043427],[3.29113215443119,51.2022885282872],[3.29188940634617,51.2024866346876],[3.2924422484666,51.2026701287071],[3.29287289280056,51.2027934076964],[3.2932577002713,51.2029046798602],[3.29443562900864,51.203259561322],[3.29549594182642,51.2035959809293],[3.29628250237633,51.2038047542342],[3.29714984628008,51.204030477963],[3.29800906689857,51.2042086094018],[3.29840199292674,51.2042886494714],[3.2987468887055,51.2043717301741],[3.29916006384178,51.2045342282398],[3.29981086692352,51.2047116200869],[3.30080326135097,51.2049558293617],[3.30111412023556,51.2050756784106],[3.30162030141834,51.2053664791098],[3.30197884393571,51.2055794628428],[3.30254370410615,51.2062091683248],[3.30349267101916,51.2070648271801],[3.30414228159615,51.2077010817871],[3.30455047514913,51.2082459303992],[3.30502011878234,51.208928072317],[3.3050289186688,51.2089466927796],[3.30544621373532,51.2097407685896],[3.30628179813766,51.2112060875038],[3.3070457842365,51.2126580094372],[3.30777266061379,51.2141211806333],[3.30836525312096,51.2153247236414],[3.30867653173119,51.2159984753457],[3.30920021059666,51.216744817107],[3.30946495861039,51.2171933368287],[3.30961406583946,51.2176153263357],[3.30975795678342,51.218023362938],[3.31001644009649,51.2198056345734],[3.31021706015834,51.2215363981925],[3.3101967154244,51.2220263993429],[3.31007431861134,51.2221342337368],[3.3059634700077,51.2232388204694],[3.30407578770905,51.2237155083867],[3.3031687844653,51.2239159316648],[3.30194735735441,51.2242270783551],[3.30055112129194,51.2245957345571],[3.29929693732217,51.2249656585106],[3.29822022790458,51.2252409926082],[3.2973158132596,51.2254066299877],[3.29690625468883,51.225480561854],[3.29513532191381,51.225848077299],[3.29449150132662,51.2259163984501],[3.29419157207236,51.2259577103132],[3.29405824035377,51.2259773582132],[3.29393782462928,51.2259971232947],[3.29369889143444,51.2260343526855],[3.29336839650483,51.2261205790096],[3.292753478764,51.2262957655579],[3.29163105131149,51.2266297245765],[3.29154820367037,51.2267807767384],[3.29137446048006,51.2268719010178],[3.29087455144428,51.2267016356425],[3.28865051329625,51.2259895335372],[3.28651620170796,51.2253106567663],[3.28539283359238,51.2249689507097],[3.28524448264525,51.2249200802117],[3.28438553475163,51.2246364094468],[3.28455497620128,51.2248894283756],[3.28525819810285,51.2275078711622],[3.28504796620513,51.2275801108615],[3.2845907023619,51.2275608571336],[3.28255127564625,51.2269279730763],[3.28231287468318,51.226783248236],[3.27974066700605,51.2268395608049],[3.2786278331317,51.2263634631899],[3.27855269967751,51.226419553618],[3.27794543685456,51.226817229685],[3.27700212424535,51.2274574744346],[3.27625188405496,51.2279697055904],[3.27527881067579,51.2286177737546],[3.27441263084588,51.2291926575279],[3.27479066091895,51.2294429839794],[3.27406535952846,51.2299125552377],[3.27349277477769,51.2303232766084],[3.27363539983374,51.2304590209441],[3.27478373014609,51.2315485131499],[3.27484152974694,51.2316811539988],[3.27458590549869,51.2320345510964],[3.27320260469986,51.2335618357406],[3.27220015104459,51.234746144114],[3.27181437029264,51.2352165294788],[3.27140535310209,51.2356542509248],[3.27082877411093,51.2362306346805],[3.26984528093524,51.2372320040839],[3.26938077729609,51.2376726797635],[3.26876161673891,51.2382521343654],[3.26803025205498,51.2388919600639],[3.26738221165927,51.2394421681929],[3.26692255855669,51.2398318910023],[3.2667208527415,51.2400084723577],[3.26666810522797,51.2400531754431],[3.26654933395653,51.2401575226553],[3.26647766345686,51.240221749486],[3.26641185854361,51.2402721249823],[3.26616183144784,51.2404621612389],[3.26606217274592,51.2405388741718],[3.26600223287971,51.2405753981632],[3.26595245310118,51.2405726166795],[3.265951631146,51.2406073738285],[3.26558821579856,51.2408299582776],[3.26510609357354,51.2410757701172],[3.2645461153863,51.2413347596],[3.26444325450093,51.2413905824253],[3.26439088736803,51.2414190644782],[3.26420196856472,51.2415227547995],[3.26414023510034,51.2415569434659],[3.26292813586562,51.2422223797558],[3.26170933685505,51.242935253009],[3.26108234860728,51.2433709000143],[3.2607529381435,51.2434813818121],[3.26045749477726,51.2435608924404],[3.26011626269093,51.2437025501139],[3.2594758328369,51.2440812802928],[3.25845830232333,51.2447114121862],[3.25784795920015,51.2450660805132],[3.25720517219477,51.245542117862],[3.25613421260968,51.2461647752796],[3.25522405273903,51.2467020239206],[3.2548076611936,51.2469739068062],[3.25480649866097,51.2470225665814],[3.2550690882482,51.24762415068],[3.25523444205725,51.2480452013205],[3.25528342790536,51.2486227573797],[3.25521351956155,51.2486893116633],[3.25471098953633,51.248624324363],[3.25467726392975,51.2488766309778],[3.25447489069633,51.2488457555296],[3.25270702326185,51.2485706827818],[3.2525640249744,51.2489135058837],[3.25245841176485,51.2489287335414],[3.25221333093091,51.2489078809],[3.25096461302798,51.2486979366727],[3.25027912478278,51.248562831907],[3.24971904230697,51.2485111854349],[3.24898433940358,51.2484265962362],[3.24863431746463,51.2483931551053],[3.24858621044027,51.2481667285268],[3.24824327690069,51.2482225830142],[3.24820152281565,51.2482696996913],[3.24809644338484,51.24857000007],[3.24785923485293,51.2489130846977],[3.24754464196929,51.2494026069524],[3.24715608750881,51.2498960628935],[3.24670834372443,51.2504700744066],[3.24640426974333,51.2509052283845],[3.24618630725918,51.2512148860647],[3.24625559581712,51.2512514667168],[3.24633375259066,51.2513031961565],[3.24642581409559,51.2513909809909],[3.24705644556514,51.2521189068497],[3.24721601707416,51.2523174191251],[3.24750349299221,51.2526492487832],[3.24783461348694,51.2530093027253],[3.24817863482751,51.2533706365789],[3.24828295920472,51.253486347699],[3.24865088641084,51.2539290240348],[3.24878465116876,51.2541261309334],[3.24885613570468,51.2542253072629],[3.24893276971823,51.2543407557945],[3.24905792738506,51.2545887691886],[3.24913241014266,51.2547169442848],[3.24929843862679,51.254954914462],[3.25114652364404,51.2572853859941],[3.25304994968528,51.2595491345959],[3.25491295565734,51.2618889506453],[3.25526758795801,51.2623523373725],[3.25546369091625,51.2625708804951],[3.2556550029367,51.2627580901067],[3.25584507847331,51.2629197937436],[3.25602823907233,51.2630617321526],[3.25614208663528,51.2631670956247],[3.25624080225407,51.263287381452],[3.25651435589089,51.2635889264233],[3.25998964483234,51.2679728747149],[3.26019527615158,51.2682587095714],[3.26033376142336,51.2684164458958],[3.26071727428689,51.2688348906164],[3.26093264387055,51.2690999564614],[3.2610171052535,51.2691992457752],[3.2610924979071,51.2692914973134],[3.26132785928408,51.269648295675],[3.26155660741223,51.2699725848574],[3.26199365616087,51.2705491241359],[3.26233075323189,51.2709787173281],[3.26263527147913,51.2713801936389],[3.26318146071906,51.2720295936182],[3.2634553363419,51.2723994935275],[3.26387483372983,51.2728611386423],[3.26498667289461,51.2741218634762],[3.26517515351057,51.2743542232742],[3.26548112654258,51.2747742458082],[3.2656719900105,51.2750622498242],[3.2663203480465,51.2760822455022],[3.26654447065414,51.2763705574121],[3.26711366310789,51.2770676621169],[3.26730922634662,51.2773139896127],[3.26740816509859,51.2774273141024],[3.26757606548435,51.2775934260445],[3.26767147535011,51.2776997646282],[3.26773641401449,51.277766420385],[3.26779499002104,51.2778677812358],[3.26796152484799,51.2780918203276],[3.26810230964377,51.2783109846482],[3.26832810971051,51.2786074199628],[3.26862657150391,51.2789566760241],[3.26874237571789,51.2791385255824],[3.26902437048823,51.2795594736799],[3.26913374562362,51.2797007048195],[3.26927243189256,51.2798526371773],[3.26941087304577,51.2800149963489],[3.269480019941,51.2801384716602],[3.26954050469004,51.2802375315838],[3.26960554768791,51.2803783508342],[3.2696561132308,51.2805062888289],[3.26971930963901,51.2806470908611],[3.26979603885454,51.2807625246361],[3.2698714676203,51.2808547701458],[3.26999185037356,51.2809995788984],[3.27009449815115,51.2811129352414],[3.2701440653583,51.2812049406957],[3.27019200395636,51.2812876605657],[3.27025495720616,51.281438889248],[3.27030147589511,51.2815818538444],[3.27035660345637,51.2817515507878],[3.27040769148064,51.2818574758765],[3.27045394771746,51.2819332271701],[3.27053100858093,51.2820347577689],[3.27074541220138,51.2822673477113],[3.27082630552906,51.2823631195843],[3.27088576765603,51.282427405014],[3.27104201359748,51.2826188971413],[3.27116875699479,51.2828077980811],[3.27162193540852,51.2834157337479],[3.27172073393982,51.2835360056663],[3.27180204065149,51.2836143985309],[3.27186023110148,51.283654336723],[3.27197164274324,51.283709832099],[3.27198954295642,51.2840483689484],[3.27261780591238,51.2848340593713],[3.27284396614458,51.2851177412029],[3.27303785499938,51.2853594071212],[3.27325146915058,51.2856267487714],[3.27331069361624,51.2857014598663],[3.26947825339915,51.2891412147653],[3.26507142245641,51.2931641688082],[3.26360966231093,51.2944808492888],[3.26212327360781,51.2958192990123],[3.26200322807461,51.2961264191208],[3.26092601418833,51.2968881151386],[3.26002898511676,51.297688569081],[3.25655103208617,51.3009087330749],[3.25349882891109,51.3036994110719],[3.25015333921334,51.3067549256548],[3.2476057897016,51.3090565654202],[3.24514026730049,51.311166567622],[3.24492693869535,51.3113487941918],[3.24342813042563,51.3126973214647],[3.24304443790033,51.3130424765381],[3.2415360502617,51.3144766400073],[3.24122535270763,51.314784242961],[3.24044615696666,51.315501077561],[3.23927130837709,51.3165953823389],[3.23777810758468,51.3179276685976],[3.23652576606209,51.3190096189672],[3.23581748510873,51.3196181735765],[3.23529423980725,51.3200697380374],[3.23525456731047,51.3201041226351],[3.2351826458368,51.3201718039736],[3.23388449515895,51.3213830737211],[3.23247253914456,51.3227079594307],[3.23093008815965,51.3241474556722],[3.22947761875285,51.3253826897573],[3.2285639684844,51.3262128751954],[3.22855357691846,51.3265615725213],[3.22855176056551,51.3266357179194],[3.22862168542054,51.327103384517],[3.22873744816656,51.3276630364123],[3.22888516062254,51.3282021368755],[3.22904287815936,51.3285594025624],[3.2293201788342,51.329018632121],[3.22975451284536,51.3296369651788],[3.23014563102167,51.3301320494165],[3.23058498059136,51.3306218011504],[3.2309891659728,51.3310370510036],[3.2309661529871,51.3310704351716],[3.23007611786321,51.3322172077824],[3.22979718191221,51.3325795484868],[3.22573221804906,51.3378152555655],[3.22522978129227,51.3384616522167],[3.22515334889196,51.3385605711823],[3.22747104921302,51.3388783872471],[3.2274448730904,51.3389650445342],[3.22727575020518,51.3395242707783],[3.22722971271969,51.3396663587077],[3.22745801707917,51.3397114309477],[3.2275997578448,51.3397406056767],[3.22786121456216,51.3397917900351],[3.22784451091577,51.3397939469382],[3.22783879153279,51.3398008446528],[3.22783660100735,51.3398147290424],[3.22776572712211,51.3400643455529],[3.2255081864251,51.3466326298399],[3.22544719411212,51.3468556876201],[3.22543956533575,51.3470155264824],[3.22545541633537,51.347198767334],[3.22554136625435,51.3473907952263],[3.22573455713698,51.3477368159994],[3.22670223267465,51.3493985622742],[3.22684847688458,51.3496977774715],[3.22692501807329,51.3499719871237],[3.22695223580988,51.3502955496693],[3.22691091570952,51.3506219288705],[3.22681375101539,51.3509616758955],[3.22668897552671,51.3512953630989],[3.22440461814136,51.3574206890789],[3.22420567688452,51.3578336136034],[3.22402560656818,51.3582316556712],[3.22382606612746,51.3585182666823],[3.22352155995463,51.3588583269616],[3.22321443276038,51.3591543275152],[3.22287610124873,51.3594395969223],[3.22254668051337,51.3596635361191],[3.22213324397056,51.3599167908612],[3.22125648794883,51.360344016675],[3.22059917624503,51.3605786846034],[3.21977030690474,51.3607896710772],[3.21933471767987,51.3608897427416],[3.21835908716027,51.361047152651],[3.19759416135762,51.3632960133711],[3.19529139914045,51.3632257542061],[3.19242751717216,51.3632391157376],[3.18985426067919,51.3632518193733],[3.18976525724935,51.3632578878444],[3.1874205015423,51.3632380451104],[3.18333864913803,51.3615078267032],[3.18291694497937,51.3612776493972],[3.18256415583542,51.3610307776258],[3.18020457702949,51.359494945795],[3.1716592230376,51.3538062728347],[3.17104674831482,51.3533713369903],[3.17061019847251,51.3530760713161],[3.17029176480587,51.3527935851549],[3.16978471610057,51.3522183341348],[3.16949980601742,51.3518562274549],[3.16929890126046,51.351465999433],[3.16915601383337,51.350907173248],[3.16913687596762,51.3502858642926],[3.16922279919264,51.3497525273829],[3.16947301721461,51.349019220501],[3.16994116774013,51.348086484596],[3.17527281863511,51.3396983931535],[3.17585917044731,51.3388375085579],[3.17637103152289,51.3381392631325],[3.18204559201075,51.3310834506336],[3.18095387026815,51.3305904576172],[3.18003049666395,51.3303146796724],[3.17935404162295,51.3302209861327],[3.17821655858082,51.3299279815646],[3.1774189023669,51.3296557626636],[3.17629235369172,51.3292979560047],[3.17539944489124,51.3289181550632],[3.17469067249223,51.3286433354267],[3.17375598217178,51.3283789817197],[3.17185785533873,51.327962365994],[3.16971955623492,51.3273926458596],[3.16742682651428,51.3267170290433],[3.16509920222562,51.3261059061679],[3.16387545330165,51.3257945035818],[3.16341344886429,51.3256368447034],[3.1624442915752,51.3253511911794],[3.1611874178658,51.3250347880807],[3.15937001110033,51.3245817093228],[3.15736601157256,51.3241220606594],[3.15627195449986,51.3238767968612],[3.15520485182358,51.3235912402159],[3.15476744892041,51.3234140989248]]]
}
}
});
map.addLayer({
'id': 'route',
'type': 'fill',
'source': 'Brugge',
'layout': {},
'paint': {
'fill-color': '#088',
'fill-opacity': 0.4
}
});
=======
var getCoordinatenGeneric = function getCoordinaten(url){
var list = [];
$.when($.getJSON(url).done(function (json) {
for (var i = 0; i < json.length; i++) {
var item = json[i];
var geo = item.json_geometry;
var coords = {
lat: geo.coordinates[1],
long: geo.coordinates[0]
};
list.push(coords);
}
}));
return list;
};
function getCoordinatenMusea(){
var list = [];
$.when($.getJSON("data/musea.json").done(function (json) {
for (var i = 0; i < json.length; i++) {
var item = json[i];
var address = item.Ligging.split(" ");
$.getJSON("https://maps.googleapis.com/maps/api/geocode/json?address="+address[0]+"+"+address[1]+"&key=AIzaSyAM6FLYxpA8usOS4sBeYwo3wwzifUMPEfE").done(function(json){
var geo = json.results[0].geometry.location;
var object;
object = {
lat:geo.lat,
long:geo.lng
};
list.push(object);
});
}
}));
return list;
}
function getCoordinatenZitBanken(){
var list = [];
$.when($.getJSON("data/zitbanken.json").done(function (json) {
for (var i = 0; i < json.length; i++) {
var item = json[i];
var geo = item.json_geometry;
if(!Array.isArray(geo.coordinates[0])){
var object;
object = {
lat:geo.coordinates[1],
long:geo.coordinates[0]
};
list.push(object);
}
else{
for(var j = 0; j<geo.coordinates.length;j++){
var object;
object = {
lat:geo.coordinates[j][1],
long:geo.coordinates[j][0]
};
list.push(object);
}}}
}));
return list;
}
var getCoordinatenParken = function getCoordinatenParken(){
var list = [];
$.when($.getJSON("data/groen.json").done(function (json) {
for (var i = 0; i < json.length; i++) {
var item = json[i];
//console.log(item.BEHEERSOBJECT);
if(item.BEHEERSOBJECT == "parken"){
if(item.PUBLIEK_TOEGANKELIJK == "J"){
console.log(item);
var geo = item.json_geometry;
var glat = 0;
var glong = 0;
for(var j=0; j<geo.coordinates.length; j++){
glat += geo.coordinates[0][j][1];
glong += geo.coordinates[0][j][0];
}
glat = glat/geo.coordinates.length;
glong = glong/geo.coordinates.length;
var object = {
lat:glat,
long:glong
};
list.push(object);
}
}
}
}));
return list;
};
function getCoordinatenBib(){
return getCoordinatenGeneric("/data/bibliotheken.json");
}
function getCoordinatenLokalen(){
return getCoordinatenGeneric("/data/jeugdlokalen.json");
}
function getCoordinatenSport(){
return getCoordinatenGeneric("/data/sport.json");
}
function getCoordinatenZwembaden(){
return getCoordinatenGeneric("/data/zwembaden.json");
}
var data = {
libPoints: getCoordinatenBib,
museumPoints: getCoordinatenMusea,
sportPoints: getCoordinatenSport,
swimmingPoints: getCoordinatenZwembaden,
youthPoints: getCoordinatenLokalen,
museaPoints: getCoordinatenMusea,
benchPoints: getCoordinatenZitBanken,
parkPoints: getCoordinatenParken
>>>>>>> dev
};
(function() {
var map;
var list = [];
$(function () {
makeMap();
addEventListeners();
$("#route").on('click', openRoute);
setInterval(determinePosition, 5000);
console.log(data.benchPoints());
});
var makeMap = function makeMap() {
mapboxgl.accessToken = 'pk.eyJ1Ijoicm9vdHNhbSIsImEiOiJjaXU5a2V4aGcwMDFlMnRtazRibjZiZGN3In0.Q1K1wv1ugX49a4e1pCLMZw';
map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/light-v9',
center: [3.227180, 51.210358],
zoom: 13.7
});
map.on('load', function () {
drawBruges(map);
});
};
})();
| added line
| public/js/app.min.js | added line | <ide><path>ublic/js/app.min.js
<ide> window.open("https://www.google.be/maps/dir/" + xStart + "," + yStart + "/" + xDestination + "," + yDestination + "/@" + xCenter + "," + yCenter + "," + zoom +"z");
<ide> };
<ide>
<del><<<<<<< HEAD
<ide> /**
<ide> * Created by Sam on 14/10/2016.
<ide> */
<ide> 'fill-opacity': 0.4
<ide> }
<ide> });
<del>=======
<add>};
<add>
<ide> var getCoordinatenGeneric = function getCoordinaten(url){
<ide> var list = [];
<ide> $.when($.getJSON(url).done(function (json) {
<ide> museaPoints: getCoordinatenMusea,
<ide> benchPoints: getCoordinatenZitBanken,
<ide> parkPoints: getCoordinatenParken
<del>>>>>>>> dev
<ide> };
<ide>
<ide> (function() { |
|
Java | apache-2.0 | e54418ed2d75fec8b15628461be544c43dac1990 | 0 | andrescabrera/gwt-dojo-toolkit,andrescabrera/gwt-dojo-toolkit,andrescabrera/gwt-dojo-toolkit,andrescabrera/gwt-dojo-toolkit,andrescabrera/gwt-dojo-toolkit | /*
* Copyright 2012 ArkaSoft LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package gwt.dojo.mobile.client;
import gwt.dojo.dijit.client.IContained;
import gwt.dojo.dijit.client.IContainer;
import gwt.dojo.dijit.client._WidgetBase;
public class Heading extends _WidgetBase implements IContainer, IContained {
/**
* back: String
* <p>
* A label for the navigational control to return to the previous View.
*/
public static final String BACK = "back";
/**
* href: String
* <p>
* A URL to open when the navigational control is pressed.
*/
public static final String HREF = "href";
/**
* moveTo: String
* <p>
* The id of the transition destination view which resides in the current
* page.
* <p>
* If the value has a hash sign ('#') before the id (e.g. #view1) and the
* dojo.hash module is loaded by the user application, the view transition
* updates the hash in the browser URL so that the user can bookmark the
* destination view. In this case, the user can also use the browser's
* back/forward button to navigate through the views in the browser history.
* <p>
* If null, transitions to a blank view. If '#', returns immediately without
* transition.
*/
public static final String MOVETO = "moveTo";
/**
* transition: String
* <p>
* A type of animated transition effect. You can choose from the standard
* transition types, "slide", "fade", "flip", or from the extended
* transition types, "cover", "coverv", "dissolve", "reveal", "revealv",
* "scaleIn", "scaleOut", "slidev", "swirl", "zoomIn", "zoomOut". If "none"
* is specified, transition occurs immediately without animation.
*/
public static final String TRANSITION = "transition";
/**
* label: String
* <p>
* A title text of the heading. If the label is not specified, the innerHTML
* of the node is used as a label.
*/
public static final String LABEL = "label";
/**
* iconBase: String
* <p>
* The default icon path for child items.
*/
public static final String ICONBASE = "iconBase";
/**
* backProp: Object
* <p>
* Properties for the back button.
*/
public static final String BACKPROP = "backProp";
/**
* fixed: String
* <p>
* "top" or "bottom".
*/
public static final String FIXED = "fixed";
public static final String MODULE = "dojox/mobile/Heading";
public static native Heading create() /*-{
return new $wnd.dojox.mobile.Heading();
}-*/;
protected Heading() {
}
}
| src/gwt/dojo/mobile/client/Heading.java | /*
* Copyright 2012 ArkaSoft LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package gwt.dojo.mobile.client;
import gwt.dojo.dijit.client.IContained;
import gwt.dojo.dijit.client.IContainer;
import gwt.dojo.dijit.client._WidgetBase;
public class Heading extends _WidgetBase implements IContainer, IContained {
public static final String MODULE = "dojox/mobile/Heading";
public static native Heading create() /*-{
return new $wnd.dojox.mobile.Heading();
}-*/;
/**
* fixed: String
* <p>
* "top" or "bottom".
*/
public static final String FIXED = "fixed";
protected Heading() {
}
}
| API properties for Heading | src/gwt/dojo/mobile/client/Heading.java | API properties for Heading | <ide><path>rc/gwt/dojo/mobile/client/Heading.java
<ide> import gwt.dojo.dijit.client._WidgetBase;
<ide>
<ide> public class Heading extends _WidgetBase implements IContainer, IContained {
<del>
<del> public static final String MODULE = "dojox/mobile/Heading";
<ide>
<del> public static native Heading create() /*-{
<del> return new $wnd.dojox.mobile.Heading();
<del> }-*/;
<del>
<add> /**
<add> * back: String
<add> * <p>
<add> * A label for the navigational control to return to the previous View.
<add> */
<add> public static final String BACK = "back";
<add>
<add> /**
<add> * href: String
<add> * <p>
<add> * A URL to open when the navigational control is pressed.
<add> */
<add> public static final String HREF = "href";
<add>
<add> /**
<add> * moveTo: String
<add> * <p>
<add> * The id of the transition destination view which resides in the current
<add> * page.
<add> * <p>
<add> * If the value has a hash sign ('#') before the id (e.g. #view1) and the
<add> * dojo.hash module is loaded by the user application, the view transition
<add> * updates the hash in the browser URL so that the user can bookmark the
<add> * destination view. In this case, the user can also use the browser's
<add> * back/forward button to navigate through the views in the browser history.
<add> * <p>
<add> * If null, transitions to a blank view. If '#', returns immediately without
<add> * transition.
<add> */
<add> public static final String MOVETO = "moveTo";
<add>
<add> /**
<add> * transition: String
<add> * <p>
<add> * A type of animated transition effect. You can choose from the standard
<add> * transition types, "slide", "fade", "flip", or from the extended
<add> * transition types, "cover", "coverv", "dissolve", "reveal", "revealv",
<add> * "scaleIn", "scaleOut", "slidev", "swirl", "zoomIn", "zoomOut". If "none"
<add> * is specified, transition occurs immediately without animation.
<add> */
<add> public static final String TRANSITION = "transition";
<add>
<add> /**
<add> * label: String
<add> * <p>
<add> * A title text of the heading. If the label is not specified, the innerHTML
<add> * of the node is used as a label.
<add> */
<add> public static final String LABEL = "label";
<add>
<add> /**
<add> * iconBase: String
<add> * <p>
<add> * The default icon path for child items.
<add> */
<add> public static final String ICONBASE = "iconBase";
<add>
<add> /**
<add> * backProp: Object
<add> * <p>
<add> * Properties for the back button.
<add> */
<add> public static final String BACKPROP = "backProp";
<add>
<ide> /**
<ide> * fixed: String
<ide> * <p>
<ide> * "top" or "bottom".
<ide> */
<ide> public static final String FIXED = "fixed";
<del>
<add>
<add> public static final String MODULE = "dojox/mobile/Heading";
<add>
<add> public static native Heading create() /*-{
<add> return new $wnd.dojox.mobile.Heading();
<add> }-*/;
<add>
<ide> protected Heading() {
<ide> }
<ide> |
|
Java | apache-2.0 | e2c37836ace551158deb878d5a2a0ed9fdf5d91c | 0 | henrichg/PhoneProfilesPlus | package sk.henrichg.phoneprofilesplus;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.KeyguardManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.WallpaperManager;
import android.appwidget.AppWidgetManager;
import android.bluetooth.BluetoothAdapter;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.location.LocationManager;
import android.media.AudioManager;
import android.media.RingtoneManager;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Handler;
import android.os.PowerManager;
import android.provider.Settings;
import android.provider.Settings.Global;
import android.service.notification.NotificationListenerService;
import android.support.v4.app.NotificationCompat;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.Surface;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.RemoteViews;
import com.stericson.RootShell.execution.Command;
import com.stericson.RootShell.execution.Shell;
import com.stericson.RootTools.RootTools;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Calendar;
public class ActivateProfileHelper {
private DataWrapper dataWrapper;
private Context context;
private NotificationManager notificationManager;
private Handler brightnessHandler;
private int networkType = -1;
public static boolean lockRefresh = false;
public static final String ADAPTIVE_BRIGHTNESS_SETTING_NAME = "screen_auto_brightness_adj";
// Setting.Global "zen_mode"
public static final int ZENMODE_ALL = 0;
public static final int ZENMODE_PRIORITY = 1;
public static final int ZENMODE_NONE = 2;
public static final int ZENMODE_ALARMS = 3;
public ActivateProfileHelper()
{
}
public void initialize(DataWrapper dataWrapper, Activity a, Context c)
{
this.dataWrapper = dataWrapper;
initializeNoNotificationManager(c);
notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
}
public void initializeNoNotificationManager(Context c)
{
context = c;
}
public void deinitialize()
{
dataWrapper = null;
context = null;
notificationManager = null;
}
public void setBrightnessHandler(Handler handler)
{
brightnessHandler = handler;
}
@SuppressWarnings("deprecation")
private void doExecuteForRadios(Profile profile, boolean onlyCheckForPPHelper)
{
if (!onlyCheckForPPHelper)
{
try {
Thread.sleep(300);
} catch (InterruptedException e) {
System.out.println(e);
}
}
// nahodenie network type
if (!onlyCheckForPPHelper) {
if (GlobalData.isPreferenceAllowed(GlobalData.PREF_PROFILE_DEVICE_NETWORK_TYPE, context) == GlobalData.PREFERENCE_ALLOWED) {
if (profile._deviceNetworkType >= 100) {
setPreferredNetworkType(context, profile._deviceNetworkType - 100);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
// nahodenie mobilnych dat
if (!onlyCheckForPPHelper) {
if (GlobalData.isPreferenceAllowed(GlobalData.PREF_PROFILE_DEVICE_MOBILE_DATA, context) == GlobalData.PREFERENCE_ALLOWED) {
boolean _isMobileData = isMobileData(context);
boolean _setMobileData = false;
switch (profile._deviceMobileData) {
case 1:
if (!_isMobileData) {
_isMobileData = true;
_setMobileData = true;
}
break;
case 2:
if (_isMobileData) {
_isMobileData = false;
_setMobileData = true;
}
break;
case 3:
_isMobileData = !_isMobileData;
_setMobileData = true;
break;
}
if (_setMobileData) {
setMobileData(context, _isMobileData);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
// nahodenie WiFi AP
boolean canChangeWifi = true;
if (!onlyCheckForPPHelper) {
if (GlobalData.isPreferenceAllowed(GlobalData.PREF_PROFILE_DEVICE_WIFI_AP, context) == GlobalData.PREFERENCE_ALLOWED) {
WifiApManager wifiApManager = null;
try {
wifiApManager = new WifiApManager(context);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
if (wifiApManager != null) {
boolean setWifiAPState = false;
boolean isWifiAPEnabled = wifiApManager.isWifiAPEnabled();
switch (profile._deviceWiFiAP) {
case 1:
if (!isWifiAPEnabled) {
isWifiAPEnabled = true;
setWifiAPState = true;
canChangeWifi = false;
}
break;
case 2:
if (isWifiAPEnabled) {
isWifiAPEnabled = false;
setWifiAPState = true;
canChangeWifi = true;
}
break;
case 3:
isWifiAPEnabled = !isWifiAPEnabled;
setWifiAPState = true;
canChangeWifi = !isWifiAPEnabled;
break;
}
if (setWifiAPState) {
wifiApManager.setWifiApState(isWifiAPEnabled);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
}
if (canChangeWifi) {
// nahodenie WiFi
if (GlobalData.isPreferenceAllowed(GlobalData.PREF_PROFILE_DEVICE_WIFI, context) == GlobalData.PREFERENCE_ALLOWED) {
boolean isWifiAPEnabled = WifiApManager.isWifiAPEnabled(context);
if (!isWifiAPEnabled) { // only when wifi AP is not enabled, change wifi
GlobalData.logE("$$$ WifiAP", "ActivateProfileHelper.doExecuteForRadios-isWifiAPEnabled=" + isWifiAPEnabled);
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
int wifiState = wifiManager.getWifiState();
boolean isWifiEnabled = ((wifiState == WifiManager.WIFI_STATE_ENABLED) || (wifiState == WifiManager.WIFI_STATE_ENABLING));
boolean setWifiState = false;
switch (profile._deviceWiFi) {
case 1:
if (!isWifiEnabled) {
isWifiEnabled = true;
setWifiState = true;
}
break;
case 2:
if (isWifiEnabled) {
isWifiEnabled = false;
setWifiState = true;
}
break;
case 3:
isWifiEnabled = !isWifiEnabled;
setWifiState = true;
break;
}
if (setWifiState) {
if (!onlyCheckForPPHelper) {
try {
wifiManager.setWifiEnabled(isWifiEnabled);
} catch (Exception e) {
wifiManager.setWifiEnabled(isWifiEnabled);
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
System.out.println(e);
}
}
if (isWifiEnabled)
// when wifi is enabled from profile, no disable wifi after scan
WifiScanAlarmBroadcastReceiver.setWifiEnabledForScan(context, false);
}
}
}
}
// nahodenie bluetooth
if (GlobalData.isPreferenceAllowed(GlobalData.PREF_PROFILE_DEVICE_BLUETOOTH, context) == GlobalData.PREFERENCE_ALLOWED)
{
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
boolean isBluetoothEnabled = bluetoothAdapter.isEnabled();
boolean setBluetoothState = false;
switch (profile._deviceBluetooth) {
case 1 :
if (!isBluetoothEnabled)
{
isBluetoothEnabled = true;
setBluetoothState = true;
}
break;
case 2 :
if (isBluetoothEnabled)
{
isBluetoothEnabled = false;
setBluetoothState = true;
}
break;
case 3 :
isBluetoothEnabled = ! isBluetoothEnabled;
setBluetoothState = true;
break;
}
if (setBluetoothState)
{
if (!onlyCheckForPPHelper)
{
if (isBluetoothEnabled)
bluetoothAdapter.enable();
else
bluetoothAdapter.disable();
}
if (isBluetoothEnabled)
// when bluetooth is enabled from profile, no disable bluetooth after scan
BluetoothScanAlarmBroadcastReceiver.setBluetoothEnabledForScan(context, false);
}
}
// nahodenie GPS
if (!onlyCheckForPPHelper) {
if (GlobalData.isPreferenceAllowed(GlobalData.PREF_PROFILE_DEVICE_GPS, context) == GlobalData.PREFERENCE_ALLOWED)
{
//String provider = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
boolean isEnabled;
if (android.os.Build.VERSION.SDK_INT < 21)
isEnabled = Settings.Secure.isLocationProviderEnabled(context.getContentResolver(), LocationManager.GPS_PROVIDER);
else {
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
isEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
GlobalData.logE("ActivateProfileHelper.doExecuteForRadios","isEnabled="+isEnabled);
switch (profile._deviceGPS) {
case 1:
setGPS(context, true);
break;
case 2:
setGPS(context, false);
break;
case 3:
if (!isEnabled) {
setGPS(context, true);
} else if (isEnabled) {
setGPS(context, false);
}
break;
}
}
}
// nahodenie NFC - len v PPHelper
}
public void executeForRadios(Profile profile, boolean onlyCheckForPPHelper)
{
boolean _isAirplaneMode = false;
boolean _setAirplaneMode = false;
if (GlobalData.isPreferenceAllowed(GlobalData.PREF_PROFILE_DEVICE_AIRPLANE_MODE, context) == GlobalData.PREFERENCE_ALLOWED)
{
_isAirplaneMode = isAirplaneMode(context);
switch (profile._deviceAirplaneMode) {
case 1:
if (!_isAirplaneMode)
{
_isAirplaneMode = true;
_setAirplaneMode = true;
}
break;
case 2:
if (_isAirplaneMode)
{
_isAirplaneMode = false;
_setAirplaneMode = true;
}
break;
case 3:
_isAirplaneMode = !_isAirplaneMode;
_setAirplaneMode = true;
break;
}
}
if (_setAirplaneMode && _isAirplaneMode)
// switch ON airplane mode, set it before executeForRadios
setAirplaneMode(context, _isAirplaneMode);
doExecuteForRadios(profile, onlyCheckForPPHelper);
if (_setAirplaneMode && !(_isAirplaneMode))
// switch OFF airplane mode, set if after executeForRadios
setAirplaneMode(context, _isAirplaneMode);
}
public void correctVolume0(/*Profile profile, */AudioManager audioManager, int linkUnlink) {
int ringerMode, zenMode;
if (linkUnlink == PhoneCallService.LINKMODE_NONE) {
ringerMode = GlobalData.getRingerMode(context);
zenMode = GlobalData.getZenMode(context);
}
else {
ringerMode = GlobalData.getRingerMode(context);
zenMode = GlobalData.getZenMode(context);
//ringerMode = RingerModeChangeReceiver.getRingerMode(context, audioManager);
}
if ((ringerMode == 1) || (ringerMode == 4) ||
((ringerMode == 5) && ((zenMode == 1) || (zenMode == 2)))) {
//if (profile._volumeRingerMode == 4) {
// last profile ringer mode = Silent
if (audioManager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE) {
// actual system ringer mode = vibrate
// volume changed it to vibrate
//RingerModeChangeReceiver.internalChange = true;
audioManager.setStreamVolume(AudioManager.STREAM_RING, 1, 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_RING, 1);
}
}
}
@SuppressLint("NewApi")
public void setVolumes(Profile profile, AudioManager audioManager, int linkUnlink)
{
if (profile.getVolumeRingtoneChange() || profile.getVolumeSystemChange()) {
if (profile.getVolumeRingtoneChange()) {
if (linkUnlink == PhoneCallService.LINKMODE_NONE)
GlobalData.setRingerVolume(context, profile.getVolumeRingtoneValue());
}
}
if (profile.getVolumeNotificationChange() || profile.getVolumeSystemChange()) {
if (profile.getVolumeNotificationChange()) {
if (linkUnlink == PhoneCallService.LINKMODE_NONE)
GlobalData.setNotificationVolume(context, profile.getVolumeNotificationValue());
}
}
int ringerMode = GlobalData.getRingerMode(context);
int zenMode = GlobalData.getZenMode(context);
// for interruption types NONE and ONLY_ALARMS not set system, ringer, npotification volume
// Android 6 - priority mode = ONLY_ALARMS
if (!( ((ringerMode == 4) && (android.os.Build.VERSION.SDK_INT >= 23)) ||
((ringerMode == 5) && ((zenMode == 3) || (zenMode == 6)))
)) {
if (profile.getVolumeSystemChange()) {
//RingerModeChangeReceiver.internalChange = true;
audioManager.setStreamVolume(AudioManager.STREAM_SYSTEM, profile.getVolumeSystemValue(), 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_SYSTEM, profile.getVolumeSystemValue());
correctVolume0(/*profile, */audioManager, linkUnlink);
}
if (Permissions.checkSavedProfileVolumes(context)) {
TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
int callState = telephony.getCallState();
if (profile.getVolumeRingtoneChange() || profile.getVolumeSystemChange()) {
if (((!GlobalData.applicationUnlinkRingerNotificationVolumes) || (callState != TelephonyManager.CALL_STATE_RINGING))
&& (linkUnlink == PhoneCallService.LINKMODE_NONE)) {
int volume = GlobalData.getRingerVolume(context);
if (volume != -999) {
//RingerModeChangeReceiver.internalChange = true;
audioManager.setStreamVolume(AudioManager.STREAM_RING, profile.getVolumeRingtoneValue(), 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_RING, profile.getVolumeRingtoneValue());
correctVolume0(/*profile, */audioManager, linkUnlink);
}
}
}
if (profile.getVolumeNotificationChange() || profile.getVolumeSystemChange()) {
if (((!GlobalData.applicationUnlinkRingerNotificationVolumes) || (callState != TelephonyManager.CALL_STATE_RINGING))
&& (linkUnlink == PhoneCallService.LINKMODE_NONE)) {
int volume = GlobalData.getNotificationVolume(context);
if (volume != -999) {
//RingerModeChangeReceiver.internalChange = true;
audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, profile.getVolumeNotificationValue(), 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_NOTIFICATION, profile.getVolumeNotificationValue());
correctVolume0(/*profile, */audioManager, linkUnlink);
}
}
}
if (GlobalData.applicationUnlinkRingerNotificationVolumes) {
boolean doUnlink = audioManager.getRingerMode() == AudioManager.RINGER_MODE_NORMAL;
if (android.os.Build.VERSION.SDK_INT >= 21)
doUnlink = doUnlink && (Settings.Global.getInt(context.getContentResolver(), "zen_mode", ZENMODE_ALL) != ZENMODE_NONE);
//Log.e("ActivateProfileHelper", "setVolumes doUnlink=" + doUnlink);
//Log.e("ActivateProfileHelper", "setVolumes ringerMode=" + audioManager.getRingerMode());
//Log.e("ActivateProfileHelper", "setVolumes zenMode=" + Settings.Global.getInt(context.getContentResolver(), "zen_mode", ZENMODE_NONE));
if (doUnlink) {
//if (linkUnlink == PhoneCallBroadcastReceiver.LINKMODE_UNLINK) {
if (callState == TelephonyManager.CALL_STATE_RINGING) {
// for separating ringing and notification
// in ringing state ringer volumes must by set
// and notification volumes must not by set
int volume = GlobalData.getRingerVolume(context);
if (volume != -999) {
//RingerModeChangeReceiver.internalChange = true;
audioManager.setStreamVolume(AudioManager.STREAM_RING, volume, 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_RING, profile.getVolumeRingtoneValue());
//RingerModeChangeReceiver.internalChange = true;
audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, volume, 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_NOTIFICATION, profile.getVolumeNotificationValue());
correctVolume0(/*profile, */audioManager, linkUnlink);
}
} else if (linkUnlink == PhoneCallService.LINKMODE_LINK) {
// for separating ringing and notification
// in not ringing state ringer and notification volume must by change
//Log.e("ActivateProfileHelper","setVolumes get audio mode="+audioManager.getMode());
int volume = GlobalData.getRingerVolume(context);
if (volume != -999) {
//Log.e("ActivateProfileHelper","setVolumes set ring volume="+volume);
//RingerModeChangeReceiver.internalChange = true;
audioManager.setStreamVolume(AudioManager.STREAM_RING, volume, 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_RING, profile.getVolumeRingtoneValue());
}
volume = GlobalData.getNotificationVolume(context);
if (volume != -999) {
//Log.e("ActivateProfileHelper","setVolumes set notification volume="+volume);
//RingerModeChangeReceiver.internalChange = true;
audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, volume, 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_NOTIFICATION, profile.getVolumeNotificationValue());
}
correctVolume0(/*profile, */audioManager, linkUnlink);
}
}
}
}
}
if (profile.getVolumeMediaChange())
{
//RingerModeChangeReceiver.internalChange = true;
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, profile.getVolumeMediaValue(), 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_MUSIC, profile.getVolumeMediaValue());
}
if (profile.getVolumeAlarmChange())
{
//RingerModeChangeReceiver.internalChange = true;
audioManager.setStreamVolume(AudioManager.STREAM_ALARM, profile.getVolumeAlarmValue(), 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_ALARM, profile.getVolumeAlarmValue());
}
if (profile.getVolumeVoiceChange()) {
//RingerModeChangeReceiver.internalChange = true;
audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, profile.getVolumeVoiceValue(), 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_VOICE, profile.getVolumeVoiceValue());
}
}
public static boolean setZenMode(Context context, int zenMode, AudioManager audioManager, int ringerMode)
{
if (android.os.Build.VERSION.SDK_INT >= 21)
{
if (PPNotificationListenerService.isNotificationListenerServiceEnabled(context)) {
int _zenMode = Settings.Global.getInt(context.getContentResolver(), "zen_mode", -1);
GlobalData.logE("ActivateProfileHelper.setZenMode","_zenMode="+_zenMode);
if (zenMode != _zenMode) {
int interruptionFilter = NotificationListenerService.INTERRUPTION_FILTER_ALL;
switch (zenMode) {
case ZENMODE_ALL:
interruptionFilter = NotificationListenerService.INTERRUPTION_FILTER_ALL;
break;
case ZENMODE_PRIORITY:
interruptionFilter = NotificationListenerService.INTERRUPTION_FILTER_PRIORITY;
break;
case ZENMODE_NONE:
interruptionFilter = NotificationListenerService.INTERRUPTION_FILTER_NONE;
break;
case ZENMODE_ALARMS:
interruptionFilter = NotificationListenerService.INTERRUPTION_FILTER_ALARMS;
break;
}
PPNotificationListenerService.requestInterruptionFilter(context, interruptionFilter);
if (ringerMode > -1)
audioManager.setRingerMode(ringerMode);
return true;
}
}
/* else
if (GlobalData.grantRoot(false) && (GlobalData.settingsBinaryExists()))
{
String command1 = "settings put global zen_mode " + mode;
//if (GlobalData.isSELinuxEnforcing())
// command1 = GlobalData.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
Command command = new Command(0, false, command1);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
//RootTools.closeAllShells();
} catch (Exception e) {
Log.e("ActivateProfileHelper.setZenMode", e.getMessage());
}
}*/
}
return false;
}
private void setVibrateWhenRinging(int value) {
if (GlobalData.isPreferenceAllowed(GlobalData.PREF_PROFILE_DEVICE_VIBRATE_WHEN_RINGING, context)
== GlobalData.PREFERENCE_ALLOWED) {
if (android.os.Build.VERSION.SDK_INT < 23) // Not working in Android M (exception)
Settings.System.putInt(context.getContentResolver(), "vibrate_when_ringing", value);
else {
String command1 = "settings put system " + Settings.System.VIBRATE_WHEN_RINGING + " " + value;
//if (GlobalData.isSELinuxEnforcing())
// command1 = GlobalData.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
Command command = new Command(0, false, command1); //, command2);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
//RootTools.closeAllShells();
} catch (Exception e) {
Log.e("ActivateProfileHelper.setVibrateWhenRinging", "Error on run su: " + e.toString());
}
}
}
}
@SuppressWarnings("deprecation")
public boolean setRingerMode(Profile profile, AudioManager audioManager, boolean forPriority, int linkUnlink)
{
GlobalData.logE("@@@ ActivateProfileHelper.setRingerMode", "andioM.ringerMode=" + audioManager.getRingerMode());
int ringerMode, oldRingerMode;
int zenMode, oldZenMode;
oldRingerMode = GlobalData.getRingerMode(context);
oldZenMode = GlobalData.getZenMode(context);
if (linkUnlink == PhoneCallService.LINKMODE_NONE) {
if (profile._volumeRingerMode != 0) {
GlobalData.setRingerMode(context, profile._volumeRingerMode);
if ((profile._volumeRingerMode == 5) && (profile._volumeZenMode != 0))
GlobalData.setZenMode(context, profile._volumeZenMode);
}
ringerMode = GlobalData.getRingerMode(context);
zenMode = GlobalData.getZenMode(context);
}
else {
/*ringerMode = RingerModeChangeReceiver.getRingerMode(context, audioManager);
zenMode = PPNotificationListenerService.getZenMode(context, audioManager);*/
ringerMode = GlobalData.getRingerMode(context);
zenMode = GlobalData.getZenMode(context);
}
GlobalData.logE("ActivateProfileHelper.setRingerMode", "ringerMode=" + ringerMode);
GlobalData.logE("ActivateProfileHelper.setRingerMode", "zenMode=" + zenMode);
// for Lollipop 4=priority mode, for pre-lillipop 4=silent ringer mode
// priority mode must by invoked be 2 calls of setRingerMode:
// first call of setRingerMode must set ringer mode to normal (1) (not called for pre-lollipop)
// second call is normal change ringer mode (4)
// this call sequence sets Lollipop priority mode (check ExecuteVolumeProfilePrefsService, how is called setRingerMode)
if (forPriority) {
if (android.os.Build.VERSION.SDK_INT >= 21) {
//boolean isPrioritySet = (Settings.Global.getInt(context.getContentResolver(), "zen_mode", -1) == ZENMODE_PRIORITY);
boolean isPrioritySet = true;
GlobalData.logE("ActivateProfileHelper.setRingerMode", "zen_mode=" + Settings.Global.getInt(context.getContentResolver(), "zen_mode", -1));
GlobalData.logE("ActivateProfileHelper.setRingerMode", "isPrioritySet=" + isPrioritySet);
if ((ringerMode == 4) && isPrioritySet) { // 4 = silent ringer mode
ringerMode = 1;
GlobalData.logE("ActivateProfileHelper.setRingerMode", "set for reset priority");
}
else
if ((ringerMode == 5) && (zenMode == 2) && isPrioritySet && (linkUnlink == PhoneCallService.LINKMODE_NONE)) {
zenMode = 1;
GlobalData.logE("ActivateProfileHelper.setRingerMode", "set for reset priority");
}
else
if ((ringerMode == 5) && (zenMode == 5) && isPrioritySet && (linkUnlink == PhoneCallService.LINKMODE_NONE)) {
zenMode = 4;
GlobalData.logE("ActivateProfileHelper.setRingerMode", "set for reset priority");
}
else
return false;
} else
return false;
}
if (Permissions.checkSavedProfileRingerMode(context)) {
switch (ringerMode) {
case 1: // Ring
//RingerModeChangeReceiver.internalChange = true;
setZenMode(context, ZENMODE_ALL, audioManager, AudioManager.RINGER_MODE_NORMAL);
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_OFF);
} catch (Exception e) {
e.printStackTrace();
}
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_OFF);
} catch (Exception e) {
e.printStackTrace();
}
setVibrateWhenRinging(0);
break;
case 2: // Ring & Vibrate
//RingerModeChangeReceiver.internalChange = true;
setZenMode(context, ZENMODE_ALL, audioManager, AudioManager.RINGER_MODE_NORMAL);
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_ON);
} catch (Exception e) {
e.printStackTrace();
}
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_ON);
} catch (Exception e) {
e.printStackTrace();
}
setVibrateWhenRinging(1);
break;
case 3: // Vibrate
//RingerModeChangeReceiver.internalChange = true;
setZenMode(context, ZENMODE_ALL, audioManager, AudioManager.RINGER_MODE_NORMAL);
audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_ON);
} catch (Exception e) {
e.printStackTrace();
}
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_ON);
} catch (Exception e) {
e.printStackTrace();
}
setVibrateWhenRinging(1);
break;
case 4: // Silent
//RingerModeChangeReceiver.internalChange = true;
audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_OFF);
} catch (Exception e) {
e.printStackTrace();
}
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_OFF);
} catch (Exception e) {
e.printStackTrace();
}
setVibrateWhenRinging(0);
break;
case 5: // Zen mode
switch (zenMode) {
case 1:
//RingerModeChangeReceiver.internalChange = true;
if (setZenMode(context, ZENMODE_ALL, audioManager, AudioManager.RINGER_MODE_NORMAL)) {
setVibrateWhenRinging(0);
}
break;
case 2:
//RingerModeChangeReceiver.internalChange = true;
if (setZenMode(context, ZENMODE_PRIORITY, audioManager, AudioManager.RINGER_MODE_NORMAL)) {
setVibrateWhenRinging(0);
}
break;
case 3:
//RingerModeChangeReceiver.internalChange = true;
setZenMode(context, ZENMODE_NONE, audioManager, -1);
break;
case 4:
//RingerModeChangeReceiver.internalChange = true;
if (setZenMode(context, ZENMODE_ALL, audioManager, AudioManager.RINGER_MODE_VIBRATE)) {
setVibrateWhenRinging(1);
}
break;
case 5:
//RingerModeChangeReceiver.internalChange = true;
if (setZenMode(context, ZENMODE_PRIORITY, audioManager, AudioManager.RINGER_MODE_VIBRATE)) {
setVibrateWhenRinging(1);
}
break;
case 6:
//RingerModeChangeReceiver.internalChange = true;
setZenMode(context, ZENMODE_ALARMS, audioManager, -1);
break;
}
break;
}
}
return true;
}
public void executeForWallpaper(Profile profile) {
if (profile._deviceWallpaperChange == 1)
{
DisplayMetrics displayMetrics = new DisplayMetrics();
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
display.getMetrics(displayMetrics);
int height = displayMetrics.heightPixels;
int width = displayMetrics.widthPixels << 1; // best wallpaper width is twice screen width
Bitmap decodedSampleBitmap = BitmapManipulator.resampleBitmap(profile.getDeviceWallpaperIdentifier(), width, height, context);
if (decodedSampleBitmap != null)
{
// set wallpaper
WallpaperManager wallpaperManager = WallpaperManager.getInstance(context);
try {
wallpaperManager.setBitmap(decodedSampleBitmap);
} catch (IOException e) {
Log.e("ActivateProfileHelper.executeForWallpaper", "Cannot set wallpaper. Image="+profile.getDeviceWallpaperIdentifier());
}
}
}
}
public void executeForRunApplications(Profile profile) {
if (profile._deviceRunApplicationChange == 1)
{
String[] splits = profile._deviceRunApplicationPackageName.split("\\|");
Intent intent;
PackageManager packageManager = context.getPackageManager();
for (int i = 0; i < splits.length; i++) {
intent = packageManager.getLaunchIntentForPackage(splits[i]);
if (intent != null) {
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
}
public void execute(Profile _profile, boolean merged, boolean _interactive, String eventNotificationSound)
{
// rozdelit zvonenie a notifikacie - zial je to oznacene ako @Hide :-(
//Settings.System.putInt(context.getContentResolver(), Settings.System.NOTIFICATIONS_USE_RING_VOLUME, 0);
Profile profile = GlobalData.getMappedProfile(_profile, context);
boolean interactive = _interactive;
// nahodenie volume
// run service for execute volumes
Intent volumeServiceIntent = new Intent(context, ExecuteVolumeProfilePrefsService.class);
volumeServiceIntent.putExtra(GlobalData.EXTRA_PROFILE_ID, profile._id);
volumeServiceIntent.putExtra(GlobalData.EXTRA_MERGED_PROFILE, merged);
volumeServiceIntent.putExtra(GlobalData.EXTRA_LINKUNLINK_VOLUMES, PhoneCallService.LINKMODE_NONE);
context.startService(volumeServiceIntent);
/*AudioManager audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
// nahodenie ringer modu - aby sa mohli nastavit hlasitosti
setRingerMode(profile, audioManager);
setVolumes(profile, audioManager);
// nahodenie ringer modu - hlasitosti zmenia silent/vibrate
setRingerMode(profile, audioManager);*/
// set vibration on touch
if (Permissions.checkProfileVibrationOnTouch(context, profile)) {
switch (profile._vibrationOnTouch) {
case 1:
Settings.System.putInt(context.getContentResolver(), Settings.System.HAPTIC_FEEDBACK_ENABLED, 1);
break;
case 2:
Settings.System.putInt(context.getContentResolver(), Settings.System.HAPTIC_FEEDBACK_ENABLED, 0);
break;
}
}
// nahodenie tonov
if (Permissions.checkProfileRingtones(context, profile)) {
if (profile._soundRingtoneChange == 1) {
if (!profile._soundRingtone.isEmpty()) {
//Settings.System.putString(context.getContentResolver(), Settings.System.RINGTONE, profile._soundRingtone);
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE, Uri.parse(profile._soundRingtone));
} else {
// selected is None tone
//Settings.System.putString(context.getContentResolver(), Settings.System.RINGTONE, null);
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE, null);
}
}
if (profile._soundNotificationChange == 1) {
if (!profile._soundNotification.isEmpty()) {
//Settings.System.putString(context.getContentResolver(), Settings.System.NOTIFICATION_SOUND, profile._soundNotification);
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_NOTIFICATION, Uri.parse(profile._soundNotification));
} else {
// selected is None tone
//Settings.System.putString(context.getContentResolver(), Settings.System.NOTIFICATION_SOUND, null);
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_NOTIFICATION, null);
}
}
if (profile._soundAlarmChange == 1) {
if (!profile._soundAlarm.isEmpty()) {
//Settings.System.putString(context.getContentResolver(), Settings.System.ALARM_ALERT, profile._soundAlarm);
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_ALARM, Uri.parse(profile._soundAlarm));
} else {
// selected is None tone
//Settings.System.putString(context.getContentResolver(), Settings.System.ALARM_ALERT, null);
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_ALARM, null);
}
}
}
//// nahodenie radio preferences
// run service for execute radios
Intent radioServiceIntent = new Intent(context, ExecuteRadioProfilePrefsService.class);
radioServiceIntent.putExtra(GlobalData.EXTRA_PROFILE_ID, profile._id);
radioServiceIntent.putExtra(GlobalData.EXTRA_MERGED_PROFILE, merged);
context.startService(radioServiceIntent);
// nahodenie auto-sync
boolean _isAutosync = ContentResolver.getMasterSyncAutomatically();
boolean _setAutosync = false;
switch (profile._deviceAutosync) {
case 1:
if (!_isAutosync)
{
_isAutosync = true;
_setAutosync = true;
}
break;
case 2:
if (_isAutosync)
{
_isAutosync = false;
_setAutosync = true;
}
break;
case 3:
_isAutosync = !_isAutosync;
_setAutosync = true;
break;
}
if (_setAutosync)
ContentResolver.setMasterSyncAutomatically(_isAutosync);
// screen timeout
if (Permissions.checkProfileScreenTimeout(context, profile)) {
switch (profile._deviceScreenTimeout) {
case 1:
screenTimeoutUnlock(context);
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 15000);
break;
case 2:
screenTimeoutUnlock(context);
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 30000);
break;
case 3:
screenTimeoutUnlock(context);
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 60000);
break;
case 4:
screenTimeoutUnlock(context);
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 120000);
break;
case 5:
screenTimeoutUnlock(context);
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 600000);
break;
case 6:
screenTimeoutUnlock(context);
//if (android.os.Build.VERSION.SDK_INT < 19)
// Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, -1);
//else
screenTimeoutLock(context);
//Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 18000000);
break;
case 7:
screenTimeoutUnlock(context);
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 300000);
break;
}
}
// zapnutie/vypnutie lockscreenu
//GlobalData.logE("$$$ ActivateProfileHelper.execute","keyguard");
boolean setLockscreen = false;
switch (profile._deviceKeyguard) {
case 1:
// enable lockscreen
GlobalData.logE("$$$ ActivateProfileHelper.execute","keyguard=ON");
GlobalData.setLockscreenDisabled(context, false);
setLockscreen = true;
break;
case 2:
// disable lockscreen
GlobalData.logE("$$$ ActivateProfileHelper.execute","keyguard=OFF");
GlobalData.setLockscreenDisabled(context, true);
setLockscreen = true;
break;
}
if (setLockscreen) {
boolean isScreenOn;
//if (android.os.Build.VERSION.SDK_INT >= 20)
//{
// Display display = ((WindowManager)context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
// isScreenOn = display.getState() != Display.STATE_OFF;
//}
//else
//{
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
isScreenOn = pm.isScreenOn();
//}
GlobalData.logE("$$$ ActivateProfileHelper.execute","isScreenOn="+isScreenOn);
boolean keyguardShowing = false;
KeyguardManager kgMgr = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= 16)
keyguardShowing = kgMgr.isKeyguardLocked();
else
keyguardShowing = kgMgr.inKeyguardRestrictedInputMode();
GlobalData.logE("$$$ ActivateProfileHelper.execute","keyguardShowing="+keyguardShowing);
if (isScreenOn && !keyguardShowing) {
Intent keyguardService = new Intent(context.getApplicationContext(), KeyguardService.class);
context.startService(keyguardService);
}
}
// nahodenie podsvietenia
if (Permissions.checkProfileScreenBrightness(context, profile)) {
if (profile.getDeviceBrightnessChange()) {
GlobalData.logE("ActivateProfileHelper.execute", "set brightness: profile=" + profile._name);
GlobalData.logE("ActivateProfileHelper.execute", "set brightness: _deviceBrightness=" + profile._deviceBrightness);
if (profile.getDeviceBrightnessAutomatic()) {
Settings.System.putInt(context.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS_MODE,
Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
Settings.System.putInt(context.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS,
profile.getDeviceBrightnessManualValue(context));
if (GlobalData.isPreferenceAllowed(GlobalData.PREF_PROFILE_DEVICE_ADAPTIVE_BRIGHTNESS, context)
== GlobalData.PREFERENCE_ALLOWED) {
if (android.os.Build.VERSION.SDK_INT < 23) // Not working in Android M (exception)
Settings.System.putFloat(context.getContentResolver(),
ADAPTIVE_BRIGHTNESS_SETTING_NAME,
profile.getDeviceBrightnessAdaptiveValue(context));
else {
String command1 = "settings put system " + ADAPTIVE_BRIGHTNESS_SETTING_NAME + " " +
Float.toString(profile.getDeviceBrightnessAdaptiveValue(context));
//if (GlobalData.isSELinuxEnforcing())
// command1 = GlobalData.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
Command command = new Command(0, false, command1); //, command2);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
//RootTools.closeAllShells();
} catch (Exception e) {
Log.e("ActivateProfileHelper.setGPS", "Error on run su: " + e.toString());
}
}
}
} else {
Settings.System.putInt(context.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS_MODE,
Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
Settings.System.putInt(context.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS,
profile.getDeviceBrightnessManualValue(context));
}
if (brightnessHandler != null) {
final Profile __profile = profile;
final Context __context = context;
brightnessHandler.post(new Runnable() {
public void run() {
createBrightnessView(__profile, __context);
}
});
} else
createBrightnessView(profile, context);
}
}
// nahodenie rotate
if (Permissions.checkProfileAutoRotation(context, profile)) {
switch (profile._deviceAutoRotate) {
case 1:
// set autorotate on
Settings.System.putInt(context.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 1);
Settings.System.putInt(context.getContentResolver(), Settings.System.USER_ROTATION, Surface.ROTATION_0);
break;
case 2:
// set autorotate off
// degree 0
Settings.System.putInt(context.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0);
Settings.System.putInt(context.getContentResolver(), Settings.System.USER_ROTATION, Surface.ROTATION_0);
break;
case 3:
// set autorotate off
// degree 90
Settings.System.putInt(context.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0);
Settings.System.putInt(context.getContentResolver(), Settings.System.USER_ROTATION, Surface.ROTATION_90);
break;
case 4:
// set autorotate off
// degree 180
Settings.System.putInt(context.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0);
Settings.System.putInt(context.getContentResolver(), Settings.System.USER_ROTATION, Surface.ROTATION_180);
break;
case 5:
// set autorotate off
// degree 270
Settings.System.putInt(context.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0);
Settings.System.putInt(context.getContentResolver(), Settings.System.USER_ROTATION, Surface.ROTATION_270);
break;
}
}
// nahodenie pozadia
if (Permissions.checkProfileWallpaper(context, profile)) {
if (profile._deviceWallpaperChange == 1) {
Intent wallpaperServiceIntent = new Intent(context, ExecuteWallpaperProfilePrefsService.class);
wallpaperServiceIntent.putExtra(GlobalData.EXTRA_PROFILE_ID, profile._id);
wallpaperServiceIntent.putExtra(GlobalData.EXTRA_MERGED_PROFILE, merged);
context.startService(wallpaperServiceIntent);
}
}
// set power save mode
if (GlobalData.isPreferenceAllowed(GlobalData.PREF_PROFILE_DEVICE_POWER_SAVE_MODE, context) == GlobalData.PREFERENCE_ALLOWED) {
PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
boolean _isPowerSaveMode = powerManager.isPowerSaveMode();
boolean _setPowerSaveMode = false;
switch (profile._devicePowerSaveMode) {
case 1:
if (!_isPowerSaveMode) {
_isPowerSaveMode = true;
_setPowerSaveMode = true;
}
break;
case 2:
if (_isPowerSaveMode) {
_isPowerSaveMode = false;
_setPowerSaveMode = true;
}
break;
case 3:
_isPowerSaveMode = !_isPowerSaveMode;
_setPowerSaveMode = true;
break;
}
if (_setPowerSaveMode) {
setPowerSaveMode(_isPowerSaveMode);
}
}
if (interactive)
{
// preferences, ktore vyzaduju interakciu uzivatela
if (GlobalData.isPreferenceAllowed(GlobalData.PREF_PROFILE_DEVICE_MOBILE_DATA_PREFS, context) == GlobalData.PREFERENCE_ALLOWED)
{
if (profile._deviceMobileDataPrefs == 1)
{
final Intent intent = new Intent(android.provider.Settings.ACTION_DATA_ROAMING_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
context.startActivity(intent);
} catch (Exception e) {
final ComponentName componentName = new ComponentName("com.android.phone", "com.android.phone.Settings");
//intent.addCategory(Intent.ACTION_MAIN);
intent.setComponent(componentName);
context.startActivity(intent);
}
}
}
//if (GlobalData.hardwareCheck(GlobalData.PREF_PROFILE_DEVICE_GPS, context))
//{ No check only GPS
if (profile._deviceLocationServicePrefs == 1)
{
final Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
//}
if (profile._deviceRunApplicationChange == 1)
{
Intent runApplicationsServiceIntent = new Intent(context, ExecuteRunApplicationsProfilePrefsService.class);
runApplicationsServiceIntent.putExtra(GlobalData.EXTRA_PROFILE_ID, profile._id);
runApplicationsServiceIntent.putExtra(GlobalData.EXTRA_MERGED_PROFILE, merged);
context.startService(runApplicationsServiceIntent);
}
}
}
private static void screenTimeoutLock(Context context)
{
WindowManager windowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
if (GUIData.keepScreenOnView != null)
{
windowManager.removeView(GUIData.keepScreenOnView);
GUIData.keepScreenOnView = null;
}
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
1, 1,
WindowManager.LayoutParams.TYPE_TOAST,
//TYPE_SYSTEM_ALERT,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
PixelFormat.TRANSLUCENT
);
params.gravity = Gravity.RIGHT | Gravity.TOP;
GUIData.keepScreenOnView = new BrightnessView(context);
windowManager.addView(GUIData.keepScreenOnView, params);
}
public static void screenTimeoutUnlock(Context context)
{
if (GUIData.keepScreenOnView != null)
{
WindowManager windowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
windowManager.removeView(GUIData.keepScreenOnView);
GUIData.keepScreenOnView = null;
}
GlobalData.logE("@@@ screenTimeoutLock.unlock", "xxx");
}
@SuppressLint("RtlHardcoded")
private void createBrightnessView(Profile profile, Context context)
{
//if (dataWrapper.context != null)
//{
WindowManager windowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
if (GUIData.brightneesView != null)
{
windowManager.removeView(GUIData.brightneesView);
GUIData.brightneesView = null;
}
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
1, 1,
WindowManager.LayoutParams.TYPE_TOAST,
//TYPE_SYSTEM_ALERT,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
PixelFormat.TRANSLUCENT
);
params.gravity = Gravity.RIGHT | Gravity.TOP;
if (profile.getDeviceBrightnessAutomatic())
params.screenBrightness = LayoutParams.BRIGHTNESS_OVERRIDE_NONE;
else
params.screenBrightness = profile.getDeviceBrightnessManualValue(context) / (float) 255;
GUIData.brightneesView = new BrightnessView(context);
windowManager.addView(GUIData.brightneesView, params);
RemoveBrightnessViewBroadcastReceiver.setAlarm(context);
//}
}
public static void removeBrightnessView(Context context) {
if (GUIData.brightneesView != null)
{
WindowManager windowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
windowManager.removeView(GUIData.brightneesView);
GUIData.brightneesView = null;
}
}
public void showNotification(Profile profile, String eventNotificationSound)
{
if (lockRefresh)
// no refres notification
return;
if ((GlobalData.notificationStatusBar) || (!eventNotificationSound.isEmpty()))
{
boolean notificationShowInStatusBar = GlobalData.notificationShowInStatusBar;
boolean notificationStatusBarPermanent = GlobalData.notificationStatusBarPermanent;
boolean forceShow = false;
if (!GlobalData.notificationStatusBar) {
notificationShowInStatusBar = false;
notificationStatusBarPermanent = false;
forceShow = true;
}
// close showed notification
//notificationManager.cancel(GlobalData.NOTIFICATION_ID);
// vytvorenie intentu na aktivitu, ktora sa otvori na kliknutie na notifikaciu
Intent intent = new Intent(context, LauncherActivity.class);
// clear all opened activities
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
// nastavime, ze aktivita sa spusti z notifikacnej listy
intent.putExtra(GlobalData.EXTRA_STARTUP_SOURCE, GlobalData.STARTUP_SOURCE_NOTIFICATION);
PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
// vytvorenie intentu na restart events
Intent intentRE = new Intent(context, RestartEventsFromNotificationActivity.class);
PendingIntent pIntentRE = PendingIntent.getActivity(context, 0, intentRE, PendingIntent.FLAG_CANCEL_CURRENT);
// vytvorenie samotnej notifikacie
NotificationCompat.Builder notificationBuilder;
RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.notification_drawer);
boolean isIconResourceID;
String iconIdentifier;
String profileName;
Bitmap iconBitmap;
Bitmap preferencesIndicator;
if (profile != null)
{
isIconResourceID = profile.getIsIconResourceID();
iconIdentifier = profile.getIconIdentifier();
profileName = dataWrapper.getProfileNameWithManualIndicator(profile, true, false);
iconBitmap = profile._iconBitmap;
preferencesIndicator = profile._preferencesIndicator;
}
else
{
isIconResourceID = true;
iconIdentifier = GlobalData.PROFILE_ICON_DEFAULT;
profileName = context.getResources().getString(R.string.profiles_header_profile_name_no_activated);
iconBitmap = null;
preferencesIndicator = null;
}
notificationBuilder = new NotificationCompat.Builder(context)
.setContentIntent(pIntent);
if (android.os.Build.VERSION.SDK_INT >= 16) {
if (notificationShowInStatusBar)
notificationBuilder.setPriority(NotificationCompat.PRIORITY_DEFAULT);
else
notificationBuilder.setPriority(NotificationCompat.PRIORITY_MIN);
//notificationBuilder.setPriority(Notification.PRIORITY_HIGH); // for heads-up in Android 5.0
}
if (android.os.Build.VERSION.SDK_INT >= 21)
{
notificationBuilder.setCategory(Notification.CATEGORY_STATUS);
notificationBuilder.setVisibility(Notification.VISIBILITY_PUBLIC);
}
notificationBuilder.setTicker(profileName);
if (isIconResourceID)
{
int iconSmallResource;
if (iconBitmap != null) {
iconSmallResource = context.getResources().getIdentifier(iconIdentifier + "_notify", "drawable", context.getPackageName());
notificationBuilder.setSmallIcon(iconSmallResource);
contentView.setImageViewBitmap(R.id.notification_activated_profile_icon, iconBitmap);
}
else {
if (GlobalData.notificationStatusBarStyle.equals("0") && (android.os.Build.VERSION.SDK_INT < 21)) {
//notificationBuilder.setSmallIcon(0);
iconSmallResource = context.getResources().getIdentifier(iconIdentifier + "_notify_color", "drawable", context.getPackageName());
notificationBuilder.setSmallIcon(iconSmallResource);
//contentView.setImageViewResource(R.id.notification_activated_profile_icon, 0);
contentView.setImageViewResource(R.id.notification_activated_profile_icon, iconSmallResource);
} else {
//notificationBuilder.setSmallIcon(0);
//contentView.setImageViewBitmap(R.id.notification_activated_profile_icon, null);
iconSmallResource = context.getResources().getIdentifier(iconIdentifier + "_notify", "drawable", context.getPackageName());
notificationBuilder.setSmallIcon(iconSmallResource);
int iconLargeResource = context.getResources().getIdentifier(iconIdentifier, "drawable", context.getPackageName());
Bitmap largeIcon = BitmapFactory.decodeResource(context.getResources(), iconLargeResource);
contentView.setImageViewBitmap(R.id.notification_activated_profile_icon, largeIcon);
}
}
}
else
{
int iconSmallResource;
if (GlobalData.notificationStatusBarStyle.equals("0"))
iconSmallResource = R.drawable.ic_profile_default;
else
iconSmallResource = R.drawable.ic_profile_default_notify;
//notificationBuilder.setSmallIcon(0);
notificationBuilder.setSmallIcon(iconSmallResource);
//contentView.setImageViewBitmap(R.id.notification_activated_profile_icon, null);
contentView.setImageViewBitmap(R.id.notification_activated_profile_icon, iconBitmap);
}
if (!eventNotificationSound.isEmpty())
{
Uri ringtoneUri=Uri.parse(eventNotificationSound);
notificationBuilder.setSound(ringtoneUri);
}
Notification notification = notificationBuilder.build();
contentView.setTextViewText(R.id.notification_activated_profile_name, profileName);
//contentView.setImageViewBitmap(R.id.notification_activated_profile_pref_indicator,
// ProfilePreferencesIndicator.paint(profile, context));
if ((preferencesIndicator != null) && (GlobalData.notificationPrefIndicator))
contentView.setImageViewBitmap(R.id.notification_activated_profile_pref_indicator, preferencesIndicator);
else
contentView.setImageViewResource(R.id.notification_activated_profile_pref_indicator, R.drawable.ic_empty);
if (android.os.Build.VERSION.SDK_INT >= 20)
contentView.setImageViewResource(R.id.notification_activated_profile_restart_events, R.drawable.ic_action_events_restart);
else
contentView.setImageViewResource(R.id.notification_activated_profile_restart_events, R.drawable.ic_action_events_restart_dark);
contentView.setOnClickPendingIntent(R.id.notification_activated_profile_restart_events, pIntentRE);
notification.contentView = contentView;
if (notificationStatusBarPermanent)
{
//notification.flags |= Notification.FLAG_NO_CLEAR;
notification.flags |= Notification.FLAG_ONGOING_EVENT;
}
else
{
setAlarmForNotificationCancel(forceShow);
}
notificationManager.notify(GlobalData.PROFILE_NOTIFICATION_ID, notification);
}
else
{
notificationManager.cancel(GlobalData.PROFILE_NOTIFICATION_ID);
}
}
public void removeNotification()
{
notificationManager.cancel(GlobalData.PROFILE_NOTIFICATION_ID);
}
@SuppressLint("NewApi")
private void setAlarmForNotificationCancel(boolean forceShow)
{
if (!forceShow) {
if (GlobalData.notificationStatusBarCancel.isEmpty() || GlobalData.notificationStatusBarCancel.equals("0"))
return;
}
int notificationStatusBarCancel = Integer.valueOf(GlobalData.notificationStatusBarCancel);
if (forceShow)
notificationStatusBarCancel = 3;
Intent intent = new Intent(context, NotificationCancelAlarmBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(), 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Activity.ALARM_SERVICE);
Calendar now = Calendar.getInstance();
long time = now.getTimeInMillis() + notificationStatusBarCancel * 1000;
// not needed exact for removing notification
/*if (GlobalData.exactAlarms && (android.os.Build.VERSION.SDK_INT >= 23))
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, time, pendingIntent);
if (GlobalData.exactAlarms && (android.os.Build.VERSION.SDK_INT >= 19))
alarmManager.setExact(AlarmManager.RTC_WAKEUP, time, pendingIntent);
else*/
alarmManager.set(AlarmManager.RTC_WAKEUP, time, pendingIntent);
//alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, alarmTime, 24 * 60 * 60 * 1000 , pendingIntent);
//alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, alarmTime, 24 * 60 * 60 * 1000 , pendingIntent);
}
public void updateWidget()
{
if (lockRefresh)
// no refres widgets
return;
// icon widget
Intent intent = new Intent(context, IconWidgetProvider.class);
intent.setAction("android.appwidget.action.APPWIDGET_UPDATE");
int ids[] = AppWidgetManager.getInstance(context).getAppWidgetIds(new ComponentName(context, IconWidgetProvider.class));
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids);
context.sendBroadcast(intent);
// one row widget
Intent intent4 = new Intent(context, OneRowWidgetProvider.class);
intent4.setAction("android.appwidget.action.APPWIDGET_UPDATE");
int ids4[] = AppWidgetManager.getInstance(context).getAppWidgetIds(new ComponentName(context, OneRowWidgetProvider.class));
intent4.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids4);
context.sendBroadcast(intent4);
// list widget
Intent intent2 = new Intent(context, ProfileListWidgetProvider.class);
intent2.setAction(ProfileListWidgetProvider.INTENT_REFRESH_LISTWIDGET);
int ids2[] = AppWidgetManager.getInstance(context).getAppWidgetIds(new ComponentName(context, ProfileListWidgetProvider.class));
intent2.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids2);
context.sendBroadcast(intent2);
// dashclock extension
Intent intent3 = new Intent();
intent3.setAction(DashClockBroadcastReceiver.INTENT_REFRESH_DASHCLOCK);
context.sendBroadcast(intent3);
// activities
Intent intent5 = new Intent();
intent5.setAction(RefreshGUIBroadcastReceiver.INTENT_REFRESH_GUI);
context.sendBroadcast(intent5);
}
private boolean isAirplaneMode(Context context)
{
if (android.os.Build.VERSION.SDK_INT >= 17)
return Settings.Global.getInt(context.getContentResolver(), Global.AIRPLANE_MODE_ON, 0) != 0;
else
return Settings.System.getInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) != 0;
}
private void setAirplaneMode(Context context, boolean mode)
{
if (android.os.Build.VERSION.SDK_INT >= 17)
setAirplaneMode_SDK17(context, mode);
else
setAirplaneMode_SDK8(context, mode);
}
private boolean isMobileData(Context context)
{
if (android.os.Build.VERSION.SDK_INT >= 21)
{
return Settings.Global.getInt(context.getContentResolver(), "mobile_data", 0) == 1;
}
else
{
final ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
final Class<?> connectivityManagerClass = Class.forName(connectivityManager.getClass().getName());
final Method getMobileDataEnabledMethod = connectivityManagerClass.getDeclaredMethod("getMobileDataEnabled");
getMobileDataEnabledMethod.setAccessible(true);
return (Boolean)getMobileDataEnabledMethod.invoke(connectivityManager);
} catch (ClassNotFoundException e) {
e.printStackTrace();
return false;
} catch (NoSuchMethodException e) {
e.printStackTrace();
return false;
} catch (IllegalArgumentException e) {
e.printStackTrace();
return false;
} catch (IllegalAccessException e) {
e.printStackTrace();
return false;
} catch (InvocationTargetException e) {
e.printStackTrace();
return false;
}
}
/*
final NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null)
{
int netvorkType = networkInfo.getType(); // 0 = mobile, 1 = wifi
//String netvorkTypeName = networkInfo.getTypeName(); // "mobile" or "WIFI"
boolean connected = networkInfo.isConnected(); // true = active connection
//if (netvorkType == 0)
//{
// connected into mobile data
return connected;
//}
//else
//{
// conected into Wifi
// return false;
//}
}
else
return false;
*/
}
private void setMobileData(Context context, boolean enable)
{
if (android.os.Build.VERSION.SDK_INT >= 21)
{
if (GlobalData.grantRoot(false))
{
int state = 0;
try {
// Get the current state of the mobile network.
state = enable ? 1 : 0;
// Get the value of the "TRANSACTION_setDataEnabled" field.
String transactionCode = GlobalData.getTransactionCode(context, "TRANSACTION_setDataEnabled");
// Android 5.1+ (API 22) and later.
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
SubscriptionManager mSubscriptionManager = (SubscriptionManager) context.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);
// Loop through the subscription list i.e. SIM list.
for (int i = 0; i < mSubscriptionManager.getActiveSubscriptionInfoCountMax(); i++) {
if (transactionCode != null && transactionCode.length() > 0) {
// Get the active subscription ID for a given SIM card.
int subscriptionId = mSubscriptionManager.getActiveSubscriptionInfoList().get(i).getSubscriptionId();
String command1 = "service call phone " + transactionCode + " i32 " + subscriptionId + " i32 " + state;
Command command = new Command(0, false, command1);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
//RootTools.closeAllShells();
} catch (Exception e) {
Log.e("ActivateProfileHelper.setMobileData", "Error on run su");
}
}
}
} else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP) {
// Android 5.0 (API 21) only.
if (transactionCode != null && transactionCode.length() > 0) {
String command1 = "service call phone " + transactionCode + " i32 " + state;
Command command = new Command(0, false, command1);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
//RootTools.closeAllShells();
} catch (Exception e) {
Log.e("ActivateProfileHelper.setMobileData", "Error on run su");
}
}
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
else
{
final ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
boolean OK = false;
try {
final Class<?> connectivityManagerClass = Class.forName(connectivityManager.getClass().getName());
final Field iConnectivityManagerField = connectivityManagerClass.getDeclaredField("mService");
iConnectivityManagerField.setAccessible(true);
final Object iConnectivityManager = iConnectivityManagerField.get(connectivityManager);
final Class<?> iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName());
final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
setMobileDataEnabledMethod.setAccessible(true);
setMobileDataEnabledMethod.invoke(iConnectivityManager, enable);
OK = true;
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
if (!OK)
{
try {
Method setMobileDataEnabledMethod = ConnectivityManager.class.getDeclaredMethod("setMobileDataEnabled", boolean.class);
setMobileDataEnabledMethod.setAccessible(true);
setMobileDataEnabledMethod.invoke(connectivityManager, enable);
OK = true;
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
private int getPreferredNetworkType(Context context) {
if (GlobalData.grantRoot(false))
{
try {
// Get the value of the "TRANSACTION_setPreferredNetworkType" field.
String transactionCode = GlobalData.getTransactionCode(context, "TRANSACTION_getPreferredNetworkType");
if (transactionCode != null && transactionCode.length() > 0) {
String command1 = "service call phone " + transactionCode + " i32";
Command command = new Command(0, false, command1) {
@Override
public void commandOutput(int id, String line) {
super.commandOutput(id, line);
String splits[] = line.split(" ");
try {
networkType = Integer.parseInt(splits[2]);
} catch (Exception e) {
networkType = -1;
}
}
@Override
public void commandTerminated(int id, String reason) {
super.commandTerminated(id, reason);
}
@Override
public void commandCompleted(int id, int exitcode) {
super.commandCompleted(id, exitcode);
}
};
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
//RootTools.closeAllShells();
} catch (Exception e) {
Log.e("ActivateProfileHelper.setPreferredNetworkType", "Error on run su");
}
}
} catch(Exception e) {
e.printStackTrace();
}
}
return networkType;
}
private void setPreferredNetworkType(Context context, int networkType)
{
if (GlobalData.grantRoot(false))
{
try {
// Get the value of the "TRANSACTION_setPreferredNetworkType" field.
String transactionCode = GlobalData.getTransactionCode(context, "TRANSACTION_setPreferredNetworkType");
if (Build.VERSION.SDK_INT >= 23) {
SubscriptionManager mSubscriptionManager = (SubscriptionManager) context.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);
// Loop through the subscription list i.e. SIM list.
for (int i = 0; i < mSubscriptionManager.getActiveSubscriptionInfoCountMax(); i++) {
if (transactionCode != null && transactionCode.length() > 0) {
// Get the active subscription ID for a given SIM card.
int subscriptionId = mSubscriptionManager.getActiveSubscriptionInfoList().get(i).getSubscriptionId();
String command1 = "service call phone " + transactionCode + " i32 " + subscriptionId + " i32 " + networkType;
Command command = new Command(0, false, command1);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
//RootTools.closeAllShells();
} catch (Exception e) {
Log.e("ActivateProfileHelper.setPreferredNetworkType", "Error on run su");
}
}
}
} else {
if (transactionCode != null && transactionCode.length() > 0) {
String command1 = "service call phone " + transactionCode + " i32 " + networkType;
Command command = new Command(0, false, command1);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
//RootTools.closeAllShells();
} catch (Exception e) {
Log.e("ActivateProfileHelper.setPreferredNetworkType", "Error on run su");
}
}
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
@SuppressWarnings("deprecation")
private void setGPS(Context context, boolean enable)
{
//boolean isEnabled;
//int locationMode = -1;
//if (android.os.Build.VERSION.SDK_INT < 19)
// isEnabled = Settings.Secure.isLocationProviderEnabled(context.getContentResolver(), LocationManager.GPS_PROVIDER);
/*else {
locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE, -1);
isEnabled = (locationMode == Settings.Secure.LOCATION_MODE_HIGH_ACCURACY) ||
(locationMode == Settings.Secure.LOCATION_MODE_SENSORS_ONLY);
}*/
boolean isEnabled;
if (android.os.Build.VERSION.SDK_INT < 21)
isEnabled = Settings.Secure.isLocationProviderEnabled(context.getContentResolver(), LocationManager.GPS_PROVIDER);
else {
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
isEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
GlobalData.logE("ActivateProfileHelper.setGPS", "isEnabled="+isEnabled);
//if(!provider.contains(LocationManager.GPS_PROVIDER) && enable)
if ((!isEnabled) && enable)
{
if (GlobalData.canExploitGPS(context))
{
GlobalData.logE("ActivateProfileHelper.setGPS", "exploit");
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
context.sendBroadcast(poke);
}
else
if ((android.os.Build.VERSION.SDK_INT >= 17) && GlobalData.grantRoot(false))
{
// zariadenie je rootnute
GlobalData.logE("ActivateProfileHelper.setGPS", "rooted");
String command1;
//String command2;
if (android.os.Build.VERSION.SDK_INT < 23) {
String provider = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
String newSet;
if (provider == "")
newSet = LocationManager.GPS_PROVIDER;
else
newSet = String.format("%s,%s", provider, LocationManager.GPS_PROVIDER);
command1 = "settings put secure location_providers_allowed \"" + newSet + "\"";
//if (GlobalData.isSELinuxEnforcing())
// command1 = GlobalData.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
//command2 = "am broadcast -a android.location.GPS_ENABLED_CHANGE --ez state true";
Command command = new Command(0, false, command1); //, command2);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
//RootTools.closeAllShells();
} catch (Exception e) {
Log.e("ActivateProfileHelper.setGPS", "Error on run su: " + e.toString());
}
}
else {
command1 = "settings put secure location_providers_allowed +gps";
Command command = new Command(0, false, command1);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
//RootTools.closeAllShells();
} catch (Exception e) {
Log.e("ActivateProfileHelper.setGPS", "Error on run su: " + e.toString());
}
}
}
else
{
/*GlobalData.logE("ActivateProfileHelper.setGPS", "old method");
try {
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", enable);
context.sendBroadcast(intent);
} catch (SecurityException e) {
e.printStackTrace();
}*/
// for normal apps it is only possible to open the system settings dialog
/* Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent); */
}
}
else
//if(provider.contains(LocationManager.GPS_PROVIDER) && (!enable))
if (isEnabled && (!enable))
{
if (GlobalData.canExploitGPS(context))
{
GlobalData.logE("ActivateProfileHelper.setGPS", "exploit");
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
context.sendBroadcast(poke);
}
else
if ((android.os.Build.VERSION.SDK_INT >= 17) && GlobalData.grantRoot(false))
{
// zariadenie je rootnute
GlobalData.logE("ActivateProfileHelper.setGPS", "rooted");
String command1;
//String command2;
if (android.os.Build.VERSION.SDK_INT < 23) {
String provider = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
String[] list = provider.split(",");
String newSet = "";
int j = 0;
for (int i = 0; i < list.length; i++) {
if (!list[i].equals(LocationManager.GPS_PROVIDER)) {
if (j > 0)
newSet += ",";
newSet += list[i];
j++;
}
}
command1 = "settings put secure location_providers_allowed \"" + newSet + "\"";
//if (GlobalData.isSELinuxEnforcing())
// command1 = GlobalData.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
//command2 = "am broadcast -a android.location.GPS_ENABLED_CHANGE --ez state false";
Command command = new Command(0, false, command1);//, command2);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
//RootTools.closeAllShells();
} catch (Exception e) {
Log.e("ActivateProfileHelper.setGPS", "Error on run su: " + e.toString());
}
}
else {
command1 = "settings put secure location_providers_allowed -gps";
Command command = new Command(0, false, command1);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
//RootTools.closeAllShells();
} catch (Exception e) {
Log.e("ActivateProfileHelper.setGPS", "Error on run su: " + e.toString());
}
}
}
else
{
//GlobalData.logE("ActivateProfileHelper.setGPS", "old method");
/*try {
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", enable);
context.sendBroadcast(intent);
} catch (SecurityException e) {
e.printStackTrace();
}*/
// for normal apps it is only possible to open the system settings dialog
/* Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent); */
}
}
}
private void setAirplaneMode_SDK17(Context context, boolean mode)
{
if (GlobalData.grantRoot(false))
{
// zariadenie je rootnute
String command1;
String command2;
if (mode)
{
command1 = "settings put global airplane_mode_on 1";
command2 = "am broadcast -a android.intent.action.AIRPLANE_MODE --ez state true";
}
else
{
command1 = "settings put global airplane_mode_on 0";
command2 = "am broadcast -a android.intent.action.AIRPLANE_MODE --ez state false";
}
//if (GlobalData.isSELinuxEnforcing())
//{
// command1 = GlobalData.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
// command2 = GlobalData.getSELinuxEnforceCommand(command2, Shell.ShellContext.SYSTEM_APP);
//}
Command command = new Command(0, false, command1, command2);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
//RootTools.closeAllShells();
} catch (Exception e) {
Log.e("AirPlaneMode_SDK17.setAirplaneMode", "Error on run su");
}
}
else
{
// for normal apps it is only possible to open the system settings dialog
/* Intent intent = new Intent(android.provider.Settings.ACTION_AIRPLANE_MODE_SETTINGS);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent); */
}
}
@SuppressWarnings("deprecation")
private void setAirplaneMode_SDK8(Context context, boolean mode)
{
Settings.System.putInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, mode ? 1 : 0);
Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
intent.putExtra("state", mode);
context.sendBroadcast(intent);
}
private void setPowerSaveMode(boolean enable) {
String command1 = "settings put global low_power " + ((enable) ? 1 : 0);
Command command = new Command(0, false, command1);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
//RootTools.closeAllShells();
} catch (Exception e) {
Log.e("ActivateProfileHelper.setPowerSaveMode", "Error on run su: " + e.toString());
}
}
private static void commandWait(Command cmd) throws Exception {
int waitTill = 50;
int waitTillMultiplier = 2;
int waitTillLimit = 3200; //7 tries, 6350 msec
while (!cmd.isFinished() && waitTill<=waitTillLimit) {
synchronized (cmd) {
try {
if (!cmd.isFinished()) {
cmd.wait(waitTill);
waitTill *= waitTillMultiplier;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
if (!cmd.isFinished()){
Log.e("ActivateProfileHelper", "Could not finish root command in " + (waitTill/waitTillMultiplier));
}
}
public static int getMinimumScreenBrightnessSetting (Context context)
{
final Resources res = Resources.getSystem();
int id = res.getIdentifier("config_screenBrightnessSettingMinimum", "integer", "android"); // API17+
if (id == 0)
id = res.getIdentifier("config_screenBrightnessDim", "integer", "android"); // lower API levels
if (id != 0)
{
try {
return res.getInteger(id);
}
catch (Resources.NotFoundException e) {
// ignore
}
}
return 0;
}
public static int getMaximumScreenBrightnessSetting (Context context)
{
final Resources res = Resources.getSystem();
final int id = res.getIdentifier("config_screenBrightnessSettingMaximum", "integer", "android"); // API17+
if (id != 0)
{
try {
return res.getInteger(id);
}
catch (Resources.NotFoundException e) {
// ignore
}
}
return 255;
}
}
| phoneProfilesPlus/src/main/java/sk/henrichg/phoneprofilesplus/ActivateProfileHelper.java | package sk.henrichg.phoneprofilesplus;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.KeyguardManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.WallpaperManager;
import android.appwidget.AppWidgetManager;
import android.bluetooth.BluetoothAdapter;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.location.LocationManager;
import android.media.AudioManager;
import android.media.RingtoneManager;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Handler;
import android.os.PowerManager;
import android.provider.Settings;
import android.provider.Settings.Global;
import android.service.notification.NotificationListenerService;
import android.support.v4.app.NotificationCompat;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.Surface;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.RemoteViews;
import com.stericson.RootShell.execution.Command;
import com.stericson.RootShell.execution.Shell;
import com.stericson.RootTools.RootTools;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Calendar;
public class ActivateProfileHelper {
private DataWrapper dataWrapper;
private Context context;
private NotificationManager notificationManager;
private Handler brightnessHandler;
private int networkType = -1;
public static boolean lockRefresh = false;
public static final String ADAPTIVE_BRIGHTNESS_SETTING_NAME = "screen_auto_brightness_adj";
// Setting.Global "zen_mode"
public static final int ZENMODE_ALL = 0;
public static final int ZENMODE_PRIORITY = 1;
public static final int ZENMODE_NONE = 2;
public static final int ZENMODE_ALARMS = 3;
public ActivateProfileHelper()
{
}
public void initialize(DataWrapper dataWrapper, Activity a, Context c)
{
this.dataWrapper = dataWrapper;
initializeNoNotificationManager(c);
notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
}
public void initializeNoNotificationManager(Context c)
{
context = c;
}
public void deinitialize()
{
dataWrapper = null;
context = null;
notificationManager = null;
}
public void setBrightnessHandler(Handler handler)
{
brightnessHandler = handler;
}
@SuppressWarnings("deprecation")
private void doExecuteForRadios(Profile profile, boolean onlyCheckForPPHelper)
{
if (!onlyCheckForPPHelper)
{
try {
Thread.sleep(300);
} catch (InterruptedException e) {
System.out.println(e);
}
}
// nahodenie network type
if (!onlyCheckForPPHelper) {
if (GlobalData.isPreferenceAllowed(GlobalData.PREF_PROFILE_DEVICE_NETWORK_TYPE, context) == GlobalData.PREFERENCE_ALLOWED) {
if (profile._deviceNetworkType >= 100) {
setPreferredNetworkType(context, profile._deviceNetworkType - 100);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
// nahodenie mobilnych dat
if (!onlyCheckForPPHelper) {
if (GlobalData.isPreferenceAllowed(GlobalData.PREF_PROFILE_DEVICE_MOBILE_DATA, context) == GlobalData.PREFERENCE_ALLOWED) {
boolean _isMobileData = isMobileData(context);
boolean _setMobileData = false;
switch (profile._deviceMobileData) {
case 1:
if (!_isMobileData) {
_isMobileData = true;
_setMobileData = true;
}
break;
case 2:
if (_isMobileData) {
_isMobileData = false;
_setMobileData = true;
}
break;
case 3:
_isMobileData = !_isMobileData;
_setMobileData = true;
break;
}
if (_setMobileData) {
setMobileData(context, _isMobileData);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
// nahodenie WiFi AP
boolean canChangeWifi = true;
if (!onlyCheckForPPHelper) {
if (GlobalData.isPreferenceAllowed(GlobalData.PREF_PROFILE_DEVICE_WIFI_AP, context) == GlobalData.PREFERENCE_ALLOWED) {
WifiApManager wifiApManager = null;
try {
wifiApManager = new WifiApManager(context);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
if (wifiApManager != null) {
boolean setWifiAPState = false;
boolean isWifiAPEnabled = wifiApManager.isWifiAPEnabled();
switch (profile._deviceWiFiAP) {
case 1:
if (!isWifiAPEnabled) {
isWifiAPEnabled = true;
setWifiAPState = true;
canChangeWifi = false;
}
break;
case 2:
if (isWifiAPEnabled) {
isWifiAPEnabled = false;
setWifiAPState = true;
canChangeWifi = true;
}
break;
case 3:
isWifiAPEnabled = !isWifiAPEnabled;
setWifiAPState = true;
canChangeWifi = !isWifiAPEnabled;
break;
}
if (setWifiAPState) {
wifiApManager.setWifiApState(isWifiAPEnabled);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
}
if (canChangeWifi) {
// nahodenie WiFi
if (GlobalData.isPreferenceAllowed(GlobalData.PREF_PROFILE_DEVICE_WIFI, context) == GlobalData.PREFERENCE_ALLOWED) {
boolean isWifiAPEnabled = WifiApManager.isWifiAPEnabled(context);
if (!isWifiAPEnabled) { // only when wifi AP is not enabled, change wifi
GlobalData.logE("$$$ WifiAP", "ActivateProfileHelper.doExecuteForRadios-isWifiAPEnabled=" + isWifiAPEnabled);
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
int wifiState = wifiManager.getWifiState();
boolean isWifiEnabled = ((wifiState == WifiManager.WIFI_STATE_ENABLED) || (wifiState == WifiManager.WIFI_STATE_ENABLING));
boolean setWifiState = false;
switch (profile._deviceWiFi) {
case 1:
if (!isWifiEnabled) {
isWifiEnabled = true;
setWifiState = true;
}
break;
case 2:
if (isWifiEnabled) {
isWifiEnabled = false;
setWifiState = true;
}
break;
case 3:
isWifiEnabled = !isWifiEnabled;
setWifiState = true;
break;
}
if (setWifiState) {
if (!onlyCheckForPPHelper) {
try {
wifiManager.setWifiEnabled(isWifiEnabled);
} catch (Exception e) {
wifiManager.setWifiEnabled(isWifiEnabled);
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
System.out.println(e);
}
}
if (isWifiEnabled)
// when wifi is enabled from profile, no disable wifi after scan
WifiScanAlarmBroadcastReceiver.setWifiEnabledForScan(context, false);
}
}
}
}
// nahodenie bluetooth
if (GlobalData.isPreferenceAllowed(GlobalData.PREF_PROFILE_DEVICE_BLUETOOTH, context) == GlobalData.PREFERENCE_ALLOWED)
{
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
boolean isBluetoothEnabled = bluetoothAdapter.isEnabled();
boolean setBluetoothState = false;
switch (profile._deviceBluetooth) {
case 1 :
if (!isBluetoothEnabled)
{
isBluetoothEnabled = true;
setBluetoothState = true;
}
break;
case 2 :
if (isBluetoothEnabled)
{
isBluetoothEnabled = false;
setBluetoothState = true;
}
break;
case 3 :
isBluetoothEnabled = ! isBluetoothEnabled;
setBluetoothState = true;
break;
}
if (setBluetoothState)
{
if (!onlyCheckForPPHelper)
{
if (isBluetoothEnabled)
bluetoothAdapter.enable();
else
bluetoothAdapter.disable();
}
if (isBluetoothEnabled)
// when bluetooth is enabled from profile, no disable bluetooth after scan
BluetoothScanAlarmBroadcastReceiver.setBluetoothEnabledForScan(context, false);
}
}
// nahodenie GPS
if (!onlyCheckForPPHelper) {
if (GlobalData.isPreferenceAllowed(GlobalData.PREF_PROFILE_DEVICE_GPS, context) == GlobalData.PREFERENCE_ALLOWED)
{
//String provider = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
boolean isEnabled;
if (android.os.Build.VERSION.SDK_INT < 21)
isEnabled = Settings.Secure.isLocationProviderEnabled(context.getContentResolver(), LocationManager.GPS_PROVIDER);
else {
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
isEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
GlobalData.logE("ActivateProfileHelper.doExecuteForRadios","isEnabled="+isEnabled);
switch (profile._deviceGPS) {
case 1:
setGPS(context, true);
break;
case 2:
setGPS(context, false);
break;
case 3:
if (!isEnabled) {
setGPS(context, true);
} else if (isEnabled) {
setGPS(context, false);
}
break;
}
}
}
// nahodenie NFC - len v PPHelper
}
public void executeForRadios(Profile profile, boolean onlyCheckForPPHelper)
{
boolean _isAirplaneMode = false;
boolean _setAirplaneMode = false;
if (GlobalData.isPreferenceAllowed(GlobalData.PREF_PROFILE_DEVICE_AIRPLANE_MODE, context) == GlobalData.PREFERENCE_ALLOWED)
{
_isAirplaneMode = isAirplaneMode(context);
switch (profile._deviceAirplaneMode) {
case 1:
if (!_isAirplaneMode)
{
_isAirplaneMode = true;
_setAirplaneMode = true;
}
break;
case 2:
if (_isAirplaneMode)
{
_isAirplaneMode = false;
_setAirplaneMode = true;
}
break;
case 3:
_isAirplaneMode = !_isAirplaneMode;
_setAirplaneMode = true;
break;
}
}
if (_setAirplaneMode && _isAirplaneMode)
// switch ON airplane mode, set it before executeForRadios
setAirplaneMode(context, _isAirplaneMode);
doExecuteForRadios(profile, onlyCheckForPPHelper);
if (_setAirplaneMode && !(_isAirplaneMode))
// switch OFF airplane mode, set if after executeForRadios
setAirplaneMode(context, _isAirplaneMode);
}
public void correctVolume0(/*Profile profile, */AudioManager audioManager, int linkUnlink) {
int ringerMode, zenMode;
if (linkUnlink == PhoneCallService.LINKMODE_NONE) {
ringerMode = GlobalData.getRingerMode(context);
zenMode = GlobalData.getZenMode(context);
}
else {
ringerMode = GlobalData.getRingerMode(context);
zenMode = GlobalData.getZenMode(context);
//ringerMode = RingerModeChangeReceiver.getRingerMode(context, audioManager);
}
if ((ringerMode == 1) || (ringerMode == 4) ||
((ringerMode == 5) && ((zenMode == 1) || (zenMode == 2)))) {
//if (profile._volumeRingerMode == 4) {
// last profile ringer mode = Silent
if (audioManager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE) {
// actual system ringer mode = vibrate
// volume changed it to vibrate
//RingerModeChangeReceiver.internalChange = true;
audioManager.setStreamVolume(AudioManager.STREAM_RING, 1, 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_RING, 1);
}
}
}
@SuppressLint("NewApi")
public void setVolumes(Profile profile, AudioManager audioManager, int linkUnlink)
{
if (profile.getVolumeRingtoneChange() || profile.getVolumeSystemChange()) {
if (profile.getVolumeRingtoneChange()) {
if (linkUnlink == PhoneCallService.LINKMODE_NONE)
GlobalData.setRingerVolume(context, profile.getVolumeRingtoneValue());
}
}
if (profile.getVolumeNotificationChange() || profile.getVolumeSystemChange()) {
if (profile.getVolumeNotificationChange()) {
if (linkUnlink == PhoneCallService.LINKMODE_NONE)
GlobalData.setNotificationVolume(context, profile.getVolumeNotificationValue());
}
}
int ringerMode = GlobalData.getRingerMode(context);
int zenMode = GlobalData.getZenMode(context);
// for interruption types NONE and ONLY_ALARMS not set system, ringer, npotification volume
// Android 6 - priority mode = ONLY_ALARMS
if (!( ((ringerMode == 4) && (android.os.Build.VERSION.SDK_INT >= 23)) ||
((ringerMode == 5) && ((zenMode == 3) || (zenMode == 6)))
)) {
if (profile.getVolumeSystemChange()) {
//RingerModeChangeReceiver.internalChange = true;
audioManager.setStreamVolume(AudioManager.STREAM_SYSTEM, profile.getVolumeSystemValue(), 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_SYSTEM, profile.getVolumeSystemValue());
correctVolume0(/*profile, */audioManager, linkUnlink);
}
if (Permissions.checkSavedProfileVolumes(context)) {
TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
int callState = telephony.getCallState();
if (profile.getVolumeRingtoneChange() || profile.getVolumeSystemChange()) {
if (((!GlobalData.applicationUnlinkRingerNotificationVolumes) || (callState != TelephonyManager.CALL_STATE_RINGING))
&& (linkUnlink == PhoneCallService.LINKMODE_NONE)) {
int volume = GlobalData.getRingerVolume(context);
if (volume != -999) {
//RingerModeChangeReceiver.internalChange = true;
audioManager.setStreamVolume(AudioManager.STREAM_RING, profile.getVolumeRingtoneValue(), 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_RING, profile.getVolumeRingtoneValue());
correctVolume0(/*profile, */audioManager, linkUnlink);
}
}
}
if (profile.getVolumeNotificationChange() || profile.getVolumeSystemChange()) {
if (((!GlobalData.applicationUnlinkRingerNotificationVolumes) || (callState != TelephonyManager.CALL_STATE_RINGING))
&& (linkUnlink == PhoneCallService.LINKMODE_NONE)) {
int volume = GlobalData.getNotificationVolume(context);
if (volume != -999) {
//RingerModeChangeReceiver.internalChange = true;
audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, profile.getVolumeNotificationValue(), 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_NOTIFICATION, profile.getVolumeNotificationValue());
correctVolume0(/*profile, */audioManager, linkUnlink);
}
}
}
if (GlobalData.applicationUnlinkRingerNotificationVolumes) {
boolean doUnlink = audioManager.getRingerMode() == AudioManager.RINGER_MODE_NORMAL;
if (android.os.Build.VERSION.SDK_INT >= 21)
doUnlink = doUnlink && (Settings.Global.getInt(context.getContentResolver(), "zen_mode", ZENMODE_ALL) != ZENMODE_NONE);
//Log.e("ActivateProfileHelper", "setVolumes doUnlink=" + doUnlink);
//Log.e("ActivateProfileHelper", "setVolumes ringerMode=" + audioManager.getRingerMode());
//Log.e("ActivateProfileHelper", "setVolumes zenMode=" + Settings.Global.getInt(context.getContentResolver(), "zen_mode", ZENMODE_NONE));
if (doUnlink) {
//if (linkUnlink == PhoneCallBroadcastReceiver.LINKMODE_UNLINK) {
if (callState == TelephonyManager.CALL_STATE_RINGING) {
// for separating ringing and notification
// in ringing state ringer volumes must by set
// and notification volumes must not by set
int volume = GlobalData.getRingerVolume(context);
if (volume != -999) {
//RingerModeChangeReceiver.internalChange = true;
audioManager.setStreamVolume(AudioManager.STREAM_RING, volume, 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_RING, profile.getVolumeRingtoneValue());
//RingerModeChangeReceiver.internalChange = true;
audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, volume, 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_NOTIFICATION, profile.getVolumeNotificationValue());
correctVolume0(/*profile, */audioManager, linkUnlink);
}
} else if (linkUnlink == PhoneCallService.LINKMODE_LINK) {
// for separating ringing and notification
// in not ringing state ringer and notification volume must by change
//Log.e("ActivateProfileHelper","setVolumes get audio mode="+audioManager.getMode());
int volume = GlobalData.getRingerVolume(context);
if (volume != -999) {
//Log.e("ActivateProfileHelper","setVolumes set ring volume="+volume);
//RingerModeChangeReceiver.internalChange = true;
audioManager.setStreamVolume(AudioManager.STREAM_RING, volume, 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_RING, profile.getVolumeRingtoneValue());
}
volume = GlobalData.getNotificationVolume(context);
if (volume != -999) {
//Log.e("ActivateProfileHelper","setVolumes set notification volume="+volume);
//RingerModeChangeReceiver.internalChange = true;
audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, volume, 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_NOTIFICATION, profile.getVolumeNotificationValue());
}
correctVolume0(/*profile, */audioManager, linkUnlink);
}
}
}
}
}
if (profile.getVolumeMediaChange())
{
//RingerModeChangeReceiver.internalChange = true;
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, profile.getVolumeMediaValue(), 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_MUSIC, profile.getVolumeMediaValue());
}
if (profile.getVolumeAlarmChange())
{
//RingerModeChangeReceiver.internalChange = true;
audioManager.setStreamVolume(AudioManager.STREAM_ALARM, profile.getVolumeAlarmValue(), 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_ALARM, profile.getVolumeAlarmValue());
}
if (profile.getVolumeVoiceChange()) {
//RingerModeChangeReceiver.internalChange = true;
audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, profile.getVolumeVoiceValue(), 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_VOICE, profile.getVolumeVoiceValue());
}
}
public static boolean setZenMode(Context context, int zenMode, AudioManager audioManager, int ringerMode)
{
if (android.os.Build.VERSION.SDK_INT >= 21)
{
if (PPNotificationListenerService.isNotificationListenerServiceEnabled(context)) {
int _zenMode = Settings.Global.getInt(context.getContentResolver(), "zen_mode", -1);
GlobalData.logE("ActivateProfileHelper.setZenMode","_zenMode="+_zenMode);
if (zenMode != _zenMode) {
int interruptionFilter = NotificationListenerService.INTERRUPTION_FILTER_ALL;
switch (zenMode) {
case ZENMODE_ALL:
interruptionFilter = NotificationListenerService.INTERRUPTION_FILTER_ALL;
break;
case ZENMODE_PRIORITY:
interruptionFilter = NotificationListenerService.INTERRUPTION_FILTER_PRIORITY;
break;
case ZENMODE_NONE:
interruptionFilter = NotificationListenerService.INTERRUPTION_FILTER_NONE;
break;
case ZENMODE_ALARMS:
interruptionFilter = NotificationListenerService.INTERRUPTION_FILTER_ALARMS;
break;
}
PPNotificationListenerService.requestInterruptionFilter(context, interruptionFilter);
if (ringerMode > -1)
audioManager.setRingerMode(ringerMode);
return true;
}
}
/* else
if (GlobalData.grantRoot(false) && (GlobalData.settingsBinaryExists()))
{
String command1 = "settings put global zen_mode " + mode;
//if (GlobalData.isSELinuxEnforcing())
// command1 = GlobalData.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
Command command = new Command(0, false, command1);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
//RootTools.closeAllShells();
} catch (Exception e) {
Log.e("ActivateProfileHelper.setZenMode", e.getMessage());
}
}*/
}
return false;
}
private void setVibrateWhenRinging(int value) {
if (GlobalData.isPreferenceAllowed(GlobalData.PREF_PROFILE_DEVICE_VIBRATE_WHEN_RINGING, context)
== GlobalData.PREFERENCE_ALLOWED) {
if (android.os.Build.VERSION.SDK_INT < 23) // Not working in Android M (exception)
Settings.System.putInt(context.getContentResolver(), "vibrate_when_ringing", value);
else {
String command1 = "settings put system " + Settings.System.VIBRATE_WHEN_RINGING + " " + value;
//if (GlobalData.isSELinuxEnforcing())
// command1 = GlobalData.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
Command command = new Command(0, false, command1); //, command2);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
//RootTools.closeAllShells();
} catch (Exception e) {
Log.e("ActivateProfileHelper.setVibrateWhenRinging", "Error on run su: " + e.toString());
}
}
}
}
@SuppressWarnings("deprecation")
public boolean setRingerMode(Profile profile, AudioManager audioManager, boolean forPriority, int linkUnlink)
{
GlobalData.logE("@@@ ActivateProfileHelper.setRingerMode", "andioM.ringerMode=" + audioManager.getRingerMode());
int ringerMode, oldRingerMode;
int zenMode, oldZenMode;
oldRingerMode = GlobalData.getRingerMode(context);
oldZenMode = GlobalData.getZenMode(context);
if (linkUnlink == PhoneCallService.LINKMODE_NONE) {
if (profile._volumeRingerMode != 0) {
GlobalData.setRingerMode(context, profile._volumeRingerMode);
if ((profile._volumeRingerMode == 5) && (profile._volumeZenMode != 0))
GlobalData.setZenMode(context, profile._volumeZenMode);
}
ringerMode = GlobalData.getRingerMode(context);
zenMode = GlobalData.getZenMode(context);
}
else {
/*ringerMode = RingerModeChangeReceiver.getRingerMode(context, audioManager);
zenMode = PPNotificationListenerService.getZenMode(context, audioManager);*/
ringerMode = GlobalData.getRingerMode(context);
zenMode = GlobalData.getZenMode(context);
}
GlobalData.logE("ActivateProfileHelper.setRingerMode", "ringerMode=" + ringerMode);
GlobalData.logE("ActivateProfileHelper.setRingerMode", "zenMode=" + zenMode);
// for Lollipop 4=priority mode, for pre-lillipop 4=silent ringer mode
// priority mode must by invoked be 2 calls of setRingerMode:
// first call of setRingerMode must set ringer mode to normal (1) (not called for pre-lollipop)
// second call is normal change ringer mode (4)
// this call sequence sets Lollipop priority mode (check ExecuteVolumeProfilePrefsService, how is called setRingerMode)
if (forPriority) {
if (android.os.Build.VERSION.SDK_INT >= 21) {
//boolean isPrioritySet = (Settings.Global.getInt(context.getContentResolver(), "zen_mode", -1) == ZENMODE_PRIORITY);
boolean isPrioritySet = true;
GlobalData.logE("ActivateProfileHelper.setRingerMode", "zen_mode=" + Settings.Global.getInt(context.getContentResolver(), "zen_mode", -1));
GlobalData.logE("ActivateProfileHelper.setRingerMode", "isPrioritySet=" + isPrioritySet);
if ((ringerMode == 4) && isPrioritySet) { // 4 = silent ringer mode
ringerMode = 1;
GlobalData.logE("ActivateProfileHelper.setRingerMode", "set for reset priority");
}
else
if ((ringerMode == 5) && (zenMode == 2) && isPrioritySet && (linkUnlink == PhoneCallService.LINKMODE_NONE)) {
zenMode = 1;
GlobalData.logE("ActivateProfileHelper.setRingerMode", "set for reset priority");
}
else
if ((ringerMode == 5) && (zenMode == 5) && isPrioritySet && (linkUnlink == PhoneCallService.LINKMODE_NONE)) {
zenMode = 4;
GlobalData.logE("ActivateProfileHelper.setRingerMode", "set for reset priority");
}
else
return false;
} else
return false;
}
if (Permissions.checkSavedProfileRingerMode(context)) {
switch (ringerMode) {
case 1: // Ring
//RingerModeChangeReceiver.internalChange = true;
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_OFF);
} catch (Exception e) {
e.printStackTrace();
}
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_OFF);
} catch (Exception e) {
e.printStackTrace();
}
setVibrateWhenRinging(0);
break;
case 2: // Ring & Vibrate
//RingerModeChangeReceiver.internalChange = true;
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_ON);
} catch (Exception e) {
e.printStackTrace();
}
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_ON);
} catch (Exception e) {
e.printStackTrace();
}
setVibrateWhenRinging(1);
break;
case 3: // Vibrate
//RingerModeChangeReceiver.internalChange = true;
audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_ON);
} catch (Exception e) {
e.printStackTrace();
}
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_ON);
} catch (Exception e) {
e.printStackTrace();
}
setVibrateWhenRinging(1);
break;
case 4: // Silent
//RingerModeChangeReceiver.internalChange = true;
audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_OFF);
} catch (Exception e) {
e.printStackTrace();
}
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_OFF);
} catch (Exception e) {
e.printStackTrace();
}
setVibrateWhenRinging(0);
break;
case 5: // Zen mode
switch (zenMode) {
case 1:
//RingerModeChangeReceiver.internalChange = true;
if (setZenMode(context, ZENMODE_ALL, audioManager, AudioManager.RINGER_MODE_NORMAL)) {
setVibrateWhenRinging(0);
}
break;
case 2:
//RingerModeChangeReceiver.internalChange = true;
if (setZenMode(context, ZENMODE_PRIORITY, audioManager, AudioManager.RINGER_MODE_NORMAL)) {
setVibrateWhenRinging(0);
}
break;
case 3:
//RingerModeChangeReceiver.internalChange = true;
setZenMode(context, ZENMODE_NONE, audioManager, -1);
break;
case 4:
//RingerModeChangeReceiver.internalChange = true;
if (setZenMode(context, ZENMODE_ALL, audioManager, AudioManager.RINGER_MODE_VIBRATE)) {
setVibrateWhenRinging(1);
}
break;
case 5:
//RingerModeChangeReceiver.internalChange = true;
if (setZenMode(context, ZENMODE_PRIORITY, audioManager, AudioManager.RINGER_MODE_VIBRATE)) {
setVibrateWhenRinging(1);
}
break;
case 6:
//RingerModeChangeReceiver.internalChange = true;
setZenMode(context, ZENMODE_ALARMS, audioManager, -1);
break;
}
break;
}
}
return true;
}
public void executeForWallpaper(Profile profile) {
if (profile._deviceWallpaperChange == 1)
{
DisplayMetrics displayMetrics = new DisplayMetrics();
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
display.getMetrics(displayMetrics);
int height = displayMetrics.heightPixels;
int width = displayMetrics.widthPixels << 1; // best wallpaper width is twice screen width
Bitmap decodedSampleBitmap = BitmapManipulator.resampleBitmap(profile.getDeviceWallpaperIdentifier(), width, height, context);
if (decodedSampleBitmap != null)
{
// set wallpaper
WallpaperManager wallpaperManager = WallpaperManager.getInstance(context);
try {
wallpaperManager.setBitmap(decodedSampleBitmap);
} catch (IOException e) {
Log.e("ActivateProfileHelper.executeForWallpaper", "Cannot set wallpaper. Image="+profile.getDeviceWallpaperIdentifier());
}
}
}
}
public void executeForRunApplications(Profile profile) {
if (profile._deviceRunApplicationChange == 1)
{
String[] splits = profile._deviceRunApplicationPackageName.split("\\|");
Intent intent;
PackageManager packageManager = context.getPackageManager();
for (int i = 0; i < splits.length; i++) {
intent = packageManager.getLaunchIntentForPackage(splits[i]);
if (intent != null) {
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
}
public void execute(Profile _profile, boolean merged, boolean _interactive, String eventNotificationSound)
{
// rozdelit zvonenie a notifikacie - zial je to oznacene ako @Hide :-(
//Settings.System.putInt(context.getContentResolver(), Settings.System.NOTIFICATIONS_USE_RING_VOLUME, 0);
Profile profile = GlobalData.getMappedProfile(_profile, context);
boolean interactive = _interactive;
// nahodenie volume
// run service for execute volumes
Intent volumeServiceIntent = new Intent(context, ExecuteVolumeProfilePrefsService.class);
volumeServiceIntent.putExtra(GlobalData.EXTRA_PROFILE_ID, profile._id);
volumeServiceIntent.putExtra(GlobalData.EXTRA_MERGED_PROFILE, merged);
volumeServiceIntent.putExtra(GlobalData.EXTRA_LINKUNLINK_VOLUMES, PhoneCallService.LINKMODE_NONE);
context.startService(volumeServiceIntent);
/*AudioManager audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
// nahodenie ringer modu - aby sa mohli nastavit hlasitosti
setRingerMode(profile, audioManager);
setVolumes(profile, audioManager);
// nahodenie ringer modu - hlasitosti zmenia silent/vibrate
setRingerMode(profile, audioManager);*/
// set vibration on touch
if (Permissions.checkProfileVibrationOnTouch(context, profile)) {
switch (profile._vibrationOnTouch) {
case 1:
Settings.System.putInt(context.getContentResolver(), Settings.System.HAPTIC_FEEDBACK_ENABLED, 1);
break;
case 2:
Settings.System.putInt(context.getContentResolver(), Settings.System.HAPTIC_FEEDBACK_ENABLED, 0);
break;
}
}
// nahodenie tonov
if (Permissions.checkProfileRingtones(context, profile)) {
if (profile._soundRingtoneChange == 1) {
if (!profile._soundRingtone.isEmpty()) {
//Settings.System.putString(context.getContentResolver(), Settings.System.RINGTONE, profile._soundRingtone);
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE, Uri.parse(profile._soundRingtone));
} else {
// selected is None tone
//Settings.System.putString(context.getContentResolver(), Settings.System.RINGTONE, null);
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE, null);
}
}
if (profile._soundNotificationChange == 1) {
if (!profile._soundNotification.isEmpty()) {
//Settings.System.putString(context.getContentResolver(), Settings.System.NOTIFICATION_SOUND, profile._soundNotification);
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_NOTIFICATION, Uri.parse(profile._soundNotification));
} else {
// selected is None tone
//Settings.System.putString(context.getContentResolver(), Settings.System.NOTIFICATION_SOUND, null);
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_NOTIFICATION, null);
}
}
if (profile._soundAlarmChange == 1) {
if (!profile._soundAlarm.isEmpty()) {
//Settings.System.putString(context.getContentResolver(), Settings.System.ALARM_ALERT, profile._soundAlarm);
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_ALARM, Uri.parse(profile._soundAlarm));
} else {
// selected is None tone
//Settings.System.putString(context.getContentResolver(), Settings.System.ALARM_ALERT, null);
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_ALARM, null);
}
}
}
//// nahodenie radio preferences
// run service for execute radios
Intent radioServiceIntent = new Intent(context, ExecuteRadioProfilePrefsService.class);
radioServiceIntent.putExtra(GlobalData.EXTRA_PROFILE_ID, profile._id);
radioServiceIntent.putExtra(GlobalData.EXTRA_MERGED_PROFILE, merged);
context.startService(radioServiceIntent);
// nahodenie auto-sync
boolean _isAutosync = ContentResolver.getMasterSyncAutomatically();
boolean _setAutosync = false;
switch (profile._deviceAutosync) {
case 1:
if (!_isAutosync)
{
_isAutosync = true;
_setAutosync = true;
}
break;
case 2:
if (_isAutosync)
{
_isAutosync = false;
_setAutosync = true;
}
break;
case 3:
_isAutosync = !_isAutosync;
_setAutosync = true;
break;
}
if (_setAutosync)
ContentResolver.setMasterSyncAutomatically(_isAutosync);
// screen timeout
if (Permissions.checkProfileScreenTimeout(context, profile)) {
switch (profile._deviceScreenTimeout) {
case 1:
screenTimeoutUnlock(context);
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 15000);
break;
case 2:
screenTimeoutUnlock(context);
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 30000);
break;
case 3:
screenTimeoutUnlock(context);
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 60000);
break;
case 4:
screenTimeoutUnlock(context);
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 120000);
break;
case 5:
screenTimeoutUnlock(context);
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 600000);
break;
case 6:
screenTimeoutUnlock(context);
//if (android.os.Build.VERSION.SDK_INT < 19)
// Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, -1);
//else
screenTimeoutLock(context);
//Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 18000000);
break;
case 7:
screenTimeoutUnlock(context);
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 300000);
break;
}
}
// zapnutie/vypnutie lockscreenu
//GlobalData.logE("$$$ ActivateProfileHelper.execute","keyguard");
boolean setLockscreen = false;
switch (profile._deviceKeyguard) {
case 1:
// enable lockscreen
GlobalData.logE("$$$ ActivateProfileHelper.execute","keyguard=ON");
GlobalData.setLockscreenDisabled(context, false);
setLockscreen = true;
break;
case 2:
// disable lockscreen
GlobalData.logE("$$$ ActivateProfileHelper.execute","keyguard=OFF");
GlobalData.setLockscreenDisabled(context, true);
setLockscreen = true;
break;
}
if (setLockscreen) {
boolean isScreenOn;
//if (android.os.Build.VERSION.SDK_INT >= 20)
//{
// Display display = ((WindowManager)context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
// isScreenOn = display.getState() != Display.STATE_OFF;
//}
//else
//{
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
isScreenOn = pm.isScreenOn();
//}
GlobalData.logE("$$$ ActivateProfileHelper.execute","isScreenOn="+isScreenOn);
boolean keyguardShowing = false;
KeyguardManager kgMgr = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= 16)
keyguardShowing = kgMgr.isKeyguardLocked();
else
keyguardShowing = kgMgr.inKeyguardRestrictedInputMode();
GlobalData.logE("$$$ ActivateProfileHelper.execute","keyguardShowing="+keyguardShowing);
if (isScreenOn && !keyguardShowing) {
Intent keyguardService = new Intent(context.getApplicationContext(), KeyguardService.class);
context.startService(keyguardService);
}
}
// nahodenie podsvietenia
if (Permissions.checkProfileScreenBrightness(context, profile)) {
if (profile.getDeviceBrightnessChange()) {
GlobalData.logE("ActivateProfileHelper.execute", "set brightness: profile=" + profile._name);
GlobalData.logE("ActivateProfileHelper.execute", "set brightness: _deviceBrightness=" + profile._deviceBrightness);
if (profile.getDeviceBrightnessAutomatic()) {
Settings.System.putInt(context.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS_MODE,
Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
Settings.System.putInt(context.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS,
profile.getDeviceBrightnessManualValue(context));
if (GlobalData.isPreferenceAllowed(GlobalData.PREF_PROFILE_DEVICE_ADAPTIVE_BRIGHTNESS, context)
== GlobalData.PREFERENCE_ALLOWED) {
if (android.os.Build.VERSION.SDK_INT < 23) // Not working in Android M (exception)
Settings.System.putFloat(context.getContentResolver(),
ADAPTIVE_BRIGHTNESS_SETTING_NAME,
profile.getDeviceBrightnessAdaptiveValue(context));
else {
String command1 = "settings put system " + ADAPTIVE_BRIGHTNESS_SETTING_NAME + " " +
Float.toString(profile.getDeviceBrightnessAdaptiveValue(context));
//if (GlobalData.isSELinuxEnforcing())
// command1 = GlobalData.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
Command command = new Command(0, false, command1); //, command2);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
//RootTools.closeAllShells();
} catch (Exception e) {
Log.e("ActivateProfileHelper.setGPS", "Error on run su: " + e.toString());
}
}
}
} else {
Settings.System.putInt(context.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS_MODE,
Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
Settings.System.putInt(context.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS,
profile.getDeviceBrightnessManualValue(context));
}
if (brightnessHandler != null) {
final Profile __profile = profile;
final Context __context = context;
brightnessHandler.post(new Runnable() {
public void run() {
createBrightnessView(__profile, __context);
}
});
} else
createBrightnessView(profile, context);
}
}
// nahodenie rotate
if (Permissions.checkProfileAutoRotation(context, profile)) {
switch (profile._deviceAutoRotate) {
case 1:
// set autorotate on
Settings.System.putInt(context.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 1);
Settings.System.putInt(context.getContentResolver(), Settings.System.USER_ROTATION, Surface.ROTATION_0);
break;
case 2:
// set autorotate off
// degree 0
Settings.System.putInt(context.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0);
Settings.System.putInt(context.getContentResolver(), Settings.System.USER_ROTATION, Surface.ROTATION_0);
break;
case 3:
// set autorotate off
// degree 90
Settings.System.putInt(context.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0);
Settings.System.putInt(context.getContentResolver(), Settings.System.USER_ROTATION, Surface.ROTATION_90);
break;
case 4:
// set autorotate off
// degree 180
Settings.System.putInt(context.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0);
Settings.System.putInt(context.getContentResolver(), Settings.System.USER_ROTATION, Surface.ROTATION_180);
break;
case 5:
// set autorotate off
// degree 270
Settings.System.putInt(context.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0);
Settings.System.putInt(context.getContentResolver(), Settings.System.USER_ROTATION, Surface.ROTATION_270);
break;
}
}
// nahodenie pozadia
if (Permissions.checkProfileWallpaper(context, profile)) {
if (profile._deviceWallpaperChange == 1) {
Intent wallpaperServiceIntent = new Intent(context, ExecuteWallpaperProfilePrefsService.class);
wallpaperServiceIntent.putExtra(GlobalData.EXTRA_PROFILE_ID, profile._id);
wallpaperServiceIntent.putExtra(GlobalData.EXTRA_MERGED_PROFILE, merged);
context.startService(wallpaperServiceIntent);
}
}
// set power save mode
if (GlobalData.isPreferenceAllowed(GlobalData.PREF_PROFILE_DEVICE_POWER_SAVE_MODE, context) == GlobalData.PREFERENCE_ALLOWED) {
PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
boolean _isPowerSaveMode = powerManager.isPowerSaveMode();
boolean _setPowerSaveMode = false;
switch (profile._devicePowerSaveMode) {
case 1:
if (!_isPowerSaveMode) {
_isPowerSaveMode = true;
_setPowerSaveMode = true;
}
break;
case 2:
if (_isPowerSaveMode) {
_isPowerSaveMode = false;
_setPowerSaveMode = true;
}
break;
case 3:
_isPowerSaveMode = !_isPowerSaveMode;
_setPowerSaveMode = true;
break;
}
if (_setPowerSaveMode) {
setPowerSaveMode(_isPowerSaveMode);
}
}
if (interactive)
{
// preferences, ktore vyzaduju interakciu uzivatela
if (GlobalData.isPreferenceAllowed(GlobalData.PREF_PROFILE_DEVICE_MOBILE_DATA_PREFS, context) == GlobalData.PREFERENCE_ALLOWED)
{
if (profile._deviceMobileDataPrefs == 1)
{
final Intent intent = new Intent(android.provider.Settings.ACTION_DATA_ROAMING_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
context.startActivity(intent);
} catch (Exception e) {
final ComponentName componentName = new ComponentName("com.android.phone", "com.android.phone.Settings");
//intent.addCategory(Intent.ACTION_MAIN);
intent.setComponent(componentName);
context.startActivity(intent);
}
}
}
//if (GlobalData.hardwareCheck(GlobalData.PREF_PROFILE_DEVICE_GPS, context))
//{ No check only GPS
if (profile._deviceLocationServicePrefs == 1)
{
final Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
//}
if (profile._deviceRunApplicationChange == 1)
{
Intent runApplicationsServiceIntent = new Intent(context, ExecuteRunApplicationsProfilePrefsService.class);
runApplicationsServiceIntent.putExtra(GlobalData.EXTRA_PROFILE_ID, profile._id);
runApplicationsServiceIntent.putExtra(GlobalData.EXTRA_MERGED_PROFILE, merged);
context.startService(runApplicationsServiceIntent);
}
}
}
private static void screenTimeoutLock(Context context)
{
WindowManager windowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
if (GUIData.keepScreenOnView != null)
{
windowManager.removeView(GUIData.keepScreenOnView);
GUIData.keepScreenOnView = null;
}
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
1, 1,
WindowManager.LayoutParams.TYPE_TOAST,
//TYPE_SYSTEM_ALERT,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
PixelFormat.TRANSLUCENT
);
params.gravity = Gravity.RIGHT | Gravity.TOP;
GUIData.keepScreenOnView = new BrightnessView(context);
windowManager.addView(GUIData.keepScreenOnView, params);
}
public static void screenTimeoutUnlock(Context context)
{
if (GUIData.keepScreenOnView != null)
{
WindowManager windowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
windowManager.removeView(GUIData.keepScreenOnView);
GUIData.keepScreenOnView = null;
}
GlobalData.logE("@@@ screenTimeoutLock.unlock", "xxx");
}
@SuppressLint("RtlHardcoded")
private void createBrightnessView(Profile profile, Context context)
{
//if (dataWrapper.context != null)
//{
WindowManager windowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
if (GUIData.brightneesView != null)
{
windowManager.removeView(GUIData.brightneesView);
GUIData.brightneesView = null;
}
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
1, 1,
WindowManager.LayoutParams.TYPE_TOAST,
//TYPE_SYSTEM_ALERT,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
PixelFormat.TRANSLUCENT
);
params.gravity = Gravity.RIGHT | Gravity.TOP;
if (profile.getDeviceBrightnessAutomatic())
params.screenBrightness = LayoutParams.BRIGHTNESS_OVERRIDE_NONE;
else
params.screenBrightness = profile.getDeviceBrightnessManualValue(context) / (float) 255;
GUIData.brightneesView = new BrightnessView(context);
windowManager.addView(GUIData.brightneesView, params);
RemoveBrightnessViewBroadcastReceiver.setAlarm(context);
//}
}
public static void removeBrightnessView(Context context) {
if (GUIData.brightneesView != null)
{
WindowManager windowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
windowManager.removeView(GUIData.brightneesView);
GUIData.brightneesView = null;
}
}
public void showNotification(Profile profile, String eventNotificationSound)
{
if (lockRefresh)
// no refres notification
return;
if ((GlobalData.notificationStatusBar) || (!eventNotificationSound.isEmpty()))
{
boolean notificationShowInStatusBar = GlobalData.notificationShowInStatusBar;
boolean notificationStatusBarPermanent = GlobalData.notificationStatusBarPermanent;
boolean forceShow = false;
if (!GlobalData.notificationStatusBar) {
notificationShowInStatusBar = false;
notificationStatusBarPermanent = false;
forceShow = true;
}
// close showed notification
//notificationManager.cancel(GlobalData.NOTIFICATION_ID);
// vytvorenie intentu na aktivitu, ktora sa otvori na kliknutie na notifikaciu
Intent intent = new Intent(context, LauncherActivity.class);
// clear all opened activities
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
// nastavime, ze aktivita sa spusti z notifikacnej listy
intent.putExtra(GlobalData.EXTRA_STARTUP_SOURCE, GlobalData.STARTUP_SOURCE_NOTIFICATION);
PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
// vytvorenie intentu na restart events
Intent intentRE = new Intent(context, RestartEventsFromNotificationActivity.class);
PendingIntent pIntentRE = PendingIntent.getActivity(context, 0, intentRE, PendingIntent.FLAG_CANCEL_CURRENT);
// vytvorenie samotnej notifikacie
NotificationCompat.Builder notificationBuilder;
RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.notification_drawer);
boolean isIconResourceID;
String iconIdentifier;
String profileName;
Bitmap iconBitmap;
Bitmap preferencesIndicator;
if (profile != null)
{
isIconResourceID = profile.getIsIconResourceID();
iconIdentifier = profile.getIconIdentifier();
profileName = dataWrapper.getProfileNameWithManualIndicator(profile, true, false);
iconBitmap = profile._iconBitmap;
preferencesIndicator = profile._preferencesIndicator;
}
else
{
isIconResourceID = true;
iconIdentifier = GlobalData.PROFILE_ICON_DEFAULT;
profileName = context.getResources().getString(R.string.profiles_header_profile_name_no_activated);
iconBitmap = null;
preferencesIndicator = null;
}
notificationBuilder = new NotificationCompat.Builder(context)
.setContentIntent(pIntent);
if (android.os.Build.VERSION.SDK_INT >= 16) {
if (notificationShowInStatusBar)
notificationBuilder.setPriority(NotificationCompat.PRIORITY_DEFAULT);
else
notificationBuilder.setPriority(NotificationCompat.PRIORITY_MIN);
//notificationBuilder.setPriority(Notification.PRIORITY_HIGH); // for heads-up in Android 5.0
}
if (android.os.Build.VERSION.SDK_INT >= 21)
{
notificationBuilder.setCategory(Notification.CATEGORY_STATUS);
notificationBuilder.setVisibility(Notification.VISIBILITY_PUBLIC);
}
notificationBuilder.setTicker(profileName);
if (isIconResourceID)
{
int iconSmallResource;
if (iconBitmap != null) {
iconSmallResource = context.getResources().getIdentifier(iconIdentifier + "_notify", "drawable", context.getPackageName());
notificationBuilder.setSmallIcon(iconSmallResource);
contentView.setImageViewBitmap(R.id.notification_activated_profile_icon, iconBitmap);
}
else {
if (GlobalData.notificationStatusBarStyle.equals("0") && (android.os.Build.VERSION.SDK_INT < 21)) {
//notificationBuilder.setSmallIcon(0);
iconSmallResource = context.getResources().getIdentifier(iconIdentifier + "_notify_color", "drawable", context.getPackageName());
notificationBuilder.setSmallIcon(iconSmallResource);
//contentView.setImageViewResource(R.id.notification_activated_profile_icon, 0);
contentView.setImageViewResource(R.id.notification_activated_profile_icon, iconSmallResource);
} else {
//notificationBuilder.setSmallIcon(0);
//contentView.setImageViewBitmap(R.id.notification_activated_profile_icon, null);
iconSmallResource = context.getResources().getIdentifier(iconIdentifier + "_notify", "drawable", context.getPackageName());
notificationBuilder.setSmallIcon(iconSmallResource);
int iconLargeResource = context.getResources().getIdentifier(iconIdentifier, "drawable", context.getPackageName());
Bitmap largeIcon = BitmapFactory.decodeResource(context.getResources(), iconLargeResource);
contentView.setImageViewBitmap(R.id.notification_activated_profile_icon, largeIcon);
}
}
}
else
{
int iconSmallResource;
if (GlobalData.notificationStatusBarStyle.equals("0"))
iconSmallResource = R.drawable.ic_profile_default;
else
iconSmallResource = R.drawable.ic_profile_default_notify;
//notificationBuilder.setSmallIcon(0);
notificationBuilder.setSmallIcon(iconSmallResource);
//contentView.setImageViewBitmap(R.id.notification_activated_profile_icon, null);
contentView.setImageViewBitmap(R.id.notification_activated_profile_icon, iconBitmap);
}
if (!eventNotificationSound.isEmpty())
{
Uri ringtoneUri=Uri.parse(eventNotificationSound);
notificationBuilder.setSound(ringtoneUri);
}
Notification notification = notificationBuilder.build();
contentView.setTextViewText(R.id.notification_activated_profile_name, profileName);
//contentView.setImageViewBitmap(R.id.notification_activated_profile_pref_indicator,
// ProfilePreferencesIndicator.paint(profile, context));
if ((preferencesIndicator != null) && (GlobalData.notificationPrefIndicator))
contentView.setImageViewBitmap(R.id.notification_activated_profile_pref_indicator, preferencesIndicator);
else
contentView.setImageViewResource(R.id.notification_activated_profile_pref_indicator, R.drawable.ic_empty);
if (android.os.Build.VERSION.SDK_INT >= 20)
contentView.setImageViewResource(R.id.notification_activated_profile_restart_events, R.drawable.ic_action_events_restart);
else
contentView.setImageViewResource(R.id.notification_activated_profile_restart_events, R.drawable.ic_action_events_restart_dark);
contentView.setOnClickPendingIntent(R.id.notification_activated_profile_restart_events, pIntentRE);
notification.contentView = contentView;
if (notificationStatusBarPermanent)
{
//notification.flags |= Notification.FLAG_NO_CLEAR;
notification.flags |= Notification.FLAG_ONGOING_EVENT;
}
else
{
setAlarmForNotificationCancel(forceShow);
}
notificationManager.notify(GlobalData.PROFILE_NOTIFICATION_ID, notification);
}
else
{
notificationManager.cancel(GlobalData.PROFILE_NOTIFICATION_ID);
}
}
public void removeNotification()
{
notificationManager.cancel(GlobalData.PROFILE_NOTIFICATION_ID);
}
@SuppressLint("NewApi")
private void setAlarmForNotificationCancel(boolean forceShow)
{
if (!forceShow) {
if (GlobalData.notificationStatusBarCancel.isEmpty() || GlobalData.notificationStatusBarCancel.equals("0"))
return;
}
int notificationStatusBarCancel = Integer.valueOf(GlobalData.notificationStatusBarCancel);
if (forceShow)
notificationStatusBarCancel = 3;
Intent intent = new Intent(context, NotificationCancelAlarmBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(), 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Activity.ALARM_SERVICE);
Calendar now = Calendar.getInstance();
long time = now.getTimeInMillis() + notificationStatusBarCancel * 1000;
// not needed exact for removing notification
/*if (GlobalData.exactAlarms && (android.os.Build.VERSION.SDK_INT >= 23))
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, time, pendingIntent);
if (GlobalData.exactAlarms && (android.os.Build.VERSION.SDK_INT >= 19))
alarmManager.setExact(AlarmManager.RTC_WAKEUP, time, pendingIntent);
else*/
alarmManager.set(AlarmManager.RTC_WAKEUP, time, pendingIntent);
//alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, alarmTime, 24 * 60 * 60 * 1000 , pendingIntent);
//alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, alarmTime, 24 * 60 * 60 * 1000 , pendingIntent);
}
public void updateWidget()
{
if (lockRefresh)
// no refres widgets
return;
// icon widget
Intent intent = new Intent(context, IconWidgetProvider.class);
intent.setAction("android.appwidget.action.APPWIDGET_UPDATE");
int ids[] = AppWidgetManager.getInstance(context).getAppWidgetIds(new ComponentName(context, IconWidgetProvider.class));
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids);
context.sendBroadcast(intent);
// one row widget
Intent intent4 = new Intent(context, OneRowWidgetProvider.class);
intent4.setAction("android.appwidget.action.APPWIDGET_UPDATE");
int ids4[] = AppWidgetManager.getInstance(context).getAppWidgetIds(new ComponentName(context, OneRowWidgetProvider.class));
intent4.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids4);
context.sendBroadcast(intent4);
// list widget
Intent intent2 = new Intent(context, ProfileListWidgetProvider.class);
intent2.setAction(ProfileListWidgetProvider.INTENT_REFRESH_LISTWIDGET);
int ids2[] = AppWidgetManager.getInstance(context).getAppWidgetIds(new ComponentName(context, ProfileListWidgetProvider.class));
intent2.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids2);
context.sendBroadcast(intent2);
// dashclock extension
Intent intent3 = new Intent();
intent3.setAction(DashClockBroadcastReceiver.INTENT_REFRESH_DASHCLOCK);
context.sendBroadcast(intent3);
// activities
Intent intent5 = new Intent();
intent5.setAction(RefreshGUIBroadcastReceiver.INTENT_REFRESH_GUI);
context.sendBroadcast(intent5);
}
private boolean isAirplaneMode(Context context)
{
if (android.os.Build.VERSION.SDK_INT >= 17)
return Settings.Global.getInt(context.getContentResolver(), Global.AIRPLANE_MODE_ON, 0) != 0;
else
return Settings.System.getInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) != 0;
}
private void setAirplaneMode(Context context, boolean mode)
{
if (android.os.Build.VERSION.SDK_INT >= 17)
setAirplaneMode_SDK17(context, mode);
else
setAirplaneMode_SDK8(context, mode);
}
private boolean isMobileData(Context context)
{
if (android.os.Build.VERSION.SDK_INT >= 21)
{
return Settings.Global.getInt(context.getContentResolver(), "mobile_data", 0) == 1;
}
else
{
final ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
final Class<?> connectivityManagerClass = Class.forName(connectivityManager.getClass().getName());
final Method getMobileDataEnabledMethod = connectivityManagerClass.getDeclaredMethod("getMobileDataEnabled");
getMobileDataEnabledMethod.setAccessible(true);
return (Boolean)getMobileDataEnabledMethod.invoke(connectivityManager);
} catch (ClassNotFoundException e) {
e.printStackTrace();
return false;
} catch (NoSuchMethodException e) {
e.printStackTrace();
return false;
} catch (IllegalArgumentException e) {
e.printStackTrace();
return false;
} catch (IllegalAccessException e) {
e.printStackTrace();
return false;
} catch (InvocationTargetException e) {
e.printStackTrace();
return false;
}
}
/*
final NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null)
{
int netvorkType = networkInfo.getType(); // 0 = mobile, 1 = wifi
//String netvorkTypeName = networkInfo.getTypeName(); // "mobile" or "WIFI"
boolean connected = networkInfo.isConnected(); // true = active connection
//if (netvorkType == 0)
//{
// connected into mobile data
return connected;
//}
//else
//{
// conected into Wifi
// return false;
//}
}
else
return false;
*/
}
private void setMobileData(Context context, boolean enable)
{
if (android.os.Build.VERSION.SDK_INT >= 21)
{
if (GlobalData.grantRoot(false))
{
int state = 0;
try {
// Get the current state of the mobile network.
state = enable ? 1 : 0;
// Get the value of the "TRANSACTION_setDataEnabled" field.
String transactionCode = GlobalData.getTransactionCode(context, "TRANSACTION_setDataEnabled");
// Android 5.1+ (API 22) and later.
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
SubscriptionManager mSubscriptionManager = (SubscriptionManager) context.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);
// Loop through the subscription list i.e. SIM list.
for (int i = 0; i < mSubscriptionManager.getActiveSubscriptionInfoCountMax(); i++) {
if (transactionCode != null && transactionCode.length() > 0) {
// Get the active subscription ID for a given SIM card.
int subscriptionId = mSubscriptionManager.getActiveSubscriptionInfoList().get(i).getSubscriptionId();
String command1 = "service call phone " + transactionCode + " i32 " + subscriptionId + " i32 " + state;
Command command = new Command(0, false, command1);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
//RootTools.closeAllShells();
} catch (Exception e) {
Log.e("ActivateProfileHelper.setMobileData", "Error on run su");
}
}
}
} else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP) {
// Android 5.0 (API 21) only.
if (transactionCode != null && transactionCode.length() > 0) {
String command1 = "service call phone " + transactionCode + " i32 " + state;
Command command = new Command(0, false, command1);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
//RootTools.closeAllShells();
} catch (Exception e) {
Log.e("ActivateProfileHelper.setMobileData", "Error on run su");
}
}
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
else
{
final ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
boolean OK = false;
try {
final Class<?> connectivityManagerClass = Class.forName(connectivityManager.getClass().getName());
final Field iConnectivityManagerField = connectivityManagerClass.getDeclaredField("mService");
iConnectivityManagerField.setAccessible(true);
final Object iConnectivityManager = iConnectivityManagerField.get(connectivityManager);
final Class<?> iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName());
final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
setMobileDataEnabledMethod.setAccessible(true);
setMobileDataEnabledMethod.invoke(iConnectivityManager, enable);
OK = true;
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
if (!OK)
{
try {
Method setMobileDataEnabledMethod = ConnectivityManager.class.getDeclaredMethod("setMobileDataEnabled", boolean.class);
setMobileDataEnabledMethod.setAccessible(true);
setMobileDataEnabledMethod.invoke(connectivityManager, enable);
OK = true;
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
private int getPreferredNetworkType(Context context) {
if (GlobalData.grantRoot(false))
{
try {
// Get the value of the "TRANSACTION_setPreferredNetworkType" field.
String transactionCode = GlobalData.getTransactionCode(context, "TRANSACTION_getPreferredNetworkType");
if (transactionCode != null && transactionCode.length() > 0) {
String command1 = "service call phone " + transactionCode + " i32";
Command command = new Command(0, false, command1) {
@Override
public void commandOutput(int id, String line) {
super.commandOutput(id, line);
String splits[] = line.split(" ");
try {
networkType = Integer.parseInt(splits[2]);
} catch (Exception e) {
networkType = -1;
}
}
@Override
public void commandTerminated(int id, String reason) {
super.commandTerminated(id, reason);
}
@Override
public void commandCompleted(int id, int exitcode) {
super.commandCompleted(id, exitcode);
}
};
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
//RootTools.closeAllShells();
} catch (Exception e) {
Log.e("ActivateProfileHelper.setPreferredNetworkType", "Error on run su");
}
}
} catch(Exception e) {
e.printStackTrace();
}
}
return networkType;
}
private void setPreferredNetworkType(Context context, int networkType)
{
if (GlobalData.grantRoot(false))
{
try {
// Get the value of the "TRANSACTION_setPreferredNetworkType" field.
String transactionCode = GlobalData.getTransactionCode(context, "TRANSACTION_setPreferredNetworkType");
if (Build.VERSION.SDK_INT >= 23) {
SubscriptionManager mSubscriptionManager = (SubscriptionManager) context.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);
// Loop through the subscription list i.e. SIM list.
for (int i = 0; i < mSubscriptionManager.getActiveSubscriptionInfoCountMax(); i++) {
if (transactionCode != null && transactionCode.length() > 0) {
// Get the active subscription ID for a given SIM card.
int subscriptionId = mSubscriptionManager.getActiveSubscriptionInfoList().get(i).getSubscriptionId();
String command1 = "service call phone " + transactionCode + " i32 " + subscriptionId + " i32 " + networkType;
Command command = new Command(0, false, command1);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
//RootTools.closeAllShells();
} catch (Exception e) {
Log.e("ActivateProfileHelper.setPreferredNetworkType", "Error on run su");
}
}
}
} else {
if (transactionCode != null && transactionCode.length() > 0) {
String command1 = "service call phone " + transactionCode + " i32 " + networkType;
Command command = new Command(0, false, command1);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
//RootTools.closeAllShells();
} catch (Exception e) {
Log.e("ActivateProfileHelper.setPreferredNetworkType", "Error on run su");
}
}
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
@SuppressWarnings("deprecation")
private void setGPS(Context context, boolean enable)
{
//boolean isEnabled;
//int locationMode = -1;
//if (android.os.Build.VERSION.SDK_INT < 19)
// isEnabled = Settings.Secure.isLocationProviderEnabled(context.getContentResolver(), LocationManager.GPS_PROVIDER);
/*else {
locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE, -1);
isEnabled = (locationMode == Settings.Secure.LOCATION_MODE_HIGH_ACCURACY) ||
(locationMode == Settings.Secure.LOCATION_MODE_SENSORS_ONLY);
}*/
boolean isEnabled;
if (android.os.Build.VERSION.SDK_INT < 21)
isEnabled = Settings.Secure.isLocationProviderEnabled(context.getContentResolver(), LocationManager.GPS_PROVIDER);
else {
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
isEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
GlobalData.logE("ActivateProfileHelper.setGPS", "isEnabled="+isEnabled);
//if(!provider.contains(LocationManager.GPS_PROVIDER) && enable)
if ((!isEnabled) && enable)
{
if (GlobalData.canExploitGPS(context))
{
GlobalData.logE("ActivateProfileHelper.setGPS", "exploit");
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
context.sendBroadcast(poke);
}
else
if ((android.os.Build.VERSION.SDK_INT >= 17) && GlobalData.grantRoot(false))
{
// zariadenie je rootnute
GlobalData.logE("ActivateProfileHelper.setGPS", "rooted");
String command1;
//String command2;
if (android.os.Build.VERSION.SDK_INT < 23) {
String provider = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
String newSet;
if (provider == "")
newSet = LocationManager.GPS_PROVIDER;
else
newSet = String.format("%s,%s", provider, LocationManager.GPS_PROVIDER);
command1 = "settings put secure location_providers_allowed \"" + newSet + "\"";
//if (GlobalData.isSELinuxEnforcing())
// command1 = GlobalData.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
//command2 = "am broadcast -a android.location.GPS_ENABLED_CHANGE --ez state true";
Command command = new Command(0, false, command1); //, command2);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
//RootTools.closeAllShells();
} catch (Exception e) {
Log.e("ActivateProfileHelper.setGPS", "Error on run su: " + e.toString());
}
}
else {
command1 = "settings put secure location_providers_allowed +gps";
Command command = new Command(0, false, command1);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
//RootTools.closeAllShells();
} catch (Exception e) {
Log.e("ActivateProfileHelper.setGPS", "Error on run su: " + e.toString());
}
}
}
else
{
/*GlobalData.logE("ActivateProfileHelper.setGPS", "old method");
try {
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", enable);
context.sendBroadcast(intent);
} catch (SecurityException e) {
e.printStackTrace();
}*/
// for normal apps it is only possible to open the system settings dialog
/* Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent); */
}
}
else
//if(provider.contains(LocationManager.GPS_PROVIDER) && (!enable))
if (isEnabled && (!enable))
{
if (GlobalData.canExploitGPS(context))
{
GlobalData.logE("ActivateProfileHelper.setGPS", "exploit");
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
context.sendBroadcast(poke);
}
else
if ((android.os.Build.VERSION.SDK_INT >= 17) && GlobalData.grantRoot(false))
{
// zariadenie je rootnute
GlobalData.logE("ActivateProfileHelper.setGPS", "rooted");
String command1;
//String command2;
if (android.os.Build.VERSION.SDK_INT < 23) {
String provider = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
String[] list = provider.split(",");
String newSet = "";
int j = 0;
for (int i = 0; i < list.length; i++) {
if (!list[i].equals(LocationManager.GPS_PROVIDER)) {
if (j > 0)
newSet += ",";
newSet += list[i];
j++;
}
}
command1 = "settings put secure location_providers_allowed \"" + newSet + "\"";
//if (GlobalData.isSELinuxEnforcing())
// command1 = GlobalData.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
//command2 = "am broadcast -a android.location.GPS_ENABLED_CHANGE --ez state false";
Command command = new Command(0, false, command1);//, command2);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
//RootTools.closeAllShells();
} catch (Exception e) {
Log.e("ActivateProfileHelper.setGPS", "Error on run su: " + e.toString());
}
}
else {
command1 = "settings put secure location_providers_allowed -gps";
Command command = new Command(0, false, command1);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
//RootTools.closeAllShells();
} catch (Exception e) {
Log.e("ActivateProfileHelper.setGPS", "Error on run su: " + e.toString());
}
}
}
else
{
//GlobalData.logE("ActivateProfileHelper.setGPS", "old method");
/*try {
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", enable);
context.sendBroadcast(intent);
} catch (SecurityException e) {
e.printStackTrace();
}*/
// for normal apps it is only possible to open the system settings dialog
/* Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent); */
}
}
}
private void setAirplaneMode_SDK17(Context context, boolean mode)
{
if (GlobalData.grantRoot(false))
{
// zariadenie je rootnute
String command1;
String command2;
if (mode)
{
command1 = "settings put global airplane_mode_on 1";
command2 = "am broadcast -a android.intent.action.AIRPLANE_MODE --ez state true";
}
else
{
command1 = "settings put global airplane_mode_on 0";
command2 = "am broadcast -a android.intent.action.AIRPLANE_MODE --ez state false";
}
//if (GlobalData.isSELinuxEnforcing())
//{
// command1 = GlobalData.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
// command2 = GlobalData.getSELinuxEnforceCommand(command2, Shell.ShellContext.SYSTEM_APP);
//}
Command command = new Command(0, false, command1, command2);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
//RootTools.closeAllShells();
} catch (Exception e) {
Log.e("AirPlaneMode_SDK17.setAirplaneMode", "Error on run su");
}
}
else
{
// for normal apps it is only possible to open the system settings dialog
/* Intent intent = new Intent(android.provider.Settings.ACTION_AIRPLANE_MODE_SETTINGS);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent); */
}
}
@SuppressWarnings("deprecation")
private void setAirplaneMode_SDK8(Context context, boolean mode)
{
Settings.System.putInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, mode ? 1 : 0);
Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
intent.putExtra("state", mode);
context.sendBroadcast(intent);
}
private void setPowerSaveMode(boolean enable) {
String command1 = "settings put global low_power " + ((enable) ? 1 : 0);
Command command = new Command(0, false, command1);
try {
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
//RootTools.closeAllShells();
} catch (Exception e) {
Log.e("ActivateProfileHelper.setPowerSaveMode", "Error on run su: " + e.toString());
}
}
private static void commandWait(Command cmd) throws Exception {
int waitTill = 50;
int waitTillMultiplier = 2;
int waitTillLimit = 3200; //7 tries, 6350 msec
while (!cmd.isFinished() && waitTill<=waitTillLimit) {
synchronized (cmd) {
try {
if (!cmd.isFinished()) {
cmd.wait(waitTill);
waitTill *= waitTillMultiplier;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
if (!cmd.isFinished()){
Log.e("ActivateProfileHelper", "Could not finish root command in " + (waitTill/waitTillMultiplier));
}
}
public static int getMinimumScreenBrightnessSetting (Context context)
{
final Resources res = Resources.getSystem();
int id = res.getIdentifier("config_screenBrightnessSettingMinimum", "integer", "android"); // API17+
if (id == 0)
id = res.getIdentifier("config_screenBrightnessDim", "integer", "android"); // lower API levels
if (id != 0)
{
try {
return res.getInteger(id);
}
catch (Resources.NotFoundException e) {
// ignore
}
}
return 0;
}
public static int getMaximumScreenBrightnessSetting (Context context)
{
final Resources res = Resources.getSystem();
final int id = res.getIdentifier("config_screenBrightnessSettingMaximum", "integer", "android"); // API17+
if (id != 0)
{
try {
return res.getInteger(id);
}
catch (Resources.NotFoundException e) {
// ignore
}
}
return 255;
}
}
| Fixed change ringer mode between Interruptions and non-interruption modes
| phoneProfilesPlus/src/main/java/sk/henrichg/phoneprofilesplus/ActivateProfileHelper.java | Fixed change ringer mode between Interruptions and non-interruption modes | <ide><path>honeProfilesPlus/src/main/java/sk/henrichg/phoneprofilesplus/ActivateProfileHelper.java
<ide> switch (ringerMode) {
<ide> case 1: // Ring
<ide> //RingerModeChangeReceiver.internalChange = true;
<add> setZenMode(context, ZENMODE_ALL, audioManager, AudioManager.RINGER_MODE_NORMAL);
<ide> audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
<ide> try {
<ide> audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_OFF);
<ide> break;
<ide> case 2: // Ring & Vibrate
<ide> //RingerModeChangeReceiver.internalChange = true;
<add> setZenMode(context, ZENMODE_ALL, audioManager, AudioManager.RINGER_MODE_NORMAL);
<ide> audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
<ide> try {
<ide> audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_ON);
<ide> break;
<ide> case 3: // Vibrate
<ide> //RingerModeChangeReceiver.internalChange = true;
<add> setZenMode(context, ZENMODE_ALL, audioManager, AudioManager.RINGER_MODE_NORMAL);
<ide> audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
<ide> try {
<ide> audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_ON); |
|
Java | lgpl-2.1 | 626be668a65ca30820109992ea0901c6425eb3c3 | 0 | iAlios/Utils |
package com.alio.utils;
public class IntUtils {
/**
* short 转 byte[] (由高位到低位)
*
* @param i
* @return
*/
public static byte[] shortToByteArray(short i) {
byte[] result = new byte[2];
// 由高位到低位
result[0] = (byte) ((i >> 8) & 0xFF);
result[1] = (byte) (i & 0xFF);
return result;
}
/**
* byte[]转 short (由高位到低位)
*
* @param bytes
* @return
*/
public static short byteArrayToShort(byte[] bytes) {
short value = 0;
int shift = 0;
// 由高位到低位
for (int i = 0; i < 2; i++) {
shift = (2 - 1 - i) * 8;
value += (bytes[i] & 0x000000FF) << shift;// 往高位游
}
return value;
}
/**
* short 转 byte[](由低位到高位)
*
* @param i
* @return
*/
public static byte[] shortToByteArrayL(short i) {
byte[] result = new byte[2];
// 由低位到高位
result[1] = (byte) ((i >> 8) & 0xFF);
result[0] = (byte) (i & 0xFF);
return result;
}
/**
* byte[]转 short (由低位到高位)
*
* @param bytes
* @return
*/
public static int byteArrayToShortL(byte[] bytes) {
int value = 0;
// 由低位到高位
int shift = 0;
for (int i = 0; i < 2; i++) {
shift = i * 8;
value += (bytes[i] & 0x000000FF) << shift;// 往高位游
}
return value;
}
/**
* int转 byte[] (由高位到低位)
*
* @param i
* @return
*/
public static byte[] intToByteArray(int fbit) {
// 由高位到低位
byte[] b = new byte[4];
for (int i = 0; i < 4; i++) {
b[i] = (byte) (fbit >> ((4 - 1 - i) * 8));
}
return b;
}
/**
* byte[]转int (由高位到低位)
*
* @param bytes
* @return
*/
public static int byteArrayToInt(byte[] bytes) {
int value = 0;
int shift = 0;
// 由高位到低位
for (int i = 0; i < 4; i++) {
shift = (4 - 1 - i) * 8;
value += (bytes[i] & 0x000000FF) << shift;// 往高位游
}
return value;
}
/**
* int 转 byte[](由低位到高位)
*
* @param i
* @return
*/
public static byte[] intToByteArrayL(int fbit) {
byte[] result = new byte[4];
for (int i = 0; i < 4; i++) {
result[i] = (byte) (fbit >> (i * 8));
}
return result;
}
/**
* byte[]转int (由低位到高位)
*
* @param bytes
* @return
*/
public static int byteArrayToIntL(byte[] bytes) {
int value = 0;
// 由低位到高位
int shift = 0;
for (int i = 0; i < 4; i++) {
shift = i * 8;
value += (bytes[i] & 0x000000FF) << shift;// 往高位游
}
return value;
}
/**
* 浮点转换为字节
*
* @param f
* @return
*/
public static byte[] floatToByteArray(float f) {
int fbit = Float.floatToIntBits(f);
byte[] b = new byte[4];
for (int i = 0; i < 4; i++) {
b[i] = (byte) (fbit >> (i * 8));
}
return b;
}
public static float byteArrayToFloat(byte[] bytes) {
int value = 0;
// 由低位到高位
int shift = 0;
for (int i = 0; i < 4; i++) {
shift = i * 8;
value += ((int) bytes[i] & 0x000000FF) << shift;// 往高位游
}
return Float.intBitsToFloat(value);
}
/**
* 将64位的long值放到8字节的byte数组
*
* @param num
* @return 返回转换后的byte数组
*/
public static byte[] longToByteArray(long num) {
byte[] result = new byte[8];
for (int i = 0; i < 8; i++) {
result[i] = (byte) (num >> (i * 8));
}
return result;
}
/**
* 将8字节的byte数组转成一个long值
*
* @param byteArray
* @return 转换后的long型数值
*/
public static long byteArrayToLong(byte[] byteArray) {
long value = 0;
int shift = 0;
for (int i = 0; i < 8; i++) {
shift = i * 8;
value += ((long) byteArray[i] & 0xFF) << shift;
}
return value;
}
/**
* double转换byte
*
* @param x
*/
public static byte[] doubleToByteArray(double x) {
byte[] b = new byte[8];
long l = Double.doubleToLongBits(x);
for (int i = 0; i < 8; i++) {
b[i] = (byte) (l >> (i * 8));
}
return b;
}
/**
* 通过byte数组取得float
*
* @param b
* @return
*/
public static double byteArrayToDouble(byte[] bytes) {
long value = 0;
int shift = 0;
for (int i = 0; i < 8; i++) {
shift = i * 8;
value += ((long) bytes[i] & 0xFF) << shift;
}
return Double.longBitsToDouble(value);
}
public static void main(String[] args) {
short dd = 2;
System.out.println("=========================SHORT========================");
System.out.println(HexDump.dumpHexString(shortToByteArray(dd)));
System.out.println(byteArrayToShort(shortToByteArray(dd)));
System.out.println(HexDump.dumpHexString(shortToByteArrayL(dd)));
System.out.println(byteArrayToShortL(shortToByteArrayL(dd)));
System.out.println("=========================INT========================");
System.out.println(HexDump.dumpHexString(intToByteArray(dd)));
System.out.println(byteArrayToInt(intToByteArray(dd)));
System.out.println(HexDump.dumpHexString(intToByteArrayL(dd)));
System.out.println(byteArrayToIntL(intToByteArrayL(dd)));
System.out.println("=========================LONG========================");
System.out.println(HexDump.dumpHexString(longToByteArray(dd * 1l)));
System.out.println(byteArrayToLong(longToByteArray(dd * 1l)));
System.out.println("=========================FLOAT========================");
System.out.println(HexDump.dumpHexString(floatToByteArray(dd * 0.1f)));
System.out.println(byteArrayToFloat(floatToByteArray(dd * 0.1f)));
System.out.println("=========================DOUBLE========================");
System.out.println(HexDump.dumpHexString(doubleToByteArray(dd * 0.1d)));
System.out.println(byteArrayToDouble(doubleToByteArray(dd * 0.1d)));
}
}
| com/alio/utils/IntUtils.java |
package com.alio.utils;
public class IntUtils {
/**
* short 转 byte[] (由高位到低位)
*
* @param i
* @return
*/
public static byte[] shortToByteArray(short i) {
byte[] result = new byte[2];
// 由高位到低位
result[0] = (byte) ((i >> 8) & 0xFF);
result[1] = (byte) (i & 0xFF);
return result;
}
/**
* byte[]转 short (由高位到低位)
*
* @param bytes
* @return
*/
public static short byteArrayToShort(byte[] bytes) {
short value = 0;
int shift = 0;
// 由高位到低位
for (int i = 0; i < 2; i++) {
shift = (2 - 1 - i) * 8;
value += (bytes[i] & 0x000000FF) << shift;// 往高位游
}
return value;
}
/**
* short 转 byte[](由低位到高位)
*
* @param i
* @return
*/
public static byte[] shortToByteArrayL(short i) {
byte[] result = new byte[2];
// 由低位到高位
result[1] = (byte) ((i >> 8) & 0xFF);
result[0] = (byte) (i & 0xFF);
return result;
}
/**
* byte[]转 short (由低位到高位)
*
* @param bytes
* @return
*/
public static int byteArrayToShortL(byte[] bytes) {
int value = 0;
// 由低位到高位
int shift = 0;
for (int i = 0; i < 2; i++) {
shift = i * 8;
value += (bytes[i] & 0x000000FF) << shift;// 往高位游
}
return value;
}
/**
* int转 byte[] (由高位到低位)
*
* @param i
* @return
*/
public static byte[] intToByteArray(int i) {
byte[] result = new byte[4];
// 由高位到低位
result[0] = (byte) ((i >> 24) & 0xFF);
result[1] = (byte) ((i >> 16) & 0xFF);
result[2] = (byte) ((i >> 8) & 0xFF);
result[3] = (byte) (i & 0xFF);
return result;
}
/**
* byte[]转int (由高位到低位)
*
* @param bytes
* @return
*/
public static int byteArrayToInt(byte[] bytes) {
int value = 0;
int shift = 0;
// 由高位到低位
for (int i = 0; i < 4; i++) {
shift = (4 - 1 - i) * 8;
value += (bytes[i] & 0x000000FF) << shift;// 往高位游
}
return value;
}
/**
* int 转 byte[](由低位到高位)
*
* @param i
* @return
*/
public static byte[] intToByteArrayL(int i) {
byte[] result = new byte[4];
// 由低位到高位
result[3] = (byte) ((i >> 24) & 0xFF);
result[2] = (byte) ((i >> 16) & 0xFF);
result[1] = (byte) ((i >> 8) & 0xFF);
result[0] = (byte) (i & 0xFF);
return result;
}
/**
* byte[]转int (由低位到高位)
*
* @param bytes
* @return
*/
public static int byteArrayToIntL(byte[] bytes) {
int value = 0;
// 由低位到高位
int shift = 0;
for (int i = 0; i < 4; i++) {
shift = i * 8;
value += (bytes[i] & 0x000000FF) << shift;// 往高位游
}
return value;
}
/**
* 浮点转换为字节
*
* @param f
* @return
*/
public static byte[] float2byte(float f) {
// 把float转换为byte[]
int fbit = Float.floatToIntBits(f);
byte[] b = new byte[4];
for (int i = 0; i < 4; i++) {
b[i] = (byte) (fbit >> (24 - i * 8));
}
// 翻转数组
int len = b.length;
// 建立一个与源数组元素类型相同的数组
byte[] dest = new byte[len];
// 为了防止修改源数组,将源数组拷贝一份副本
System.arraycopy(b, 0, dest, 0, len);
byte temp;
// 将顺位第i个与倒数第i个交换
for (int i = 0; i < len / 2; ++i) {
temp = dest[i];
dest[i] = dest[len - i - 1];
dest[len - i - 1] = temp;
}
return dest;
}
public static float byteArrayToFloat(byte[] b) {
int l = b[0];
l &= 0xff;
l |= ((long) b[1] << 8);
l &= 0xffff;
l |= ((long) b[2] << 16);
l &= 0xffffff;
l |= ((long) b[3] << 24);
return Float.intBitsToFloat(l);
}
public static void main(String[] args) {
short dd = 2;
System.out.println(HexDump.dumpHexString(shortToByteArray(dd)));
System.out.println(byteArrayToShort(shortToByteArray(dd)));
System.out.println(HexDump.dumpHexString(shortToByteArrayL(dd)));
System.out.println(byteArrayToShortL(shortToByteArrayL(dd)));
System.out.println(HexDump.dumpHexString(intToByteArray(dd)));
System.out.println(byteArrayToInt(intToByteArray(dd)));
System.out.println(HexDump.dumpHexString(intToByteArrayL(dd)));
System.out.println(byteArrayToIntL(intToByteArrayL(dd)));
System.out.println(HexDump.dumpHexString(float2byte(dd * 0.1f)));
System.out.println(byteArrayToFloat(float2byte(dd * 0.1f)));
}
}
| 添加 long double 数据转换方式 | com/alio/utils/IntUtils.java | 添加 long double 数据转换方式 | <ide><path>om/alio/utils/IntUtils.java
<ide> * @param i
<ide> * @return
<ide> */
<del> public static byte[] intToByteArray(int i) {
<add> public static byte[] intToByteArray(int fbit) {
<add> // 由高位到低位
<add> byte[] b = new byte[4];
<add> for (int i = 0; i < 4; i++) {
<add> b[i] = (byte) (fbit >> ((4 - 1 - i) * 8));
<add> }
<add> return b;
<add> }
<add>
<add> /**
<add> * byte[]转int (由高位到低位)
<add> *
<add> * @param bytes
<add> * @return
<add> */
<add> public static int byteArrayToInt(byte[] bytes) {
<add> int value = 0;
<add> int shift = 0;
<add> // 由高位到低位
<add> for (int i = 0; i < 4; i++) {
<add> shift = (4 - 1 - i) * 8;
<add> value += (bytes[i] & 0x000000FF) << shift;// 往高位游
<add> }
<add> return value;
<add> }
<add>
<add> /**
<add> * int 转 byte[](由低位到高位)
<add> *
<add> * @param i
<add> * @return
<add> */
<add> public static byte[] intToByteArrayL(int fbit) {
<ide> byte[] result = new byte[4];
<del> // 由高位到低位
<del> result[0] = (byte) ((i >> 24) & 0xFF);
<del> result[1] = (byte) ((i >> 16) & 0xFF);
<del> result[2] = (byte) ((i >> 8) & 0xFF);
<del> result[3] = (byte) (i & 0xFF);
<del> return result;
<del> }
<del>
<del> /**
<del> * byte[]转int (由高位到低位)
<del> *
<del> * @param bytes
<del> * @return
<del> */
<del> public static int byteArrayToInt(byte[] bytes) {
<del> int value = 0;
<del> int shift = 0;
<del> // 由高位到低位
<del> for (int i = 0; i < 4; i++) {
<del> shift = (4 - 1 - i) * 8;
<del> value += (bytes[i] & 0x000000FF) << shift;// 往高位游
<del> }
<del> return value;
<del> }
<del>
<del> /**
<del> * int 转 byte[](由低位到高位)
<del> *
<del> * @param i
<del> * @return
<del> */
<del> public static byte[] intToByteArrayL(int i) {
<del> byte[] result = new byte[4];
<del> // 由低位到高位
<del> result[3] = (byte) ((i >> 24) & 0xFF);
<del> result[2] = (byte) ((i >> 16) & 0xFF);
<del> result[1] = (byte) ((i >> 8) & 0xFF);
<del> result[0] = (byte) (i & 0xFF);
<add> for (int i = 0; i < 4; i++) {
<add> result[i] = (byte) (fbit >> (i * 8));
<add> }
<ide> return result;
<ide> }
<ide>
<ide> * @param f
<ide> * @return
<ide> */
<del> public static byte[] float2byte(float f) {
<del> // 把float转换为byte[]
<add> public static byte[] floatToByteArray(float f) {
<ide> int fbit = Float.floatToIntBits(f);
<ide> byte[] b = new byte[4];
<ide> for (int i = 0; i < 4; i++) {
<del> b[i] = (byte) (fbit >> (24 - i * 8));
<del> }
<del> // 翻转数组
<del> int len = b.length;
<del> // 建立一个与源数组元素类型相同的数组
<del> byte[] dest = new byte[len];
<del> // 为了防止修改源数组,将源数组拷贝一份副本
<del> System.arraycopy(b, 0, dest, 0, len);
<del> byte temp;
<del> // 将顺位第i个与倒数第i个交换
<del> for (int i = 0; i < len / 2; ++i) {
<del> temp = dest[i];
<del> dest[i] = dest[len - i - 1];
<del> dest[len - i - 1] = temp;
<del> }
<del> return dest;
<del> }
<del>
<del> public static float byteArrayToFloat(byte[] b) {
<del> int l = b[0];
<del> l &= 0xff;
<del> l |= ((long) b[1] << 8);
<del> l &= 0xffff;
<del> l |= ((long) b[2] << 16);
<del> l &= 0xffffff;
<del> l |= ((long) b[3] << 24);
<del> return Float.intBitsToFloat(l);
<add> b[i] = (byte) (fbit >> (i * 8));
<add> }
<add> return b;
<add> }
<add>
<add> public static float byteArrayToFloat(byte[] bytes) {
<add> int value = 0;
<add> // 由低位到高位
<add> int shift = 0;
<add> for (int i = 0; i < 4; i++) {
<add> shift = i * 8;
<add> value += ((int) bytes[i] & 0x000000FF) << shift;// 往高位游
<add> }
<add> return Float.intBitsToFloat(value);
<add> }
<add>
<add> /**
<add> * 将64位的long值放到8字节的byte数组
<add> *
<add> * @param num
<add> * @return 返回转换后的byte数组
<add> */
<add> public static byte[] longToByteArray(long num) {
<add> byte[] result = new byte[8];
<add> for (int i = 0; i < 8; i++) {
<add> result[i] = (byte) (num >> (i * 8));
<add> }
<add> return result;
<add> }
<add>
<add> /**
<add> * 将8字节的byte数组转成一个long值
<add> *
<add> * @param byteArray
<add> * @return 转换后的long型数值
<add> */
<add> public static long byteArrayToLong(byte[] byteArray) {
<add> long value = 0;
<add> int shift = 0;
<add> for (int i = 0; i < 8; i++) {
<add> shift = i * 8;
<add> value += ((long) byteArray[i] & 0xFF) << shift;
<add> }
<add> return value;
<add> }
<add>
<add> /**
<add> * double转换byte
<add> *
<add> * @param x
<add> */
<add> public static byte[] doubleToByteArray(double x) {
<add> byte[] b = new byte[8];
<add> long l = Double.doubleToLongBits(x);
<add> for (int i = 0; i < 8; i++) {
<add> b[i] = (byte) (l >> (i * 8));
<add> }
<add> return b;
<add> }
<add>
<add> /**
<add> * 通过byte数组取得float
<add> *
<add> * @param b
<add> * @return
<add> */
<add> public static double byteArrayToDouble(byte[] bytes) {
<add> long value = 0;
<add> int shift = 0;
<add> for (int i = 0; i < 8; i++) {
<add> shift = i * 8;
<add> value += ((long) bytes[i] & 0xFF) << shift;
<add> }
<add> return Double.longBitsToDouble(value);
<ide> }
<ide>
<ide> public static void main(String[] args) {
<ide> short dd = 2;
<add> System.out.println("=========================SHORT========================");
<ide> System.out.println(HexDump.dumpHexString(shortToByteArray(dd)));
<ide> System.out.println(byteArrayToShort(shortToByteArray(dd)));
<ide> System.out.println(HexDump.dumpHexString(shortToByteArrayL(dd)));
<ide> System.out.println(byteArrayToShortL(shortToByteArrayL(dd)));
<ide>
<add> System.out.println("=========================INT========================");
<ide> System.out.println(HexDump.dumpHexString(intToByteArray(dd)));
<ide> System.out.println(byteArrayToInt(intToByteArray(dd)));
<ide> System.out.println(HexDump.dumpHexString(intToByteArrayL(dd)));
<ide> System.out.println(byteArrayToIntL(intToByteArrayL(dd)));
<ide>
<del> System.out.println(HexDump.dumpHexString(float2byte(dd * 0.1f)));
<del> System.out.println(byteArrayToFloat(float2byte(dd * 0.1f)));
<add> System.out.println("=========================LONG========================");
<add> System.out.println(HexDump.dumpHexString(longToByteArray(dd * 1l)));
<add> System.out.println(byteArrayToLong(longToByteArray(dd * 1l)));
<add>
<add> System.out.println("=========================FLOAT========================");
<add> System.out.println(HexDump.dumpHexString(floatToByteArray(dd * 0.1f)));
<add> System.out.println(byteArrayToFloat(floatToByteArray(dd * 0.1f)));
<add>
<add> System.out.println("=========================DOUBLE========================");
<add> System.out.println(HexDump.dumpHexString(doubleToByteArray(dd * 0.1d)));
<add> System.out.println(byteArrayToDouble(doubleToByteArray(dd * 0.1d)));
<ide> }
<ide>
<ide> } |
|
Java | apache-2.0 | 57a14266d81055c83f63848820c59b8827b11586 | 0 | jcshen007/cloudstack,resmo/cloudstack,mufaddalq/cloudstack-datera-driver,GabrielBrascher/cloudstack,DaanHoogland/cloudstack,DaanHoogland/cloudstack,mufaddalq/cloudstack-datera-driver,resmo/cloudstack,jcshen007/cloudstack,DaanHoogland/cloudstack,wido/cloudstack,wido/cloudstack,jcshen007/cloudstack,jcshen007/cloudstack,GabrielBrascher/cloudstack,mufaddalq/cloudstack-datera-driver,wido/cloudstack,resmo/cloudstack,resmo/cloudstack,GabrielBrascher/cloudstack,DaanHoogland/cloudstack,wido/cloudstack,resmo/cloudstack,GabrielBrascher/cloudstack,wido/cloudstack,mufaddalq/cloudstack-datera-driver,resmo/cloudstack,mufaddalq/cloudstack-datera-driver,DaanHoogland/cloudstack,DaanHoogland/cloudstack,mufaddalq/cloudstack-datera-driver,GabrielBrascher/cloudstack,DaanHoogland/cloudstack,wido/cloudstack,GabrielBrascher/cloudstack,GabrielBrascher/cloudstack,jcshen007/cloudstack,wido/cloudstack,jcshen007/cloudstack,jcshen007/cloudstack,resmo/cloudstack | // 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.hypervisor.kvm.resource;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import javax.ejb.Local;
import javax.naming.ConfigurationException;
import org.apache.log4j.Logger;
import org.libvirt.Connect;
import org.libvirt.Domain;
import org.libvirt.DomainInfo;
import org.libvirt.DomainInterfaceStats;
import org.libvirt.DomainSnapshot;
import org.libvirt.LibvirtException;
import org.libvirt.NodeInfo;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.AttachIsoCommand;
import com.cloud.agent.api.AttachVolumeAnswer;
import com.cloud.agent.api.AttachVolumeCommand;
import com.cloud.agent.api.BackupSnapshotAnswer;
import com.cloud.agent.api.BackupSnapshotCommand;
import com.cloud.agent.api.CheckHealthAnswer;
import com.cloud.agent.api.CheckHealthCommand;
import com.cloud.agent.api.CheckNetworkAnswer;
import com.cloud.agent.api.CheckNetworkCommand;
import com.cloud.agent.api.CheckStateCommand;
import com.cloud.agent.api.CheckVirtualMachineAnswer;
import com.cloud.agent.api.CheckVirtualMachineCommand;
import com.cloud.agent.api.CleanupNetworkRulesCmd;
import com.cloud.agent.api.Command;
import com.cloud.agent.api.CreatePrivateTemplateFromSnapshotCommand;
import com.cloud.agent.api.CreatePrivateTemplateFromVolumeCommand;
import com.cloud.agent.api.CreateStoragePoolCommand;
import com.cloud.agent.api.CreateVolumeFromSnapshotAnswer;
import com.cloud.agent.api.CreateVolumeFromSnapshotCommand;
import com.cloud.agent.api.DeleteSnapshotBackupAnswer;
import com.cloud.agent.api.DeleteSnapshotBackupCommand;
import com.cloud.agent.api.DeleteSnapshotsDirCommand;
import com.cloud.agent.api.DeleteStoragePoolCommand;
import com.cloud.agent.api.FenceAnswer;
import com.cloud.agent.api.FenceCommand;
import com.cloud.agent.api.GetHostStatsAnswer;
import com.cloud.agent.api.GetHostStatsCommand;
import com.cloud.agent.api.GetStorageStatsAnswer;
import com.cloud.agent.api.GetStorageStatsCommand;
import com.cloud.agent.api.GetVmStatsAnswer;
import com.cloud.agent.api.GetVmStatsCommand;
import com.cloud.agent.api.GetVncPortAnswer;
import com.cloud.agent.api.GetVncPortCommand;
import com.cloud.agent.api.HostStatsEntry;
import com.cloud.agent.api.MaintainAnswer;
import com.cloud.agent.api.MaintainCommand;
import com.cloud.agent.api.ManageSnapshotAnswer;
import com.cloud.agent.api.ManageSnapshotCommand;
import com.cloud.agent.api.MigrateAnswer;
import com.cloud.agent.api.MigrateCommand;
import com.cloud.agent.api.ModifySshKeysCommand;
import com.cloud.agent.api.ModifyStoragePoolAnswer;
import com.cloud.agent.api.ModifyStoragePoolCommand;
import com.cloud.agent.api.NetworkRulesSystemVmCommand;
import com.cloud.agent.api.NetworkUsageAnswer;
import com.cloud.agent.api.NetworkUsageCommand;
import com.cloud.agent.api.PingCommand;
import com.cloud.agent.api.PingRoutingCommand;
import com.cloud.agent.api.PingRoutingWithNwGroupsCommand;
import com.cloud.agent.api.PingTestCommand;
import com.cloud.agent.api.PrepareForMigrationAnswer;
import com.cloud.agent.api.PrepareForMigrationCommand;
import com.cloud.agent.api.ReadyAnswer;
import com.cloud.agent.api.ReadyCommand;
import com.cloud.agent.api.RebootAnswer;
import com.cloud.agent.api.RebootCommand;
import com.cloud.agent.api.RebootRouterCommand;
import com.cloud.agent.api.SecurityGroupRuleAnswer;
import com.cloud.agent.api.SecurityGroupRulesCmd;
import com.cloud.agent.api.StartAnswer;
import com.cloud.agent.api.StartCommand;
import com.cloud.agent.api.StartupCommand;
import com.cloud.agent.api.StartupRoutingCommand;
import com.cloud.agent.api.StartupStorageCommand;
import com.cloud.agent.api.StopAnswer;
import com.cloud.agent.api.StopCommand;
import com.cloud.agent.api.UpgradeSnapshotCommand;
import com.cloud.agent.api.VmStatsEntry;
import com.cloud.agent.api.check.CheckSshAnswer;
import com.cloud.agent.api.check.CheckSshCommand;
import com.cloud.agent.api.proxy.CheckConsoleProxyLoadCommand;
import com.cloud.agent.api.proxy.ConsoleProxyLoadAnswer;
import com.cloud.agent.api.proxy.WatchConsoleProxyLoadCommand;
import com.cloud.agent.api.routing.IpAssocAnswer;
import com.cloud.agent.api.routing.IpAssocCommand;
import com.cloud.agent.api.routing.NetworkElementCommand;
import com.cloud.agent.api.storage.CopyVolumeAnswer;
import com.cloud.agent.api.storage.CopyVolumeCommand;
import com.cloud.agent.api.storage.CreateAnswer;
import com.cloud.agent.api.storage.CreateCommand;
import com.cloud.agent.api.storage.CreatePrivateTemplateAnswer;
import com.cloud.agent.api.storage.DestroyCommand;
import com.cloud.agent.api.storage.PrimaryStorageDownloadAnswer;
import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand;
import com.cloud.agent.api.to.IpAddressTO;
import com.cloud.agent.api.to.NicTO;
import com.cloud.agent.api.to.StorageFilerTO;
import com.cloud.agent.api.to.VirtualMachineTO;
import com.cloud.agent.api.to.VolumeTO;
import com.cloud.hypervisor.kvm.resource.KVMHABase.NfsStoragePool;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.ConsoleDef;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.CpuTuneDef;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DevicesDef;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DiskDef;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DiskDef.diskProtocol;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.FeaturesDef;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.GraphicDef;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.GuestDef;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.GuestResourceDef;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.InputDef;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.InterfaceDef;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.InterfaceDef.hostNicType;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.SerialDef;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.TermPolicy;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.ClockDef;
import com.cloud.agent.resource.virtualnetwork.VirtualRoutingResource;
import com.cloud.hypervisor.kvm.storage.KVMPhysicalDisk;
import com.cloud.hypervisor.kvm.storage.KVMPhysicalDisk.PhysicalDiskFormat;
import com.cloud.hypervisor.kvm.storage.KVMStoragePool;
import com.cloud.hypervisor.kvm.storage.KVMStoragePoolManager;
import com.cloud.dc.Vlan;
import com.cloud.exception.InternalErrorException;
import com.cloud.host.Host.Type;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.network.Networks.BroadcastDomainType;
import com.cloud.network.Networks.IsolationType;
import com.cloud.network.Networks.RouterPrivateIpStrategy;
import com.cloud.network.Networks.TrafficType;
import com.cloud.network.PhysicalNetworkSetupInfo;
import com.cloud.resource.ServerResource;
import com.cloud.resource.ServerResourceBase;
import com.cloud.storage.Storage;
import com.cloud.storage.Storage.ImageFormat;
import com.cloud.storage.Storage.StoragePoolType;
import com.cloud.storage.StorageLayer;
import com.cloud.storage.Volume;
import com.cloud.storage.template.Processor;
import com.cloud.storage.template.Processor.FormatInfo;
import com.cloud.storage.template.QCOW2Processor;
import com.cloud.storage.template.TemplateInfo;
import com.cloud.storage.template.TemplateLocation;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair;
import com.cloud.utils.PropertiesUtil;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.net.NetUtils;
import com.cloud.utils.script.OutputInterpreter;
import com.cloud.utils.script.Script;
import com.cloud.vm.DiskProfile;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachine.State;
import com.cloud.vm.VirtualMachineName;
/**
* LibvirtComputingResource execute requests on the computing/routing host using
* the libvirt API
*
* @config {@table || Param Name | Description | Values | Default || ||
* hypervisor.type | type of local hypervisor | string | kvm || ||
* hypervisor.uri | local hypervisor to connect to | URI |
* qemu:///system || || domr.arch | instruction set for domr template |
* string | i686 || || private.bridge.name | private bridge where the
* domrs have their private interface | string | vmops0 || ||
* public.bridge.name | public bridge where the domrs have their public
* interface | string | br0 || || private.network.name | name of the
* network where the domrs have their private interface | string |
* vmops-private || || private.ipaddr.start | start of the range of
* private ip addresses for domrs | ip address | 192.168.166.128 || ||
* private.ipaddr.end | end of the range of private ip addresses for
* domrs | ip address | start + 126 || || private.macaddr.start | start
* of the range of private mac addresses for domrs | mac address |
* 00:16:3e:77:e2:a0 || || private.macaddr.end | end of the range of
* private mac addresses for domrs | mac address | start + 126 || ||
* pool | the parent of the storage pool hierarchy * }
**/
@Local(value = { ServerResource.class })
public class LibvirtComputingResource extends ServerResourceBase implements
ServerResource {
private static final Logger s_logger = Logger
.getLogger(LibvirtComputingResource.class);
private String _modifyVlanPath;
private String _versionstringpath;
private String _patchdomrPath;
private String _createvmPath;
private String _manageSnapshotPath;
private String _createTmplPath;
private String _heartBeatPath;
private String _securityGroupPath;
private String _networkUsagePath;
private String _host;
private String _dcId;
private String _pod;
private String _clusterId;
private int _migrateSpeed;
private long _hvVersion;
private KVMHAMonitor _monitor;
private final String _SSHKEYSPATH = "/root/.ssh";
private final String _SSHPRVKEYPATH = _SSHKEYSPATH + File.separator
+ "id_rsa.cloud";
private final String _SSHPUBKEYPATH = _SSHKEYSPATH + File.separator
+ "id_rsa.pub.cloud";
private String _mountPoint = "/mnt";
StorageLayer _storage;
private KVMStoragePoolManager _storagePoolMgr;
private static final class KeyValueInterpreter extends OutputInterpreter {
private final Map<String, String> map = new HashMap<String, String>();
@Override
public String interpret(BufferedReader reader) throws IOException {
String line = null;
int numLines = 0;
while ((line = reader.readLine()) != null) {
String[] toks = line.trim().split("=");
if (toks.length < 2) {
s_logger.warn("Failed to parse Script output: " + line);
} else {
map.put(toks[0].trim(), toks[1].trim());
}
numLines++;
}
if (numLines == 0) {
s_logger.warn("KeyValueInterpreter: no output lines?");
}
return null;
}
public Map<String, String> getKeyValues() {
return map;
}
}
@Override
protected String getDefaultScriptsDir() {
return null;
}
protected static MessageFormat SnapshotXML = new MessageFormat(
" <domainsnapshot>" + " <name>{0}</name>" + " <domain>"
+ " <uuid>{1}</uuid>" + " </domain>"
+ " </domainsnapshot>");
protected String _hypervisorType;
protected String _hypervisorURI;
protected String _hypervisorPath;
protected String _sysvmISOPath;
protected String _privNwName;
protected String _privBridgeName;
protected String _linkLocalBridgeName;
protected String _publicBridgeName;
protected String _guestBridgeName;
protected String _privateIp;
protected String _pool;
protected String _localGateway;
private boolean _can_bridge_firewall;
protected String _localStoragePath;
protected String _localStorageUUID;
private Pair<String, String> _pifs;
private final Map<String, vmStats> _vmStats = new ConcurrentHashMap<String, vmStats>();
protected boolean _disconnected = true;
protected int _timeout;
protected int _cmdsTimeout;
protected int _stopTimeout;
protected static HashMap<DomainInfo.DomainState, State> s_statesTable;
static {
s_statesTable = new HashMap<DomainInfo.DomainState, State>();
s_statesTable.put(DomainInfo.DomainState.VIR_DOMAIN_SHUTOFF,
State.Stopped);
s_statesTable.put(DomainInfo.DomainState.VIR_DOMAIN_PAUSED,
State.Running);
s_statesTable.put(DomainInfo.DomainState.VIR_DOMAIN_RUNNING,
State.Running);
s_statesTable.put(DomainInfo.DomainState.VIR_DOMAIN_BLOCKED,
State.Running);
s_statesTable.put(DomainInfo.DomainState.VIR_DOMAIN_NOSTATE,
State.Unknown);
s_statesTable.put(DomainInfo.DomainState.VIR_DOMAIN_SHUTDOWN,
State.Stopping);
}
protected HashMap<String, State> _vms = new HashMap<String, State>(20);
protected List<String> _vmsKilled = new ArrayList<String>();
private VirtualRoutingResource _virtRouterResource;
private String _pingTestPath;
private int _dom0MinMem;
protected enum defineOps {
UNDEFINE_VM, DEFINE_VM
}
private String getEndIpFromStartIp(String startIp, int numIps) {
String[] tokens = startIp.split("[.]");
assert (tokens.length == 4);
int lastbyte = Integer.parseInt(tokens[3]);
lastbyte = lastbyte + numIps;
tokens[3] = Integer.toString(lastbyte);
StringBuilder end = new StringBuilder(15);
end.append(tokens[0]).append(".").append(tokens[1]).append(".")
.append(tokens[2]).append(".").append(tokens[3]);
return end.toString();
}
private Map<String, Object> getDeveloperProperties()
throws ConfigurationException {
final File file = PropertiesUtil.findConfigFile("developer.properties");
if (file == null) {
throw new ConfigurationException(
"Unable to find developer.properties.");
}
s_logger.info("developer.properties found at " + file.getAbsolutePath());
Properties properties = new Properties();
try {
properties.load(new FileInputStream(file));
String startMac = (String) properties.get("private.macaddr.start");
if (startMac == null) {
throw new ConfigurationException(
"Developers must specify start mac for private ip range");
}
String startIp = (String) properties.get("private.ipaddr.start");
if (startIp == null) {
throw new ConfigurationException(
"Developers must specify start ip for private ip range");
}
final Map<String, Object> params = PropertiesUtil.toMap(properties);
String endIp = (String) properties.get("private.ipaddr.end");
if (endIp == null) {
endIp = getEndIpFromStartIp(startIp, 16);
params.put("private.ipaddr.end", endIp);
}
return params;
} catch (final FileNotFoundException ex) {
throw new CloudRuntimeException("Cannot find the file: "
+ file.getAbsolutePath(), ex);
} catch (final IOException ex) {
throw new CloudRuntimeException("IOException in reading "
+ file.getAbsolutePath(), ex);
}
}
protected String getDefaultNetworkScriptsDir() {
return "scripts/vm/network/vnet";
}
protected String getDefaultStorageScriptsDir() {
return "scripts/storage/qcow2";
}
protected String getDefaultKvmScriptsDir() {
return "scripts/vm/hypervisor/kvm";
}
protected String getDefaultDomrScriptsDir() {
return "scripts/network/domr/kvm";
}
@Override
public boolean configure(String name, Map<String, Object> params)
throws ConfigurationException {
boolean success = super.configure(name, params);
if (!success) {
return false;
}
try {
Class<?> clazz = Class
.forName("com.cloud.storage.JavaStorageLayer");
_storage = (StorageLayer) ComponentLocator.inject(clazz);
_storage.configure("StorageLayer", params);
} catch (ClassNotFoundException e) {
throw new ConfigurationException("Unable to find class "
+ "com.cloud.storage.JavaStorageLayer");
}
String domrScriptsDir = (String) params.get("domr.scripts.dir");
if (domrScriptsDir == null) {
domrScriptsDir = getDefaultDomrScriptsDir();
}
String kvmScriptsDir = (String) params.get("kvm.scripts.dir");
if (kvmScriptsDir == null) {
kvmScriptsDir = getDefaultKvmScriptsDir();
}
String networkScriptsDir = (String) params.get("network.scripts.dir");
if (networkScriptsDir == null) {
networkScriptsDir = getDefaultNetworkScriptsDir();
}
String storageScriptsDir = (String) params.get("storage.scripts.dir");
if (storageScriptsDir == null) {
storageScriptsDir = getDefaultStorageScriptsDir();
}
params.put("domr.scripts.dir", domrScriptsDir);
_virtRouterResource = new VirtualRoutingResource();
success = _virtRouterResource.configure(name, params);
if (!success) {
return false;
}
_host = (String) params.get("host");
if (_host == null) {
_host = "localhost";
}
_dcId = (String) params.get("zone");
if (_dcId == null) {
_dcId = "default";
}
_pod = (String) params.get("pod");
if (_pod == null) {
_pod = "default";
}
_clusterId = (String) params.get("cluster");
_modifyVlanPath = Script.findScript(networkScriptsDir, "modifyvlan.sh");
if (_modifyVlanPath == null) {
throw new ConfigurationException("Unable to find modifyvlan.sh");
}
_versionstringpath = Script.findScript(kvmScriptsDir, "versions.sh");
if (_versionstringpath == null) {
throw new ConfigurationException("Unable to find versions.sh");
}
_patchdomrPath = Script.findScript(kvmScriptsDir + "/patch/",
"rundomrpre.sh");
if (_patchdomrPath == null) {
throw new ConfigurationException("Unable to find rundomrpre.sh");
}
_heartBeatPath = Script.findScript(kvmScriptsDir, "kvmheartbeat.sh");
if (_heartBeatPath == null) {
throw new ConfigurationException("Unable to find kvmheartbeat.sh");
}
_createvmPath = Script.findScript(storageScriptsDir, "createvm.sh");
if (_createvmPath == null) {
throw new ConfigurationException("Unable to find the createvm.sh");
}
_manageSnapshotPath = Script.findScript(storageScriptsDir,
"managesnapshot.sh");
if (_manageSnapshotPath == null) {
throw new ConfigurationException(
"Unable to find the managesnapshot.sh");
}
_createTmplPath = Script
.findScript(storageScriptsDir, "createtmplt.sh");
if (_createTmplPath == null) {
throw new ConfigurationException(
"Unable to find the createtmplt.sh");
}
_securityGroupPath = Script.findScript(networkScriptsDir,
"security_group.py");
if (_securityGroupPath == null) {
throw new ConfigurationException(
"Unable to find the security_group.py");
}
_networkUsagePath = Script.findScript("scripts/network/domr/",
"networkUsage.sh");
if (_networkUsagePath == null) {
throw new ConfigurationException(
"Unable to find the networkUsage.sh");
}
String value = (String) params.get("developer");
boolean isDeveloper = Boolean.parseBoolean(value);
if (isDeveloper) {
params.putAll(getDeveloperProperties());
}
_pool = (String) params.get("pool");
if (_pool == null) {
_pool = "/root";
}
String instance = (String) params.get("instance");
_hypervisorType = (String) params.get("hypervisor.type");
if (_hypervisorType == null) {
_hypervisorType = "kvm";
}
_hypervisorURI = (String) params.get("hypervisor.uri");
if (_hypervisorURI == null) {
_hypervisorURI = "qemu:///system";
}
String startMac = (String) params.get("private.macaddr.start");
if (startMac == null) {
startMac = "00:16:3e:77:e2:a0";
}
String startIp = (String) params.get("private.ipaddr.start");
if (startIp == null) {
startIp = "192.168.166.128";
}
_pingTestPath = Script.findScript(kvmScriptsDir, "pingtest.sh");
if (_pingTestPath == null) {
throw new ConfigurationException("Unable to find the pingtest.sh");
}
_linkLocalBridgeName = (String) params.get("private.bridge.name");
if (_linkLocalBridgeName == null) {
if (isDeveloper) {
_linkLocalBridgeName = "cloud-" + instance + "-0";
} else {
_linkLocalBridgeName = "cloud0";
}
}
_publicBridgeName = (String) params.get("public.network.device");
if (_publicBridgeName == null) {
_publicBridgeName = "cloudbr0";
}
_privBridgeName = (String) params.get("private.network.device");
if (_privBridgeName == null) {
_privBridgeName = "cloudbr1";
}
_guestBridgeName = (String) params.get("guest.network.device");
if (_guestBridgeName == null) {
_guestBridgeName = _privBridgeName;
}
_privNwName = (String) params.get("private.network.name");
if (_privNwName == null) {
if (isDeveloper) {
_privNwName = "cloud-" + instance + "-private";
} else {
_privNwName = "cloud-private";
}
}
_localStoragePath = (String) params.get("local.storage.path");
if (_localStoragePath == null) {
_localStoragePath = "/var/lib/libvirt/images/";
}
_localStorageUUID = (String) params.get("local.storage.uuid");
if (_localStorageUUID == null) {
_localStorageUUID = UUID.randomUUID().toString();
params.put("local.storage.uuid", _localStorageUUID);
}
value = (String) params.get("scripts.timeout");
_timeout = NumbersUtil.parseInt(value, 30 * 60) * 1000;
value = (String) params.get("stop.script.timeout");
_stopTimeout = NumbersUtil.parseInt(value, 120) * 1000;
value = (String) params.get("cmds.timeout");
_cmdsTimeout = NumbersUtil.parseInt(value, 7200) * 1000;
value = (String) params.get("host.reserved.mem.mb");
_dom0MinMem = NumbersUtil.parseInt(value, 0) * 1024 * 1024;
LibvirtConnection.initialize(_hypervisorURI);
Connect conn = null;
try {
conn = LibvirtConnection.getConnection();
} catch (LibvirtException e) {
throw new CloudRuntimeException(e.getMessage());
}
/* Does node support HVM guest? If not, exit */
if (!IsHVMEnabled(conn)) {
throw new ConfigurationException(
"NO HVM support on this machine, pls make sure: "
+ "1. VT/SVM is supported by your CPU, or is enabled in BIOS. "
+ "2. kvm modules is installed");
}
_hypervisorPath = getHypervisorPath(conn);
try {
_hvVersion = conn.getVersion();
_hvVersion = (_hvVersion % 1000000) / 1000;
} catch (LibvirtException e) {
}
String[] info = NetUtils.getNetworkParams(_privateNic);
_monitor = new KVMHAMonitor(null, info[0], _heartBeatPath);
Thread ha = new Thread(_monitor);
ha.start();
_storagePoolMgr = new KVMStoragePoolManager(_storage, _monitor);
_sysvmISOPath = (String) params.get("systemvm.iso.path");
if (_sysvmISOPath == null) {
String[] isoPaths = { "/usr/lib64/cloud/agent/vms/systemvm.iso",
"/usr/lib/cloud/agent/vms/systemvm.iso" };
for (String isoPath : isoPaths) {
if (_storage.exists(isoPath)) {
_sysvmISOPath = isoPath;
break;
}
}
if (_sysvmISOPath == null) {
s_logger.debug("Can't find system vm ISO");
}
}
try {
createControlNetwork();
} catch (LibvirtException e) {
throw new ConfigurationException(e.getMessage());
}
_pifs = getPifs();
if (_pifs.first() == null) {
s_logger.debug("Failed to get private nic name");
throw new ConfigurationException("Failed to get private nic name");
}
if (_pifs.second() == null) {
s_logger.debug("Failed to get public nic name");
throw new ConfigurationException("Failed to get public nic name");
}
s_logger.debug("Found pif: " + _pifs.first() + " on " + _privBridgeName
+ ", pif: " + _pifs.second() + " on " + _publicBridgeName);
_can_bridge_firewall = can_bridge_firewall(_pifs.second());
_localGateway = Script
.runSimpleBashScript("ip route |grep default|awk '{print $3}'");
if (_localGateway == null) {
s_logger.debug("Failed to found the local gateway");
}
_mountPoint = (String) params.get("mount.path");
if (_mountPoint == null) {
_mountPoint = "/mnt";
}
value = (String) params.get("vm.migrate.speed");
_migrateSpeed = NumbersUtil.parseInt(value, -1);
if (_migrateSpeed == -1) {
//get guest network device speed
_migrateSpeed = 0;
String speed = Script.runSimpleBashScript("ethtool " + _pifs.second() + " |grep Speed | cut -d \\ -f 2");
if (speed != null) {
String[] tokens = speed.split("M");
if (tokens.length == 2) {
try {
_migrateSpeed = Integer.parseInt(tokens[0]);
} catch (Exception e) {
}
s_logger.debug("device " + _pifs.second() + " has speed: " + String.valueOf(_migrateSpeed));
}
}
params.put("vm.migrate.speed", String.valueOf(_migrateSpeed));
}
return true;
}
private Pair<String, String> getPifs() {
/* get pifs from bridge */
String pubPif = null;
String privPif = null;
String vlan = null;
if (_publicBridgeName != null) {
pubPif = Script.runSimpleBashScript("brctl show | grep "
+ _publicBridgeName + " | awk '{print $4}'");
vlan = Script.runSimpleBashScript("ls /proc/net/vlan/" + pubPif);
if (vlan != null && !vlan.isEmpty()) {
pubPif = Script
.runSimpleBashScript("grep ^Device\\: /proc/net/vlan/"
+ pubPif + " | awk {'print $2'}");
}
}
if (_guestBridgeName != null) {
privPif = Script.runSimpleBashScript("brctl show | grep "
+ _guestBridgeName + " | awk '{print $4}'");
vlan = Script.runSimpleBashScript("ls /proc/net/vlan/" + privPif);
if (vlan != null && !vlan.isEmpty()) {
privPif = Script
.runSimpleBashScript("grep ^Device\\: /proc/net/vlan/"
+ privPif + " | awk {'print $2'}");
}
}
return new Pair<String, String>(privPif, pubPif);
}
private boolean checkNetwork(String networkName) {
if (networkName == null) {
return true;
}
String name = Script.runSimpleBashScript("brctl show | grep "
+ networkName + " | awk '{print $4}'");
if (name == null) {
return false;
} else {
return true;
}
}
private String getVnetId(String vnetId) {
return vnetId;
}
private void patchSystemVm(String cmdLine, String dataDiskPath,
String vmName) throws InternalErrorException {
String result;
final Script command = new Script(_patchdomrPath, _timeout, s_logger);
command.add("-l", vmName);
command.add("-t", "all");
command.add("-d", dataDiskPath);
command.add("-p", cmdLine.replaceAll(" ", "%"));
result = command.execute();
if (result != null) {
throw new InternalErrorException(result);
}
}
boolean isDirectAttachedNetwork(String type) {
if ("untagged".equalsIgnoreCase(type)) {
return true;
} else {
try {
Long.valueOf(type);
} catch (NumberFormatException e) {
return true;
}
return false;
}
}
protected String startDomain(Connect conn, String vmName, String domainXML)
throws LibvirtException, InternalErrorException {
/* No duplicated vm, we will success, or failed */
boolean failed = false;
Domain dm = null;
try {
dm = conn.domainDefineXML(domainXML);
} catch (final LibvirtException e) {
/* Duplicated defined vm */
s_logger.warn("Failed to define domain " + vmName + ": "
+ e.getMessage());
failed = true;
} finally {
try {
if (dm != null) {
dm.free();
}
} catch (final LibvirtException e) {
}
}
/* If failed, undefine the vm */
Domain dmOld = null;
Domain dmNew = null;
try {
if (failed) {
dmOld = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
.getBytes()));
dmOld.undefine();
dmNew = conn.domainDefineXML(domainXML);
}
} catch (final LibvirtException e) {
s_logger.warn("Failed to define domain (second time) " + vmName
+ ": " + e.getMessage());
throw e;
} catch (Exception e) {
s_logger.warn("Failed to define domain (second time) " + vmName
+ ": " + e.getMessage());
throw new InternalErrorException(e.toString());
} finally {
try {
if (dmOld != null) {
dmOld.free();
}
if (dmNew != null) {
dmNew.free();
}
} catch (final LibvirtException e) {
}
}
/* Start the VM */
try {
dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
.getBytes()));
dm.create();
} catch (LibvirtException e) {
s_logger.warn("Failed to start domain: " + vmName + ": "
+ e.getMessage());
throw e;
} finally {
try {
if (dm != null) {
dm.free();
}
} catch (final LibvirtException e) {
}
}
return null;
}
@Override
public boolean stop() {
try {
Connect conn = LibvirtConnection.getConnection();
conn.close();
} catch (LibvirtException e) {
}
return true;
}
public static void main(String[] args) {
s_logger.addAppender(new org.apache.log4j.ConsoleAppender(
new org.apache.log4j.PatternLayout(), "System.out"));
LibvirtComputingResource test = new LibvirtComputingResource();
Map<String, Object> params = new HashMap<String, Object>();
try {
test.configure("test", params);
} catch (ConfigurationException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
String result = null;
// String result = test.startDomainRouter("domr1",
// "/var/lib/images/centos.5-4.x86-64/centos-small.img", 128, "0064",
// "02:00:30:00:01:01", "00:16:3e:77:e2:a1", "02:00:30:00:64:01");
boolean created = (result == null);
s_logger.info("Domain " + (created ? " " : " not ") + " created");
s_logger.info("Rule " + (created ? " " : " not ") + " created");
test.stop();
}
@Override
public Answer executeRequest(Command cmd) {
try {
if (cmd instanceof StopCommand) {
return execute((StopCommand) cmd);
} else if (cmd instanceof GetVmStatsCommand) {
return execute((GetVmStatsCommand) cmd);
} else if (cmd instanceof RebootRouterCommand) {
return execute((RebootRouterCommand) cmd);
} else if (cmd instanceof RebootCommand) {
return execute((RebootCommand) cmd);
} else if (cmd instanceof GetHostStatsCommand) {
return execute((GetHostStatsCommand) cmd);
} else if (cmd instanceof CheckStateCommand) {
return executeRequest(cmd);
} else if (cmd instanceof CheckHealthCommand) {
return execute((CheckHealthCommand) cmd);
} else if (cmd instanceof PrepareForMigrationCommand) {
return execute((PrepareForMigrationCommand) cmd);
} else if (cmd instanceof MigrateCommand) {
return execute((MigrateCommand) cmd);
} else if (cmd instanceof PingTestCommand) {
return execute((PingTestCommand) cmd);
} else if (cmd instanceof CheckVirtualMachineCommand) {
return execute((CheckVirtualMachineCommand) cmd);
} else if (cmd instanceof ReadyCommand) {
return execute((ReadyCommand) cmd);
} else if (cmd instanceof AttachIsoCommand) {
return execute((AttachIsoCommand) cmd);
} else if (cmd instanceof AttachVolumeCommand) {
return execute((AttachVolumeCommand) cmd);
} else if (cmd instanceof StopCommand) {
return execute((StopCommand) cmd);
} else if (cmd instanceof CheckConsoleProxyLoadCommand) {
return execute((CheckConsoleProxyLoadCommand) cmd);
} else if (cmd instanceof WatchConsoleProxyLoadCommand) {
return execute((WatchConsoleProxyLoadCommand) cmd);
} else if (cmd instanceof GetVncPortCommand) {
return execute((GetVncPortCommand) cmd);
} else if (cmd instanceof ModifySshKeysCommand) {
return execute((ModifySshKeysCommand) cmd);
} else if (cmd instanceof MaintainCommand) {
return execute((MaintainCommand) cmd);
} else if (cmd instanceof CreateCommand) {
return execute((CreateCommand) cmd);
} else if (cmd instanceof DestroyCommand) {
return execute((DestroyCommand) cmd);
} else if (cmd instanceof PrimaryStorageDownloadCommand) {
return execute((PrimaryStorageDownloadCommand) cmd);
} else if (cmd instanceof CreatePrivateTemplateFromVolumeCommand) {
return execute((CreatePrivateTemplateFromVolumeCommand) cmd);
} else if (cmd instanceof GetStorageStatsCommand) {
return execute((GetStorageStatsCommand) cmd);
} else if (cmd instanceof ManageSnapshotCommand) {
return execute((ManageSnapshotCommand) cmd);
} else if (cmd instanceof BackupSnapshotCommand) {
return execute((BackupSnapshotCommand) cmd);
} else if (cmd instanceof CreateVolumeFromSnapshotCommand) {
return execute((CreateVolumeFromSnapshotCommand) cmd);
} else if (cmd instanceof CreatePrivateTemplateFromSnapshotCommand) {
return execute((CreatePrivateTemplateFromSnapshotCommand) cmd);
} else if (cmd instanceof UpgradeSnapshotCommand) {
return execute((UpgradeSnapshotCommand) cmd);
} else if (cmd instanceof CreateStoragePoolCommand) {
return execute((CreateStoragePoolCommand) cmd);
} else if (cmd instanceof ModifyStoragePoolCommand) {
return execute((ModifyStoragePoolCommand) cmd);
} else if (cmd instanceof SecurityGroupRulesCmd) {
return execute((SecurityGroupRulesCmd) cmd);
} else if (cmd instanceof DeleteStoragePoolCommand) {
return execute((DeleteStoragePoolCommand) cmd);
} else if (cmd instanceof FenceCommand) {
return execute((FenceCommand) cmd);
} else if (cmd instanceof StartCommand) {
return execute((StartCommand) cmd);
} else if (cmd instanceof IpAssocCommand) {
return execute((IpAssocCommand) cmd);
} else if (cmd instanceof NetworkElementCommand) {
return _virtRouterResource.executeRequest(cmd);
} else if (cmd instanceof CheckSshCommand) {
return execute((CheckSshCommand) cmd);
} else if (cmd instanceof NetworkUsageCommand) {
return execute((NetworkUsageCommand) cmd);
} else if (cmd instanceof NetworkRulesSystemVmCommand) {
return execute((NetworkRulesSystemVmCommand) cmd);
} else if (cmd instanceof CleanupNetworkRulesCmd) {
return execute((CleanupNetworkRulesCmd) cmd);
} else if (cmd instanceof CopyVolumeCommand) {
return execute((CopyVolumeCommand) cmd);
} else if (cmd instanceof CheckNetworkCommand) {
return execute((CheckNetworkCommand) cmd);
} else {
s_logger.warn("Unsupported command ");
return Answer.createUnsupportedCommandAnswer(cmd);
}
} catch (final IllegalArgumentException e) {
return new Answer(cmd, false, e.getMessage());
}
}
private CheckNetworkAnswer execute(CheckNetworkCommand cmd) {
List<PhysicalNetworkSetupInfo> phyNics = cmd
.getPhysicalNetworkInfoList();
String errMsg = null;
for (PhysicalNetworkSetupInfo nic : phyNics) {
if (!checkNetwork(nic.getGuestNetworkName())) {
errMsg = "Can not find network: " + nic.getGuestNetworkName();
break;
} else if (!checkNetwork(nic.getPrivateNetworkName())) {
errMsg = "Can not find network: " + nic.getPrivateNetworkName();
break;
} else if (!checkNetwork(nic.getPublicNetworkName())) {
errMsg = "Can not find network: " + nic.getPublicNetworkName();
break;
}
}
if (errMsg != null) {
return new CheckNetworkAnswer(cmd, false, errMsg);
} else {
return new CheckNetworkAnswer(cmd, true, null);
}
}
private CopyVolumeAnswer execute(CopyVolumeCommand cmd) {
boolean copyToSecondary = cmd.toSecondaryStorage();
String volumePath = cmd.getVolumePath();
StorageFilerTO pool = cmd.getPool();
String secondaryStorageUrl = cmd.getSecondaryStorageURL();
KVMStoragePool secondaryStoragePool = null;
try {
KVMStoragePool primaryPool = _storagePoolMgr.getStoragePool(pool
.getUuid());
String volumeName = UUID.randomUUID().toString();
if (copyToSecondary) {
String destVolumeName = volumeName + ".qcow2";
KVMPhysicalDisk volume = primaryPool.getPhysicalDisk(cmd
.getVolumePath());
String volumeDestPath = "/volumes/" + cmd.getVolumeId()
+ File.separator;
secondaryStoragePool = _storagePoolMgr
.getStoragePoolByURI(secondaryStorageUrl);
secondaryStoragePool.createFolder(volumeDestPath);
secondaryStoragePool.delete();
secondaryStoragePool = _storagePoolMgr
.getStoragePoolByURI(secondaryStorageUrl
+ volumeDestPath);
_storagePoolMgr.copyPhysicalDisk(volume, destVolumeName,
secondaryStoragePool);
return new CopyVolumeAnswer(cmd, true, null, null, volumeName);
} else {
volumePath = "/volumes/" + cmd.getVolumeId() + File.separator;
secondaryStoragePool = _storagePoolMgr
.getStoragePoolByURI(secondaryStorageUrl + volumePath);
KVMPhysicalDisk volume = secondaryStoragePool
.getPhysicalDisk(cmd.getVolumePath() + ".qcow2");
_storagePoolMgr.copyPhysicalDisk(volume, volumeName,
primaryPool);
return new CopyVolumeAnswer(cmd, true, null, null, volumeName);
}
} catch (CloudRuntimeException e) {
return new CopyVolumeAnswer(cmd, false, e.toString(), null, null);
} finally {
if (secondaryStoragePool != null) {
secondaryStoragePool.delete();
}
}
}
protected Answer execute(DeleteStoragePoolCommand cmd) {
try {
_storagePoolMgr.deleteStoragePool(cmd.getPool().getUuid());
return new Answer(cmd);
} catch (CloudRuntimeException e) {
return new Answer(cmd, false, e.toString());
}
}
protected FenceAnswer execute(FenceCommand cmd) {
ExecutorService executors = Executors.newSingleThreadExecutor();
List<NfsStoragePool> pools = _monitor.getStoragePools();
KVMHAChecker ha = new KVMHAChecker(pools, cmd.getHostIp());
Future<Boolean> future = executors.submit(ha);
try {
Boolean result = future.get();
if (result) {
return new FenceAnswer(cmd, false, "Heart is still beating...");
} else {
return new FenceAnswer(cmd);
}
} catch (InterruptedException e) {
s_logger.warn("Unable to fence", e);
return new FenceAnswer(cmd, false, e.getMessage());
} catch (ExecutionException e) {
s_logger.warn("Unable to fence", e);
return new FenceAnswer(cmd, false, e.getMessage());
}
}
protected Storage.StorageResourceType getStorageResourceType() {
return Storage.StorageResourceType.STORAGE_POOL;
}
protected Answer execute(CreateCommand cmd) {
StorageFilerTO pool = cmd.getPool();
DiskProfile dskch = cmd.getDiskCharacteristics();
KVMPhysicalDisk BaseVol = null;
KVMStoragePool primaryPool = null;
KVMPhysicalDisk vol = null;
long disksize;
try {
primaryPool = _storagePoolMgr.getStoragePool(pool.getUuid());
if (cmd.getTemplateUrl() != null) {
BaseVol = primaryPool.getPhysicalDisk(cmd.getTemplateUrl());
vol = _storagePoolMgr.createDiskFromTemplate(BaseVol, UUID
.randomUUID().toString(), primaryPool);
if (vol == null) {
return new Answer(cmd, false,
" Can't create storage volume on storage pool");
}
disksize = vol.getSize();
} else {
disksize = dskch.getSize();
vol = primaryPool.createPhysicalDisk(UUID.randomUUID()
.toString(), dskch.getSize());
}
VolumeTO volume = new VolumeTO(cmd.getVolumeId(), dskch.getType(),
pool.getType(), pool.getUuid(), pool.getPath(),
vol.getName(), vol.getName(), disksize, null);
return new CreateAnswer(cmd, volume);
} catch (CloudRuntimeException e) {
s_logger.debug("Failed to create volume: " + e.toString());
return new CreateAnswer(cmd, e);
}
}
public Answer execute(DestroyCommand cmd) {
VolumeTO vol = cmd.getVolume();
try {
KVMStoragePool pool = _storagePoolMgr.getStoragePool(vol
.getPoolUuid());
pool.deletePhysicalDisk(vol.getPath());
return new Answer(cmd, true, "Success");
} catch (CloudRuntimeException e) {
s_logger.debug("Failed to delete volume: " + e.toString());
return new Answer(cmd, false, e.toString());
}
}
private String getVlanIdFromBridge(String brName) {
OutputInterpreter.OneLineParser vlanIdParser = new OutputInterpreter.OneLineParser();
final Script cmd = new Script("/bin/bash", s_logger);
cmd.add("-c");
cmd.add("vlanid=$(brctl show |grep " + brName
+ " |awk '{print $4}' | cut -s -d. -f 2);echo $vlanid");
String result = cmd.execute(vlanIdParser);
if (result != null) {
return null;
}
String vlanId = vlanIdParser.getLine();
if (vlanId.equalsIgnoreCase("")) {
return null;
} else {
return vlanId;
}
}
private void VifHotPlug(Connect conn, String vmName, String vlanId,
String macAddr) throws InternalErrorException, LibvirtException {
NicTO nicTO = new NicTO();
nicTO.setMac(macAddr);
nicTO.setType(TrafficType.Public);
if (vlanId == null) {
nicTO.setBroadcastType(BroadcastDomainType.Native);
} else {
nicTO.setBroadcastType(BroadcastDomainType.Vlan);
nicTO.setBroadcastUri(BroadcastDomainType.Vlan.toUri(vlanId));
}
InterfaceDef nic = createVif(nicTO, InterfaceDef.nicModel.VIRTIO);
Domain vm = getDomain(conn, vmName);
vm.attachDevice(nic.toString());
}
public Answer execute(IpAssocCommand cmd) {
String routerName = cmd
.getAccessDetail(NetworkElementCommand.ROUTER_NAME);
String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
String[] results = new String[cmd.getIpAddresses().length];
Connect conn;
try {
conn = LibvirtConnection.getConnection();
List<InterfaceDef> nics = getInterfaces(conn, routerName);
Map<String, Integer> vlanAllocatedToVM = new HashMap<String, Integer>();
Integer nicPos = 0;
for (InterfaceDef nic : nics) {
if (nic.getBrName().equalsIgnoreCase(_linkLocalBridgeName)) {
vlanAllocatedToVM.put("LinkLocal", nicPos);
} else {
String vlanId = getVlanIdFromBridge(nic.getBrName());
if (vlanId != null) {
vlanAllocatedToVM.put(vlanId, nicPos);
} else {
vlanAllocatedToVM.put(Vlan.UNTAGGED, nicPos);
}
}
nicPos++;
}
IpAddressTO[] ips = cmd.getIpAddresses();
int i = 0;
String result = null;
int nicNum = 0;
for (IpAddressTO ip : ips) {
if (!vlanAllocatedToVM.containsKey(ip.getVlanId())) {
/* plug a vif into router */
VifHotPlug(conn, routerName, ip.getVlanId(),
ip.getVifMacAddress());
vlanAllocatedToVM.put(ip.getVlanId(), nicPos++);
}
nicNum = vlanAllocatedToVM.get(ip.getVlanId());
networkUsage(routerIp, "addVif", "eth" + nicNum);
result = _virtRouterResource.assignPublicIpAddress(routerName,
routerIp, ip.getPublicIp(), ip.isAdd(), ip.isFirstIP(),
ip.isSourceNat(), ip.getVlanId(), ip.getVlanGateway(),
ip.getVlanNetmask(), ip.getVifMacAddress(),
ip.getGuestIp(), nicNum);
if (result != null) {
results[i++] = IpAssocAnswer.errorResult;
} else {
results[i++] = ip.getPublicIp() + " - success";
;
}
}
return new IpAssocAnswer(cmd, results);
} catch (LibvirtException e) {
return new IpAssocAnswer(cmd, results);
} catch (InternalErrorException e) {
return new IpAssocAnswer(cmd, results);
}
}
protected ManageSnapshotAnswer execute(final ManageSnapshotCommand cmd) {
String snapshotName = cmd.getSnapshotName();
String snapshotPath = cmd.getSnapshotPath();
String vmName = cmd.getVmName();
try {
Connect conn = LibvirtConnection.getConnection();
DomainInfo.DomainState state = null;
Domain vm = null;
if (vmName != null) {
try {
vm = getDomain(conn, cmd.getVmName());
state = vm.getInfo().state;
} catch (LibvirtException e) {
}
}
KVMStoragePool primaryPool = _storagePoolMgr.getStoragePool(cmd
.getPool().getUuid());
if (primaryPool.getType() == StoragePoolType.RBD) {
s_logger.debug("Snapshots are not supported on RBD volumes");
return new ManageSnapshotAnswer(cmd, false,
"Snapshots are not supported on RBD volumes");
}
KVMPhysicalDisk disk = primaryPool.getPhysicalDisk(cmd
.getVolumePath());
if (state == DomainInfo.DomainState.VIR_DOMAIN_RUNNING
&& !primaryPool.isExternalSnapshot()) {
String vmUuid = vm.getUUIDString();
Object[] args = new Object[] { snapshotName, vmUuid };
String snapshot = SnapshotXML.format(args);
s_logger.debug(snapshot);
if (cmd.getCommandSwitch().equalsIgnoreCase(
ManageSnapshotCommand.CREATE_SNAPSHOT)) {
vm.snapshotCreateXML(snapshot);
} else {
DomainSnapshot snap = vm.snapshotLookupByName(snapshotName);
snap.delete(0);
}
/*
* libvirt on RHEL6 doesn't handle resume event emitted from
* qemu
*/
vm = getDomain(conn, cmd.getVmName());
state = vm.getInfo().state;
if (state == DomainInfo.DomainState.VIR_DOMAIN_PAUSED) {
vm.resume();
}
} else {
/* VM is not running, create a snapshot by ourself */
final Script command = new Script(_manageSnapshotPath,
_cmdsTimeout, s_logger);
if (cmd.getCommandSwitch().equalsIgnoreCase(
ManageSnapshotCommand.CREATE_SNAPSHOT)) {
command.add("-c", disk.getPath());
} else {
command.add("-d", snapshotPath);
}
command.add("-n", snapshotName);
String result = command.execute();
if (result != null) {
s_logger.debug("Failed to manage snapshot: " + result);
return new ManageSnapshotAnswer(cmd, false,
"Failed to manage snapshot: " + result);
}
}
return new ManageSnapshotAnswer(cmd, cmd.getSnapshotId(),
disk.getPath() + File.separator + snapshotName, true, null);
} catch (LibvirtException e) {
s_logger.debug("Failed to manage snapshot: " + e.toString());
return new ManageSnapshotAnswer(cmd, false,
"Failed to manage snapshot: " + e.toString());
}
}
protected BackupSnapshotAnswer execute(final BackupSnapshotCommand cmd) {
Long dcId = cmd.getDataCenterId();
Long accountId = cmd.getAccountId();
Long volumeId = cmd.getVolumeId();
String secondaryStoragePoolUrl = cmd.getSecondaryStorageUrl();
String snapshotName = cmd.getSnapshotName();
String snapshotPath = cmd.getVolumePath();
String snapshotDestPath = null;
String snapshotRelPath = null;
String vmName = cmd.getVmName();
KVMStoragePool secondaryStoragePool = null;
try {
Connect conn = LibvirtConnection.getConnection();
secondaryStoragePool = _storagePoolMgr
.getStoragePoolByURI(secondaryStoragePoolUrl);
String ssPmountPath = secondaryStoragePool.getLocalPath();
snapshotRelPath = File.separator + "snapshots" + File.separator
+ dcId + File.separator + accountId + File.separator
+ volumeId;
snapshotDestPath = ssPmountPath + File.separator + "snapshots"
+ File.separator + dcId + File.separator + accountId
+ File.separator + volumeId;
KVMStoragePool primaryPool = _storagePoolMgr.getStoragePool(cmd
.getPrimaryStoragePoolNameLabel());
KVMPhysicalDisk snapshotDisk = primaryPool.getPhysicalDisk(cmd
.getVolumePath());
Script command = new Script(_manageSnapshotPath, _cmdsTimeout,
s_logger);
command.add("-b", snapshotDisk.getPath());
command.add("-n", snapshotName);
command.add("-p", snapshotDestPath);
command.add("-t", snapshotName);
String result = command.execute();
if (result != null) {
s_logger.debug("Failed to backup snaptshot: " + result);
return new BackupSnapshotAnswer(cmd, false, result, null, true);
}
/* Delete the snapshot on primary */
DomainInfo.DomainState state = null;
Domain vm = null;
if (vmName != null) {
try {
vm = getDomain(conn, cmd.getVmName());
state = vm.getInfo().state;
} catch (LibvirtException e) {
}
}
KVMStoragePool primaryStorage = _storagePoolMgr.getStoragePool(cmd
.getPool().getUuid());
if (state == DomainInfo.DomainState.VIR_DOMAIN_RUNNING
&& !primaryStorage.isExternalSnapshot()) {
String vmUuid = vm.getUUIDString();
Object[] args = new Object[] { snapshotName, vmUuid };
String snapshot = SnapshotXML.format(args);
s_logger.debug(snapshot);
DomainSnapshot snap = vm.snapshotLookupByName(snapshotName);
snap.delete(0);
/*
* libvirt on RHEL6 doesn't handle resume event emitted from
* qemu
*/
vm = getDomain(conn, cmd.getVmName());
state = vm.getInfo().state;
if (state == DomainInfo.DomainState.VIR_DOMAIN_PAUSED) {
vm.resume();
}
} else {
command = new Script(_manageSnapshotPath, _cmdsTimeout,
s_logger);
command.add("-d", snapshotDisk.getPath());
command.add("-n", snapshotName);
result = command.execute();
if (result != null) {
s_logger.debug("Failed to backup snapshot: " + result);
return new BackupSnapshotAnswer(cmd, false,
"Failed to backup snapshot: " + result, null, true);
}
}
} catch (LibvirtException e) {
return new BackupSnapshotAnswer(cmd, false, e.toString(), null,
true);
} catch (CloudRuntimeException e) {
return new BackupSnapshotAnswer(cmd, false, e.toString(), null,
true);
} finally {
if (secondaryStoragePool != null) {
secondaryStoragePool.delete();
}
}
return new BackupSnapshotAnswer(cmd, true, null, snapshotRelPath
+ File.separator + snapshotName, true);
}
protected DeleteSnapshotBackupAnswer execute(
final DeleteSnapshotBackupCommand cmd) {
Long dcId = cmd.getDataCenterId();
Long accountId = cmd.getAccountId();
Long volumeId = cmd.getVolumeId();
KVMStoragePool secondaryStoragePool = null;
try {
secondaryStoragePool = _storagePoolMgr.getStoragePoolByURI(cmd
.getSecondaryStorageUrl());
String ssPmountPath = secondaryStoragePool.getLocalPath();
String snapshotDestPath = ssPmountPath + File.separator
+ "snapshots" + File.separator + dcId + File.separator
+ accountId + File.separator + volumeId;
final Script command = new Script(_manageSnapshotPath,
_cmdsTimeout, s_logger);
command.add("-d", snapshotDestPath);
command.add("-n", cmd.getSnapshotName());
command.execute();
} catch (CloudRuntimeException e) {
return new DeleteSnapshotBackupAnswer(cmd, false, e.toString());
} finally {
if (secondaryStoragePool != null) {
secondaryStoragePool.delete();
}
}
return new DeleteSnapshotBackupAnswer(cmd, true, null);
}
protected Answer execute(DeleteSnapshotsDirCommand cmd) {
Long dcId = cmd.getDcId();
Long accountId = cmd.getAccountId();
Long volumeId = cmd.getVolumeId();
KVMStoragePool secondaryStoragePool = null;
try {
secondaryStoragePool = _storagePoolMgr.getStoragePoolByURI(cmd
.getSecondaryStorageUrl());
String ssPmountPath = secondaryStoragePool.getLocalPath();
String snapshotDestPath = ssPmountPath + File.separator
+ "snapshots" + File.separator + dcId + File.separator
+ accountId + File.separator + volumeId;
final Script command = new Script(_manageSnapshotPath,
_cmdsTimeout, s_logger);
command.add("-d", snapshotDestPath);
command.add("-f");
command.execute();
} catch (CloudRuntimeException e) {
return new Answer(cmd, false, e.toString());
} finally {
if (secondaryStoragePool != null) {
secondaryStoragePool.delete();
}
}
return new Answer(cmd, true, null);
}
protected CreateVolumeFromSnapshotAnswer execute(
final CreateVolumeFromSnapshotCommand cmd) {
try {
String snapshotPath = cmd.getSnapshotUuid();
int index = snapshotPath.lastIndexOf("/");
snapshotPath = snapshotPath.substring(0, index);
KVMStoragePool secondaryPool = _storagePoolMgr
.getStoragePoolByURI(cmd.getSecondaryStorageUrl()
+ snapshotPath);
KVMPhysicalDisk snapshot = secondaryPool.getPhysicalDisk(cmd
.getSnapshotName());
String primaryUuid = cmd.getPrimaryStoragePoolNameLabel();
KVMStoragePool primaryPool = _storagePoolMgr
.getStoragePool(primaryUuid);
String volUuid = UUID.randomUUID().toString();
KVMPhysicalDisk disk = _storagePoolMgr.copyPhysicalDisk(snapshot,
volUuid, primaryPool);
return new CreateVolumeFromSnapshotAnswer(cmd, true, "",
disk.getName());
} catch (CloudRuntimeException e) {
return new CreateVolumeFromSnapshotAnswer(cmd, false, e.toString(),
null);
}
}
protected Answer execute(final UpgradeSnapshotCommand cmd) {
return new Answer(cmd, true, "success");
}
protected CreatePrivateTemplateAnswer execute(
final CreatePrivateTemplateFromSnapshotCommand cmd) {
String templateFolder = cmd.getAccountId() + File.separator
+ cmd.getNewTemplateId();
String templateInstallFolder = "template/tmpl/" + templateFolder;
String tmplName = UUID.randomUUID().toString();
String tmplFileName = tmplName + ".qcow2";
KVMStoragePool secondaryPool = null;
KVMStoragePool snapshotPool = null;
try {
String snapshotPath = cmd.getSnapshotUuid();
int index = snapshotPath.lastIndexOf("/");
snapshotPath = snapshotPath.substring(0, index);
snapshotPool = _storagePoolMgr.getStoragePoolByURI(cmd
.getSecondaryStorageUrl() + snapshotPath);
KVMPhysicalDisk snapshot = snapshotPool.getPhysicalDisk(cmd
.getSnapshotName());
secondaryPool = _storagePoolMgr.getStoragePoolByURI(cmd
.getSecondaryStorageUrl());
String templatePath = secondaryPool.getLocalPath() + File.separator
+ templateInstallFolder;
_storage.mkdirs(templatePath);
String tmplPath = templateInstallFolder + File.separator
+ tmplFileName;
Script command = new Script(_createTmplPath, _cmdsTimeout, s_logger);
command.add("-t", templatePath);
command.add("-n", tmplFileName);
command.add("-f", snapshot.getPath());
command.execute();
Map<String, Object> params = new HashMap<String, Object>();
params.put(StorageLayer.InstanceConfigKey, _storage);
Processor qcow2Processor = new QCOW2Processor();
qcow2Processor.configure("QCOW2 Processor", params);
FormatInfo info = qcow2Processor.process(templatePath, null,
tmplName);
TemplateLocation loc = new TemplateLocation(_storage, templatePath);
loc.create(1, true, tmplName);
loc.addFormat(info);
loc.save();
return new CreatePrivateTemplateAnswer(cmd, true, "", tmplPath,
info.virtualSize, info.size, tmplName, info.format);
} catch (ConfigurationException e) {
return new CreatePrivateTemplateAnswer(cmd, false, e.getMessage());
} catch (InternalErrorException e) {
return new CreatePrivateTemplateAnswer(cmd, false, e.getMessage());
} catch (IOException e) {
return new CreatePrivateTemplateAnswer(cmd, false, e.getMessage());
} catch (CloudRuntimeException e) {
return new CreatePrivateTemplateAnswer(cmd, false, e.getMessage());
} finally {
if (secondaryPool != null) {
secondaryPool.delete();
}
if (snapshotPool != null) {
snapshotPool.delete();
}
}
}
protected GetStorageStatsAnswer execute(final GetStorageStatsCommand cmd) {
try {
KVMStoragePool sp = _storagePoolMgr.getStoragePool(cmd
.getStorageId());
return new GetStorageStatsAnswer(cmd, sp.getCapacity(),
sp.getUsed());
} catch (CloudRuntimeException e) {
return new GetStorageStatsAnswer(cmd, e.toString());
}
}
protected CreatePrivateTemplateAnswer execute(
CreatePrivateTemplateFromVolumeCommand cmd) {
String secondaryStorageURL = cmd.getSecondaryStorageUrl();
KVMStoragePool secondaryStorage = null;
try {
Connect conn = LibvirtConnection.getConnection();
String templateFolder = cmd.getAccountId() + File.separator
+ cmd.getTemplateId() + File.separator;
String templateInstallFolder = "/template/tmpl/" + templateFolder;
secondaryStorage = _storagePoolMgr
.getStoragePoolByURI(secondaryStorageURL);
KVMStoragePool primary = _storagePoolMgr.getStoragePool(cmd
.getPrimaryStoragePoolNameLabel());
KVMPhysicalDisk disk = primary.getPhysicalDisk(cmd.getVolumePath());
String tmpltPath = secondaryStorage.getLocalPath() + File.separator
+ templateInstallFolder;
_storage.mkdirs(tmpltPath);
if (primary.getType() != StoragePoolType.RBD) {
Script command = new Script(_createTmplPath, _cmdsTimeout, s_logger);
command.add("-f", disk.getPath());
command.add("-t", tmpltPath);
command.add("-n", cmd.getUniqueName() + ".qcow2");
String result = command.execute();
if (result != null) {
s_logger.debug("failed to create template: " + result);
return new CreatePrivateTemplateAnswer(cmd, false, result);
}
} else {
s_logger.debug("Converting RBD disk " + disk.getPath() + " into template " + cmd.getUniqueName());
Script.runSimpleBashScript("qemu-img convert"
+ " -f raw -O qcow2 "
+ KVMPhysicalDisk.RBDStringBuilder(primary.getSourceHost(),
primary.getSourcePort(),
primary.getAuthUserName(),
primary.getAuthSecret(),
disk.getPath())
+ " " + tmpltPath + "/" + cmd.getUniqueName() + ".qcow2");
File templateProp = new File(tmpltPath + "/template.properties");
if (!templateProp.exists()) {
templateProp.createNewFile();
}
String templateContent = "filename=" + cmd.getUniqueName() + ".qcow2" + System.getProperty("line.separator");
DateFormat dateFormat = new SimpleDateFormat("MM_dd_yyyy");
Date date = new Date();
templateContent += "snapshot.name=" + dateFormat.format(date) + System.getProperty("line.separator");
FileOutputStream templFo = new FileOutputStream(templateProp);
templFo.write(templateContent.getBytes());
templFo.flush();
templFo.close();
}
Map<String, Object> params = new HashMap<String, Object>();
params.put(StorageLayer.InstanceConfigKey, _storage);
Processor qcow2Processor = new QCOW2Processor();
qcow2Processor.configure("QCOW2 Processor", params);
FormatInfo info = qcow2Processor.process(tmpltPath, null,
cmd.getUniqueName());
TemplateLocation loc = new TemplateLocation(_storage, tmpltPath);
loc.create(1, true, cmd.getUniqueName());
loc.addFormat(info);
loc.save();
return new CreatePrivateTemplateAnswer(cmd, true, null,
templateInstallFolder + cmd.getUniqueName() + ".qcow2",
info.virtualSize, info.size, cmd.getUniqueName(),
ImageFormat.QCOW2);
} catch (LibvirtException e) {
s_logger.debug("Failed to get secondary storage pool: "
+ e.toString());
return new CreatePrivateTemplateAnswer(cmd, false, e.toString());
} catch (InternalErrorException e) {
return new CreatePrivateTemplateAnswer(cmd, false, e.toString());
} catch (IOException e) {
return new CreatePrivateTemplateAnswer(cmd, false, e.toString());
} catch (ConfigurationException e) {
return new CreatePrivateTemplateAnswer(cmd, false, e.toString());
} catch (CloudRuntimeException e) {
return new CreatePrivateTemplateAnswer(cmd, false, e.toString());
} finally {
if (secondaryStorage != null) {
secondaryStorage.delete();
}
}
}
protected PrimaryStorageDownloadAnswer execute(
final PrimaryStorageDownloadCommand cmd) {
String tmplturl = cmd.getUrl();
int index = tmplturl.lastIndexOf("/");
String mountpoint = tmplturl.substring(0, index);
String tmpltname = null;
if (index < tmplturl.length() - 1) {
tmpltname = tmplturl.substring(index + 1);
}
KVMPhysicalDisk tmplVol = null;
KVMStoragePool secondaryPool = null;
try {
secondaryPool = _storagePoolMgr.getStoragePoolByURI(mountpoint);
/* Get template vol */
if (tmpltname == null) {
secondaryPool.refresh();
List<KVMPhysicalDisk> disks = secondaryPool.listPhysicalDisks();
if (disks == null || disks.isEmpty()) {
return new PrimaryStorageDownloadAnswer(
"Failed to get volumes from pool: "
+ secondaryPool.getUuid());
}
for (KVMPhysicalDisk disk : disks) {
if (disk.getName().endsWith("qcow2")) {
tmplVol = disk;
break;
}
}
if (tmplVol == null) {
return new PrimaryStorageDownloadAnswer(
"Failed to get template from pool: "
+ secondaryPool.getUuid());
}
} else {
tmplVol = secondaryPool.getPhysicalDisk(tmpltname);
}
/* Copy volume to primary storage */
KVMStoragePool primaryPool = _storagePoolMgr.getStoragePool(cmd
.getPoolUuid());
KVMPhysicalDisk primaryVol = _storagePoolMgr.copyPhysicalDisk(
tmplVol, UUID.randomUUID().toString(), primaryPool);
return new PrimaryStorageDownloadAnswer(primaryVol.getName(),
primaryVol.getSize());
} catch (CloudRuntimeException e) {
return new PrimaryStorageDownloadAnswer(e.toString());
} finally {
if (secondaryPool != null) {
secondaryPool.delete();
}
}
}
protected Answer execute(CreateStoragePoolCommand cmd) {
return new Answer(cmd, true, "success");
}
protected Answer execute(ModifyStoragePoolCommand cmd) {
KVMStoragePool storagepool = _storagePoolMgr.createStoragePool(cmd
.getPool().getUuid(), cmd.getPool().getHost(), cmd.getPool().getPort(),
cmd.getPool().getPath(), cmd.getPool().getUserInfo(), cmd.getPool().getType());
if (storagepool == null) {
return new Answer(cmd, false, " Failed to create storage pool");
}
Map<String, TemplateInfo> tInfo = new HashMap<String, TemplateInfo>();
ModifyStoragePoolAnswer answer = new ModifyStoragePoolAnswer(cmd,
storagepool.getCapacity(), storagepool.getUsed(), tInfo);
return answer;
}
private Answer execute(SecurityGroupRulesCmd cmd) {
String vif = null;
String brname = null;
try {
Connect conn = LibvirtConnection.getConnection();
List<InterfaceDef> nics = getInterfaces(conn, cmd.getVmName());
vif = nics.get(0).getDevName();
brname = nics.get(0).getBrName();
} catch (LibvirtException e) {
return new SecurityGroupRuleAnswer(cmd, false, e.toString());
}
boolean result = add_network_rules(cmd.getVmName(),
Long.toString(cmd.getVmId()), cmd.getGuestIp(),
cmd.getSignature(), Long.toString(cmd.getSeqNum()),
cmd.getGuestMac(), cmd.stringifyRules(), vif, brname);
if (!result) {
s_logger.warn("Failed to program network rules for vm "
+ cmd.getVmName());
return new SecurityGroupRuleAnswer(cmd, false,
"programming network rules failed");
} else {
s_logger.debug("Programmed network rules for vm " + cmd.getVmName()
+ " guestIp=" + cmd.getGuestIp() + ",ingress numrules="
+ cmd.getIngressRuleSet().length + ",egress numrules="
+ cmd.getEgressRuleSet().length);
return new SecurityGroupRuleAnswer(cmd);
}
}
private Answer execute(CleanupNetworkRulesCmd cmd) {
boolean result = cleanup_rules();
return new Answer(cmd, result, "");
}
protected GetVncPortAnswer execute(GetVncPortCommand cmd) {
try {
Connect conn = LibvirtConnection.getConnection();
Integer vncPort = getVncPort(conn, cmd.getName());
return new GetVncPortAnswer(cmd, _privateIp, 5900 + vncPort);
} catch (Exception e) {
return new GetVncPortAnswer(cmd, e.toString());
}
}
protected Answer execute(final CheckConsoleProxyLoadCommand cmd) {
return executeProxyLoadScan(cmd, cmd.getProxyVmId(),
cmd.getProxyVmName(), cmd.getProxyManagementIp(),
cmd.getProxyCmdPort());
}
protected Answer execute(final WatchConsoleProxyLoadCommand cmd) {
return executeProxyLoadScan(cmd, cmd.getProxyVmId(),
cmd.getProxyVmName(), cmd.getProxyManagementIp(),
cmd.getProxyCmdPort());
}
protected MaintainAnswer execute(MaintainCommand cmd) {
return new MaintainAnswer(cmd);
}
private Answer executeProxyLoadScan(final Command cmd,
final long proxyVmId, final String proxyVmName,
final String proxyManagementIp, final int cmdPort) {
String result = null;
final StringBuffer sb = new StringBuffer();
sb.append("http://").append(proxyManagementIp).append(":" + cmdPort)
.append("/cmd/getstatus");
boolean success = true;
try {
final URL url = new URL(sb.toString());
final URLConnection conn = url.openConnection();
final InputStream is = conn.getInputStream();
final BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
final StringBuilder sb2 = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb2.append(line + "\n");
}
result = sb2.toString();
} catch (final IOException e) {
success = false;
} finally {
try {
is.close();
} catch (final IOException e) {
s_logger.warn("Exception when closing , console proxy address : "
+ proxyManagementIp);
success = false;
}
}
} catch (final IOException e) {
s_logger.warn("Unable to open console proxy command port url, console proxy address : "
+ proxyManagementIp);
success = false;
}
return new ConsoleProxyLoadAnswer(cmd, proxyVmId, proxyVmName, success,
result);
}
private Answer execute(AttachIsoCommand cmd) {
try {
Connect conn = LibvirtConnection.getConnection();
attachOrDetachISO(conn, cmd.getVmName(), cmd.getIsoPath(),
cmd.isAttach());
} catch (LibvirtException e) {
return new Answer(cmd, false, e.toString());
} catch (URISyntaxException e) {
return new Answer(cmd, false, e.toString());
} catch (InternalErrorException e) {
return new Answer(cmd, false, e.toString());
}
return new Answer(cmd);
}
private AttachVolumeAnswer execute(AttachVolumeCommand cmd) {
try {
Connect conn = LibvirtConnection.getConnection();
KVMStoragePool primary = _storagePoolMgr.getStoragePool(cmd
.getPoolUuid());
KVMPhysicalDisk disk = primary.getPhysicalDisk(cmd.getVolumePath());
attachOrDetachDisk(conn, cmd.getAttach(), cmd.getVmName(), disk,
cmd.getDeviceId().intValue());
} catch (LibvirtException e) {
return new AttachVolumeAnswer(cmd, e.toString());
} catch (InternalErrorException e) {
return new AttachVolumeAnswer(cmd, e.toString());
}
return new AttachVolumeAnswer(cmd, cmd.getDeviceId());
}
private Answer execute(ReadyCommand cmd) {
return new ReadyAnswer(cmd);
}
protected State convertToState(DomainInfo.DomainState ps) {
final State state = s_statesTable.get(ps);
return state == null ? State.Unknown : state;
}
protected State getVmState(Connect conn, final String vmName) {
int retry = 3;
Domain vms = null;
while (retry-- > 0) {
try {
vms = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
.getBytes()));
State s = convertToState(vms.getInfo().state);
return s;
} catch (final LibvirtException e) {
s_logger.warn("Can't get vm state " + vmName + e.getMessage()
+ "retry:" + retry);
} catch (Exception e) {
s_logger.warn("Can't get vm state " + vmName + e.getMessage()
+ "retry:" + retry);
} finally {
try {
if (vms != null) {
vms.free();
}
} catch (final LibvirtException e) {
}
}
}
return State.Stopped;
}
private Answer execute(CheckVirtualMachineCommand cmd) {
try {
Connect conn = LibvirtConnection.getConnection();
final State state = getVmState(conn, cmd.getVmName());
Integer vncPort = null;
if (state == State.Running) {
vncPort = getVncPort(conn, cmd.getVmName());
synchronized (_vms) {
_vms.put(cmd.getVmName(), State.Running);
}
}
return new CheckVirtualMachineAnswer(cmd, state, vncPort);
} catch (LibvirtException e) {
return new CheckVirtualMachineAnswer(cmd, e.getMessage());
}
}
private Answer execute(PingTestCommand cmd) {
String result = null;
final String computingHostIp = cmd.getComputingHostIp(); // TODO, split
// the
// command
// into 2
// types
if (computingHostIp != null) {
result = doPingTest(computingHostIp);
} else if (cmd.getRouterIp() != null && cmd.getPrivateIp() != null) {
result = doPingTest(cmd.getRouterIp(), cmd.getPrivateIp());
} else {
return new Answer(cmd, false, "routerip and private ip is null");
}
if (result != null) {
return new Answer(cmd, false, result);
}
return new Answer(cmd);
}
private String doPingTest(final String computingHostIp) {
final Script command = new Script(_pingTestPath, 10000, s_logger);
command.add("-h", computingHostIp);
return command.execute();
}
private String doPingTest(final String domRIp, final String vmIp) {
final Script command = new Script(_pingTestPath, 10000, s_logger);
command.add("-i", domRIp);
command.add("-p", vmIp);
return command.execute();
}
private synchronized Answer execute(MigrateCommand cmd) {
String vmName = cmd.getVmName();
State state = null;
String result = null;
synchronized (_vms) {
state = _vms.get(vmName);
_vms.put(vmName, State.Stopping);
}
Domain dm = null;
Connect dconn = null;
Domain destDomain = null;
Connect conn = null;
try {
conn = LibvirtConnection.getConnection();
dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
.getBytes()));
dconn = new Connect("qemu+tcp://" + cmd.getDestinationIp()
+ "/system");
/*
* Hard code lm flags: VIR_MIGRATE_LIVE(1<<0) and
* VIR_MIGRATE_PERSIST_DEST(1<<3)
*/
destDomain = dm.migrate(dconn, (1 << 0) | (1 << 3), vmName, "tcp:"
+ cmd.getDestinationIp(), _migrateSpeed);
} catch (LibvirtException e) {
s_logger.debug("Can't migrate domain: " + e.getMessage());
result = e.getMessage();
} catch (Exception e) {
s_logger.debug("Can't migrate domain: " + e.getMessage());
result = e.getMessage();
} finally {
try {
if (dm != null) {
dm.free();
}
if (dconn != null) {
dconn.close();
}
if (destDomain != null) {
destDomain.free();
}
} catch (final LibvirtException e) {
}
}
if (result != null) {
synchronized (_vms) {
_vms.put(vmName, state);
}
} else {
destroy_network_rules_for_vm(conn, vmName);
cleanupVM(conn, vmName,
getVnetId(VirtualMachineName.getVnet(vmName)));
}
return new MigrateAnswer(cmd, result == null, result, null);
}
private synchronized Answer execute(PrepareForMigrationCommand cmd) {
VirtualMachineTO vm = cmd.getVirtualMachine();
if (s_logger.isDebugEnabled()) {
s_logger.debug("Preparing host for migrating " + vm);
}
NicTO[] nics = vm.getNics();
try {
Connect conn = LibvirtConnection.getConnection();
for (NicTO nic : nics) {
String vlanId = null;
if (nic.getBroadcastType() == BroadcastDomainType.Vlan) {
URI broadcastUri = nic.getBroadcastUri();
vlanId = broadcastUri.getHost();
}
if (nic.getType() == TrafficType.Guest) {
if (nic.getBroadcastType() == BroadcastDomainType.Vlan
&& !vlanId.equalsIgnoreCase("untagged")) {
createVlanBr(vlanId, _pifs.first());
}
} else if (nic.getType() == TrafficType.Control) {
/* Make sure the network is still there */
createControlNetwork();
} else if (nic.getType() == TrafficType.Public) {
if (nic.getBroadcastType() == BroadcastDomainType.Vlan
&& !vlanId.equalsIgnoreCase("untagged")) {
createVlanBr(vlanId, _pifs.second());
}
}
}
/* setup disks, e.g for iso */
VolumeTO[] volumes = vm.getDisks();
for (VolumeTO volume : volumes) {
if (volume.getType() == Volume.Type.ISO) {
getVolumePath(conn, volume);
}
}
synchronized (_vms) {
_vms.put(vm.getName(), State.Migrating);
}
return new PrepareForMigrationAnswer(cmd);
} catch (LibvirtException e) {
return new PrepareForMigrationAnswer(cmd, e.toString());
} catch (InternalErrorException e) {
return new PrepareForMigrationAnswer(cmd, e.toString());
} catch (URISyntaxException e) {
return new PrepareForMigrationAnswer(cmd, e.toString());
}
}
public void createVnet(String vnetId, String pif)
throws InternalErrorException {
final Script command = new Script(_modifyVlanPath, _timeout, s_logger);
command.add("-v", vnetId);
command.add("-p", pif);
command.add("-o", "add");
final String result = command.execute();
if (result != null) {
throw new InternalErrorException("Failed to create vnet " + vnetId
+ ": " + result);
}
}
private Answer execute(CheckHealthCommand cmd) {
return new CheckHealthAnswer(cmd, true);
}
private Answer execute(GetHostStatsCommand cmd) {
final Script cpuScript = new Script("/bin/bash", s_logger);
cpuScript.add("-c");
cpuScript
.add("idle=$(top -b -n 1|grep Cpu\\(s\\):|cut -d% -f4|cut -d, -f2);echo $idle");
final OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser();
String result = cpuScript.execute(parser);
if (result != null) {
s_logger.debug("Unable to get the host CPU state: " + result);
return new Answer(cmd, false, result);
}
double cpuUtil = (100.0D - Double.parseDouble(parser.getLine()));
long freeMem = 0;
final Script memScript = new Script("/bin/bash", s_logger);
memScript.add("-c");
memScript
.add("freeMem=$(free|grep cache:|awk '{print $4}');echo $freeMem");
final OutputInterpreter.OneLineParser Memparser = new OutputInterpreter.OneLineParser();
result = memScript.execute(Memparser);
if (result != null) {
s_logger.debug("Unable to get the host Mem state: " + result);
return new Answer(cmd, false, result);
}
freeMem = Long.parseLong(Memparser.getLine());
Script totalMem = new Script("/bin/bash", s_logger);
totalMem.add("-c");
totalMem.add("free|grep Mem:|awk '{print $2}'");
final OutputInterpreter.OneLineParser totMemparser = new OutputInterpreter.OneLineParser();
result = totalMem.execute(totMemparser);
if (result != null) {
s_logger.debug("Unable to get the host Mem state: " + result);
return new Answer(cmd, false, result);
}
long totMem = Long.parseLong(totMemparser.getLine());
Pair<Double, Double> nicStats = getNicStats(_publicBridgeName);
HostStatsEntry hostStats = new HostStatsEntry(cmd.getHostId(), cpuUtil,
nicStats.first() / 1000, nicStats.second() / 1000, "host",
totMem, freeMem, 0, 0);
return new GetHostStatsAnswer(cmd, hostStats);
}
protected String networkUsage(final String privateIpAddress,
final String option, final String vif) {
Script getUsage = new Script(_networkUsagePath, s_logger);
if (option.equals("get")) {
getUsage.add("-g");
} else if (option.equals("create")) {
getUsage.add("-c");
} else if (option.equals("reset")) {
getUsage.add("-r");
} else if (option.equals("addVif")) {
getUsage.add("-a", vif);
} else if (option.equals("deleteVif")) {
getUsage.add("-d", vif);
}
getUsage.add("-i", privateIpAddress);
final OutputInterpreter.OneLineParser usageParser = new OutputInterpreter.OneLineParser();
String result = getUsage.execute(usageParser);
if (result != null) {
s_logger.debug("Failed to execute networkUsage:" + result);
return null;
}
return usageParser.getLine();
}
protected long[] getNetworkStats(String privateIP) {
String result = networkUsage(privateIP, "get", null);
long[] stats = new long[2];
if (result != null) {
String[] splitResult = result.split(":");
int i = 0;
while (i < splitResult.length - 1) {
stats[0] += (new Long(splitResult[i++])).longValue();
stats[1] += (new Long(splitResult[i++])).longValue();
}
}
return stats;
}
private Answer execute(NetworkUsageCommand cmd) {
if (cmd.getOption() != null && cmd.getOption().equals("create")) {
String result = networkUsage(cmd.getPrivateIP(), "create", null);
NetworkUsageAnswer answer = new NetworkUsageAnswer(cmd, result, 0L,
0L);
return answer;
}
long[] stats = getNetworkStats(cmd.getPrivateIP());
NetworkUsageAnswer answer = new NetworkUsageAnswer(cmd, "", stats[0],
stats[1]);
return answer;
}
private Answer execute(RebootCommand cmd) {
synchronized (_vms) {
_vms.put(cmd.getVmName(), State.Starting);
}
try {
Connect conn = LibvirtConnection.getConnection();
final String result = rebootVM(conn, cmd.getVmName());
if (result == null) {
Integer vncPort = null;
try {
vncPort = getVncPort(conn, cmd.getVmName());
} catch (Exception e) {
}
get_rule_logs_for_vms();
return new RebootAnswer(cmd, null, vncPort);
} else {
return new RebootAnswer(cmd, result, false);
}
} catch (LibvirtException e) {
return new RebootAnswer(cmd, e.getMessage(), false);
} finally {
synchronized (_vms) {
_vms.put(cmd.getVmName(), State.Running);
}
}
}
protected Answer execute(RebootRouterCommand cmd) {
RebootAnswer answer = (RebootAnswer) execute((RebootCommand) cmd);
String result = _virtRouterResource.connect(cmd.getPrivateIpAddress());
if (result == null) {
networkUsage(cmd.getPrivateIpAddress(), "create", null);
return answer;
} else {
return new Answer(cmd, false, result);
}
}
protected GetVmStatsAnswer execute(GetVmStatsCommand cmd) {
List<String> vmNames = cmd.getVmNames();
try {
HashMap<String, VmStatsEntry> vmStatsNameMap = new HashMap<String, VmStatsEntry>();
Connect conn = LibvirtConnection.getConnection();
for (String vmName : vmNames) {
VmStatsEntry statEntry = getVmStat(conn, vmName);
if (statEntry == null) {
continue;
}
vmStatsNameMap.put(vmName, statEntry);
}
return new GetVmStatsAnswer(cmd, vmStatsNameMap);
} catch (LibvirtException e) {
s_logger.debug("Can't get vm stats: " + e.toString());
return new GetVmStatsAnswer(cmd, null);
}
}
protected Answer execute(StopCommand cmd) {
final String vmName = cmd.getVmName();
State state = null;
synchronized (_vms) {
state = _vms.get(vmName);
_vms.put(vmName, State.Stopping);
}
try {
Connect conn = LibvirtConnection.getConnection();
List<DiskDef> disks = getDisks(conn, vmName);
destroy_network_rules_for_vm(conn, vmName);
String result = stopVM(conn, vmName, defineOps.UNDEFINE_VM);
if (result == null) {
for (DiskDef disk : disks) {
if (disk.getDeviceType() == DiskDef.deviceType.CDROM
&& disk.getDiskPath() != null)
cleanupDisk(conn, disk);
}
}
final String result2 = cleanupVnet(conn, cmd.getVnet());
if (result != null && result2 != null) {
result = result2 + result;
}
state = State.Stopped;
return new StopAnswer(cmd, result, 0, true);
} catch (LibvirtException e) {
return new StopAnswer(cmd, e.getMessage(), false);
} finally {
synchronized (_vms) {
if (state != null) {
_vms.put(vmName, state);
} else {
_vms.remove(vmName);
}
}
}
}
protected Answer execute(ModifySshKeysCommand cmd) {
File sshKeysDir = new File(_SSHKEYSPATH);
String result = null;
if (!sshKeysDir.exists()) {
sshKeysDir.mkdir();
// Change permissions for the 600
Script script = new Script("chmod", _timeout, s_logger);
script.add("600", _SSHKEYSPATH);
script.execute();
}
File pubKeyFile = new File(_SSHPUBKEYPATH);
if (!pubKeyFile.exists()) {
try {
pubKeyFile.createNewFile();
} catch (IOException e) {
result = "Failed to create file: " + e.toString();
s_logger.debug(result);
}
}
if (pubKeyFile.exists()) {
String pubKey = cmd.getPubKey();
try {
FileOutputStream pubkStream = new FileOutputStream(pubKeyFile);
pubkStream.write(pubKey.getBytes());
pubkStream.close();
} catch (FileNotFoundException e) {
result = "File" + _SSHPUBKEYPATH + "is not found:"
+ e.toString();
s_logger.debug(result);
} catch (IOException e) {
result = "Write file " + _SSHPUBKEYPATH + ":" + e.toString();
s_logger.debug(result);
}
}
File prvKeyFile = new File(_SSHPRVKEYPATH);
if (!prvKeyFile.exists()) {
try {
prvKeyFile.createNewFile();
} catch (IOException e) {
result = "Failed to create file: " + e.toString();
s_logger.debug(result);
}
}
if (prvKeyFile.exists()) {
String prvKey = cmd.getPrvKey();
try {
FileOutputStream prvKStream = new FileOutputStream(prvKeyFile);
prvKStream.write(prvKey.getBytes());
prvKStream.close();
} catch (FileNotFoundException e) {
result = "File" + _SSHPRVKEYPATH + "is not found:"
+ e.toString();
s_logger.debug(result);
} catch (IOException e) {
result = "Write file " + _SSHPRVKEYPATH + ":" + e.toString();
s_logger.debug(result);
}
Script script = new Script("chmod", _timeout, s_logger);
script.add("600", _SSHPRVKEYPATH);
script.execute();
}
if (result != null) {
return new Answer(cmd, false, result);
} else {
return new Answer(cmd, true, null);
}
}
protected void handleVmStartFailure(Connect conn, String vmName,
LibvirtVMDef vm) {
if (vm != null && vm.getDevices() != null) {
cleanupVMNetworks(conn, vm.getDevices().getInterfaces());
}
}
protected LibvirtVMDef createVMFromSpec(VirtualMachineTO vmTO) {
LibvirtVMDef vm = new LibvirtVMDef();
vm.setHvsType(_hypervisorType);
vm.setDomainName(vmTO.getName());
vm.setDomUUID(UUID.nameUUIDFromBytes(vmTO.getName().getBytes())
.toString());
vm.setDomDescription(vmTO.getOs());
GuestDef guest = new GuestDef();
guest.setGuestType(GuestDef.guestType.KVM);
guest.setGuestArch(vmTO.getArch());
guest.setMachineType("pc");
guest.setBootOrder(GuestDef.bootOrder.CDROM);
guest.setBootOrder(GuestDef.bootOrder.HARDISK);
vm.addComp(guest);
GuestResourceDef grd = new GuestResourceDef();
grd.setMemorySize(vmTO.getMinRam() / 1024);
grd.setVcpuNum(vmTO.getCpus());
vm.addComp(grd);
CpuTuneDef ctd = new CpuTuneDef();
ctd.setShares(vmTO.getCpus() * vmTO.getSpeed());
vm.addComp(ctd);
FeaturesDef features = new FeaturesDef();
features.addFeatures("pae");
features.addFeatures("apic");
features.addFeatures("acpi");
vm.addComp(features);
TermPolicy term = new TermPolicy();
term.setCrashPolicy("destroy");
term.setPowerOffPolicy("destroy");
term.setRebootPolicy("restart");
vm.addComp(term);
ClockDef clock = new ClockDef();
if (vmTO.getOs().startsWith("Windows")) {
clock.setClockOffset(ClockDef.ClockOffset.LOCALTIME);
clock.setTimer("rtc", "catchup", null);
}
vm.addComp(clock);
DevicesDef devices = new DevicesDef();
devices.setEmulatorPath(_hypervisorPath);
SerialDef serial = new SerialDef("pty", null, (short) 0);
devices.addDevice(serial);
ConsoleDef console = new ConsoleDef("pty", null, null, (short) 0);
devices.addDevice(console);
GraphicDef grap = new GraphicDef("vnc", (short) 0, true, vmTO.getVncAddr(), null,
null);
devices.addDevice(grap);
InputDef input = new InputDef("tablet", "usb");
devices.addDevice(input);
vm.addComp(devices);
return vm;
}
protected void createVifs(VirtualMachineTO vmSpec,
LibvirtVMDef vm) throws InternalErrorException, LibvirtException {
NicTO[] nics = vmSpec.getNics();
for (int i = 0; i < nics.length; i++) {
for (NicTO nic : vmSpec.getNics()) {
if (nic.getDeviceId() == i) {
createVif(vm, nic);
}
}
}
}
protected synchronized StartAnswer execute(StartCommand cmd) {
VirtualMachineTO vmSpec = cmd.getVirtualMachine();
vmSpec.setVncAddr(cmd.getHostIp());
String vmName = vmSpec.getName();
LibvirtVMDef vm = null;
State state = State.Stopped;
Connect conn = null;
try {
conn = LibvirtConnection.getConnection();
synchronized (_vms) {
_vms.put(vmName, State.Starting);
}
vm = createVMFromSpec(vmSpec);
createVbd(conn, vmSpec, vmName, vm);
createVifs(vmSpec, vm);
s_logger.debug("starting " + vmName + ": " + vm.toString());
startDomain(conn, vmName, vm.toString());
NicTO[] nics = vmSpec.getNics();
for (NicTO nic : nics) {
if (nic.getIsolationUri() != null
&& nic.getIsolationUri().getScheme()
.equalsIgnoreCase(IsolationType.Ec2.toString())) {
if (vmSpec.getType() != VirtualMachine.Type.User) {
default_network_rules_for_systemvm(conn, vmName);
break;
} else {
default_network_rules(conn, vmName, nic, vmSpec.getId());
}
}
}
state = State.Running;
return new StartAnswer(cmd);
} catch (Exception e) {
s_logger.warn("Exception ", e);
if (conn != null) {
handleVmStartFailure(conn, vmName, vm);
}
return new StartAnswer(cmd, e.getMessage());
} finally {
synchronized (_vms) {
if (state != State.Stopped) {
_vms.put(vmName, state);
} else {
_vms.remove(vmName);
}
}
}
}
private String getVolumePath(Connect conn, VolumeTO volume)
throws LibvirtException, URISyntaxException {
if (volume.getType() == Volume.Type.ISO && volume.getPath() != null) {
String isoPath = volume.getPath();
int index = isoPath.lastIndexOf("/");
String path = isoPath.substring(0, index);
String name = isoPath.substring(index + 1);
KVMStoragePool secondaryPool = _storagePoolMgr
.getStoragePoolByURI(path);
KVMPhysicalDisk isoVol = secondaryPool.getPhysicalDisk(name);
return isoVol.getPath();
} else {
return volume.getPath();
}
}
protected void createVbd(Connect conn, VirtualMachineTO vmSpec,
String vmName, LibvirtVMDef vm) throws InternalErrorException,
LibvirtException, URISyntaxException {
List<VolumeTO> disks = Arrays.asList(vmSpec.getDisks());
Collections.sort(disks, new Comparator<VolumeTO>() {
@Override
public int compare(VolumeTO arg0, VolumeTO arg1) {
return arg0.getDeviceId() > arg1.getDeviceId() ? 1 : -1;
}
});
for (VolumeTO volume : disks) {
KVMPhysicalDisk physicalDisk = null;
KVMStoragePool pool = null;
if (volume.getType() == Volume.Type.ISO && volume.getPath() != null) {
String volPath = volume.getPath();
int index = volPath.lastIndexOf("/");
String volDir = volPath.substring(0, index);
String volName = volPath.substring(index + 1);
KVMStoragePool secondaryStorage = _storagePoolMgr
.getStoragePoolByURI(volDir);
physicalDisk = secondaryStorage.getPhysicalDisk(volName);
} else if (volume.getType() != Volume.Type.ISO) {
pool = _storagePoolMgr.getStoragePool(volume.getPoolUuid());
physicalDisk = pool.getPhysicalDisk(volume.getPath());
}
String volPath = null;
if (physicalDisk != null) {
volPath = physicalDisk.getPath();
}
DiskDef.diskBus diskBusType = getGuestDiskModel(vmSpec.getOs());
DiskDef disk = new DiskDef();
if (volume.getType() == Volume.Type.ISO) {
if (volPath == null) {
/* Add iso as placeholder */
disk.defISODisk(null);
} else {
disk.defISODisk(volPath);
}
} else {
int devId = (int) volume.getDeviceId();
if (pool.getType() == StoragePoolType.RBD) {
/*
For RBD pools we use the secret mechanism in libvirt.
We store the secret under the UUID of the pool, that's why
we pass the pool's UUID as the authSecret
*/
disk.defNetworkBasedDisk(physicalDisk.getPath().replace("rbd:", ""), pool.getSourceHost(), pool.getSourcePort(),
pool.getAuthUserName(), pool.getUuid(),
devId, diskBusType, diskProtocol.RBD);
} else if (volume.getType() == Volume.Type.DATADISK) {
disk.defFileBasedDisk(physicalDisk.getPath(), devId,
DiskDef.diskBus.VIRTIO,
DiskDef.diskFmtType.QCOW2);
} else {
disk.defFileBasedDisk(physicalDisk.getPath(), devId,
diskBusType, DiskDef.diskFmtType.QCOW2);
}
}
vm.getDevices().addDevice(disk);
}
if (vmSpec.getType() != VirtualMachine.Type.User) {
if (_sysvmISOPath != null) {
DiskDef iso = new DiskDef();
iso.defISODisk(_sysvmISOPath);
vm.getDevices().addDevice(iso);
}
createPatchVbd(conn, vmName, vm, vmSpec);
}
}
private VolumeTO getVolume(VirtualMachineTO vmSpec, Volume.Type type) {
VolumeTO volumes[] = vmSpec.getDisks();
for (VolumeTO volume : volumes) {
if (volume.getType() == type) {
return volume;
}
}
return null;
}
private void createPatchVbd(Connect conn, String vmName, LibvirtVMDef vm,
VirtualMachineTO vmSpec) throws LibvirtException,
InternalErrorException {
List<DiskDef> disks = vm.getDevices().getDisks();
DiskDef rootDisk = disks.get(0);
VolumeTO rootVol = getVolume(vmSpec, Volume.Type.ROOT);
KVMStoragePool pool = _storagePoolMgr.getStoragePool(rootVol
.getPoolUuid());
KVMPhysicalDisk disk = pool.createPhysicalDisk(UUID.randomUUID()
.toString(), KVMPhysicalDisk.PhysicalDiskFormat.RAW,
10L * 1024 * 1024);
/* Format/create fs on this disk */
final Script command = new Script(_createvmPath, _timeout, s_logger);
command.add("-f", disk.getPath());
String result = command.execute();
if (result != null) {
s_logger.debug("Failed to create data disk: " + result);
throw new InternalErrorException("Failed to create data disk: "
+ result);
}
String datadiskPath = disk.getPath();
/* add patch disk */
DiskDef patchDisk = new DiskDef();
patchDisk.defFileBasedDisk(datadiskPath, 1, rootDisk.getBusType(),
DiskDef.diskFmtType.RAW);
disks.add(patchDisk);
String bootArgs = vmSpec.getBootArgs();
patchSystemVm(bootArgs, datadiskPath, vmName);
}
private String createVlanBr(String vlanId, String nic)
throws InternalErrorException {
String brName = setVnetBrName(vlanId);
createVnet(vlanId, nic);
return brName;
}
private InterfaceDef createVif(NicTO nic,
InterfaceDef.nicModel model) throws InternalErrorException,
LibvirtException {
InterfaceDef intf = new InterfaceDef();
String vlanId = null;
if (nic.getBroadcastType() == BroadcastDomainType.Vlan) {
URI broadcastUri = nic.getBroadcastUri();
vlanId = broadcastUri.getHost();
}
if (nic.getType() == TrafficType.Guest) {
if (nic.getBroadcastType() == BroadcastDomainType.Vlan
&& !vlanId.equalsIgnoreCase("untagged")) {
String brName = createVlanBr(vlanId, _pifs.first());
intf.defBridgeNet(brName, null, nic.getMac(), model);
} else {
intf.defBridgeNet(_guestBridgeName, null, nic.getMac(), model);
}
} else if (nic.getType() == TrafficType.Control) {
/* Make sure the network is still there */
createControlNetwork();
intf.defBridgeNet(_linkLocalBridgeName, null, nic.getMac(), model);
} else if (nic.getType() == TrafficType.Public) {
if (nic.getBroadcastType() == BroadcastDomainType.Vlan
&& !vlanId.equalsIgnoreCase("untagged")) {
String brName = createVlanBr(vlanId, _pifs.second());
intf.defBridgeNet(brName, null, nic.getMac(), model);
} else {
intf.defBridgeNet(_publicBridgeName, null, nic.getMac(), model);
}
} else if (nic.getType() == TrafficType.Management) {
intf.defBridgeNet(_privBridgeName, null, nic.getMac(), model);
} else if (nic.getType() == TrafficType.Storage) {
String storageBrName = nic.getName() == null ? _privBridgeName
: nic.getName();
intf.defBridgeNet(storageBrName, null, nic.getMac(), model);
}
return intf;
}
private void createVif(LibvirtVMDef vm, NicTO nic)
throws InternalErrorException, LibvirtException {
vm.getDevices().addDevice(
createVif(nic, getGuestNicModel(vm.getGuestOSType())));
}
protected CheckSshAnswer execute(CheckSshCommand cmd) {
String vmName = cmd.getName();
String privateIp = cmd.getIp();
int cmdPort = cmd.getPort();
if (s_logger.isDebugEnabled()) {
s_logger.debug("Ping command port, " + privateIp + ":" + cmdPort);
}
try {
String result = _virtRouterResource.connect(privateIp, cmdPort);
if (result != null) {
return new CheckSshAnswer(cmd, "Can not ping System vm "
+ vmName + "due to:" + result);
}
} catch (Exception e) {
return new CheckSshAnswer(cmd, e);
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Ping command port succeeded for vm " + vmName);
}
return new CheckSshAnswer(cmd);
}
private boolean cleanupDisk(Connect conn, DiskDef disk) {
// need to umount secondary storage
String path = disk.getDiskPath();
String poolUuid = null;
if (path != null) {
String[] token = path.split("/");
if (token.length > 3) {
poolUuid = token[2];
}
}
if (poolUuid == null) {
return true;
}
try {
KVMStoragePool pool = _storagePoolMgr.getStoragePool(poolUuid);
if (pool != null) {
pool.delete();
}
return true;
} catch (CloudRuntimeException e) {
return false;
}
}
protected synchronized String attachOrDetachISO(Connect conn,
String vmName, String isoPath, boolean isAttach)
throws LibvirtException, URISyntaxException, InternalErrorException {
String isoXml = null;
if (isoPath != null && isAttach) {
int index = isoPath.lastIndexOf("/");
String path = isoPath.substring(0, index);
String name = isoPath.substring(index + 1);
KVMStoragePool secondaryPool = _storagePoolMgr
.getStoragePoolByURI(path);
KVMPhysicalDisk isoVol = secondaryPool.getPhysicalDisk(name);
isoPath = isoVol.getPath();
DiskDef iso = new DiskDef();
iso.defISODisk(isoPath);
isoXml = iso.toString();
} else {
DiskDef iso = new DiskDef();
iso.defISODisk(null);
isoXml = iso.toString();
}
List<DiskDef> disks = getDisks(conn, vmName);
String result = attachOrDetachDevice(conn, true, vmName, isoXml);
if (result == null && !isAttach) {
for (DiskDef disk : disks) {
if (disk.getDeviceType() == DiskDef.deviceType.CDROM) {
cleanupDisk(conn, disk);
}
}
}
return result;
}
protected synchronized String attachOrDetachDisk(Connect conn,
boolean attach, String vmName, KVMPhysicalDisk attachingDisk,
int devId) throws LibvirtException, InternalErrorException {
List<DiskDef> disks = null;
Domain dm = null;
DiskDef diskdef = null;
try {
if (!attach) {
dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
.getBytes()));
LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser();
String xml = dm.getXMLDesc(0);
parser.parseDomainXML(xml);
disks = parser.getDisks();
for (DiskDef disk : disks) {
String file = disk.getDiskPath();
if (file != null
&& file.equalsIgnoreCase(attachingDisk.getPath())) {
diskdef = disk;
break;
}
}
if (diskdef == null) {
throw new InternalErrorException("disk: "
+ attachingDisk.getPath()
+ " is not attached before");
}
} else {
diskdef = new DiskDef();
if (attachingDisk.getFormat() == PhysicalDiskFormat.QCOW2) {
diskdef.defFileBasedDisk(attachingDisk.getPath(), devId,
DiskDef.diskBus.VIRTIO, DiskDef.diskFmtType.QCOW2);
} else if (attachingDisk.getFormat() == PhysicalDiskFormat.RAW) {
diskdef.defBlockBasedDisk(attachingDisk.getPath(), devId,
DiskDef.diskBus.VIRTIO);
}
}
String xml = diskdef.toString();
return attachOrDetachDevice(conn, attach, vmName, xml);
} finally {
if (dm != null) {
dm.free();
}
}
}
protected synchronized String attachOrDetachDevice(Connect conn,
boolean attach, String vmName, String xml) throws LibvirtException,
InternalErrorException {
Domain dm = null;
try {
dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes((vmName
.getBytes())));
if (attach) {
s_logger.debug("Attaching device: " + xml);
dm.attachDevice(xml);
} else {
s_logger.debug("Detaching device: " + xml);
dm.detachDevice(xml);
}
} catch (LibvirtException e) {
if (attach) {
s_logger.warn("Failed to attach device to " + vmName + ": "
+ e.getMessage());
} else {
s_logger.warn("Failed to detach device from " + vmName + ": "
+ e.getMessage());
}
throw e;
} catch (Exception e) {
throw new InternalErrorException(e.toString());
} finally {
if (dm != null) {
try {
dm.free();
} catch (LibvirtException l) {
}
}
}
return null;
}
@Override
public PingCommand getCurrentStatus(long id) {
final HashMap<String, State> newStates = sync();
if (!_can_bridge_firewall) {
return new PingRoutingCommand(com.cloud.host.Host.Type.Routing, id,
newStates);
} else {
HashMap<String, Pair<Long, Long>> nwGrpStates = syncNetworkGroups(id);
return new PingRoutingWithNwGroupsCommand(getType(), id, newStates,
nwGrpStates);
}
}
@Override
public Type getType() {
return Type.Routing;
}
private Map<String, String> getVersionStrings() {
final Script command = new Script(_versionstringpath, _timeout,
s_logger);
KeyValueInterpreter kvi = new KeyValueInterpreter();
String result = command.execute(kvi);
if (result == null) {
return kvi.getKeyValues();
} else {
return new HashMap<String, String>(1);
}
}
@Override
public StartupCommand[] initialize() {
Map<String, State> changes = null;
synchronized (_vms) {
_vms.clear();
changes = sync();
}
final List<Object> info = getHostInfo();
final StartupRoutingCommand cmd = new StartupRoutingCommand(
(Integer) info.get(0), (Long) info.get(1), (Long) info.get(2),
(Long) info.get(4), (String) info.get(3), HypervisorType.KVM,
RouterPrivateIpStrategy.HostLocal);
cmd.setStateChanges(changes);
fillNetworkInformation(cmd);
_privateIp = cmd.getPrivateIpAddress();
cmd.getHostDetails().putAll(getVersionStrings());
cmd.setPool(_pool);
cmd.setCluster(_clusterId);
cmd.setGatewayIpAddress(_localGateway);
StartupStorageCommand sscmd = null;
try {
KVMStoragePool localStoragePool = _storagePoolMgr
.createStoragePool(_localStorageUUID, "localhost", -1,
_localStoragePath, "", StoragePoolType.Filesystem);
com.cloud.agent.api.StoragePoolInfo pi = new com.cloud.agent.api.StoragePoolInfo(
localStoragePool.getUuid(), cmd.getPrivateIpAddress(),
_localStoragePath, _localStoragePath,
StoragePoolType.Filesystem, localStoragePool.getCapacity(),
localStoragePool.getUsed());
sscmd = new StartupStorageCommand();
sscmd.setPoolInfo(pi);
sscmd.setGuid(pi.getUuid());
sscmd.setDataCenter(_dcId);
sscmd.setResourceType(Storage.StorageResourceType.STORAGE_POOL);
} catch (CloudRuntimeException e) {
}
if (sscmd != null) {
return new StartupCommand[] { cmd, sscmd };
} else {
return new StartupCommand[] { cmd };
}
}
protected HashMap<String, State> sync() {
HashMap<String, State> newStates;
HashMap<String, State> oldStates = null;
final HashMap<String, State> changes = new HashMap<String, State>();
synchronized (_vms) {
newStates = getAllVms();
if (newStates == null) {
s_logger.debug("Unable to get the vm states so no state sync at this point.");
return changes;
}
oldStates = new HashMap<String, State>(_vms.size());
oldStates.putAll(_vms);
for (final Map.Entry<String, State> entry : newStates.entrySet()) {
final String vm = entry.getKey();
State newState = entry.getValue();
final State oldState = oldStates.remove(vm);
if (newState == State.Stopped && oldState != State.Stopping
&& oldState != null && oldState != State.Stopped) {
newState = getRealPowerState(vm);
}
if (s_logger.isTraceEnabled()) {
s_logger.trace("VM " + vm + ": libvirt has state "
+ newState + " and we have state "
+ (oldState != null ? oldState.toString() : "null"));
}
if (vm.startsWith("migrating")) {
s_logger.debug("Migration detected. Skipping");
continue;
}
if (oldState == null) {
_vms.put(vm, newState);
s_logger.debug("Detecting a new state but couldn't find a old state so adding it to the changes: "
+ vm);
changes.put(vm, newState);
} else if (oldState == State.Starting) {
if (newState == State.Running) {
_vms.put(vm, newState);
} else if (newState == State.Stopped) {
s_logger.debug("Ignoring vm " + vm
+ " because of a lag in starting the vm.");
}
} else if (oldState == State.Migrating) {
if (newState == State.Running) {
s_logger.debug("Detected that an migrating VM is now running: "
+ vm);
_vms.put(vm, newState);
}
} else if (oldState == State.Stopping) {
if (newState == State.Stopped) {
_vms.put(vm, newState);
} else if (newState == State.Running) {
s_logger.debug("Ignoring vm " + vm
+ " because of a lag in stopping the vm. ");
}
} else if (oldState != newState) {
_vms.put(vm, newState);
if (newState == State.Stopped) {
if (_vmsKilled.remove(vm)) {
s_logger.debug("VM " + vm
+ " has been killed for storage. ");
newState = State.Error;
}
}
changes.put(vm, newState);
}
}
for (final Map.Entry<String, State> entry : oldStates.entrySet()) {
final String vm = entry.getKey();
final State oldState = entry.getValue();
if (s_logger.isTraceEnabled()) {
s_logger.trace("VM "
+ vm
+ " is now missing from libvirt so reporting stopped");
}
if (oldState == State.Stopping) {
s_logger.debug("Ignoring VM " + vm
+ " in transition state stopping.");
_vms.remove(vm);
} else if (oldState == State.Starting) {
s_logger.debug("Ignoring VM " + vm
+ " in transition state starting.");
} else if (oldState == State.Stopped) {
_vms.remove(vm);
} else if (oldState == State.Migrating) {
s_logger.debug("Ignoring VM " + vm + " in migrating state.");
} else {
_vms.remove(vm);
State state = State.Stopped;
if (_vmsKilled.remove(entry.getKey())) {
s_logger.debug("VM " + vm
+ " has been killed by storage monitor");
state = State.Error;
}
changes.put(entry.getKey(), state);
}
}
}
return changes;
}
protected State getRealPowerState(String vm) {
int i = 0;
s_logger.trace("Checking on the HALTED State");
Domain dm = null;
for (; i < 5; i++) {
try {
Connect conn = LibvirtConnection.getConnection();
dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vm
.getBytes()));
DomainInfo.DomainState vps = dm.getInfo().state;
if (vps != null
&& vps != DomainInfo.DomainState.VIR_DOMAIN_SHUTOFF
&& vps != DomainInfo.DomainState.VIR_DOMAIN_NOSTATE) {
return convertToState(vps);
}
} catch (final LibvirtException e) {
s_logger.trace(e.getMessage());
} catch (Exception e) {
s_logger.trace(e.getMessage());
} finally {
try {
if (dm != null) {
dm.free();
}
} catch (final LibvirtException e) {
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
return State.Stopped;
}
protected List<String> getAllVmNames(Connect conn) {
ArrayList<String> la = new ArrayList<String>();
try {
final String names[] = conn.listDefinedDomains();
for (int i = 0; i < names.length; i++) {
la.add(names[i]);
}
} catch (final LibvirtException e) {
s_logger.warn("Failed to list Defined domains", e);
}
int[] ids = null;
try {
ids = conn.listDomains();
} catch (final LibvirtException e) {
s_logger.warn("Failed to list domains", e);
return la;
}
Domain dm = null;
for (int i = 0; i < ids.length; i++) {
try {
dm = conn.domainLookupByID(ids[i]);
la.add(dm.getName());
} catch (final LibvirtException e) {
s_logger.warn("Unable to get vms", e);
} finally {
try {
if (dm != null) {
dm.free();
}
} catch (final LibvirtException e) {
}
}
}
return la;
}
private HashMap<String, State> getAllVms() {
final HashMap<String, State> vmStates = new HashMap<String, State>();
String[] vms = null;
int[] ids = null;
Connect conn = null;
try {
conn = LibvirtConnection.getConnection();
} catch (LibvirtException e) {
s_logger.debug("Failed to get connection: " + e.getMessage());
return vmStates;
}
try {
ids = conn.listDomains();
} catch (final LibvirtException e) {
s_logger.warn("Unable to listDomains", e);
return null;
}
try {
vms = conn.listDefinedDomains();
} catch (final LibvirtException e) {
s_logger.warn("Unable to listDomains", e);
return null;
}
Domain dm = null;
for (int i = 0; i < ids.length; i++) {
try {
dm = conn.domainLookupByID(ids[i]);
DomainInfo.DomainState ps = dm.getInfo().state;
final State state = convertToState(ps);
s_logger.trace("VM " + dm.getName() + ": powerstate = " + ps
+ "; vm state=" + state.toString());
String vmName = dm.getName();
vmStates.put(vmName, state);
} catch (final LibvirtException e) {
s_logger.warn("Unable to get vms", e);
} finally {
try {
if (dm != null) {
dm.free();
}
} catch (LibvirtException e) {
}
}
}
for (int i = 0; i < vms.length; i++) {
try {
dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vms[i]
.getBytes()));
DomainInfo.DomainState ps = dm.getInfo().state;
final State state = convertToState(ps);
String vmName = dm.getName();
s_logger.trace("VM " + vmName + ": powerstate = " + ps
+ "; vm state=" + state.toString());
vmStates.put(vmName, state);
} catch (final LibvirtException e) {
s_logger.warn("Unable to get vms", e);
} catch (Exception e) {
s_logger.warn("Unable to get vms", e);
} finally {
try {
if (dm != null) {
dm.free();
}
} catch (LibvirtException e) {
}
}
}
return vmStates;
}
protected List<Object> getHostInfo() {
final ArrayList<Object> info = new ArrayList<Object>();
long speed = 0;
long cpus = 0;
long ram = 0;
String cap = null;
try {
Connect conn = LibvirtConnection.getConnection();
final NodeInfo hosts = conn.nodeInfo();
boolean result = false;
try {
BufferedReader in = new BufferedReader(
new FileReader(
"/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq"));
speed = Long.parseLong(in.readLine()) / 1000;
result = true;
} catch (FileNotFoundException e) {
} catch (IOException e) {
} catch (NumberFormatException e) {
}
if (!result) {
speed = hosts.mhz;
}
cpus = hosts.cpus;
ram = hosts.memory * 1024L;
LibvirtCapXMLParser parser = new LibvirtCapXMLParser();
parser.parseCapabilitiesXML(conn.getCapabilities());
ArrayList<String> oss = parser.getGuestOsType();
for (String s : oss) {
/*
* Even host supports guest os type more than hvm, we only
* report hvm to management server
*/
if (s.equalsIgnoreCase("hvm")) {
cap = "hvm";
}
}
} catch (LibvirtException e) {
}
if (isSnapshotSupported()) {
cap = cap + ",snapshot";
}
info.add((int) cpus);
info.add(speed);
info.add(ram);
info.add(cap);
long dom0ram = Math.min(ram / 10, 768 * 1024 * 1024L);// save a maximum
// of 10% of
// system ram or
// 768M
dom0ram = Math.max(dom0ram, _dom0MinMem);
info.add(dom0ram);
s_logger.debug("cpus=" + cpus + ", speed=" + speed + ", ram=" + ram
+ ", dom0ram=" + dom0ram);
return info;
}
protected void cleanupVM(Connect conn, final String vmName,
final String vnet) {
s_logger.debug("Trying to cleanup the vnet: " + vnet);
if (vnet != null) {
cleanupVnet(conn, vnet);
}
_vmStats.remove(vmName);
}
protected String rebootVM(Connect conn, String vmName) {
Domain dm = null;
String msg = null;
try {
dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
.getBytes()));
String vmDef = dm.getXMLDesc(0);
s_logger.debug(vmDef);
msg = stopVM(conn, vmName, defineOps.UNDEFINE_VM);
msg = startDomain(conn, vmName, vmDef);
return null;
} catch (LibvirtException e) {
s_logger.warn("Failed to create vm", e);
msg = e.getMessage();
} catch (Exception e) {
s_logger.warn("Failed to create vm", e);
msg = e.getMessage();
} finally {
try {
if (dm != null) {
dm.free();
}
} catch (LibvirtException e) {
}
}
return msg;
}
protected String stopVM(Connect conn, String vmName, defineOps df) {
DomainInfo.DomainState state = null;
Domain dm = null;
s_logger.debug("Try to stop the vm at first");
String ret = stopVM(conn, vmName, false);
if (ret == Script.ERR_TIMEOUT) {
ret = stopVM(conn, vmName, true);
} else if (ret != null) {
/*
* There is a race condition between libvirt and qemu: libvirt
* listens on qemu's monitor fd. If qemu is shutdown, while libvirt
* is reading on the fd, then libvirt will report an error.
*/
/* Retry 3 times, to make sure we can get the vm's status */
for (int i = 0; i < 3; i++) {
try {
dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
.getBytes()));
state = dm.getInfo().state;
break;
} catch (LibvirtException e) {
s_logger.debug("Failed to get vm status:" + e.getMessage());
} catch (Exception e) {
s_logger.debug("Failed to get vm status:" + e.getMessage());
} finally {
try {
if (dm != null) {
dm.free();
}
} catch (LibvirtException l) {
}
}
}
if (state == null) {
s_logger.debug("Can't get vm's status, assume it's dead already");
return null;
}
if (state != DomainInfo.DomainState.VIR_DOMAIN_SHUTOFF) {
s_logger.debug("Try to destroy the vm");
ret = stopVM(conn, vmName, true);
if (ret != null) {
return ret;
}
}
}
if (df == defineOps.UNDEFINE_VM) {
try {
dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
.getBytes()));
dm.undefine();
} catch (LibvirtException e) {
} finally {
try {
if (dm != null) {
dm.free();
}
} catch (LibvirtException l) {
}
}
}
return null;
}
protected String stopVM(Connect conn, String vmName, boolean force) {
Domain dm = null;
try {
dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
.getBytes()));
if (force) {
if (dm.getInfo().state != DomainInfo.DomainState.VIR_DOMAIN_SHUTOFF) {
dm.destroy();
}
} else {
if (dm.getInfo().state == DomainInfo.DomainState.VIR_DOMAIN_SHUTOFF) {
return null;
}
dm.shutdown();
int retry = _stopTimeout / 2000;
/* Wait for the domain gets into shutoff state */
while ((dm.getInfo().state != DomainInfo.DomainState.VIR_DOMAIN_SHUTOFF)
&& (retry >= 0)) {
Thread.sleep(2000);
retry--;
}
if (retry < 0) {
s_logger.warn("Timed out waiting for domain " + vmName
+ " to shutdown gracefully");
return Script.ERR_TIMEOUT;
}
}
} catch (LibvirtException e) {
s_logger.debug("Failed to stop VM :" + vmName + " :", e);
return e.getMessage();
} catch (InterruptedException ie) {
s_logger.debug("Interrupted sleep");
return ie.getMessage();
} catch (Exception e) {
s_logger.debug("Failed to stop VM :" + vmName + " :", e);
return e.getMessage();
} finally {
try {
if (dm != null) {
dm.free();
}
} catch (LibvirtException e) {
}
}
return null;
}
public synchronized String cleanupVnet(Connect conn, final String vnetId) {
// VNC proxy VMs do not have vnet
if (vnetId == null || vnetId.isEmpty()
|| isDirectAttachedNetwork(vnetId)) {
return null;
}
final List<String> names = getAllVmNames(conn);
if (!names.isEmpty()) {
for (final String name : names) {
if (VirtualMachineName.getVnet(name).equals(vnetId)) {
return null; // Can't remove the vnet yet.
}
}
}
final Script command = new Script(_modifyVlanPath, _timeout, s_logger);
command.add("-o", "delete");
command.add("-v", vnetId);
return command.execute();
}
protected Integer getVncPort(Connect conn, String vmName)
throws LibvirtException {
LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser();
Domain dm = null;
try {
dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
.getBytes()));
String xmlDesc = dm.getXMLDesc(0);
parser.parseDomainXML(xmlDesc);
return parser.getVncPort();
} finally {
try {
if (dm != null) {
dm.free();
}
} catch (LibvirtException l) {
}
}
}
private boolean IsHVMEnabled(Connect conn) {
LibvirtCapXMLParser parser = new LibvirtCapXMLParser();
try {
parser.parseCapabilitiesXML(conn.getCapabilities());
ArrayList<String> osTypes = parser.getGuestOsType();
for (String o : osTypes) {
if (o.equalsIgnoreCase("hvm")) {
return true;
}
}
} catch (LibvirtException e) {
}
return false;
}
private String getHypervisorPath(Connect conn) {
LibvirtCapXMLParser parser = new LibvirtCapXMLParser();
try {
parser.parseCapabilitiesXML(conn.getCapabilities());
} catch (LibvirtException e) {
s_logger.debug(e.getMessage());
}
return parser.getEmulator();
}
private String getGuestType(Connect conn, String vmName) {
LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser();
Domain dm = null;
try {
dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
.getBytes()));
String xmlDesc = dm.getXMLDesc(0);
parser.parseDomainXML(xmlDesc);
return parser.getDescription();
} catch (LibvirtException e) {
return null;
} catch (Exception e) {
return null;
} finally {
try {
if (dm != null) {
dm.free();
}
} catch (LibvirtException l) {
}
}
}
private boolean isGuestPVEnabled(String guestOS) {
if (guestOS == null) {
return false;
}
String guestOSName = KVMGuestOsMapper.getGuestOsName(guestOS);
if (guestOS.startsWith("Ubuntu")
|| guestOSName.startsWith("Fedora 13")
|| guestOSName.startsWith("Fedora 12")
|| guestOSName.startsWith("Fedora 11")
|| guestOSName.startsWith("Fedora 10")
|| guestOSName.startsWith("Fedora 9")
|| guestOSName.startsWith("CentOS 5.3")
|| guestOSName.startsWith("CentOS 5.4")
|| guestOSName.startsWith("CentOS 5.5")
|| guestOS.startsWith("CentOS")
|| guestOS.startsWith("Fedora")
|| guestOSName.startsWith("Red Hat Enterprise Linux 5.3")
|| guestOSName.startsWith("Red Hat Enterprise Linux 5.4")
|| guestOSName.startsWith("Red Hat Enterprise Linux 5.5")
|| guestOSName.startsWith("Red Hat Enterprise Linux 6")
|| guestOS.startsWith("Debian GNU/Linux")
|| guestOSName.startsWith("Other PV")) {
return true;
} else {
return false;
}
}
public boolean isCentosHost() {
if (_hvVersion <= 9) {
return true;
} else {
return false;
}
}
private InterfaceDef.nicModel getGuestNicModel(String guestOSType) {
if (isGuestPVEnabled(guestOSType)) {
return InterfaceDef.nicModel.VIRTIO;
} else {
return InterfaceDef.nicModel.E1000;
}
}
private DiskDef.diskBus getGuestDiskModel(String guestOSType) {
if (isGuestPVEnabled(guestOSType)) {
return DiskDef.diskBus.VIRTIO;
} else {
return DiskDef.diskBus.IDE;
}
}
private String setVnetBrName(String vnetId) {
return "cloudVirBr" + vnetId;
}
private String getVnetIdFromBrName(String vnetBrName) {
return vnetBrName.replaceAll("cloudVirBr", "");
}
private void cleanupVMNetworks(Connect conn, List<InterfaceDef> nics) {
for (InterfaceDef nic : nics) {
if (nic.getHostNetType() == hostNicType.VNET) {
cleanupVnet(conn, getVnetIdFromBrName(nic.getBrName()));
}
}
}
private Domain getDomain(Connect conn, String vmName)
throws LibvirtException {
return conn
.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName.getBytes()));
}
protected List<InterfaceDef> getInterfaces(Connect conn, String vmName) {
LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser();
Domain dm = null;
try {
dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
.getBytes()));
parser.parseDomainXML(dm.getXMLDesc(0));
return parser.getInterfaces();
} catch (LibvirtException e) {
s_logger.debug("Failed to get dom xml: " + e.toString());
return new ArrayList<InterfaceDef>();
} catch (Exception e) {
s_logger.debug("Failed to get dom xml: " + e.toString());
return new ArrayList<InterfaceDef>();
} finally {
try {
if (dm != null) {
dm.free();
}
} catch (LibvirtException e) {
}
}
}
protected List<DiskDef> getDisks(Connect conn, String vmName) {
LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser();
Domain dm = null;
try {
dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
.getBytes()));
parser.parseDomainXML(dm.getXMLDesc(0));
return parser.getDisks();
} catch (LibvirtException e) {
s_logger.debug("Failed to get dom xml: " + e.toString());
return new ArrayList<DiskDef>();
} catch (Exception e) {
s_logger.debug("Failed to get dom xml: " + e.toString());
return new ArrayList<DiskDef>();
} finally {
try {
if (dm != null) {
dm.free();
}
} catch (LibvirtException e) {
}
}
}
private String executeBashScript(String script) {
Script command = new Script("/bin/bash", _timeout, s_logger);
command.add("-c");
command.add(script);
return command.execute();
}
private String executeBashScript(String script, OutputInterpreter parser) {
Script command = new Script("/bin/bash", _timeout, s_logger);
command.add("-c");
command.add(script);
return command.execute(parser);
}
private void deletExitingLinkLocalRoutTable(String linkLocalBr) {
Script command = new Script("/bin/bash", _timeout);
command.add("-c");
command.add("ip route | grep " + NetUtils.getLinkLocalCIDR());
OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser();
String result = command.execute(parser);
boolean foundLinkLocalBr = false;
if (result == null && parser.getLines() != null) {
String[] lines = parser.getLines().split("\\n");
for (String line : lines) {
String[] tokens = line.split(" ");
if (!tokens[2].equalsIgnoreCase(linkLocalBr)) {
Script.runSimpleBashScript("ip route del "
+ NetUtils.getLinkLocalCIDR());
} else {
foundLinkLocalBr = true;
}
}
}
if (!foundLinkLocalBr) {
Script.runSimpleBashScript("ip route add "
+ NetUtils.getLinkLocalCIDR() + " dev " + linkLocalBr
+ " src " + NetUtils.getLinkLocalGateway());
}
}
private class vmStats {
long _usedTime;
long _tx;
long _rx;
Calendar _timestamp;
}
private VmStatsEntry getVmStat(Connect conn, String vmName)
throws LibvirtException {
Domain dm = null;
try {
dm = getDomain(conn, vmName);
DomainInfo info = dm.getInfo();
VmStatsEntry stats = new VmStatsEntry();
stats.setNumCPUs(info.nrVirtCpu);
stats.setEntityType("vm");
/* get cpu utilization */
vmStats oldStats = null;
Calendar now = Calendar.getInstance();
oldStats = _vmStats.get(vmName);
long elapsedTime = 0;
if (oldStats != null) {
elapsedTime = now.getTimeInMillis()
- oldStats._timestamp.getTimeInMillis();
double utilization = (info.cpuTime - oldStats._usedTime)
/ ((double) elapsedTime * 1000000);
NodeInfo node = conn.nodeInfo();
utilization = utilization / node.cpus;
stats.setCPUUtilization(utilization * 100);
}
/* get network stats */
List<InterfaceDef> vifs = getInterfaces(conn, vmName);
long rx = 0;
long tx = 0;
for (InterfaceDef vif : vifs) {
DomainInterfaceStats ifStats = dm.interfaceStats(vif
.getDevName());
rx += ifStats.rx_bytes;
tx += ifStats.tx_bytes;
}
if (oldStats != null) {
long deltarx = rx - oldStats._rx;
if (deltarx > 0)
stats.setNetworkReadKBs(deltarx / 1000);
long deltatx = tx - oldStats._tx;
if (deltatx > 0)
stats.setNetworkWriteKBs(deltatx / 1000);
}
vmStats newStat = new vmStats();
newStat._usedTime = info.cpuTime;
newStat._rx = rx;
newStat._tx = tx;
newStat._timestamp = now;
_vmStats.put(vmName, newStat);
return stats;
} finally {
if (dm != null) {
dm.free();
}
}
}
private boolean can_bridge_firewall(String prvNic) {
Script cmd = new Script(_securityGroupPath, _timeout, s_logger);
cmd.add("can_bridge_firewall");
cmd.add(prvNic);
String result = cmd.execute();
if (result != null) {
return false;
}
return true;
}
protected boolean destroy_network_rules_for_vm(Connect conn, String vmName) {
if (!_can_bridge_firewall) {
return false;
}
String vif = null;
List<InterfaceDef> intfs = getInterfaces(conn, vmName);
if (intfs.size() > 0) {
InterfaceDef intf = intfs.get(0);
vif = intf.getDevName();
}
Script cmd = new Script(_securityGroupPath, _timeout, s_logger);
cmd.add("destroy_network_rules_for_vm");
cmd.add("--vmname", vmName);
if (vif != null) {
cmd.add("--vif", vif);
}
String result = cmd.execute();
if (result != null) {
return false;
}
return true;
}
protected boolean default_network_rules(Connect conn, String vmName,
NicTO nic, Long vmId) {
if (!_can_bridge_firewall) {
return false;
}
List<InterfaceDef> intfs = getInterfaces(conn, vmName);
if (intfs.size() < nic.getDeviceId()) {
return false;
}
InterfaceDef intf = intfs.get(nic.getDeviceId());
String brname = intf.getBrName();
String vif = intf.getDevName();
Script cmd = new Script(_securityGroupPath, _timeout, s_logger);
cmd.add("default_network_rules");
cmd.add("--vmname", vmName);
cmd.add("--vmid", vmId.toString());
if (nic.getIp() != null) {
cmd.add("--vmip", nic.getIp());
}
cmd.add("--vmmac", nic.getMac());
cmd.add("--vif", vif);
cmd.add("--brname", brname);
String result = cmd.execute();
if (result != null) {
return false;
}
return true;
}
protected boolean post_default_network_rules(Connect conn, String vmName,
NicTO nic, Long vmId, InetAddress dhcpServerIp, String hostIp,
String hostMacAddr) {
if (!_can_bridge_firewall) {
return false;
}
List<InterfaceDef> intfs = getInterfaces(conn, vmName);
if (intfs.size() < nic.getDeviceId()) {
return false;
}
InterfaceDef intf = intfs.get(nic.getDeviceId());
String brname = intf.getBrName();
String vif = intf.getDevName();
Script cmd = new Script(_securityGroupPath, _timeout, s_logger);
cmd.add("post_default_network_rules");
cmd.add("--vmname", vmName);
cmd.add("--vmid", vmId.toString());
cmd.add("--vmip", nic.getIp());
cmd.add("--vmmac", nic.getMac());
cmd.add("--vif", vif);
cmd.add("--brname", brname);
if (dhcpServerIp != null)
cmd.add("--dhcpSvr", dhcpServerIp.getHostAddress());
cmd.add("--hostIp", hostIp);
cmd.add("--hostMacAddr", hostMacAddr);
String result = cmd.execute();
if (result != null) {
return false;
}
return true;
}
protected boolean default_network_rules_for_systemvm(Connect conn,
String vmName) {
if (!_can_bridge_firewall) {
return false;
}
Script cmd = new Script(_securityGroupPath, _timeout, s_logger);
cmd.add("default_network_rules_systemvm");
cmd.add("--vmname", vmName);
cmd.add("--localbrname", _linkLocalBridgeName);
String result = cmd.execute();
if (result != null) {
return false;
}
return true;
}
private boolean add_network_rules(String vmName, String vmId,
String guestIP, String sig, String seq, String mac, String rules,
String vif, String brname) {
if (!_can_bridge_firewall) {
return false;
}
String newRules = rules.replace(" ", ";");
Script cmd = new Script(_securityGroupPath, _timeout, s_logger);
cmd.add("add_network_rules");
cmd.add("--vmname", vmName);
cmd.add("--vmid", vmId);
cmd.add("--vmip", guestIP);
cmd.add("--sig", sig);
cmd.add("--seq", seq);
cmd.add("--vmmac", mac);
cmd.add("--vif", vif);
cmd.add("--brname", brname);
if (rules != null) {
cmd.add("--rules", newRules);
}
String result = cmd.execute();
if (result != null) {
return false;
}
return true;
}
private boolean cleanup_rules() {
if (!_can_bridge_firewall) {
return false;
}
Script cmd = new Script(_securityGroupPath, _timeout, s_logger);
cmd.add("cleanup_rules");
String result = cmd.execute();
if (result != null) {
return false;
}
return true;
}
private String get_rule_logs_for_vms() {
Script cmd = new Script(_securityGroupPath, _timeout, s_logger);
cmd.add("get_rule_logs_for_vms");
OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser();
String result = cmd.execute(parser);
if (result == null) {
return parser.getLine();
}
return null;
}
private HashMap<String, Pair<Long, Long>> syncNetworkGroups(long id) {
HashMap<String, Pair<Long, Long>> states = new HashMap<String, Pair<Long, Long>>();
String result = get_rule_logs_for_vms();
s_logger.trace("syncNetworkGroups: id=" + id + " got: " + result);
String[] rulelogs = result != null ? result.split(";") : new String[0];
for (String rulesforvm : rulelogs) {
String[] log = rulesforvm.split(",");
if (log.length != 6) {
continue;
}
try {
states.put(log[0], new Pair<Long, Long>(Long.parseLong(log[1]),
Long.parseLong(log[5])));
} catch (NumberFormatException nfe) {
states.put(log[0], new Pair<Long, Long>(-1L, -1L));
}
}
return states;
}
/* online snapshot supported by enhanced qemu-kvm */
private boolean isSnapshotSupported() {
String result = executeBashScript("qemu-img --help|grep convert |grep snapshot");
if (result != null) {
return false;
} else {
return true;
}
}
private Pair<Double, Double> getNicStats(String nicName) {
double rx = 0.0;
OutputInterpreter.OneLineParser rxParser = new OutputInterpreter.OneLineParser();
String result = executeBashScript("cat /sys/class/net/" + nicName
+ "/statistics/rx_bytes", rxParser);
if (result == null && rxParser.getLine() != null) {
rx = Double.parseDouble(rxParser.getLine());
}
double tx = 0.0;
OutputInterpreter.OneLineParser txParser = new OutputInterpreter.OneLineParser();
result = executeBashScript("cat /sys/class/net/" + nicName
+ "/statistics/tx_bytes", txParser);
if (result == null && txParser.getLine() != null) {
tx = Double.parseDouble(txParser.getLine());
}
return new Pair<Double, Double>(rx, tx);
}
private void createControlNetwork() throws LibvirtException {
_virtRouterResource.createControlNetwork(_linkLocalBridgeName);
}
private Answer execute(NetworkRulesSystemVmCommand cmd) {
boolean success = false;
Connect conn;
try {
conn = LibvirtConnection.getConnection();
success = default_network_rules_for_systemvm(conn, cmd.getVmName());
} catch (LibvirtException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return new Answer(cmd, success, "");
}
}
| plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java | // 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.hypervisor.kvm.resource;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import javax.ejb.Local;
import javax.naming.ConfigurationException;
import org.apache.log4j.Logger;
import org.libvirt.Connect;
import org.libvirt.Domain;
import org.libvirt.DomainInfo;
import org.libvirt.DomainInterfaceStats;
import org.libvirt.DomainSnapshot;
import org.libvirt.LibvirtException;
import org.libvirt.NodeInfo;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.AttachIsoCommand;
import com.cloud.agent.api.AttachVolumeAnswer;
import com.cloud.agent.api.AttachVolumeCommand;
import com.cloud.agent.api.BackupSnapshotAnswer;
import com.cloud.agent.api.BackupSnapshotCommand;
import com.cloud.agent.api.CheckHealthAnswer;
import com.cloud.agent.api.CheckHealthCommand;
import com.cloud.agent.api.CheckNetworkAnswer;
import com.cloud.agent.api.CheckNetworkCommand;
import com.cloud.agent.api.CheckStateCommand;
import com.cloud.agent.api.CheckVirtualMachineAnswer;
import com.cloud.agent.api.CheckVirtualMachineCommand;
import com.cloud.agent.api.CleanupNetworkRulesCmd;
import com.cloud.agent.api.Command;
import com.cloud.agent.api.CreatePrivateTemplateFromSnapshotCommand;
import com.cloud.agent.api.CreatePrivateTemplateFromVolumeCommand;
import com.cloud.agent.api.CreateStoragePoolCommand;
import com.cloud.agent.api.CreateVolumeFromSnapshotAnswer;
import com.cloud.agent.api.CreateVolumeFromSnapshotCommand;
import com.cloud.agent.api.DeleteSnapshotBackupAnswer;
import com.cloud.agent.api.DeleteSnapshotBackupCommand;
import com.cloud.agent.api.DeleteSnapshotsDirCommand;
import com.cloud.agent.api.DeleteStoragePoolCommand;
import com.cloud.agent.api.FenceAnswer;
import com.cloud.agent.api.FenceCommand;
import com.cloud.agent.api.GetHostStatsAnswer;
import com.cloud.agent.api.GetHostStatsCommand;
import com.cloud.agent.api.GetStorageStatsAnswer;
import com.cloud.agent.api.GetStorageStatsCommand;
import com.cloud.agent.api.GetVmStatsAnswer;
import com.cloud.agent.api.GetVmStatsCommand;
import com.cloud.agent.api.GetVncPortAnswer;
import com.cloud.agent.api.GetVncPortCommand;
import com.cloud.agent.api.HostStatsEntry;
import com.cloud.agent.api.MaintainAnswer;
import com.cloud.agent.api.MaintainCommand;
import com.cloud.agent.api.ManageSnapshotAnswer;
import com.cloud.agent.api.ManageSnapshotCommand;
import com.cloud.agent.api.MigrateAnswer;
import com.cloud.agent.api.MigrateCommand;
import com.cloud.agent.api.ModifySshKeysCommand;
import com.cloud.agent.api.ModifyStoragePoolAnswer;
import com.cloud.agent.api.ModifyStoragePoolCommand;
import com.cloud.agent.api.NetworkRulesSystemVmCommand;
import com.cloud.agent.api.NetworkUsageAnswer;
import com.cloud.agent.api.NetworkUsageCommand;
import com.cloud.agent.api.PingCommand;
import com.cloud.agent.api.PingRoutingCommand;
import com.cloud.agent.api.PingRoutingWithNwGroupsCommand;
import com.cloud.agent.api.PingTestCommand;
import com.cloud.agent.api.PrepareForMigrationAnswer;
import com.cloud.agent.api.PrepareForMigrationCommand;
import com.cloud.agent.api.ReadyAnswer;
import com.cloud.agent.api.ReadyCommand;
import com.cloud.agent.api.RebootAnswer;
import com.cloud.agent.api.RebootCommand;
import com.cloud.agent.api.RebootRouterCommand;
import com.cloud.agent.api.SecurityGroupRuleAnswer;
import com.cloud.agent.api.SecurityGroupRulesCmd;
import com.cloud.agent.api.StartAnswer;
import com.cloud.agent.api.StartCommand;
import com.cloud.agent.api.StartupCommand;
import com.cloud.agent.api.StartupRoutingCommand;
import com.cloud.agent.api.StartupStorageCommand;
import com.cloud.agent.api.StopAnswer;
import com.cloud.agent.api.StopCommand;
import com.cloud.agent.api.UpgradeSnapshotCommand;
import com.cloud.agent.api.VmStatsEntry;
import com.cloud.agent.api.check.CheckSshAnswer;
import com.cloud.agent.api.check.CheckSshCommand;
import com.cloud.agent.api.proxy.CheckConsoleProxyLoadCommand;
import com.cloud.agent.api.proxy.ConsoleProxyLoadAnswer;
import com.cloud.agent.api.proxy.WatchConsoleProxyLoadCommand;
import com.cloud.agent.api.routing.IpAssocAnswer;
import com.cloud.agent.api.routing.IpAssocCommand;
import com.cloud.agent.api.routing.NetworkElementCommand;
import com.cloud.agent.api.storage.CopyVolumeAnswer;
import com.cloud.agent.api.storage.CopyVolumeCommand;
import com.cloud.agent.api.storage.CreateAnswer;
import com.cloud.agent.api.storage.CreateCommand;
import com.cloud.agent.api.storage.CreatePrivateTemplateAnswer;
import com.cloud.agent.api.storage.DestroyCommand;
import com.cloud.agent.api.storage.PrimaryStorageDownloadAnswer;
import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand;
import com.cloud.agent.api.to.IpAddressTO;
import com.cloud.agent.api.to.NicTO;
import com.cloud.agent.api.to.StorageFilerTO;
import com.cloud.agent.api.to.VirtualMachineTO;
import com.cloud.agent.api.to.VolumeTO;
import com.cloud.hypervisor.kvm.resource.KVMHABase.NfsStoragePool;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.ConsoleDef;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.CpuTuneDef;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DevicesDef;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DiskDef;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DiskDef.diskProtocol;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.FeaturesDef;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.GraphicDef;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.GuestDef;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.GuestResourceDef;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.InputDef;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.InterfaceDef;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.InterfaceDef.hostNicType;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.SerialDef;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.TermPolicy;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.ClockDef;
import com.cloud.agent.resource.virtualnetwork.VirtualRoutingResource;
import com.cloud.hypervisor.kvm.storage.KVMPhysicalDisk;
import com.cloud.hypervisor.kvm.storage.KVMPhysicalDisk.PhysicalDiskFormat;
import com.cloud.hypervisor.kvm.storage.KVMStoragePool;
import com.cloud.hypervisor.kvm.storage.KVMStoragePoolManager;
import com.cloud.dc.Vlan;
import com.cloud.exception.InternalErrorException;
import com.cloud.host.Host.Type;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.network.Networks.BroadcastDomainType;
import com.cloud.network.Networks.IsolationType;
import com.cloud.network.Networks.RouterPrivateIpStrategy;
import com.cloud.network.Networks.TrafficType;
import com.cloud.network.PhysicalNetworkSetupInfo;
import com.cloud.resource.ServerResource;
import com.cloud.resource.ServerResourceBase;
import com.cloud.storage.Storage;
import com.cloud.storage.Storage.ImageFormat;
import com.cloud.storage.Storage.StoragePoolType;
import com.cloud.storage.StorageLayer;
import com.cloud.storage.Volume;
import com.cloud.storage.template.Processor;
import com.cloud.storage.template.Processor.FormatInfo;
import com.cloud.storage.template.QCOW2Processor;
import com.cloud.storage.template.TemplateInfo;
import com.cloud.storage.template.TemplateLocation;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair;
import com.cloud.utils.PropertiesUtil;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.net.NetUtils;
import com.cloud.utils.script.OutputInterpreter;
import com.cloud.utils.script.Script;
import com.cloud.vm.DiskProfile;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachine.State;
import com.cloud.vm.VirtualMachineName;
/**
* LibvirtComputingResource execute requests on the computing/routing host using
* the libvirt API
*
* @config {@table || Param Name | Description | Values | Default || ||
* hypervisor.type | type of local hypervisor | string | kvm || ||
* hypervisor.uri | local hypervisor to connect to | URI |
* qemu:///system || || domr.arch | instruction set for domr template |
* string | i686 || || private.bridge.name | private bridge where the
* domrs have their private interface | string | vmops0 || ||
* public.bridge.name | public bridge where the domrs have their public
* interface | string | br0 || || private.network.name | name of the
* network where the domrs have their private interface | string |
* vmops-private || || private.ipaddr.start | start of the range of
* private ip addresses for domrs | ip address | 192.168.166.128 || ||
* private.ipaddr.end | end of the range of private ip addresses for
* domrs | ip address | start + 126 || || private.macaddr.start | start
* of the range of private mac addresses for domrs | mac address |
* 00:16:3e:77:e2:a0 || || private.macaddr.end | end of the range of
* private mac addresses for domrs | mac address | start + 126 || ||
* pool | the parent of the storage pool hierarchy * }
**/
@Local(value = { ServerResource.class })
public class LibvirtComputingResource extends ServerResourceBase implements
ServerResource {
private static final Logger s_logger = Logger
.getLogger(LibvirtComputingResource.class);
private String _modifyVlanPath;
private String _versionstringpath;
private String _patchdomrPath;
private String _createvmPath;
private String _manageSnapshotPath;
private String _createTmplPath;
private String _heartBeatPath;
private String _securityGroupPath;
private String _networkUsagePath;
private String _host;
private String _dcId;
private String _pod;
private String _clusterId;
private int _migrateSpeed;
private long _hvVersion;
private KVMHAMonitor _monitor;
private final String _SSHKEYSPATH = "/root/.ssh";
private final String _SSHPRVKEYPATH = _SSHKEYSPATH + File.separator
+ "id_rsa.cloud";
private final String _SSHPUBKEYPATH = _SSHKEYSPATH + File.separator
+ "id_rsa.pub.cloud";
private String _mountPoint = "/mnt";
StorageLayer _storage;
private KVMStoragePoolManager _storagePoolMgr;
private static final class KeyValueInterpreter extends OutputInterpreter {
private final Map<String, String> map = new HashMap<String, String>();
@Override
public String interpret(BufferedReader reader) throws IOException {
String line = null;
int numLines = 0;
while ((line = reader.readLine()) != null) {
String[] toks = line.trim().split("=");
if (toks.length < 2) {
s_logger.warn("Failed to parse Script output: " + line);
} else {
map.put(toks[0].trim(), toks[1].trim());
}
numLines++;
}
if (numLines == 0) {
s_logger.warn("KeyValueInterpreter: no output lines?");
}
return null;
}
public Map<String, String> getKeyValues() {
return map;
}
}
@Override
protected String getDefaultScriptsDir() {
return null;
}
protected static MessageFormat SnapshotXML = new MessageFormat(
" <domainsnapshot>" + " <name>{0}</name>" + " <domain>"
+ " <uuid>{1}</uuid>" + " </domain>"
+ " </domainsnapshot>");
protected String _hypervisorType;
protected String _hypervisorURI;
protected String _hypervisorPath;
protected String _sysvmISOPath;
protected String _privNwName;
protected String _privBridgeName;
protected String _linkLocalBridgeName;
protected String _publicBridgeName;
protected String _guestBridgeName;
protected String _privateIp;
protected String _pool;
protected String _localGateway;
private boolean _can_bridge_firewall;
protected String _localStoragePath;
protected String _localStorageUUID;
private Pair<String, String> _pifs;
private final Map<String, vmStats> _vmStats = new ConcurrentHashMap<String, vmStats>();
protected boolean _disconnected = true;
protected int _timeout;
protected int _cmdsTimeout;
protected int _stopTimeout;
protected static HashMap<DomainInfo.DomainState, State> s_statesTable;
static {
s_statesTable = new HashMap<DomainInfo.DomainState, State>();
s_statesTable.put(DomainInfo.DomainState.VIR_DOMAIN_SHUTOFF,
State.Stopped);
s_statesTable.put(DomainInfo.DomainState.VIR_DOMAIN_PAUSED,
State.Running);
s_statesTable.put(DomainInfo.DomainState.VIR_DOMAIN_RUNNING,
State.Running);
s_statesTable.put(DomainInfo.DomainState.VIR_DOMAIN_BLOCKED,
State.Running);
s_statesTable.put(DomainInfo.DomainState.VIR_DOMAIN_NOSTATE,
State.Unknown);
s_statesTable.put(DomainInfo.DomainState.VIR_DOMAIN_SHUTDOWN,
State.Stopping);
}
protected HashMap<String, State> _vms = new HashMap<String, State>(20);
protected List<String> _vmsKilled = new ArrayList<String>();
private VirtualRoutingResource _virtRouterResource;
private String _pingTestPath;
private int _dom0MinMem;
protected enum defineOps {
UNDEFINE_VM, DEFINE_VM
}
private String getEndIpFromStartIp(String startIp, int numIps) {
String[] tokens = startIp.split("[.]");
assert (tokens.length == 4);
int lastbyte = Integer.parseInt(tokens[3]);
lastbyte = lastbyte + numIps;
tokens[3] = Integer.toString(lastbyte);
StringBuilder end = new StringBuilder(15);
end.append(tokens[0]).append(".").append(tokens[1]).append(".")
.append(tokens[2]).append(".").append(tokens[3]);
return end.toString();
}
private Map<String, Object> getDeveloperProperties()
throws ConfigurationException {
final File file = PropertiesUtil.findConfigFile("developer.properties");
if (file == null) {
throw new ConfigurationException(
"Unable to find developer.properties.");
}
s_logger.info("developer.properties found at " + file.getAbsolutePath());
Properties properties = new Properties();
try {
properties.load(new FileInputStream(file));
String startMac = (String) properties.get("private.macaddr.start");
if (startMac == null) {
throw new ConfigurationException(
"Developers must specify start mac for private ip range");
}
String startIp = (String) properties.get("private.ipaddr.start");
if (startIp == null) {
throw new ConfigurationException(
"Developers must specify start ip for private ip range");
}
final Map<String, Object> params = PropertiesUtil.toMap(properties);
String endIp = (String) properties.get("private.ipaddr.end");
if (endIp == null) {
endIp = getEndIpFromStartIp(startIp, 16);
params.put("private.ipaddr.end", endIp);
}
return params;
} catch (final FileNotFoundException ex) {
throw new CloudRuntimeException("Cannot find the file: "
+ file.getAbsolutePath(), ex);
} catch (final IOException ex) {
throw new CloudRuntimeException("IOException in reading "
+ file.getAbsolutePath(), ex);
}
}
protected String getDefaultNetworkScriptsDir() {
return "scripts/vm/network/vnet";
}
protected String getDefaultStorageScriptsDir() {
return "scripts/storage/qcow2";
}
protected String getDefaultKvmScriptsDir() {
return "scripts/vm/hypervisor/kvm";
}
protected String getDefaultDomrScriptsDir() {
return "scripts/network/domr/kvm";
}
@Override
public boolean configure(String name, Map<String, Object> params)
throws ConfigurationException {
boolean success = super.configure(name, params);
if (!success) {
return false;
}
try {
Class<?> clazz = Class
.forName("com.cloud.storage.JavaStorageLayer");
_storage = (StorageLayer) ComponentLocator.inject(clazz);
_storage.configure("StorageLayer", params);
} catch (ClassNotFoundException e) {
throw new ConfigurationException("Unable to find class "
+ "com.cloud.storage.JavaStorageLayer");
}
String domrScriptsDir = (String) params.get("domr.scripts.dir");
if (domrScriptsDir == null) {
domrScriptsDir = getDefaultDomrScriptsDir();
}
String kvmScriptsDir = (String) params.get("kvm.scripts.dir");
if (kvmScriptsDir == null) {
kvmScriptsDir = getDefaultKvmScriptsDir();
}
String networkScriptsDir = (String) params.get("network.scripts.dir");
if (networkScriptsDir == null) {
networkScriptsDir = getDefaultNetworkScriptsDir();
}
String storageScriptsDir = (String) params.get("storage.scripts.dir");
if (storageScriptsDir == null) {
storageScriptsDir = getDefaultStorageScriptsDir();
}
params.put("domr.scripts.dir", domrScriptsDir);
_virtRouterResource = new VirtualRoutingResource();
success = _virtRouterResource.configure(name, params);
if (!success) {
return false;
}
_host = (String) params.get("host");
if (_host == null) {
_host = "localhost";
}
_dcId = (String) params.get("zone");
if (_dcId == null) {
_dcId = "default";
}
_pod = (String) params.get("pod");
if (_pod == null) {
_pod = "default";
}
_clusterId = (String) params.get("cluster");
_modifyVlanPath = Script.findScript(networkScriptsDir, "modifyvlan.sh");
if (_modifyVlanPath == null) {
throw new ConfigurationException("Unable to find modifyvlan.sh");
}
_versionstringpath = Script.findScript(kvmScriptsDir, "versions.sh");
if (_versionstringpath == null) {
throw new ConfigurationException("Unable to find versions.sh");
}
_patchdomrPath = Script.findScript(kvmScriptsDir + "/patch/",
"rundomrpre.sh");
if (_patchdomrPath == null) {
throw new ConfigurationException("Unable to find rundomrpre.sh");
}
_heartBeatPath = Script.findScript(kvmScriptsDir, "kvmheartbeat.sh");
if (_heartBeatPath == null) {
throw new ConfigurationException("Unable to find kvmheartbeat.sh");
}
_createvmPath = Script.findScript(storageScriptsDir, "createvm.sh");
if (_createvmPath == null) {
throw new ConfigurationException("Unable to find the createvm.sh");
}
_manageSnapshotPath = Script.findScript(storageScriptsDir,
"managesnapshot.sh");
if (_manageSnapshotPath == null) {
throw new ConfigurationException(
"Unable to find the managesnapshot.sh");
}
_createTmplPath = Script
.findScript(storageScriptsDir, "createtmplt.sh");
if (_createTmplPath == null) {
throw new ConfigurationException(
"Unable to find the createtmplt.sh");
}
_securityGroupPath = Script.findScript(networkScriptsDir,
"security_group.py");
if (_securityGroupPath == null) {
throw new ConfigurationException(
"Unable to find the security_group.py");
}
_networkUsagePath = Script.findScript("scripts/network/domr/",
"networkUsage.sh");
if (_networkUsagePath == null) {
throw new ConfigurationException(
"Unable to find the networkUsage.sh");
}
String value = (String) params.get("developer");
boolean isDeveloper = Boolean.parseBoolean(value);
if (isDeveloper) {
params.putAll(getDeveloperProperties());
}
_pool = (String) params.get("pool");
if (_pool == null) {
_pool = "/root";
}
String instance = (String) params.get("instance");
_hypervisorType = (String) params.get("hypervisor.type");
if (_hypervisorType == null) {
_hypervisorType = "kvm";
}
_hypervisorURI = (String) params.get("hypervisor.uri");
if (_hypervisorURI == null) {
_hypervisorURI = "qemu:///system";
}
String startMac = (String) params.get("private.macaddr.start");
if (startMac == null) {
startMac = "00:16:3e:77:e2:a0";
}
String startIp = (String) params.get("private.ipaddr.start");
if (startIp == null) {
startIp = "192.168.166.128";
}
_pingTestPath = Script.findScript(kvmScriptsDir, "pingtest.sh");
if (_pingTestPath == null) {
throw new ConfigurationException("Unable to find the pingtest.sh");
}
_linkLocalBridgeName = (String) params.get("private.bridge.name");
if (_linkLocalBridgeName == null) {
if (isDeveloper) {
_linkLocalBridgeName = "cloud-" + instance + "-0";
} else {
_linkLocalBridgeName = "cloud0";
}
}
_publicBridgeName = (String) params.get("public.network.device");
if (_publicBridgeName == null) {
_publicBridgeName = "cloudbr0";
}
_privBridgeName = (String) params.get("private.network.device");
if (_privBridgeName == null) {
_privBridgeName = "cloudbr1";
}
_guestBridgeName = (String) params.get("guest.network.device");
if (_guestBridgeName == null) {
_guestBridgeName = _privBridgeName;
}
_privNwName = (String) params.get("private.network.name");
if (_privNwName == null) {
if (isDeveloper) {
_privNwName = "cloud-" + instance + "-private";
} else {
_privNwName = "cloud-private";
}
}
_localStoragePath = (String) params.get("local.storage.path");
if (_localStoragePath == null) {
_localStoragePath = "/var/lib/libvirt/images/";
}
_localStorageUUID = (String) params.get("local.storage.uuid");
if (_localStorageUUID == null) {
_localStorageUUID = UUID.randomUUID().toString();
params.put("local.storage.uuid", _localStorageUUID);
}
value = (String) params.get("scripts.timeout");
_timeout = NumbersUtil.parseInt(value, 30 * 60) * 1000;
value = (String) params.get("stop.script.timeout");
_stopTimeout = NumbersUtil.parseInt(value, 120) * 1000;
value = (String) params.get("cmds.timeout");
_cmdsTimeout = NumbersUtil.parseInt(value, 7200) * 1000;
value = (String) params.get("host.reserved.mem.mb");
_dom0MinMem = NumbersUtil.parseInt(value, 0) * 1024 * 1024;
value = (String) params.get("debug.mode");
LibvirtConnection.initialize(_hypervisorURI);
Connect conn = null;
try {
conn = LibvirtConnection.getConnection();
} catch (LibvirtException e) {
throw new CloudRuntimeException(e.getMessage());
}
/* Does node support HVM guest? If not, exit */
if (!IsHVMEnabled(conn)) {
throw new ConfigurationException(
"NO HVM support on this machine, pls make sure: "
+ "1. VT/SVM is supported by your CPU, or is enabled in BIOS. "
+ "2. kvm modules is installed");
}
_hypervisorPath = getHypervisorPath(conn);
try {
_hvVersion = conn.getVersion();
_hvVersion = (_hvVersion % 1000000) / 1000;
} catch (LibvirtException e) {
}
String[] info = NetUtils.getNetworkParams(_privateNic);
_monitor = new KVMHAMonitor(null, info[0], _heartBeatPath);
Thread ha = new Thread(_monitor);
ha.start();
_storagePoolMgr = new KVMStoragePoolManager(_storage, _monitor);
_sysvmISOPath = (String) params.get("systemvm.iso.path");
if (_sysvmISOPath == null) {
String[] isoPaths = { "/usr/lib64/cloud/agent/vms/systemvm.iso",
"/usr/lib/cloud/agent/vms/systemvm.iso" };
for (String isoPath : isoPaths) {
if (_storage.exists(isoPath)) {
_sysvmISOPath = isoPath;
break;
}
}
if (_sysvmISOPath == null) {
s_logger.debug("Can't find system vm ISO");
}
}
try {
createControlNetwork();
} catch (LibvirtException e) {
throw new ConfigurationException(e.getMessage());
}
_pifs = getPifs();
if (_pifs.first() == null) {
s_logger.debug("Failed to get private nic name");
throw new ConfigurationException("Failed to get private nic name");
}
if (_pifs.second() == null) {
s_logger.debug("Failed to get public nic name");
throw new ConfigurationException("Failed to get public nic name");
}
s_logger.debug("Found pif: " + _pifs.first() + " on " + _privBridgeName
+ ", pif: " + _pifs.second() + " on " + _publicBridgeName);
_can_bridge_firewall = can_bridge_firewall(_pifs.second());
_localGateway = Script
.runSimpleBashScript("ip route |grep default|awk '{print $3}'");
if (_localGateway == null) {
s_logger.debug("Failed to found the local gateway");
}
_mountPoint = (String) params.get("mount.path");
if (_mountPoint == null) {
_mountPoint = "/mnt";
}
value = (String) params.get("vm.migrate.speed");
_migrateSpeed = NumbersUtil.parseInt(value, -1);
if (_migrateSpeed == -1) {
//get guest network device speed
_migrateSpeed = 0;
String speed = Script.runSimpleBashScript("ethtool " + _pifs.second() + " |grep Speed | cut -d \\ -f 2");
if (speed != null) {
String[] tokens = speed.split("M");
if (tokens.length == 2) {
try {
_migrateSpeed = Integer.parseInt(tokens[0]);
} catch (Exception e) {
}
s_logger.debug("device " + _pifs.second() + " has speed: " + String.valueOf(_migrateSpeed));
}
}
params.put("vm.migrate.speed", String.valueOf(_migrateSpeed));
}
return true;
}
private Pair<String, String> getPifs() {
/* get pifs from bridge */
String pubPif = null;
String privPif = null;
String vlan = null;
if (_publicBridgeName != null) {
pubPif = Script.runSimpleBashScript("brctl show | grep "
+ _publicBridgeName + " | awk '{print $4}'");
vlan = Script.runSimpleBashScript("ls /proc/net/vlan/" + pubPif);
if (vlan != null && !vlan.isEmpty()) {
pubPif = Script
.runSimpleBashScript("grep ^Device\\: /proc/net/vlan/"
+ pubPif + " | awk {'print $2'}");
}
}
if (_guestBridgeName != null) {
privPif = Script.runSimpleBashScript("brctl show | grep "
+ _guestBridgeName + " | awk '{print $4}'");
vlan = Script.runSimpleBashScript("ls /proc/net/vlan/" + privPif);
if (vlan != null && !vlan.isEmpty()) {
privPif = Script
.runSimpleBashScript("grep ^Device\\: /proc/net/vlan/"
+ privPif + " | awk {'print $2'}");
}
}
return new Pair<String, String>(privPif, pubPif);
}
private boolean checkNetwork(String networkName) {
if (networkName == null) {
return true;
}
String name = Script.runSimpleBashScript("brctl show | grep "
+ networkName + " | awk '{print $4}'");
if (name == null) {
return false;
} else {
return true;
}
}
private String getVnetId(String vnetId) {
return vnetId;
}
private void patchSystemVm(String cmdLine, String dataDiskPath,
String vmName) throws InternalErrorException {
String result;
final Script command = new Script(_patchdomrPath, _timeout, s_logger);
command.add("-l", vmName);
command.add("-t", "all");
command.add("-d", dataDiskPath);
command.add("-p", cmdLine.replaceAll(" ", "%"));
result = command.execute();
if (result != null) {
throw new InternalErrorException(result);
}
}
boolean isDirectAttachedNetwork(String type) {
if ("untagged".equalsIgnoreCase(type)) {
return true;
} else {
try {
Long.valueOf(type);
} catch (NumberFormatException e) {
return true;
}
return false;
}
}
protected String startDomain(Connect conn, String vmName, String domainXML)
throws LibvirtException, InternalErrorException {
/* No duplicated vm, we will success, or failed */
boolean failed = false;
Domain dm = null;
try {
dm = conn.domainDefineXML(domainXML);
} catch (final LibvirtException e) {
/* Duplicated defined vm */
s_logger.warn("Failed to define domain " + vmName + ": "
+ e.getMessage());
failed = true;
} finally {
try {
if (dm != null) {
dm.free();
}
} catch (final LibvirtException e) {
}
}
/* If failed, undefine the vm */
Domain dmOld = null;
Domain dmNew = null;
try {
if (failed) {
dmOld = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
.getBytes()));
dmOld.undefine();
dmNew = conn.domainDefineXML(domainXML);
}
} catch (final LibvirtException e) {
s_logger.warn("Failed to define domain (second time) " + vmName
+ ": " + e.getMessage());
throw e;
} catch (Exception e) {
s_logger.warn("Failed to define domain (second time) " + vmName
+ ": " + e.getMessage());
throw new InternalErrorException(e.toString());
} finally {
try {
if (dmOld != null) {
dmOld.free();
}
if (dmNew != null) {
dmNew.free();
}
} catch (final LibvirtException e) {
}
}
/* Start the VM */
try {
dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
.getBytes()));
dm.create();
} catch (LibvirtException e) {
s_logger.warn("Failed to start domain: " + vmName + ": "
+ e.getMessage());
throw e;
} finally {
try {
if (dm != null) {
dm.free();
}
} catch (final LibvirtException e) {
}
}
return null;
}
@Override
public boolean stop() {
try {
Connect conn = LibvirtConnection.getConnection();
conn.close();
} catch (LibvirtException e) {
}
return true;
}
public static void main(String[] args) {
s_logger.addAppender(new org.apache.log4j.ConsoleAppender(
new org.apache.log4j.PatternLayout(), "System.out"));
LibvirtComputingResource test = new LibvirtComputingResource();
Map<String, Object> params = new HashMap<String, Object>();
try {
test.configure("test", params);
} catch (ConfigurationException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
String result = null;
// String result = test.startDomainRouter("domr1",
// "/var/lib/images/centos.5-4.x86-64/centos-small.img", 128, "0064",
// "02:00:30:00:01:01", "00:16:3e:77:e2:a1", "02:00:30:00:64:01");
boolean created = (result == null);
s_logger.info("Domain " + (created ? " " : " not ") + " created");
s_logger.info("Rule " + (created ? " " : " not ") + " created");
test.stop();
}
@Override
public Answer executeRequest(Command cmd) {
try {
if (cmd instanceof StopCommand) {
return execute((StopCommand) cmd);
} else if (cmd instanceof GetVmStatsCommand) {
return execute((GetVmStatsCommand) cmd);
} else if (cmd instanceof RebootRouterCommand) {
return execute((RebootRouterCommand) cmd);
} else if (cmd instanceof RebootCommand) {
return execute((RebootCommand) cmd);
} else if (cmd instanceof GetHostStatsCommand) {
return execute((GetHostStatsCommand) cmd);
} else if (cmd instanceof CheckStateCommand) {
return executeRequest(cmd);
} else if (cmd instanceof CheckHealthCommand) {
return execute((CheckHealthCommand) cmd);
} else if (cmd instanceof PrepareForMigrationCommand) {
return execute((PrepareForMigrationCommand) cmd);
} else if (cmd instanceof MigrateCommand) {
return execute((MigrateCommand) cmd);
} else if (cmd instanceof PingTestCommand) {
return execute((PingTestCommand) cmd);
} else if (cmd instanceof CheckVirtualMachineCommand) {
return execute((CheckVirtualMachineCommand) cmd);
} else if (cmd instanceof ReadyCommand) {
return execute((ReadyCommand) cmd);
} else if (cmd instanceof AttachIsoCommand) {
return execute((AttachIsoCommand) cmd);
} else if (cmd instanceof AttachVolumeCommand) {
return execute((AttachVolumeCommand) cmd);
} else if (cmd instanceof StopCommand) {
return execute((StopCommand) cmd);
} else if (cmd instanceof CheckConsoleProxyLoadCommand) {
return execute((CheckConsoleProxyLoadCommand) cmd);
} else if (cmd instanceof WatchConsoleProxyLoadCommand) {
return execute((WatchConsoleProxyLoadCommand) cmd);
} else if (cmd instanceof GetVncPortCommand) {
return execute((GetVncPortCommand) cmd);
} else if (cmd instanceof ModifySshKeysCommand) {
return execute((ModifySshKeysCommand) cmd);
} else if (cmd instanceof MaintainCommand) {
return execute((MaintainCommand) cmd);
} else if (cmd instanceof CreateCommand) {
return execute((CreateCommand) cmd);
} else if (cmd instanceof DestroyCommand) {
return execute((DestroyCommand) cmd);
} else if (cmd instanceof PrimaryStorageDownloadCommand) {
return execute((PrimaryStorageDownloadCommand) cmd);
} else if (cmd instanceof CreatePrivateTemplateFromVolumeCommand) {
return execute((CreatePrivateTemplateFromVolumeCommand) cmd);
} else if (cmd instanceof GetStorageStatsCommand) {
return execute((GetStorageStatsCommand) cmd);
} else if (cmd instanceof ManageSnapshotCommand) {
return execute((ManageSnapshotCommand) cmd);
} else if (cmd instanceof BackupSnapshotCommand) {
return execute((BackupSnapshotCommand) cmd);
} else if (cmd instanceof CreateVolumeFromSnapshotCommand) {
return execute((CreateVolumeFromSnapshotCommand) cmd);
} else if (cmd instanceof CreatePrivateTemplateFromSnapshotCommand) {
return execute((CreatePrivateTemplateFromSnapshotCommand) cmd);
} else if (cmd instanceof UpgradeSnapshotCommand) {
return execute((UpgradeSnapshotCommand) cmd);
} else if (cmd instanceof CreateStoragePoolCommand) {
return execute((CreateStoragePoolCommand) cmd);
} else if (cmd instanceof ModifyStoragePoolCommand) {
return execute((ModifyStoragePoolCommand) cmd);
} else if (cmd instanceof SecurityGroupRulesCmd) {
return execute((SecurityGroupRulesCmd) cmd);
} else if (cmd instanceof DeleteStoragePoolCommand) {
return execute((DeleteStoragePoolCommand) cmd);
} else if (cmd instanceof FenceCommand) {
return execute((FenceCommand) cmd);
} else if (cmd instanceof StartCommand) {
return execute((StartCommand) cmd);
} else if (cmd instanceof IpAssocCommand) {
return execute((IpAssocCommand) cmd);
} else if (cmd instanceof NetworkElementCommand) {
return _virtRouterResource.executeRequest(cmd);
} else if (cmd instanceof CheckSshCommand) {
return execute((CheckSshCommand) cmd);
} else if (cmd instanceof NetworkUsageCommand) {
return execute((NetworkUsageCommand) cmd);
} else if (cmd instanceof NetworkRulesSystemVmCommand) {
return execute((NetworkRulesSystemVmCommand) cmd);
} else if (cmd instanceof CleanupNetworkRulesCmd) {
return execute((CleanupNetworkRulesCmd) cmd);
} else if (cmd instanceof CopyVolumeCommand) {
return execute((CopyVolumeCommand) cmd);
} else if (cmd instanceof CheckNetworkCommand) {
return execute((CheckNetworkCommand) cmd);
} else {
s_logger.warn("Unsupported command ");
return Answer.createUnsupportedCommandAnswer(cmd);
}
} catch (final IllegalArgumentException e) {
return new Answer(cmd, false, e.getMessage());
}
}
private CheckNetworkAnswer execute(CheckNetworkCommand cmd) {
List<PhysicalNetworkSetupInfo> phyNics = cmd
.getPhysicalNetworkInfoList();
String errMsg = null;
for (PhysicalNetworkSetupInfo nic : phyNics) {
if (!checkNetwork(nic.getGuestNetworkName())) {
errMsg = "Can not find network: " + nic.getGuestNetworkName();
break;
} else if (!checkNetwork(nic.getPrivateNetworkName())) {
errMsg = "Can not find network: " + nic.getPrivateNetworkName();
break;
} else if (!checkNetwork(nic.getPublicNetworkName())) {
errMsg = "Can not find network: " + nic.getPublicNetworkName();
break;
}
}
if (errMsg != null) {
return new CheckNetworkAnswer(cmd, false, errMsg);
} else {
return new CheckNetworkAnswer(cmd, true, null);
}
}
private CopyVolumeAnswer execute(CopyVolumeCommand cmd) {
boolean copyToSecondary = cmd.toSecondaryStorage();
String volumePath = cmd.getVolumePath();
StorageFilerTO pool = cmd.getPool();
String secondaryStorageUrl = cmd.getSecondaryStorageURL();
KVMStoragePool secondaryStoragePool = null;
try {
KVMStoragePool primaryPool = _storagePoolMgr.getStoragePool(pool
.getUuid());
String volumeName = UUID.randomUUID().toString();
if (copyToSecondary) {
String destVolumeName = volumeName + ".qcow2";
KVMPhysicalDisk volume = primaryPool.getPhysicalDisk(cmd
.getVolumePath());
String volumeDestPath = "/volumes/" + cmd.getVolumeId()
+ File.separator;
secondaryStoragePool = _storagePoolMgr
.getStoragePoolByURI(secondaryStorageUrl);
secondaryStoragePool.createFolder(volumeDestPath);
secondaryStoragePool.delete();
secondaryStoragePool = _storagePoolMgr
.getStoragePoolByURI(secondaryStorageUrl
+ volumeDestPath);
_storagePoolMgr.copyPhysicalDisk(volume, destVolumeName,
secondaryStoragePool);
return new CopyVolumeAnswer(cmd, true, null, null, volumeName);
} else {
volumePath = "/volumes/" + cmd.getVolumeId() + File.separator;
secondaryStoragePool = _storagePoolMgr
.getStoragePoolByURI(secondaryStorageUrl + volumePath);
KVMPhysicalDisk volume = secondaryStoragePool
.getPhysicalDisk(cmd.getVolumePath() + ".qcow2");
_storagePoolMgr.copyPhysicalDisk(volume, volumeName,
primaryPool);
return new CopyVolumeAnswer(cmd, true, null, null, volumeName);
}
} catch (CloudRuntimeException e) {
return new CopyVolumeAnswer(cmd, false, e.toString(), null, null);
} finally {
if (secondaryStoragePool != null) {
secondaryStoragePool.delete();
}
}
}
protected Answer execute(DeleteStoragePoolCommand cmd) {
try {
_storagePoolMgr.deleteStoragePool(cmd.getPool().getUuid());
return new Answer(cmd);
} catch (CloudRuntimeException e) {
return new Answer(cmd, false, e.toString());
}
}
protected FenceAnswer execute(FenceCommand cmd) {
ExecutorService executors = Executors.newSingleThreadExecutor();
List<NfsStoragePool> pools = _monitor.getStoragePools();
KVMHAChecker ha = new KVMHAChecker(pools, cmd.getHostIp());
Future<Boolean> future = executors.submit(ha);
try {
Boolean result = future.get();
if (result) {
return new FenceAnswer(cmd, false, "Heart is still beating...");
} else {
return new FenceAnswer(cmd);
}
} catch (InterruptedException e) {
s_logger.warn("Unable to fence", e);
return new FenceAnswer(cmd, false, e.getMessage());
} catch (ExecutionException e) {
s_logger.warn("Unable to fence", e);
return new FenceAnswer(cmd, false, e.getMessage());
}
}
protected Storage.StorageResourceType getStorageResourceType() {
return Storage.StorageResourceType.STORAGE_POOL;
}
protected Answer execute(CreateCommand cmd) {
StorageFilerTO pool = cmd.getPool();
DiskProfile dskch = cmd.getDiskCharacteristics();
KVMPhysicalDisk BaseVol = null;
KVMStoragePool primaryPool = null;
KVMPhysicalDisk vol = null;
long disksize;
try {
primaryPool = _storagePoolMgr.getStoragePool(pool.getUuid());
if (cmd.getTemplateUrl() != null) {
BaseVol = primaryPool.getPhysicalDisk(cmd.getTemplateUrl());
vol = _storagePoolMgr.createDiskFromTemplate(BaseVol, UUID
.randomUUID().toString(), primaryPool);
if (vol == null) {
return new Answer(cmd, false,
" Can't create storage volume on storage pool");
}
disksize = vol.getSize();
} else {
disksize = dskch.getSize();
vol = primaryPool.createPhysicalDisk(UUID.randomUUID()
.toString(), dskch.getSize());
}
VolumeTO volume = new VolumeTO(cmd.getVolumeId(), dskch.getType(),
pool.getType(), pool.getUuid(), pool.getPath(),
vol.getName(), vol.getName(), disksize, null);
return new CreateAnswer(cmd, volume);
} catch (CloudRuntimeException e) {
s_logger.debug("Failed to create volume: " + e.toString());
return new CreateAnswer(cmd, e);
}
}
public Answer execute(DestroyCommand cmd) {
VolumeTO vol = cmd.getVolume();
try {
KVMStoragePool pool = _storagePoolMgr.getStoragePool(vol
.getPoolUuid());
pool.deletePhysicalDisk(vol.getPath());
return new Answer(cmd, true, "Success");
} catch (CloudRuntimeException e) {
s_logger.debug("Failed to delete volume: " + e.toString());
return new Answer(cmd, false, e.toString());
}
}
private String getVlanIdFromBridge(String brName) {
OutputInterpreter.OneLineParser vlanIdParser = new OutputInterpreter.OneLineParser();
final Script cmd = new Script("/bin/bash", s_logger);
cmd.add("-c");
cmd.add("vlanid=$(brctl show |grep " + brName
+ " |awk '{print $4}' | cut -s -d. -f 2);echo $vlanid");
String result = cmd.execute(vlanIdParser);
if (result != null) {
return null;
}
String vlanId = vlanIdParser.getLine();
if (vlanId.equalsIgnoreCase("")) {
return null;
} else {
return vlanId;
}
}
private void VifHotPlug(Connect conn, String vmName, String vlanId,
String macAddr) throws InternalErrorException, LibvirtException {
NicTO nicTO = new NicTO();
nicTO.setMac(macAddr);
nicTO.setType(TrafficType.Public);
if (vlanId == null) {
nicTO.setBroadcastType(BroadcastDomainType.Native);
} else {
nicTO.setBroadcastType(BroadcastDomainType.Vlan);
nicTO.setBroadcastUri(BroadcastDomainType.Vlan.toUri(vlanId));
}
InterfaceDef nic = createVif(nicTO, InterfaceDef.nicModel.VIRTIO);
Domain vm = getDomain(conn, vmName);
vm.attachDevice(nic.toString());
}
public Answer execute(IpAssocCommand cmd) {
String routerName = cmd
.getAccessDetail(NetworkElementCommand.ROUTER_NAME);
String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
String[] results = new String[cmd.getIpAddresses().length];
Connect conn;
try {
conn = LibvirtConnection.getConnection();
List<InterfaceDef> nics = getInterfaces(conn, routerName);
Map<String, Integer> vlanAllocatedToVM = new HashMap<String, Integer>();
Integer nicPos = 0;
for (InterfaceDef nic : nics) {
if (nic.getBrName().equalsIgnoreCase(_linkLocalBridgeName)) {
vlanAllocatedToVM.put("LinkLocal", nicPos);
} else {
String vlanId = getVlanIdFromBridge(nic.getBrName());
if (vlanId != null) {
vlanAllocatedToVM.put(vlanId, nicPos);
} else {
vlanAllocatedToVM.put(Vlan.UNTAGGED, nicPos);
}
}
nicPos++;
}
IpAddressTO[] ips = cmd.getIpAddresses();
int i = 0;
String result = null;
int nicNum = 0;
for (IpAddressTO ip : ips) {
if (!vlanAllocatedToVM.containsKey(ip.getVlanId())) {
/* plug a vif into router */
VifHotPlug(conn, routerName, ip.getVlanId(),
ip.getVifMacAddress());
vlanAllocatedToVM.put(ip.getVlanId(), nicPos++);
}
nicNum = vlanAllocatedToVM.get(ip.getVlanId());
networkUsage(routerIp, "addVif", "eth" + nicNum);
result = _virtRouterResource.assignPublicIpAddress(routerName,
routerIp, ip.getPublicIp(), ip.isAdd(), ip.isFirstIP(),
ip.isSourceNat(), ip.getVlanId(), ip.getVlanGateway(),
ip.getVlanNetmask(), ip.getVifMacAddress(),
ip.getGuestIp(), nicNum);
if (result != null) {
results[i++] = IpAssocAnswer.errorResult;
} else {
results[i++] = ip.getPublicIp() + " - success";
;
}
}
return new IpAssocAnswer(cmd, results);
} catch (LibvirtException e) {
return new IpAssocAnswer(cmd, results);
} catch (InternalErrorException e) {
return new IpAssocAnswer(cmd, results);
}
}
protected ManageSnapshotAnswer execute(final ManageSnapshotCommand cmd) {
String snapshotName = cmd.getSnapshotName();
String snapshotPath = cmd.getSnapshotPath();
String vmName = cmd.getVmName();
try {
Connect conn = LibvirtConnection.getConnection();
DomainInfo.DomainState state = null;
Domain vm = null;
if (vmName != null) {
try {
vm = getDomain(conn, cmd.getVmName());
state = vm.getInfo().state;
} catch (LibvirtException e) {
}
}
KVMStoragePool primaryPool = _storagePoolMgr.getStoragePool(cmd
.getPool().getUuid());
if (primaryPool.getType() == StoragePoolType.RBD) {
s_logger.debug("Snapshots are not supported on RBD volumes");
return new ManageSnapshotAnswer(cmd, false,
"Snapshots are not supported on RBD volumes");
}
KVMPhysicalDisk disk = primaryPool.getPhysicalDisk(cmd
.getVolumePath());
if (state == DomainInfo.DomainState.VIR_DOMAIN_RUNNING
&& !primaryPool.isExternalSnapshot()) {
String vmUuid = vm.getUUIDString();
Object[] args = new Object[] { snapshotName, vmUuid };
String snapshot = SnapshotXML.format(args);
s_logger.debug(snapshot);
if (cmd.getCommandSwitch().equalsIgnoreCase(
ManageSnapshotCommand.CREATE_SNAPSHOT)) {
vm.snapshotCreateXML(snapshot);
} else {
DomainSnapshot snap = vm.snapshotLookupByName(snapshotName);
snap.delete(0);
}
/*
* libvirt on RHEL6 doesn't handle resume event emitted from
* qemu
*/
vm = getDomain(conn, cmd.getVmName());
state = vm.getInfo().state;
if (state == DomainInfo.DomainState.VIR_DOMAIN_PAUSED) {
vm.resume();
}
} else {
/* VM is not running, create a snapshot by ourself */
final Script command = new Script(_manageSnapshotPath,
_cmdsTimeout, s_logger);
if (cmd.getCommandSwitch().equalsIgnoreCase(
ManageSnapshotCommand.CREATE_SNAPSHOT)) {
command.add("-c", disk.getPath());
} else {
command.add("-d", snapshotPath);
}
command.add("-n", snapshotName);
String result = command.execute();
if (result != null) {
s_logger.debug("Failed to manage snapshot: " + result);
return new ManageSnapshotAnswer(cmd, false,
"Failed to manage snapshot: " + result);
}
}
return new ManageSnapshotAnswer(cmd, cmd.getSnapshotId(),
disk.getPath() + File.separator + snapshotName, true, null);
} catch (LibvirtException e) {
s_logger.debug("Failed to manage snapshot: " + e.toString());
return new ManageSnapshotAnswer(cmd, false,
"Failed to manage snapshot: " + e.toString());
}
}
protected BackupSnapshotAnswer execute(final BackupSnapshotCommand cmd) {
Long dcId = cmd.getDataCenterId();
Long accountId = cmd.getAccountId();
Long volumeId = cmd.getVolumeId();
String secondaryStoragePoolUrl = cmd.getSecondaryStorageUrl();
String snapshotName = cmd.getSnapshotName();
String snapshotPath = cmd.getVolumePath();
String snapshotDestPath = null;
String snapshotRelPath = null;
String vmName = cmd.getVmName();
KVMStoragePool secondaryStoragePool = null;
try {
Connect conn = LibvirtConnection.getConnection();
secondaryStoragePool = _storagePoolMgr
.getStoragePoolByURI(secondaryStoragePoolUrl);
String ssPmountPath = secondaryStoragePool.getLocalPath();
snapshotRelPath = File.separator + "snapshots" + File.separator
+ dcId + File.separator + accountId + File.separator
+ volumeId;
snapshotDestPath = ssPmountPath + File.separator + "snapshots"
+ File.separator + dcId + File.separator + accountId
+ File.separator + volumeId;
KVMStoragePool primaryPool = _storagePoolMgr.getStoragePool(cmd
.getPrimaryStoragePoolNameLabel());
KVMPhysicalDisk snapshotDisk = primaryPool.getPhysicalDisk(cmd
.getVolumePath());
Script command = new Script(_manageSnapshotPath, _cmdsTimeout,
s_logger);
command.add("-b", snapshotDisk.getPath());
command.add("-n", snapshotName);
command.add("-p", snapshotDestPath);
command.add("-t", snapshotName);
String result = command.execute();
if (result != null) {
s_logger.debug("Failed to backup snaptshot: " + result);
return new BackupSnapshotAnswer(cmd, false, result, null, true);
}
/* Delete the snapshot on primary */
DomainInfo.DomainState state = null;
Domain vm = null;
if (vmName != null) {
try {
vm = getDomain(conn, cmd.getVmName());
state = vm.getInfo().state;
} catch (LibvirtException e) {
}
}
KVMStoragePool primaryStorage = _storagePoolMgr.getStoragePool(cmd
.getPool().getUuid());
if (state == DomainInfo.DomainState.VIR_DOMAIN_RUNNING
&& !primaryStorage.isExternalSnapshot()) {
String vmUuid = vm.getUUIDString();
Object[] args = new Object[] { snapshotName, vmUuid };
String snapshot = SnapshotXML.format(args);
s_logger.debug(snapshot);
DomainSnapshot snap = vm.snapshotLookupByName(snapshotName);
snap.delete(0);
/*
* libvirt on RHEL6 doesn't handle resume event emitted from
* qemu
*/
vm = getDomain(conn, cmd.getVmName());
state = vm.getInfo().state;
if (state == DomainInfo.DomainState.VIR_DOMAIN_PAUSED) {
vm.resume();
}
} else {
command = new Script(_manageSnapshotPath, _cmdsTimeout,
s_logger);
command.add("-d", snapshotDisk.getPath());
command.add("-n", snapshotName);
result = command.execute();
if (result != null) {
s_logger.debug("Failed to backup snapshot: " + result);
return new BackupSnapshotAnswer(cmd, false,
"Failed to backup snapshot: " + result, null, true);
}
}
} catch (LibvirtException e) {
return new BackupSnapshotAnswer(cmd, false, e.toString(), null,
true);
} catch (CloudRuntimeException e) {
return new BackupSnapshotAnswer(cmd, false, e.toString(), null,
true);
} finally {
if (secondaryStoragePool != null) {
secondaryStoragePool.delete();
}
}
return new BackupSnapshotAnswer(cmd, true, null, snapshotRelPath
+ File.separator + snapshotName, true);
}
protected DeleteSnapshotBackupAnswer execute(
final DeleteSnapshotBackupCommand cmd) {
Long dcId = cmd.getDataCenterId();
Long accountId = cmd.getAccountId();
Long volumeId = cmd.getVolumeId();
KVMStoragePool secondaryStoragePool = null;
try {
secondaryStoragePool = _storagePoolMgr.getStoragePoolByURI(cmd
.getSecondaryStorageUrl());
String ssPmountPath = secondaryStoragePool.getLocalPath();
String snapshotDestPath = ssPmountPath + File.separator
+ "snapshots" + File.separator + dcId + File.separator
+ accountId + File.separator + volumeId;
final Script command = new Script(_manageSnapshotPath,
_cmdsTimeout, s_logger);
command.add("-d", snapshotDestPath);
command.add("-n", cmd.getSnapshotName());
command.execute();
} catch (CloudRuntimeException e) {
return new DeleteSnapshotBackupAnswer(cmd, false, e.toString());
} finally {
if (secondaryStoragePool != null) {
secondaryStoragePool.delete();
}
}
return new DeleteSnapshotBackupAnswer(cmd, true, null);
}
protected Answer execute(DeleteSnapshotsDirCommand cmd) {
Long dcId = cmd.getDcId();
Long accountId = cmd.getAccountId();
Long volumeId = cmd.getVolumeId();
KVMStoragePool secondaryStoragePool = null;
try {
secondaryStoragePool = _storagePoolMgr.getStoragePoolByURI(cmd
.getSecondaryStorageUrl());
String ssPmountPath = secondaryStoragePool.getLocalPath();
String snapshotDestPath = ssPmountPath + File.separator
+ "snapshots" + File.separator + dcId + File.separator
+ accountId + File.separator + volumeId;
final Script command = new Script(_manageSnapshotPath,
_cmdsTimeout, s_logger);
command.add("-d", snapshotDestPath);
command.add("-f");
command.execute();
} catch (CloudRuntimeException e) {
return new Answer(cmd, false, e.toString());
} finally {
if (secondaryStoragePool != null) {
secondaryStoragePool.delete();
}
}
return new Answer(cmd, true, null);
}
protected CreateVolumeFromSnapshotAnswer execute(
final CreateVolumeFromSnapshotCommand cmd) {
try {
String snapshotPath = cmd.getSnapshotUuid();
int index = snapshotPath.lastIndexOf("/");
snapshotPath = snapshotPath.substring(0, index);
KVMStoragePool secondaryPool = _storagePoolMgr
.getStoragePoolByURI(cmd.getSecondaryStorageUrl()
+ snapshotPath);
KVMPhysicalDisk snapshot = secondaryPool.getPhysicalDisk(cmd
.getSnapshotName());
String primaryUuid = cmd.getPrimaryStoragePoolNameLabel();
KVMStoragePool primaryPool = _storagePoolMgr
.getStoragePool(primaryUuid);
String volUuid = UUID.randomUUID().toString();
KVMPhysicalDisk disk = _storagePoolMgr.copyPhysicalDisk(snapshot,
volUuid, primaryPool);
return new CreateVolumeFromSnapshotAnswer(cmd, true, "",
disk.getName());
} catch (CloudRuntimeException e) {
return new CreateVolumeFromSnapshotAnswer(cmd, false, e.toString(),
null);
}
}
protected Answer execute(final UpgradeSnapshotCommand cmd) {
return new Answer(cmd, true, "success");
}
protected CreatePrivateTemplateAnswer execute(
final CreatePrivateTemplateFromSnapshotCommand cmd) {
String templateFolder = cmd.getAccountId() + File.separator
+ cmd.getNewTemplateId();
String templateInstallFolder = "template/tmpl/" + templateFolder;
String tmplName = UUID.randomUUID().toString();
String tmplFileName = tmplName + ".qcow2";
KVMStoragePool secondaryPool = null;
KVMStoragePool snapshotPool = null;
try {
String snapshotPath = cmd.getSnapshotUuid();
int index = snapshotPath.lastIndexOf("/");
snapshotPath = snapshotPath.substring(0, index);
snapshotPool = _storagePoolMgr.getStoragePoolByURI(cmd
.getSecondaryStorageUrl() + snapshotPath);
KVMPhysicalDisk snapshot = snapshotPool.getPhysicalDisk(cmd
.getSnapshotName());
secondaryPool = _storagePoolMgr.getStoragePoolByURI(cmd
.getSecondaryStorageUrl());
String templatePath = secondaryPool.getLocalPath() + File.separator
+ templateInstallFolder;
_storage.mkdirs(templatePath);
String tmplPath = templateInstallFolder + File.separator
+ tmplFileName;
Script command = new Script(_createTmplPath, _cmdsTimeout, s_logger);
command.add("-t", templatePath);
command.add("-n", tmplFileName);
command.add("-f", snapshot.getPath());
command.execute();
Map<String, Object> params = new HashMap<String, Object>();
params.put(StorageLayer.InstanceConfigKey, _storage);
Processor qcow2Processor = new QCOW2Processor();
qcow2Processor.configure("QCOW2 Processor", params);
FormatInfo info = qcow2Processor.process(templatePath, null,
tmplName);
TemplateLocation loc = new TemplateLocation(_storage, templatePath);
loc.create(1, true, tmplName);
loc.addFormat(info);
loc.save();
return new CreatePrivateTemplateAnswer(cmd, true, "", tmplPath,
info.virtualSize, info.size, tmplName, info.format);
} catch (ConfigurationException e) {
return new CreatePrivateTemplateAnswer(cmd, false, e.getMessage());
} catch (InternalErrorException e) {
return new CreatePrivateTemplateAnswer(cmd, false, e.getMessage());
} catch (IOException e) {
return new CreatePrivateTemplateAnswer(cmd, false, e.getMessage());
} catch (CloudRuntimeException e) {
return new CreatePrivateTemplateAnswer(cmd, false, e.getMessage());
} finally {
if (secondaryPool != null) {
secondaryPool.delete();
}
if (snapshotPool != null) {
snapshotPool.delete();
}
}
}
protected GetStorageStatsAnswer execute(final GetStorageStatsCommand cmd) {
try {
KVMStoragePool sp = _storagePoolMgr.getStoragePool(cmd
.getStorageId());
return new GetStorageStatsAnswer(cmd, sp.getCapacity(),
sp.getUsed());
} catch (CloudRuntimeException e) {
return new GetStorageStatsAnswer(cmd, e.toString());
}
}
protected CreatePrivateTemplateAnswer execute(
CreatePrivateTemplateFromVolumeCommand cmd) {
String secondaryStorageURL = cmd.getSecondaryStorageUrl();
KVMStoragePool secondaryStorage = null;
try {
Connect conn = LibvirtConnection.getConnection();
String templateFolder = cmd.getAccountId() + File.separator
+ cmd.getTemplateId() + File.separator;
String templateInstallFolder = "/template/tmpl/" + templateFolder;
secondaryStorage = _storagePoolMgr
.getStoragePoolByURI(secondaryStorageURL);
KVMStoragePool primary = _storagePoolMgr.getStoragePool(cmd
.getPrimaryStoragePoolNameLabel());
KVMPhysicalDisk disk = primary.getPhysicalDisk(cmd.getVolumePath());
String tmpltPath = secondaryStorage.getLocalPath() + File.separator
+ templateInstallFolder;
_storage.mkdirs(tmpltPath);
if (primary.getType() != StoragePoolType.RBD) {
Script command = new Script(_createTmplPath, _cmdsTimeout, s_logger);
command.add("-f", disk.getPath());
command.add("-t", tmpltPath);
command.add("-n", cmd.getUniqueName() + ".qcow2");
String result = command.execute();
if (result != null) {
s_logger.debug("failed to create template: " + result);
return new CreatePrivateTemplateAnswer(cmd, false, result);
}
} else {
s_logger.debug("Converting RBD disk " + disk.getPath() + " into template " + cmd.getUniqueName());
Script.runSimpleBashScript("qemu-img convert"
+ " -f raw -O qcow2 "
+ KVMPhysicalDisk.RBDStringBuilder(primary.getSourceHost(),
primary.getSourcePort(),
primary.getAuthUserName(),
primary.getAuthSecret(),
disk.getPath())
+ " " + tmpltPath + "/" + cmd.getUniqueName() + ".qcow2");
File templateProp = new File(tmpltPath + "/template.properties");
if (!templateProp.exists()) {
templateProp.createNewFile();
}
String templateContent = "filename=" + cmd.getUniqueName() + ".qcow2" + System.getProperty("line.separator");
DateFormat dateFormat = new SimpleDateFormat("MM_dd_yyyy");
Date date = new Date();
templateContent += "snapshot.name=" + dateFormat.format(date) + System.getProperty("line.separator");
FileOutputStream templFo = new FileOutputStream(templateProp);
templFo.write(templateContent.getBytes());
templFo.flush();
templFo.close();
}
Map<String, Object> params = new HashMap<String, Object>();
params.put(StorageLayer.InstanceConfigKey, _storage);
Processor qcow2Processor = new QCOW2Processor();
qcow2Processor.configure("QCOW2 Processor", params);
FormatInfo info = qcow2Processor.process(tmpltPath, null,
cmd.getUniqueName());
TemplateLocation loc = new TemplateLocation(_storage, tmpltPath);
loc.create(1, true, cmd.getUniqueName());
loc.addFormat(info);
loc.save();
return new CreatePrivateTemplateAnswer(cmd, true, null,
templateInstallFolder + cmd.getUniqueName() + ".qcow2",
info.virtualSize, info.size, cmd.getUniqueName(),
ImageFormat.QCOW2);
} catch (LibvirtException e) {
s_logger.debug("Failed to get secondary storage pool: "
+ e.toString());
return new CreatePrivateTemplateAnswer(cmd, false, e.toString());
} catch (InternalErrorException e) {
return new CreatePrivateTemplateAnswer(cmd, false, e.toString());
} catch (IOException e) {
return new CreatePrivateTemplateAnswer(cmd, false, e.toString());
} catch (ConfigurationException e) {
return new CreatePrivateTemplateAnswer(cmd, false, e.toString());
} catch (CloudRuntimeException e) {
return new CreatePrivateTemplateAnswer(cmd, false, e.toString());
} finally {
if (secondaryStorage != null) {
secondaryStorage.delete();
}
}
}
protected PrimaryStorageDownloadAnswer execute(
final PrimaryStorageDownloadCommand cmd) {
String tmplturl = cmd.getUrl();
int index = tmplturl.lastIndexOf("/");
String mountpoint = tmplturl.substring(0, index);
String tmpltname = null;
if (index < tmplturl.length() - 1) {
tmpltname = tmplturl.substring(index + 1);
}
KVMPhysicalDisk tmplVol = null;
KVMStoragePool secondaryPool = null;
try {
secondaryPool = _storagePoolMgr.getStoragePoolByURI(mountpoint);
/* Get template vol */
if (tmpltname == null) {
secondaryPool.refresh();
List<KVMPhysicalDisk> disks = secondaryPool.listPhysicalDisks();
if (disks == null || disks.isEmpty()) {
return new PrimaryStorageDownloadAnswer(
"Failed to get volumes from pool: "
+ secondaryPool.getUuid());
}
for (KVMPhysicalDisk disk : disks) {
if (disk.getName().endsWith("qcow2")) {
tmplVol = disk;
break;
}
}
if (tmplVol == null) {
return new PrimaryStorageDownloadAnswer(
"Failed to get template from pool: "
+ secondaryPool.getUuid());
}
} else {
tmplVol = secondaryPool.getPhysicalDisk(tmpltname);
}
/* Copy volume to primary storage */
KVMStoragePool primaryPool = _storagePoolMgr.getStoragePool(cmd
.getPoolUuid());
KVMPhysicalDisk primaryVol = _storagePoolMgr.copyPhysicalDisk(
tmplVol, UUID.randomUUID().toString(), primaryPool);
return new PrimaryStorageDownloadAnswer(primaryVol.getName(),
primaryVol.getSize());
} catch (CloudRuntimeException e) {
return new PrimaryStorageDownloadAnswer(e.toString());
} finally {
if (secondaryPool != null) {
secondaryPool.delete();
}
}
}
protected Answer execute(CreateStoragePoolCommand cmd) {
return new Answer(cmd, true, "success");
}
protected Answer execute(ModifyStoragePoolCommand cmd) {
KVMStoragePool storagepool = _storagePoolMgr.createStoragePool(cmd
.getPool().getUuid(), cmd.getPool().getHost(), cmd.getPool().getPort(),
cmd.getPool().getPath(), cmd.getPool().getUserInfo(), cmd.getPool().getType());
if (storagepool == null) {
return new Answer(cmd, false, " Failed to create storage pool");
}
Map<String, TemplateInfo> tInfo = new HashMap<String, TemplateInfo>();
ModifyStoragePoolAnswer answer = new ModifyStoragePoolAnswer(cmd,
storagepool.getCapacity(), storagepool.getUsed(), tInfo);
return answer;
}
private Answer execute(SecurityGroupRulesCmd cmd) {
String vif = null;
String brname = null;
try {
Connect conn = LibvirtConnection.getConnection();
List<InterfaceDef> nics = getInterfaces(conn, cmd.getVmName());
vif = nics.get(0).getDevName();
brname = nics.get(0).getBrName();
} catch (LibvirtException e) {
return new SecurityGroupRuleAnswer(cmd, false, e.toString());
}
boolean result = add_network_rules(cmd.getVmName(),
Long.toString(cmd.getVmId()), cmd.getGuestIp(),
cmd.getSignature(), Long.toString(cmd.getSeqNum()),
cmd.getGuestMac(), cmd.stringifyRules(), vif, brname);
if (!result) {
s_logger.warn("Failed to program network rules for vm "
+ cmd.getVmName());
return new SecurityGroupRuleAnswer(cmd, false,
"programming network rules failed");
} else {
s_logger.debug("Programmed network rules for vm " + cmd.getVmName()
+ " guestIp=" + cmd.getGuestIp() + ",ingress numrules="
+ cmd.getIngressRuleSet().length + ",egress numrules="
+ cmd.getEgressRuleSet().length);
return new SecurityGroupRuleAnswer(cmd);
}
}
private Answer execute(CleanupNetworkRulesCmd cmd) {
boolean result = cleanup_rules();
return new Answer(cmd, result, "");
}
protected GetVncPortAnswer execute(GetVncPortCommand cmd) {
try {
Connect conn = LibvirtConnection.getConnection();
Integer vncPort = getVncPort(conn, cmd.getName());
return new GetVncPortAnswer(cmd, _privateIp, 5900 + vncPort);
} catch (Exception e) {
return new GetVncPortAnswer(cmd, e.toString());
}
}
protected Answer execute(final CheckConsoleProxyLoadCommand cmd) {
return executeProxyLoadScan(cmd, cmd.getProxyVmId(),
cmd.getProxyVmName(), cmd.getProxyManagementIp(),
cmd.getProxyCmdPort());
}
protected Answer execute(final WatchConsoleProxyLoadCommand cmd) {
return executeProxyLoadScan(cmd, cmd.getProxyVmId(),
cmd.getProxyVmName(), cmd.getProxyManagementIp(),
cmd.getProxyCmdPort());
}
protected MaintainAnswer execute(MaintainCommand cmd) {
return new MaintainAnswer(cmd);
}
private Answer executeProxyLoadScan(final Command cmd,
final long proxyVmId, final String proxyVmName,
final String proxyManagementIp, final int cmdPort) {
String result = null;
final StringBuffer sb = new StringBuffer();
sb.append("http://").append(proxyManagementIp).append(":" + cmdPort)
.append("/cmd/getstatus");
boolean success = true;
try {
final URL url = new URL(sb.toString());
final URLConnection conn = url.openConnection();
final InputStream is = conn.getInputStream();
final BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
final StringBuilder sb2 = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb2.append(line + "\n");
}
result = sb2.toString();
} catch (final IOException e) {
success = false;
} finally {
try {
is.close();
} catch (final IOException e) {
s_logger.warn("Exception when closing , console proxy address : "
+ proxyManagementIp);
success = false;
}
}
} catch (final IOException e) {
s_logger.warn("Unable to open console proxy command port url, console proxy address : "
+ proxyManagementIp);
success = false;
}
return new ConsoleProxyLoadAnswer(cmd, proxyVmId, proxyVmName, success,
result);
}
private Answer execute(AttachIsoCommand cmd) {
try {
Connect conn = LibvirtConnection.getConnection();
attachOrDetachISO(conn, cmd.getVmName(), cmd.getIsoPath(),
cmd.isAttach());
} catch (LibvirtException e) {
return new Answer(cmd, false, e.toString());
} catch (URISyntaxException e) {
return new Answer(cmd, false, e.toString());
} catch (InternalErrorException e) {
return new Answer(cmd, false, e.toString());
}
return new Answer(cmd);
}
private AttachVolumeAnswer execute(AttachVolumeCommand cmd) {
try {
Connect conn = LibvirtConnection.getConnection();
KVMStoragePool primary = _storagePoolMgr.getStoragePool(cmd
.getPoolUuid());
KVMPhysicalDisk disk = primary.getPhysicalDisk(cmd.getVolumePath());
attachOrDetachDisk(conn, cmd.getAttach(), cmd.getVmName(), disk,
cmd.getDeviceId().intValue());
} catch (LibvirtException e) {
return new AttachVolumeAnswer(cmd, e.toString());
} catch (InternalErrorException e) {
return new AttachVolumeAnswer(cmd, e.toString());
}
return new AttachVolumeAnswer(cmd, cmd.getDeviceId());
}
private Answer execute(ReadyCommand cmd) {
return new ReadyAnswer(cmd);
}
protected State convertToState(DomainInfo.DomainState ps) {
final State state = s_statesTable.get(ps);
return state == null ? State.Unknown : state;
}
protected State getVmState(Connect conn, final String vmName) {
int retry = 3;
Domain vms = null;
while (retry-- > 0) {
try {
vms = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
.getBytes()));
State s = convertToState(vms.getInfo().state);
return s;
} catch (final LibvirtException e) {
s_logger.warn("Can't get vm state " + vmName + e.getMessage()
+ "retry:" + retry);
} catch (Exception e) {
s_logger.warn("Can't get vm state " + vmName + e.getMessage()
+ "retry:" + retry);
} finally {
try {
if (vms != null) {
vms.free();
}
} catch (final LibvirtException e) {
}
}
}
return State.Stopped;
}
private Answer execute(CheckVirtualMachineCommand cmd) {
try {
Connect conn = LibvirtConnection.getConnection();
final State state = getVmState(conn, cmd.getVmName());
Integer vncPort = null;
if (state == State.Running) {
vncPort = getVncPort(conn, cmd.getVmName());
synchronized (_vms) {
_vms.put(cmd.getVmName(), State.Running);
}
}
return new CheckVirtualMachineAnswer(cmd, state, vncPort);
} catch (LibvirtException e) {
return new CheckVirtualMachineAnswer(cmd, e.getMessage());
}
}
private Answer execute(PingTestCommand cmd) {
String result = null;
final String computingHostIp = cmd.getComputingHostIp(); // TODO, split
// the
// command
// into 2
// types
if (computingHostIp != null) {
result = doPingTest(computingHostIp);
} else if (cmd.getRouterIp() != null && cmd.getPrivateIp() != null) {
result = doPingTest(cmd.getRouterIp(), cmd.getPrivateIp());
} else {
return new Answer(cmd, false, "routerip and private ip is null");
}
if (result != null) {
return new Answer(cmd, false, result);
}
return new Answer(cmd);
}
private String doPingTest(final String computingHostIp) {
final Script command = new Script(_pingTestPath, 10000, s_logger);
command.add("-h", computingHostIp);
return command.execute();
}
private String doPingTest(final String domRIp, final String vmIp) {
final Script command = new Script(_pingTestPath, 10000, s_logger);
command.add("-i", domRIp);
command.add("-p", vmIp);
return command.execute();
}
private synchronized Answer execute(MigrateCommand cmd) {
String vmName = cmd.getVmName();
State state = null;
String result = null;
synchronized (_vms) {
state = _vms.get(vmName);
_vms.put(vmName, State.Stopping);
}
Domain dm = null;
Connect dconn = null;
Domain destDomain = null;
Connect conn = null;
try {
conn = LibvirtConnection.getConnection();
dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
.getBytes()));
dconn = new Connect("qemu+tcp://" + cmd.getDestinationIp()
+ "/system");
/*
* Hard code lm flags: VIR_MIGRATE_LIVE(1<<0) and
* VIR_MIGRATE_PERSIST_DEST(1<<3)
*/
destDomain = dm.migrate(dconn, (1 << 0) | (1 << 3), vmName, "tcp:"
+ cmd.getDestinationIp(), _migrateSpeed);
} catch (LibvirtException e) {
s_logger.debug("Can't migrate domain: " + e.getMessage());
result = e.getMessage();
} catch (Exception e) {
s_logger.debug("Can't migrate domain: " + e.getMessage());
result = e.getMessage();
} finally {
try {
if (dm != null) {
dm.free();
}
if (dconn != null) {
dconn.close();
}
if (destDomain != null) {
destDomain.free();
}
} catch (final LibvirtException e) {
}
}
if (result != null) {
synchronized (_vms) {
_vms.put(vmName, state);
}
} else {
destroy_network_rules_for_vm(conn, vmName);
cleanupVM(conn, vmName,
getVnetId(VirtualMachineName.getVnet(vmName)));
}
return new MigrateAnswer(cmd, result == null, result, null);
}
private synchronized Answer execute(PrepareForMigrationCommand cmd) {
VirtualMachineTO vm = cmd.getVirtualMachine();
if (s_logger.isDebugEnabled()) {
s_logger.debug("Preparing host for migrating " + vm);
}
NicTO[] nics = vm.getNics();
try {
Connect conn = LibvirtConnection.getConnection();
for (NicTO nic : nics) {
String vlanId = null;
if (nic.getBroadcastType() == BroadcastDomainType.Vlan) {
URI broadcastUri = nic.getBroadcastUri();
vlanId = broadcastUri.getHost();
}
if (nic.getType() == TrafficType.Guest) {
if (nic.getBroadcastType() == BroadcastDomainType.Vlan
&& !vlanId.equalsIgnoreCase("untagged")) {
createVlanBr(vlanId, _pifs.first());
}
} else if (nic.getType() == TrafficType.Control) {
/* Make sure the network is still there */
createControlNetwork();
} else if (nic.getType() == TrafficType.Public) {
if (nic.getBroadcastType() == BroadcastDomainType.Vlan
&& !vlanId.equalsIgnoreCase("untagged")) {
createVlanBr(vlanId, _pifs.second());
}
}
}
/* setup disks, e.g for iso */
VolumeTO[] volumes = vm.getDisks();
for (VolumeTO volume : volumes) {
if (volume.getType() == Volume.Type.ISO) {
getVolumePath(conn, volume);
}
}
synchronized (_vms) {
_vms.put(vm.getName(), State.Migrating);
}
return new PrepareForMigrationAnswer(cmd);
} catch (LibvirtException e) {
return new PrepareForMigrationAnswer(cmd, e.toString());
} catch (InternalErrorException e) {
return new PrepareForMigrationAnswer(cmd, e.toString());
} catch (URISyntaxException e) {
return new PrepareForMigrationAnswer(cmd, e.toString());
}
}
public void createVnet(String vnetId, String pif)
throws InternalErrorException {
final Script command = new Script(_modifyVlanPath, _timeout, s_logger);
command.add("-v", vnetId);
command.add("-p", pif);
command.add("-o", "add");
final String result = command.execute();
if (result != null) {
throw new InternalErrorException("Failed to create vnet " + vnetId
+ ": " + result);
}
}
private Answer execute(CheckHealthCommand cmd) {
return new CheckHealthAnswer(cmd, true);
}
private Answer execute(GetHostStatsCommand cmd) {
final Script cpuScript = new Script("/bin/bash", s_logger);
cpuScript.add("-c");
cpuScript
.add("idle=$(top -b -n 1|grep Cpu\\(s\\):|cut -d% -f4|cut -d, -f2);echo $idle");
final OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser();
String result = cpuScript.execute(parser);
if (result != null) {
s_logger.debug("Unable to get the host CPU state: " + result);
return new Answer(cmd, false, result);
}
double cpuUtil = (100.0D - Double.parseDouble(parser.getLine()));
long freeMem = 0;
final Script memScript = new Script("/bin/bash", s_logger);
memScript.add("-c");
memScript
.add("freeMem=$(free|grep cache:|awk '{print $4}');echo $freeMem");
final OutputInterpreter.OneLineParser Memparser = new OutputInterpreter.OneLineParser();
result = memScript.execute(Memparser);
if (result != null) {
s_logger.debug("Unable to get the host Mem state: " + result);
return new Answer(cmd, false, result);
}
freeMem = Long.parseLong(Memparser.getLine());
Script totalMem = new Script("/bin/bash", s_logger);
totalMem.add("-c");
totalMem.add("free|grep Mem:|awk '{print $2}'");
final OutputInterpreter.OneLineParser totMemparser = new OutputInterpreter.OneLineParser();
result = totalMem.execute(totMemparser);
if (result != null) {
s_logger.debug("Unable to get the host Mem state: " + result);
return new Answer(cmd, false, result);
}
long totMem = Long.parseLong(totMemparser.getLine());
Pair<Double, Double> nicStats = getNicStats(_publicBridgeName);
HostStatsEntry hostStats = new HostStatsEntry(cmd.getHostId(), cpuUtil,
nicStats.first() / 1000, nicStats.second() / 1000, "host",
totMem, freeMem, 0, 0);
return new GetHostStatsAnswer(cmd, hostStats);
}
protected String networkUsage(final String privateIpAddress,
final String option, final String vif) {
Script getUsage = new Script(_networkUsagePath, s_logger);
if (option.equals("get")) {
getUsage.add("-g");
} else if (option.equals("create")) {
getUsage.add("-c");
} else if (option.equals("reset")) {
getUsage.add("-r");
} else if (option.equals("addVif")) {
getUsage.add("-a", vif);
} else if (option.equals("deleteVif")) {
getUsage.add("-d", vif);
}
getUsage.add("-i", privateIpAddress);
final OutputInterpreter.OneLineParser usageParser = new OutputInterpreter.OneLineParser();
String result = getUsage.execute(usageParser);
if (result != null) {
s_logger.debug("Failed to execute networkUsage:" + result);
return null;
}
return usageParser.getLine();
}
protected long[] getNetworkStats(String privateIP) {
String result = networkUsage(privateIP, "get", null);
long[] stats = new long[2];
if (result != null) {
String[] splitResult = result.split(":");
int i = 0;
while (i < splitResult.length - 1) {
stats[0] += (new Long(splitResult[i++])).longValue();
stats[1] += (new Long(splitResult[i++])).longValue();
}
}
return stats;
}
private Answer execute(NetworkUsageCommand cmd) {
if (cmd.getOption() != null && cmd.getOption().equals("create")) {
String result = networkUsage(cmd.getPrivateIP(), "create", null);
NetworkUsageAnswer answer = new NetworkUsageAnswer(cmd, result, 0L,
0L);
return answer;
}
long[] stats = getNetworkStats(cmd.getPrivateIP());
NetworkUsageAnswer answer = new NetworkUsageAnswer(cmd, "", stats[0],
stats[1]);
return answer;
}
private Answer execute(RebootCommand cmd) {
synchronized (_vms) {
_vms.put(cmd.getVmName(), State.Starting);
}
try {
Connect conn = LibvirtConnection.getConnection();
final String result = rebootVM(conn, cmd.getVmName());
if (result == null) {
Integer vncPort = null;
try {
vncPort = getVncPort(conn, cmd.getVmName());
} catch (Exception e) {
}
get_rule_logs_for_vms();
return new RebootAnswer(cmd, null, vncPort);
} else {
return new RebootAnswer(cmd, result, false);
}
} catch (LibvirtException e) {
return new RebootAnswer(cmd, e.getMessage(), false);
} finally {
synchronized (_vms) {
_vms.put(cmd.getVmName(), State.Running);
}
}
}
protected Answer execute(RebootRouterCommand cmd) {
RebootAnswer answer = (RebootAnswer) execute((RebootCommand) cmd);
String result = _virtRouterResource.connect(cmd.getPrivateIpAddress());
if (result == null) {
networkUsage(cmd.getPrivateIpAddress(), "create", null);
return answer;
} else {
return new Answer(cmd, false, result);
}
}
protected GetVmStatsAnswer execute(GetVmStatsCommand cmd) {
List<String> vmNames = cmd.getVmNames();
try {
HashMap<String, VmStatsEntry> vmStatsNameMap = new HashMap<String, VmStatsEntry>();
Connect conn = LibvirtConnection.getConnection();
for (String vmName : vmNames) {
VmStatsEntry statEntry = getVmStat(conn, vmName);
if (statEntry == null) {
continue;
}
vmStatsNameMap.put(vmName, statEntry);
}
return new GetVmStatsAnswer(cmd, vmStatsNameMap);
} catch (LibvirtException e) {
s_logger.debug("Can't get vm stats: " + e.toString());
return new GetVmStatsAnswer(cmd, null);
}
}
protected Answer execute(StopCommand cmd) {
final String vmName = cmd.getVmName();
State state = null;
synchronized (_vms) {
state = _vms.get(vmName);
_vms.put(vmName, State.Stopping);
}
try {
Connect conn = LibvirtConnection.getConnection();
List<DiskDef> disks = getDisks(conn, vmName);
destroy_network_rules_for_vm(conn, vmName);
String result = stopVM(conn, vmName, defineOps.UNDEFINE_VM);
if (result == null) {
for (DiskDef disk : disks) {
if (disk.getDeviceType() == DiskDef.deviceType.CDROM
&& disk.getDiskPath() != null)
cleanupDisk(conn, disk);
}
}
final String result2 = cleanupVnet(conn, cmd.getVnet());
if (result != null && result2 != null) {
result = result2 + result;
}
state = State.Stopped;
return new StopAnswer(cmd, result, 0, true);
} catch (LibvirtException e) {
return new StopAnswer(cmd, e.getMessage(), false);
} finally {
synchronized (_vms) {
if (state != null) {
_vms.put(vmName, state);
} else {
_vms.remove(vmName);
}
}
}
}
protected Answer execute(ModifySshKeysCommand cmd) {
File sshKeysDir = new File(_SSHKEYSPATH);
String result = null;
if (!sshKeysDir.exists()) {
sshKeysDir.mkdir();
// Change permissions for the 600
Script script = new Script("chmod", _timeout, s_logger);
script.add("600", _SSHKEYSPATH);
script.execute();
}
File pubKeyFile = new File(_SSHPUBKEYPATH);
if (!pubKeyFile.exists()) {
try {
pubKeyFile.createNewFile();
} catch (IOException e) {
result = "Failed to create file: " + e.toString();
s_logger.debug(result);
}
}
if (pubKeyFile.exists()) {
String pubKey = cmd.getPubKey();
try {
FileOutputStream pubkStream = new FileOutputStream(pubKeyFile);
pubkStream.write(pubKey.getBytes());
pubkStream.close();
} catch (FileNotFoundException e) {
result = "File" + _SSHPUBKEYPATH + "is not found:"
+ e.toString();
s_logger.debug(result);
} catch (IOException e) {
result = "Write file " + _SSHPUBKEYPATH + ":" + e.toString();
s_logger.debug(result);
}
}
File prvKeyFile = new File(_SSHPRVKEYPATH);
if (!prvKeyFile.exists()) {
try {
prvKeyFile.createNewFile();
} catch (IOException e) {
result = "Failed to create file: " + e.toString();
s_logger.debug(result);
}
}
if (prvKeyFile.exists()) {
String prvKey = cmd.getPrvKey();
try {
FileOutputStream prvKStream = new FileOutputStream(prvKeyFile);
prvKStream.write(prvKey.getBytes());
prvKStream.close();
} catch (FileNotFoundException e) {
result = "File" + _SSHPRVKEYPATH + "is not found:"
+ e.toString();
s_logger.debug(result);
} catch (IOException e) {
result = "Write file " + _SSHPRVKEYPATH + ":" + e.toString();
s_logger.debug(result);
}
Script script = new Script("chmod", _timeout, s_logger);
script.add("600", _SSHPRVKEYPATH);
script.execute();
}
if (result != null) {
return new Answer(cmd, false, result);
} else {
return new Answer(cmd, true, null);
}
}
protected void handleVmStartFailure(Connect conn, String vmName,
LibvirtVMDef vm) {
if (vm != null && vm.getDevices() != null) {
cleanupVMNetworks(conn, vm.getDevices().getInterfaces());
}
}
protected LibvirtVMDef createVMFromSpec(VirtualMachineTO vmTO) {
LibvirtVMDef vm = new LibvirtVMDef();
vm.setHvsType(_hypervisorType);
vm.setDomainName(vmTO.getName());
vm.setDomUUID(UUID.nameUUIDFromBytes(vmTO.getName().getBytes())
.toString());
vm.setDomDescription(vmTO.getOs());
GuestDef guest = new GuestDef();
guest.setGuestType(GuestDef.guestType.KVM);
guest.setGuestArch(vmTO.getArch());
guest.setMachineType("pc");
guest.setBootOrder(GuestDef.bootOrder.CDROM);
guest.setBootOrder(GuestDef.bootOrder.HARDISK);
vm.addComp(guest);
GuestResourceDef grd = new GuestResourceDef();
grd.setMemorySize(vmTO.getMinRam() / 1024);
grd.setVcpuNum(vmTO.getCpus());
vm.addComp(grd);
CpuTuneDef ctd = new CpuTuneDef();
ctd.setShares(vmTO.getCpus() * vmTO.getSpeed());
vm.addComp(ctd);
FeaturesDef features = new FeaturesDef();
features.addFeatures("pae");
features.addFeatures("apic");
features.addFeatures("acpi");
vm.addComp(features);
TermPolicy term = new TermPolicy();
term.setCrashPolicy("destroy");
term.setPowerOffPolicy("destroy");
term.setRebootPolicy("restart");
vm.addComp(term);
ClockDef clock = new ClockDef();
if (vmTO.getOs().startsWith("Windows")) {
clock.setClockOffset(ClockDef.ClockOffset.LOCALTIME);
clock.setTimer("rtc", "catchup", null);
}
vm.addComp(clock);
DevicesDef devices = new DevicesDef();
devices.setEmulatorPath(_hypervisorPath);
SerialDef serial = new SerialDef("pty", null, (short) 0);
devices.addDevice(serial);
ConsoleDef console = new ConsoleDef("pty", null, null, (short) 0);
devices.addDevice(console);
GraphicDef grap = new GraphicDef("vnc", (short) 0, true, vmTO.getVncAddr(), null,
null);
devices.addDevice(grap);
InputDef input = new InputDef("tablet", "usb");
devices.addDevice(input);
vm.addComp(devices);
return vm;
}
protected void createVifs(VirtualMachineTO vmSpec,
LibvirtVMDef vm) throws InternalErrorException, LibvirtException {
NicTO[] nics = vmSpec.getNics();
for (int i = 0; i < nics.length; i++) {
for (NicTO nic : vmSpec.getNics()) {
if (nic.getDeviceId() == i) {
createVif(vm, nic);
}
}
}
}
protected synchronized StartAnswer execute(StartCommand cmd) {
VirtualMachineTO vmSpec = cmd.getVirtualMachine();
vmSpec.setVncAddr(cmd.getHostIp());
String vmName = vmSpec.getName();
LibvirtVMDef vm = null;
State state = State.Stopped;
Connect conn = null;
try {
conn = LibvirtConnection.getConnection();
synchronized (_vms) {
_vms.put(vmName, State.Starting);
}
vm = createVMFromSpec(vmSpec);
createVbd(conn, vmSpec, vmName, vm);
createVifs(vmSpec, vm);
s_logger.debug("starting " + vmName + ": " + vm.toString());
startDomain(conn, vmName, vm.toString());
NicTO[] nics = vmSpec.getNics();
for (NicTO nic : nics) {
if (nic.getIsolationUri() != null
&& nic.getIsolationUri().getScheme()
.equalsIgnoreCase(IsolationType.Ec2.toString())) {
if (vmSpec.getType() != VirtualMachine.Type.User) {
default_network_rules_for_systemvm(conn, vmName);
break;
} else {
default_network_rules(conn, vmName, nic, vmSpec.getId());
}
}
}
state = State.Running;
return new StartAnswer(cmd);
} catch (Exception e) {
s_logger.warn("Exception ", e);
if (conn != null) {
handleVmStartFailure(conn, vmName, vm);
}
return new StartAnswer(cmd, e.getMessage());
} finally {
synchronized (_vms) {
if (state != State.Stopped) {
_vms.put(vmName, state);
} else {
_vms.remove(vmName);
}
}
}
}
private String getVolumePath(Connect conn, VolumeTO volume)
throws LibvirtException, URISyntaxException {
if (volume.getType() == Volume.Type.ISO && volume.getPath() != null) {
String isoPath = volume.getPath();
int index = isoPath.lastIndexOf("/");
String path = isoPath.substring(0, index);
String name = isoPath.substring(index + 1);
KVMStoragePool secondaryPool = _storagePoolMgr
.getStoragePoolByURI(path);
KVMPhysicalDisk isoVol = secondaryPool.getPhysicalDisk(name);
return isoVol.getPath();
} else {
return volume.getPath();
}
}
protected void createVbd(Connect conn, VirtualMachineTO vmSpec,
String vmName, LibvirtVMDef vm) throws InternalErrorException,
LibvirtException, URISyntaxException {
List<VolumeTO> disks = Arrays.asList(vmSpec.getDisks());
Collections.sort(disks, new Comparator<VolumeTO>() {
@Override
public int compare(VolumeTO arg0, VolumeTO arg1) {
return arg0.getDeviceId() > arg1.getDeviceId() ? 1 : -1;
}
});
for (VolumeTO volume : disks) {
KVMPhysicalDisk physicalDisk = null;
KVMStoragePool pool = null;
if (volume.getType() == Volume.Type.ISO && volume.getPath() != null) {
String volPath = volume.getPath();
int index = volPath.lastIndexOf("/");
String volDir = volPath.substring(0, index);
String volName = volPath.substring(index + 1);
KVMStoragePool secondaryStorage = _storagePoolMgr
.getStoragePoolByURI(volDir);
physicalDisk = secondaryStorage.getPhysicalDisk(volName);
} else if (volume.getType() != Volume.Type.ISO) {
pool = _storagePoolMgr.getStoragePool(volume.getPoolUuid());
physicalDisk = pool.getPhysicalDisk(volume.getPath());
}
String volPath = null;
if (physicalDisk != null) {
volPath = physicalDisk.getPath();
}
DiskDef.diskBus diskBusType = getGuestDiskModel(vmSpec.getOs());
DiskDef disk = new DiskDef();
if (volume.getType() == Volume.Type.ISO) {
if (volPath == null) {
/* Add iso as placeholder */
disk.defISODisk(null);
} else {
disk.defISODisk(volPath);
}
} else {
int devId = (int) volume.getDeviceId();
if (pool.getType() == StoragePoolType.RBD) {
/*
For RBD pools we use the secret mechanism in libvirt.
We store the secret under the UUID of the pool, that's why
we pass the pool's UUID as the authSecret
*/
disk.defNetworkBasedDisk(physicalDisk.getPath().replace("rbd:", ""), pool.getSourceHost(), pool.getSourcePort(),
pool.getAuthUserName(), pool.getUuid(),
devId, diskBusType, diskProtocol.RBD);
} else if (volume.getType() == Volume.Type.DATADISK) {
disk.defFileBasedDisk(physicalDisk.getPath(), devId,
DiskDef.diskBus.VIRTIO,
DiskDef.diskFmtType.QCOW2);
} else {
disk.defFileBasedDisk(physicalDisk.getPath(), devId,
diskBusType, DiskDef.diskFmtType.QCOW2);
}
}
vm.getDevices().addDevice(disk);
}
if (vmSpec.getType() != VirtualMachine.Type.User) {
if (_sysvmISOPath != null) {
DiskDef iso = new DiskDef();
iso.defISODisk(_sysvmISOPath);
vm.getDevices().addDevice(iso);
}
createPatchVbd(conn, vmName, vm, vmSpec);
}
}
private VolumeTO getVolume(VirtualMachineTO vmSpec, Volume.Type type) {
VolumeTO volumes[] = vmSpec.getDisks();
for (VolumeTO volume : volumes) {
if (volume.getType() == type) {
return volume;
}
}
return null;
}
private void createPatchVbd(Connect conn, String vmName, LibvirtVMDef vm,
VirtualMachineTO vmSpec) throws LibvirtException,
InternalErrorException {
List<DiskDef> disks = vm.getDevices().getDisks();
DiskDef rootDisk = disks.get(0);
VolumeTO rootVol = getVolume(vmSpec, Volume.Type.ROOT);
KVMStoragePool pool = _storagePoolMgr.getStoragePool(rootVol
.getPoolUuid());
KVMPhysicalDisk disk = pool.createPhysicalDisk(UUID.randomUUID()
.toString(), KVMPhysicalDisk.PhysicalDiskFormat.RAW,
10L * 1024 * 1024);
/* Format/create fs on this disk */
final Script command = new Script(_createvmPath, _timeout, s_logger);
command.add("-f", disk.getPath());
String result = command.execute();
if (result != null) {
s_logger.debug("Failed to create data disk: " + result);
throw new InternalErrorException("Failed to create data disk: "
+ result);
}
String datadiskPath = disk.getPath();
/* add patch disk */
DiskDef patchDisk = new DiskDef();
patchDisk.defFileBasedDisk(datadiskPath, 1, rootDisk.getBusType(),
DiskDef.diskFmtType.RAW);
disks.add(patchDisk);
String bootArgs = vmSpec.getBootArgs();
patchSystemVm(bootArgs, datadiskPath, vmName);
}
private String createVlanBr(String vlanId, String nic)
throws InternalErrorException {
String brName = setVnetBrName(vlanId);
createVnet(vlanId, nic);
return brName;
}
private InterfaceDef createVif(NicTO nic,
InterfaceDef.nicModel model) throws InternalErrorException,
LibvirtException {
InterfaceDef intf = new InterfaceDef();
String vlanId = null;
if (nic.getBroadcastType() == BroadcastDomainType.Vlan) {
URI broadcastUri = nic.getBroadcastUri();
vlanId = broadcastUri.getHost();
}
if (nic.getType() == TrafficType.Guest) {
if (nic.getBroadcastType() == BroadcastDomainType.Vlan
&& !vlanId.equalsIgnoreCase("untagged")) {
String brName = createVlanBr(vlanId, _pifs.first());
intf.defBridgeNet(brName, null, nic.getMac(), model);
} else {
intf.defBridgeNet(_guestBridgeName, null, nic.getMac(), model);
}
} else if (nic.getType() == TrafficType.Control) {
/* Make sure the network is still there */
createControlNetwork();
intf.defBridgeNet(_linkLocalBridgeName, null, nic.getMac(), model);
} else if (nic.getType() == TrafficType.Public) {
if (nic.getBroadcastType() == BroadcastDomainType.Vlan
&& !vlanId.equalsIgnoreCase("untagged")) {
String brName = createVlanBr(vlanId, _pifs.second());
intf.defBridgeNet(brName, null, nic.getMac(), model);
} else {
intf.defBridgeNet(_publicBridgeName, null, nic.getMac(), model);
}
} else if (nic.getType() == TrafficType.Management) {
intf.defBridgeNet(_privBridgeName, null, nic.getMac(), model);
} else if (nic.getType() == TrafficType.Storage) {
String storageBrName = nic.getName() == null ? _privBridgeName
: nic.getName();
intf.defBridgeNet(storageBrName, null, nic.getMac(), model);
}
return intf;
}
private void createVif(LibvirtVMDef vm, NicTO nic)
throws InternalErrorException, LibvirtException {
vm.getDevices().addDevice(
createVif(nic, getGuestNicModel(vm.getGuestOSType())));
}
protected CheckSshAnswer execute(CheckSshCommand cmd) {
String vmName = cmd.getName();
String privateIp = cmd.getIp();
int cmdPort = cmd.getPort();
if (s_logger.isDebugEnabled()) {
s_logger.debug("Ping command port, " + privateIp + ":" + cmdPort);
}
try {
String result = _virtRouterResource.connect(privateIp, cmdPort);
if (result != null) {
return new CheckSshAnswer(cmd, "Can not ping System vm "
+ vmName + "due to:" + result);
}
} catch (Exception e) {
return new CheckSshAnswer(cmd, e);
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Ping command port succeeded for vm " + vmName);
}
return new CheckSshAnswer(cmd);
}
private boolean cleanupDisk(Connect conn, DiskDef disk) {
// need to umount secondary storage
String path = disk.getDiskPath();
String poolUuid = null;
if (path != null) {
String[] token = path.split("/");
if (token.length > 3) {
poolUuid = token[2];
}
}
if (poolUuid == null) {
return true;
}
try {
KVMStoragePool pool = _storagePoolMgr.getStoragePool(poolUuid);
if (pool != null) {
pool.delete();
}
return true;
} catch (CloudRuntimeException e) {
return false;
}
}
protected synchronized String attachOrDetachISO(Connect conn,
String vmName, String isoPath, boolean isAttach)
throws LibvirtException, URISyntaxException, InternalErrorException {
String isoXml = null;
if (isoPath != null && isAttach) {
int index = isoPath.lastIndexOf("/");
String path = isoPath.substring(0, index);
String name = isoPath.substring(index + 1);
KVMStoragePool secondaryPool = _storagePoolMgr
.getStoragePoolByURI(path);
KVMPhysicalDisk isoVol = secondaryPool.getPhysicalDisk(name);
isoPath = isoVol.getPath();
DiskDef iso = new DiskDef();
iso.defISODisk(isoPath);
isoXml = iso.toString();
} else {
DiskDef iso = new DiskDef();
iso.defISODisk(null);
isoXml = iso.toString();
}
List<DiskDef> disks = getDisks(conn, vmName);
String result = attachOrDetachDevice(conn, true, vmName, isoXml);
if (result == null && !isAttach) {
for (DiskDef disk : disks) {
if (disk.getDeviceType() == DiskDef.deviceType.CDROM) {
cleanupDisk(conn, disk);
}
}
}
return result;
}
protected synchronized String attachOrDetachDisk(Connect conn,
boolean attach, String vmName, KVMPhysicalDisk attachingDisk,
int devId) throws LibvirtException, InternalErrorException {
List<DiskDef> disks = null;
Domain dm = null;
DiskDef diskdef = null;
try {
if (!attach) {
dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
.getBytes()));
LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser();
String xml = dm.getXMLDesc(0);
parser.parseDomainXML(xml);
disks = parser.getDisks();
for (DiskDef disk : disks) {
String file = disk.getDiskPath();
if (file != null
&& file.equalsIgnoreCase(attachingDisk.getPath())) {
diskdef = disk;
break;
}
}
if (diskdef == null) {
throw new InternalErrorException("disk: "
+ attachingDisk.getPath()
+ " is not attached before");
}
} else {
diskdef = new DiskDef();
if (attachingDisk.getFormat() == PhysicalDiskFormat.QCOW2) {
diskdef.defFileBasedDisk(attachingDisk.getPath(), devId,
DiskDef.diskBus.VIRTIO, DiskDef.diskFmtType.QCOW2);
} else if (attachingDisk.getFormat() == PhysicalDiskFormat.RAW) {
diskdef.defBlockBasedDisk(attachingDisk.getPath(), devId,
DiskDef.diskBus.VIRTIO);
}
}
String xml = diskdef.toString();
return attachOrDetachDevice(conn, attach, vmName, xml);
} finally {
if (dm != null) {
dm.free();
}
}
}
protected synchronized String attachOrDetachDevice(Connect conn,
boolean attach, String vmName, String xml) throws LibvirtException,
InternalErrorException {
Domain dm = null;
try {
dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes((vmName
.getBytes())));
if (attach) {
s_logger.debug("Attaching device: " + xml);
dm.attachDevice(xml);
} else {
s_logger.debug("Detaching device: " + xml);
dm.detachDevice(xml);
}
} catch (LibvirtException e) {
if (attach) {
s_logger.warn("Failed to attach device to " + vmName + ": "
+ e.getMessage());
} else {
s_logger.warn("Failed to detach device from " + vmName + ": "
+ e.getMessage());
}
throw e;
} catch (Exception e) {
throw new InternalErrorException(e.toString());
} finally {
if (dm != null) {
try {
dm.free();
} catch (LibvirtException l) {
}
}
}
return null;
}
@Override
public PingCommand getCurrentStatus(long id) {
final HashMap<String, State> newStates = sync();
if (!_can_bridge_firewall) {
return new PingRoutingCommand(com.cloud.host.Host.Type.Routing, id,
newStates);
} else {
HashMap<String, Pair<Long, Long>> nwGrpStates = syncNetworkGroups(id);
return new PingRoutingWithNwGroupsCommand(getType(), id, newStates,
nwGrpStates);
}
}
@Override
public Type getType() {
return Type.Routing;
}
private Map<String, String> getVersionStrings() {
final Script command = new Script(_versionstringpath, _timeout,
s_logger);
KeyValueInterpreter kvi = new KeyValueInterpreter();
String result = command.execute(kvi);
if (result == null) {
return kvi.getKeyValues();
} else {
return new HashMap<String, String>(1);
}
}
@Override
public StartupCommand[] initialize() {
Map<String, State> changes = null;
synchronized (_vms) {
_vms.clear();
changes = sync();
}
final List<Object> info = getHostInfo();
final StartupRoutingCommand cmd = new StartupRoutingCommand(
(Integer) info.get(0), (Long) info.get(1), (Long) info.get(2),
(Long) info.get(4), (String) info.get(3), HypervisorType.KVM,
RouterPrivateIpStrategy.HostLocal);
cmd.setStateChanges(changes);
fillNetworkInformation(cmd);
_privateIp = cmd.getPrivateIpAddress();
cmd.getHostDetails().putAll(getVersionStrings());
cmd.setPool(_pool);
cmd.setCluster(_clusterId);
cmd.setGatewayIpAddress(_localGateway);
StartupStorageCommand sscmd = null;
try {
KVMStoragePool localStoragePool = _storagePoolMgr
.createStoragePool(_localStorageUUID, "localhost", -1,
_localStoragePath, "", StoragePoolType.Filesystem);
com.cloud.agent.api.StoragePoolInfo pi = new com.cloud.agent.api.StoragePoolInfo(
localStoragePool.getUuid(), cmd.getPrivateIpAddress(),
_localStoragePath, _localStoragePath,
StoragePoolType.Filesystem, localStoragePool.getCapacity(),
localStoragePool.getUsed());
sscmd = new StartupStorageCommand();
sscmd.setPoolInfo(pi);
sscmd.setGuid(pi.getUuid());
sscmd.setDataCenter(_dcId);
sscmd.setResourceType(Storage.StorageResourceType.STORAGE_POOL);
} catch (CloudRuntimeException e) {
}
if (sscmd != null) {
return new StartupCommand[] { cmd, sscmd };
} else {
return new StartupCommand[] { cmd };
}
}
protected HashMap<String, State> sync() {
HashMap<String, State> newStates;
HashMap<String, State> oldStates = null;
final HashMap<String, State> changes = new HashMap<String, State>();
synchronized (_vms) {
newStates = getAllVms();
if (newStates == null) {
s_logger.debug("Unable to get the vm states so no state sync at this point.");
return changes;
}
oldStates = new HashMap<String, State>(_vms.size());
oldStates.putAll(_vms);
for (final Map.Entry<String, State> entry : newStates.entrySet()) {
final String vm = entry.getKey();
State newState = entry.getValue();
final State oldState = oldStates.remove(vm);
if (newState == State.Stopped && oldState != State.Stopping
&& oldState != null && oldState != State.Stopped) {
newState = getRealPowerState(vm);
}
if (s_logger.isTraceEnabled()) {
s_logger.trace("VM " + vm + ": libvirt has state "
+ newState + " and we have state "
+ (oldState != null ? oldState.toString() : "null"));
}
if (vm.startsWith("migrating")) {
s_logger.debug("Migration detected. Skipping");
continue;
}
if (oldState == null) {
_vms.put(vm, newState);
s_logger.debug("Detecting a new state but couldn't find a old state so adding it to the changes: "
+ vm);
changes.put(vm, newState);
} else if (oldState == State.Starting) {
if (newState == State.Running) {
_vms.put(vm, newState);
} else if (newState == State.Stopped) {
s_logger.debug("Ignoring vm " + vm
+ " because of a lag in starting the vm.");
}
} else if (oldState == State.Migrating) {
if (newState == State.Running) {
s_logger.debug("Detected that an migrating VM is now running: "
+ vm);
_vms.put(vm, newState);
}
} else if (oldState == State.Stopping) {
if (newState == State.Stopped) {
_vms.put(vm, newState);
} else if (newState == State.Running) {
s_logger.debug("Ignoring vm " + vm
+ " because of a lag in stopping the vm. ");
}
} else if (oldState != newState) {
_vms.put(vm, newState);
if (newState == State.Stopped) {
if (_vmsKilled.remove(vm)) {
s_logger.debug("VM " + vm
+ " has been killed for storage. ");
newState = State.Error;
}
}
changes.put(vm, newState);
}
}
for (final Map.Entry<String, State> entry : oldStates.entrySet()) {
final String vm = entry.getKey();
final State oldState = entry.getValue();
if (s_logger.isTraceEnabled()) {
s_logger.trace("VM "
+ vm
+ " is now missing from libvirt so reporting stopped");
}
if (oldState == State.Stopping) {
s_logger.debug("Ignoring VM " + vm
+ " in transition state stopping.");
_vms.remove(vm);
} else if (oldState == State.Starting) {
s_logger.debug("Ignoring VM " + vm
+ " in transition state starting.");
} else if (oldState == State.Stopped) {
_vms.remove(vm);
} else if (oldState == State.Migrating) {
s_logger.debug("Ignoring VM " + vm + " in migrating state.");
} else {
_vms.remove(vm);
State state = State.Stopped;
if (_vmsKilled.remove(entry.getKey())) {
s_logger.debug("VM " + vm
+ " has been killed by storage monitor");
state = State.Error;
}
changes.put(entry.getKey(), state);
}
}
}
return changes;
}
protected State getRealPowerState(String vm) {
int i = 0;
s_logger.trace("Checking on the HALTED State");
Domain dm = null;
for (; i < 5; i++) {
try {
Connect conn = LibvirtConnection.getConnection();
dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vm
.getBytes()));
DomainInfo.DomainState vps = dm.getInfo().state;
if (vps != null
&& vps != DomainInfo.DomainState.VIR_DOMAIN_SHUTOFF
&& vps != DomainInfo.DomainState.VIR_DOMAIN_NOSTATE) {
return convertToState(vps);
}
} catch (final LibvirtException e) {
s_logger.trace(e.getMessage());
} catch (Exception e) {
s_logger.trace(e.getMessage());
} finally {
try {
if (dm != null) {
dm.free();
}
} catch (final LibvirtException e) {
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
return State.Stopped;
}
protected List<String> getAllVmNames(Connect conn) {
ArrayList<String> la = new ArrayList<String>();
try {
final String names[] = conn.listDefinedDomains();
for (int i = 0; i < names.length; i++) {
la.add(names[i]);
}
} catch (final LibvirtException e) {
s_logger.warn("Failed to list Defined domains", e);
}
int[] ids = null;
try {
ids = conn.listDomains();
} catch (final LibvirtException e) {
s_logger.warn("Failed to list domains", e);
return la;
}
Domain dm = null;
for (int i = 0; i < ids.length; i++) {
try {
dm = conn.domainLookupByID(ids[i]);
la.add(dm.getName());
} catch (final LibvirtException e) {
s_logger.warn("Unable to get vms", e);
} finally {
try {
if (dm != null) {
dm.free();
}
} catch (final LibvirtException e) {
}
}
}
return la;
}
private HashMap<String, State> getAllVms() {
final HashMap<String, State> vmStates = new HashMap<String, State>();
String[] vms = null;
int[] ids = null;
Connect conn = null;
try {
conn = LibvirtConnection.getConnection();
} catch (LibvirtException e) {
s_logger.debug("Failed to get connection: " + e.getMessage());
return vmStates;
}
try {
ids = conn.listDomains();
} catch (final LibvirtException e) {
s_logger.warn("Unable to listDomains", e);
return null;
}
try {
vms = conn.listDefinedDomains();
} catch (final LibvirtException e) {
s_logger.warn("Unable to listDomains", e);
return null;
}
Domain dm = null;
for (int i = 0; i < ids.length; i++) {
try {
dm = conn.domainLookupByID(ids[i]);
DomainInfo.DomainState ps = dm.getInfo().state;
final State state = convertToState(ps);
s_logger.trace("VM " + dm.getName() + ": powerstate = " + ps
+ "; vm state=" + state.toString());
String vmName = dm.getName();
vmStates.put(vmName, state);
} catch (final LibvirtException e) {
s_logger.warn("Unable to get vms", e);
} finally {
try {
if (dm != null) {
dm.free();
}
} catch (LibvirtException e) {
}
}
}
for (int i = 0; i < vms.length; i++) {
try {
dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vms[i]
.getBytes()));
DomainInfo.DomainState ps = dm.getInfo().state;
final State state = convertToState(ps);
String vmName = dm.getName();
s_logger.trace("VM " + vmName + ": powerstate = " + ps
+ "; vm state=" + state.toString());
vmStates.put(vmName, state);
} catch (final LibvirtException e) {
s_logger.warn("Unable to get vms", e);
} catch (Exception e) {
s_logger.warn("Unable to get vms", e);
} finally {
try {
if (dm != null) {
dm.free();
}
} catch (LibvirtException e) {
}
}
}
return vmStates;
}
protected List<Object> getHostInfo() {
final ArrayList<Object> info = new ArrayList<Object>();
long speed = 0;
long cpus = 0;
long ram = 0;
String cap = null;
try {
Connect conn = LibvirtConnection.getConnection();
final NodeInfo hosts = conn.nodeInfo();
boolean result = false;
try {
BufferedReader in = new BufferedReader(
new FileReader(
"/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq"));
speed = Long.parseLong(in.readLine()) / 1000;
result = true;
} catch (FileNotFoundException e) {
} catch (IOException e) {
} catch (NumberFormatException e) {
}
if (!result) {
speed = hosts.mhz;
}
cpus = hosts.cpus;
ram = hosts.memory * 1024L;
LibvirtCapXMLParser parser = new LibvirtCapXMLParser();
parser.parseCapabilitiesXML(conn.getCapabilities());
ArrayList<String> oss = parser.getGuestOsType();
for (String s : oss) {
/*
* Even host supports guest os type more than hvm, we only
* report hvm to management server
*/
if (s.equalsIgnoreCase("hvm")) {
cap = "hvm";
}
}
} catch (LibvirtException e) {
}
if (isSnapshotSupported()) {
cap = cap + ",snapshot";
}
info.add((int) cpus);
info.add(speed);
info.add(ram);
info.add(cap);
long dom0ram = Math.min(ram / 10, 768 * 1024 * 1024L);// save a maximum
// of 10% of
// system ram or
// 768M
dom0ram = Math.max(dom0ram, _dom0MinMem);
info.add(dom0ram);
s_logger.debug("cpus=" + cpus + ", speed=" + speed + ", ram=" + ram
+ ", dom0ram=" + dom0ram);
return info;
}
protected void cleanupVM(Connect conn, final String vmName,
final String vnet) {
s_logger.debug("Trying to cleanup the vnet: " + vnet);
if (vnet != null) {
cleanupVnet(conn, vnet);
}
_vmStats.remove(vmName);
}
protected String rebootVM(Connect conn, String vmName) {
Domain dm = null;
String msg = null;
try {
dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
.getBytes()));
String vmDef = dm.getXMLDesc(0);
s_logger.debug(vmDef);
msg = stopVM(conn, vmName, defineOps.UNDEFINE_VM);
msg = startDomain(conn, vmName, vmDef);
return null;
} catch (LibvirtException e) {
s_logger.warn("Failed to create vm", e);
msg = e.getMessage();
} catch (Exception e) {
s_logger.warn("Failed to create vm", e);
msg = e.getMessage();
} finally {
try {
if (dm != null) {
dm.free();
}
} catch (LibvirtException e) {
}
}
return msg;
}
protected String stopVM(Connect conn, String vmName, defineOps df) {
DomainInfo.DomainState state = null;
Domain dm = null;
s_logger.debug("Try to stop the vm at first");
String ret = stopVM(conn, vmName, false);
if (ret == Script.ERR_TIMEOUT) {
ret = stopVM(conn, vmName, true);
} else if (ret != null) {
/*
* There is a race condition between libvirt and qemu: libvirt
* listens on qemu's monitor fd. If qemu is shutdown, while libvirt
* is reading on the fd, then libvirt will report an error.
*/
/* Retry 3 times, to make sure we can get the vm's status */
for (int i = 0; i < 3; i++) {
try {
dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
.getBytes()));
state = dm.getInfo().state;
break;
} catch (LibvirtException e) {
s_logger.debug("Failed to get vm status:" + e.getMessage());
} catch (Exception e) {
s_logger.debug("Failed to get vm status:" + e.getMessage());
} finally {
try {
if (dm != null) {
dm.free();
}
} catch (LibvirtException l) {
}
}
}
if (state == null) {
s_logger.debug("Can't get vm's status, assume it's dead already");
return null;
}
if (state != DomainInfo.DomainState.VIR_DOMAIN_SHUTOFF) {
s_logger.debug("Try to destroy the vm");
ret = stopVM(conn, vmName, true);
if (ret != null) {
return ret;
}
}
}
if (df == defineOps.UNDEFINE_VM) {
try {
dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
.getBytes()));
dm.undefine();
} catch (LibvirtException e) {
} finally {
try {
if (dm != null) {
dm.free();
}
} catch (LibvirtException l) {
}
}
}
return null;
}
protected String stopVM(Connect conn, String vmName, boolean force) {
Domain dm = null;
try {
dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
.getBytes()));
if (force) {
if (dm.getInfo().state != DomainInfo.DomainState.VIR_DOMAIN_SHUTOFF) {
dm.destroy();
}
} else {
if (dm.getInfo().state == DomainInfo.DomainState.VIR_DOMAIN_SHUTOFF) {
return null;
}
dm.shutdown();
int retry = _stopTimeout / 2000;
/* Wait for the domain gets into shutoff state */
while ((dm.getInfo().state != DomainInfo.DomainState.VIR_DOMAIN_SHUTOFF)
&& (retry >= 0)) {
Thread.sleep(2000);
retry--;
}
if (retry < 0) {
s_logger.warn("Timed out waiting for domain " + vmName
+ " to shutdown gracefully");
return Script.ERR_TIMEOUT;
}
}
} catch (LibvirtException e) {
s_logger.debug("Failed to stop VM :" + vmName + " :", e);
return e.getMessage();
} catch (InterruptedException ie) {
s_logger.debug("Interrupted sleep");
return ie.getMessage();
} catch (Exception e) {
s_logger.debug("Failed to stop VM :" + vmName + " :", e);
return e.getMessage();
} finally {
try {
if (dm != null) {
dm.free();
}
} catch (LibvirtException e) {
}
}
return null;
}
public synchronized String cleanupVnet(Connect conn, final String vnetId) {
// VNC proxy VMs do not have vnet
if (vnetId == null || vnetId.isEmpty()
|| isDirectAttachedNetwork(vnetId)) {
return null;
}
final List<String> names = getAllVmNames(conn);
if (!names.isEmpty()) {
for (final String name : names) {
if (VirtualMachineName.getVnet(name).equals(vnetId)) {
return null; // Can't remove the vnet yet.
}
}
}
final Script command = new Script(_modifyVlanPath, _timeout, s_logger);
command.add("-o", "delete");
command.add("-v", vnetId);
return command.execute();
}
protected Integer getVncPort(Connect conn, String vmName)
throws LibvirtException {
LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser();
Domain dm = null;
try {
dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
.getBytes()));
String xmlDesc = dm.getXMLDesc(0);
parser.parseDomainXML(xmlDesc);
return parser.getVncPort();
} finally {
try {
if (dm != null) {
dm.free();
}
} catch (LibvirtException l) {
}
}
}
private boolean IsHVMEnabled(Connect conn) {
LibvirtCapXMLParser parser = new LibvirtCapXMLParser();
try {
parser.parseCapabilitiesXML(conn.getCapabilities());
ArrayList<String> osTypes = parser.getGuestOsType();
for (String o : osTypes) {
if (o.equalsIgnoreCase("hvm")) {
return true;
}
}
} catch (LibvirtException e) {
}
return false;
}
private String getHypervisorPath(Connect conn) {
LibvirtCapXMLParser parser = new LibvirtCapXMLParser();
try {
parser.parseCapabilitiesXML(conn.getCapabilities());
} catch (LibvirtException e) {
s_logger.debug(e.getMessage());
}
return parser.getEmulator();
}
private String getGuestType(Connect conn, String vmName) {
LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser();
Domain dm = null;
try {
dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
.getBytes()));
String xmlDesc = dm.getXMLDesc(0);
parser.parseDomainXML(xmlDesc);
return parser.getDescription();
} catch (LibvirtException e) {
return null;
} catch (Exception e) {
return null;
} finally {
try {
if (dm != null) {
dm.free();
}
} catch (LibvirtException l) {
}
}
}
private boolean isGuestPVEnabled(String guestOS) {
if (guestOS == null) {
return false;
}
String guestOSName = KVMGuestOsMapper.getGuestOsName(guestOS);
if (guestOS.startsWith("Ubuntu")
|| guestOSName.startsWith("Fedora 13")
|| guestOSName.startsWith("Fedora 12")
|| guestOSName.startsWith("Fedora 11")
|| guestOSName.startsWith("Fedora 10")
|| guestOSName.startsWith("Fedora 9")
|| guestOSName.startsWith("CentOS 5.3")
|| guestOSName.startsWith("CentOS 5.4")
|| guestOSName.startsWith("CentOS 5.5")
|| guestOS.startsWith("CentOS")
|| guestOS.startsWith("Fedora")
|| guestOSName.startsWith("Red Hat Enterprise Linux 5.3")
|| guestOSName.startsWith("Red Hat Enterprise Linux 5.4")
|| guestOSName.startsWith("Red Hat Enterprise Linux 5.5")
|| guestOSName.startsWith("Red Hat Enterprise Linux 6")
|| guestOS.startsWith("Debian GNU/Linux")
|| guestOSName.startsWith("Other PV")) {
return true;
} else {
return false;
}
}
public boolean isCentosHost() {
if (_hvVersion <= 9) {
return true;
} else {
return false;
}
}
private InterfaceDef.nicModel getGuestNicModel(String guestOSType) {
if (isGuestPVEnabled(guestOSType)) {
return InterfaceDef.nicModel.VIRTIO;
} else {
return InterfaceDef.nicModel.E1000;
}
}
private DiskDef.diskBus getGuestDiskModel(String guestOSType) {
if (isGuestPVEnabled(guestOSType)) {
return DiskDef.diskBus.VIRTIO;
} else {
return DiskDef.diskBus.IDE;
}
}
private String setVnetBrName(String vnetId) {
return "cloudVirBr" + vnetId;
}
private String getVnetIdFromBrName(String vnetBrName) {
return vnetBrName.replaceAll("cloudVirBr", "");
}
private void cleanupVMNetworks(Connect conn, List<InterfaceDef> nics) {
for (InterfaceDef nic : nics) {
if (nic.getHostNetType() == hostNicType.VNET) {
cleanupVnet(conn, getVnetIdFromBrName(nic.getBrName()));
}
}
}
private Domain getDomain(Connect conn, String vmName)
throws LibvirtException {
return conn
.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName.getBytes()));
}
protected List<InterfaceDef> getInterfaces(Connect conn, String vmName) {
LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser();
Domain dm = null;
try {
dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
.getBytes()));
parser.parseDomainXML(dm.getXMLDesc(0));
return parser.getInterfaces();
} catch (LibvirtException e) {
s_logger.debug("Failed to get dom xml: " + e.toString());
return new ArrayList<InterfaceDef>();
} catch (Exception e) {
s_logger.debug("Failed to get dom xml: " + e.toString());
return new ArrayList<InterfaceDef>();
} finally {
try {
if (dm != null) {
dm.free();
}
} catch (LibvirtException e) {
}
}
}
protected List<DiskDef> getDisks(Connect conn, String vmName) {
LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser();
Domain dm = null;
try {
dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
.getBytes()));
parser.parseDomainXML(dm.getXMLDesc(0));
return parser.getDisks();
} catch (LibvirtException e) {
s_logger.debug("Failed to get dom xml: " + e.toString());
return new ArrayList<DiskDef>();
} catch (Exception e) {
s_logger.debug("Failed to get dom xml: " + e.toString());
return new ArrayList<DiskDef>();
} finally {
try {
if (dm != null) {
dm.free();
}
} catch (LibvirtException e) {
}
}
}
private String executeBashScript(String script) {
Script command = new Script("/bin/bash", _timeout, s_logger);
command.add("-c");
command.add(script);
return command.execute();
}
private String executeBashScript(String script, OutputInterpreter parser) {
Script command = new Script("/bin/bash", _timeout, s_logger);
command.add("-c");
command.add(script);
return command.execute(parser);
}
private void deletExitingLinkLocalRoutTable(String linkLocalBr) {
Script command = new Script("/bin/bash", _timeout);
command.add("-c");
command.add("ip route | grep " + NetUtils.getLinkLocalCIDR());
OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser();
String result = command.execute(parser);
boolean foundLinkLocalBr = false;
if (result == null && parser.getLines() != null) {
String[] lines = parser.getLines().split("\\n");
for (String line : lines) {
String[] tokens = line.split(" ");
if (!tokens[2].equalsIgnoreCase(linkLocalBr)) {
Script.runSimpleBashScript("ip route del "
+ NetUtils.getLinkLocalCIDR());
} else {
foundLinkLocalBr = true;
}
}
}
if (!foundLinkLocalBr) {
Script.runSimpleBashScript("ip route add "
+ NetUtils.getLinkLocalCIDR() + " dev " + linkLocalBr
+ " src " + NetUtils.getLinkLocalGateway());
}
}
private class vmStats {
long _usedTime;
long _tx;
long _rx;
Calendar _timestamp;
}
private VmStatsEntry getVmStat(Connect conn, String vmName)
throws LibvirtException {
Domain dm = null;
try {
dm = getDomain(conn, vmName);
DomainInfo info = dm.getInfo();
VmStatsEntry stats = new VmStatsEntry();
stats.setNumCPUs(info.nrVirtCpu);
stats.setEntityType("vm");
/* get cpu utilization */
vmStats oldStats = null;
Calendar now = Calendar.getInstance();
oldStats = _vmStats.get(vmName);
long elapsedTime = 0;
if (oldStats != null) {
elapsedTime = now.getTimeInMillis()
- oldStats._timestamp.getTimeInMillis();
double utilization = (info.cpuTime - oldStats._usedTime)
/ ((double) elapsedTime * 1000000);
NodeInfo node = conn.nodeInfo();
utilization = utilization / node.cpus;
stats.setCPUUtilization(utilization * 100);
}
/* get network stats */
List<InterfaceDef> vifs = getInterfaces(conn, vmName);
long rx = 0;
long tx = 0;
for (InterfaceDef vif : vifs) {
DomainInterfaceStats ifStats = dm.interfaceStats(vif
.getDevName());
rx += ifStats.rx_bytes;
tx += ifStats.tx_bytes;
}
if (oldStats != null) {
long deltarx = rx - oldStats._rx;
if (deltarx > 0)
stats.setNetworkReadKBs(deltarx / 1000);
long deltatx = tx - oldStats._tx;
if (deltatx > 0)
stats.setNetworkWriteKBs(deltatx / 1000);
}
vmStats newStat = new vmStats();
newStat._usedTime = info.cpuTime;
newStat._rx = rx;
newStat._tx = tx;
newStat._timestamp = now;
_vmStats.put(vmName, newStat);
return stats;
} finally {
if (dm != null) {
dm.free();
}
}
}
private boolean can_bridge_firewall(String prvNic) {
Script cmd = new Script(_securityGroupPath, _timeout, s_logger);
cmd.add("can_bridge_firewall");
cmd.add(prvNic);
String result = cmd.execute();
if (result != null) {
return false;
}
return true;
}
protected boolean destroy_network_rules_for_vm(Connect conn, String vmName) {
if (!_can_bridge_firewall) {
return false;
}
String vif = null;
List<InterfaceDef> intfs = getInterfaces(conn, vmName);
if (intfs.size() > 0) {
InterfaceDef intf = intfs.get(0);
vif = intf.getDevName();
}
Script cmd = new Script(_securityGroupPath, _timeout, s_logger);
cmd.add("destroy_network_rules_for_vm");
cmd.add("--vmname", vmName);
if (vif != null) {
cmd.add("--vif", vif);
}
String result = cmd.execute();
if (result != null) {
return false;
}
return true;
}
protected boolean default_network_rules(Connect conn, String vmName,
NicTO nic, Long vmId) {
if (!_can_bridge_firewall) {
return false;
}
List<InterfaceDef> intfs = getInterfaces(conn, vmName);
if (intfs.size() < nic.getDeviceId()) {
return false;
}
InterfaceDef intf = intfs.get(nic.getDeviceId());
String brname = intf.getBrName();
String vif = intf.getDevName();
Script cmd = new Script(_securityGroupPath, _timeout, s_logger);
cmd.add("default_network_rules");
cmd.add("--vmname", vmName);
cmd.add("--vmid", vmId.toString());
if (nic.getIp() != null) {
cmd.add("--vmip", nic.getIp());
}
cmd.add("--vmmac", nic.getMac());
cmd.add("--vif", vif);
cmd.add("--brname", brname);
String result = cmd.execute();
if (result != null) {
return false;
}
return true;
}
protected boolean post_default_network_rules(Connect conn, String vmName,
NicTO nic, Long vmId, InetAddress dhcpServerIp, String hostIp,
String hostMacAddr) {
if (!_can_bridge_firewall) {
return false;
}
List<InterfaceDef> intfs = getInterfaces(conn, vmName);
if (intfs.size() < nic.getDeviceId()) {
return false;
}
InterfaceDef intf = intfs.get(nic.getDeviceId());
String brname = intf.getBrName();
String vif = intf.getDevName();
Script cmd = new Script(_securityGroupPath, _timeout, s_logger);
cmd.add("post_default_network_rules");
cmd.add("--vmname", vmName);
cmd.add("--vmid", vmId.toString());
cmd.add("--vmip", nic.getIp());
cmd.add("--vmmac", nic.getMac());
cmd.add("--vif", vif);
cmd.add("--brname", brname);
if (dhcpServerIp != null)
cmd.add("--dhcpSvr", dhcpServerIp.getHostAddress());
cmd.add("--hostIp", hostIp);
cmd.add("--hostMacAddr", hostMacAddr);
String result = cmd.execute();
if (result != null) {
return false;
}
return true;
}
protected boolean default_network_rules_for_systemvm(Connect conn,
String vmName) {
if (!_can_bridge_firewall) {
return false;
}
Script cmd = new Script(_securityGroupPath, _timeout, s_logger);
cmd.add("default_network_rules_systemvm");
cmd.add("--vmname", vmName);
cmd.add("--localbrname", _linkLocalBridgeName);
String result = cmd.execute();
if (result != null) {
return false;
}
return true;
}
private boolean add_network_rules(String vmName, String vmId,
String guestIP, String sig, String seq, String mac, String rules,
String vif, String brname) {
if (!_can_bridge_firewall) {
return false;
}
String newRules = rules.replace(" ", ";");
Script cmd = new Script(_securityGroupPath, _timeout, s_logger);
cmd.add("add_network_rules");
cmd.add("--vmname", vmName);
cmd.add("--vmid", vmId);
cmd.add("--vmip", guestIP);
cmd.add("--sig", sig);
cmd.add("--seq", seq);
cmd.add("--vmmac", mac);
cmd.add("--vif", vif);
cmd.add("--brname", brname);
if (rules != null) {
cmd.add("--rules", newRules);
}
String result = cmd.execute();
if (result != null) {
return false;
}
return true;
}
private boolean cleanup_rules() {
if (!_can_bridge_firewall) {
return false;
}
Script cmd = new Script(_securityGroupPath, _timeout, s_logger);
cmd.add("cleanup_rules");
String result = cmd.execute();
if (result != null) {
return false;
}
return true;
}
private String get_rule_logs_for_vms() {
Script cmd = new Script(_securityGroupPath, _timeout, s_logger);
cmd.add("get_rule_logs_for_vms");
OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser();
String result = cmd.execute(parser);
if (result == null) {
return parser.getLine();
}
return null;
}
private HashMap<String, Pair<Long, Long>> syncNetworkGroups(long id) {
HashMap<String, Pair<Long, Long>> states = new HashMap<String, Pair<Long, Long>>();
String result = get_rule_logs_for_vms();
s_logger.trace("syncNetworkGroups: id=" + id + " got: " + result);
String[] rulelogs = result != null ? result.split(";") : new String[0];
for (String rulesforvm : rulelogs) {
String[] log = rulesforvm.split(",");
if (log.length != 6) {
continue;
}
try {
states.put(log[0], new Pair<Long, Long>(Long.parseLong(log[1]),
Long.parseLong(log[5])));
} catch (NumberFormatException nfe) {
states.put(log[0], new Pair<Long, Long>(-1L, -1L));
}
}
return states;
}
/* online snapshot supported by enhanced qemu-kvm */
private boolean isSnapshotSupported() {
String result = executeBashScript("qemu-img --help|grep convert |grep snapshot");
if (result != null) {
return false;
} else {
return true;
}
}
private Pair<Double, Double> getNicStats(String nicName) {
double rx = 0.0;
OutputInterpreter.OneLineParser rxParser = new OutputInterpreter.OneLineParser();
String result = executeBashScript("cat /sys/class/net/" + nicName
+ "/statistics/rx_bytes", rxParser);
if (result == null && rxParser.getLine() != null) {
rx = Double.parseDouble(rxParser.getLine());
}
double tx = 0.0;
OutputInterpreter.OneLineParser txParser = new OutputInterpreter.OneLineParser();
result = executeBashScript("cat /sys/class/net/" + nicName
+ "/statistics/tx_bytes", txParser);
if (result == null && txParser.getLine() != null) {
tx = Double.parseDouble(txParser.getLine());
}
return new Pair<Double, Double>(rx, tx);
}
private void createControlNetwork() throws LibvirtException {
_virtRouterResource.createControlNetwork(_linkLocalBridgeName);
}
private Answer execute(NetworkRulesSystemVmCommand cmd) {
boolean success = false;
Connect conn;
try {
conn = LibvirtConnection.getConnection();
success = default_network_rules_for_systemvm(conn, cmd.getVmName());
} catch (LibvirtException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return new Answer(cmd, success, "");
}
}
| agent: Remove dummy debug line
This does nothing
| plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java | agent: Remove dummy debug line | <ide><path>lugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
<ide> value = (String) params.get("host.reserved.mem.mb");
<ide> _dom0MinMem = NumbersUtil.parseInt(value, 0) * 1024 * 1024;
<ide>
<del> value = (String) params.get("debug.mode");
<del>
<ide> LibvirtConnection.initialize(_hypervisorURI);
<ide> Connect conn = null;
<ide> try { |
|
Java | apache-2.0 | 1a9ee30dbab8b3e66ccffae0f133f4a8779072d1 | 0 | MichaelNedzelsky/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,semonte/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,diorcety/intellij-community,diorcety/intellij-community,petteyg/intellij-community,kdwink/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,holmes/intellij-community,akosyakov/intellij-community,ernestp/consulo,ivan-fedorov/intellij-community,da1z/intellij-community,suncycheng/intellij-community,ernestp/consulo,vladmm/intellij-community,asedunov/intellij-community,da1z/intellij-community,robovm/robovm-studio,adedayo/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,signed/intellij-community,TangHao1987/intellij-community,clumsy/intellij-community,caot/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,retomerz/intellij-community,petteyg/intellij-community,amith01994/intellij-community,izonder/intellij-community,izonder/intellij-community,semonte/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,signed/intellij-community,ibinti/intellij-community,adedayo/intellij-community,supersven/intellij-community,fnouama/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,clumsy/intellij-community,diorcety/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,robovm/robovm-studio,slisson/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,xfournet/intellij-community,hurricup/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,semonte/intellij-community,fnouama/intellij-community,caot/intellij-community,holmes/intellij-community,samthor/intellij-community,allotria/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,Lekanich/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,petteyg/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,hurricup/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,allotria/intellij-community,retomerz/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,xfournet/intellij-community,da1z/intellij-community,FHannes/intellij-community,semonte/intellij-community,amith01994/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,izonder/intellij-community,FHannes/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,amith01994/intellij-community,retomerz/intellij-community,fnouama/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,izonder/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,jagguli/intellij-community,kdwink/intellij-community,xfournet/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,da1z/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,da1z/intellij-community,allotria/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,clumsy/intellij-community,diorcety/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,caot/intellij-community,ibinti/intellij-community,allotria/intellij-community,youdonghai/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,consulo/consulo,idea4bsd/idea4bsd,akosyakov/intellij-community,holmes/intellij-community,retomerz/intellij-community,slisson/intellij-community,allotria/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,consulo/consulo,fitermay/intellij-community,izonder/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,diorcety/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,signed/intellij-community,adedayo/intellij-community,consulo/consulo,robovm/robovm-studio,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,jagguli/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,caot/intellij-community,ol-loginov/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,signed/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,samthor/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,signed/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,xfournet/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,apixandru/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,consulo/consulo,caot/intellij-community,samthor/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,slisson/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,ernestp/consulo,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,adedayo/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,kool79/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,da1z/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,fengbaicanhe/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,retomerz/intellij-community,FHannes/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,signed/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,ibinti/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,caot/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,ernestp/consulo,muntasirsyed/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,consulo/consulo,retomerz/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,semonte/intellij-community,fnouama/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,supersven/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,clumsy/intellij-community,apixandru/intellij-community,izonder/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,Lekanich/intellij-community,kool79/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,allotria/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,ryano144/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,ernestp/consulo,Lekanich/intellij-community,semonte/intellij-community,kdwink/intellij-community,clumsy/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,slisson/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,robovm/robovm-studio,lucafavatella/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,caot/intellij-community,dslomov/intellij-community,signed/intellij-community,fitermay/intellij-community,ibinti/intellij-community,signed/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,allotria/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,kool79/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,da1z/intellij-community,tmpgit/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,ryano144/intellij-community,fnouama/intellij-community,fitermay/intellij-community,amith01994/intellij-community,slisson/intellij-community,diorcety/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,FHannes/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,holmes/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,kdwink/intellij-community,hurricup/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,kool79/intellij-community,asedunov/intellij-community,adedayo/intellij-community,izonder/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,samthor/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,slisson/intellij-community,ernestp/consulo,salguarnieri/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,ibinti/intellij-community,da1z/intellij-community,fitermay/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,blademainer/intellij-community,tmpgit/intellij-community,supersven/intellij-community,hurricup/intellij-community,apixandru/intellij-community,allotria/intellij-community,asedunov/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,da1z/intellij-community,signed/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,kdwink/intellij-community,blademainer/intellij-community,robovm/robovm-studio,ryano144/intellij-community,da1z/intellij-community,asedunov/intellij-community,samthor/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,adedayo/intellij-community,samthor/intellij-community,kdwink/intellij-community,dslomov/intellij-community,kool79/intellij-community,asedunov/intellij-community,dslomov/intellij-community,fitermay/intellij-community,caot/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,supersven/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,holmes/intellij-community,salguarnieri/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,fitermay/intellij-community,clumsy/intellij-community,supersven/intellij-community,xfournet/intellij-community,jagguli/intellij-community,slisson/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,da1z/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,semonte/intellij-community,signed/intellij-community,kdwink/intellij-community,apixandru/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,slisson/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,samthor/intellij-community,ivan-fedorov/intellij-community,consulo/consulo,muntasirsyed/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.refactoring.util.duplicates;
import com.intellij.analysis.AnalysisScope;
import com.intellij.analysis.AnalysisUIOptions;
import com.intellij.analysis.BaseAnalysisActionDialog;
import com.intellij.history.LocalHistory;
import com.intellij.history.LocalHistoryAction;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ApplicationNamesInfo;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtil;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.impl.source.PostprocessReformattingAspect;
import com.intellij.psi.search.LocalSearchScope;
import com.intellij.psi.util.InheritanceUtil;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiTypesUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.refactoring.HelpID;
import com.intellij.refactoring.RefactoringActionHandler;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.extractMethod.InputVariables;
import com.intellij.refactoring.util.CommonRefactoringUtil;
import com.intellij.refactoring.util.RefactoringUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.VisibilityUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
/**
* @author dsl
*/
public class MethodDuplicatesHandler implements RefactoringActionHandler {
public static final String REFACTORING_NAME = RefactoringBundle.message("replace.method.code.duplicates.title");
private static final Logger LOG = Logger.getInstance("#" + MethodDuplicatesHandler.class.getName());
public void invoke(@NotNull final Project project, final Editor editor, PsiFile file, DataContext dataContext) {
final int offset = editor.getCaretModel().getOffset();
final PsiElement element = file.findElementAt(offset);
final PsiMethod method = PsiTreeUtil.getParentOfType(element, PsiMethod.class);
if (method == null) {
String message = RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("locate.caret.inside.a.method"));
showErrorMessage(message, project, editor);
return;
}
if (method.isConstructor()) {
String message = RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("replace.with.method.call.does.not.work.for.constructors"));
showErrorMessage(message, project, editor);
}
final PsiCodeBlock body = method.getBody();
if (body == null) {
String message = RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("method.does.not.have.a.body", method.getName()));
showErrorMessage(message, project, editor);
return;
}
final PsiStatement[] statements = body.getStatements();
if (statements.length == 0) {
String message = RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("method.has.an.empty.body", method.getName()));
showErrorMessage(message, project, editor);
return;
}
final AnalysisScope scope = new AnalysisScope(file);
final Module module = ModuleUtil.findModuleForPsiElement(file);
final BaseAnalysisActionDialog dlg = new BaseAnalysisActionDialog(RefactoringBundle.message("replace.method.duplicates.scope.chooser.title", REFACTORING_NAME),
RefactoringBundle.message("replace.method.duplicates.scope.chooser.message"),
project, scope, module != null ? module.getName() : null, false,
AnalysisUIOptions.getInstance(project), element);
dlg.show();
if (dlg.isOK()) {
ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() {
public void run() {
ProgressManager.getInstance().getProgressIndicator().setIndeterminate(true);
invokeOnScope(project, method, dlg.getScope(AnalysisUIOptions.getInstance(project), scope, project, module));
}
}, "Locate method duplicates", true, project) ;
}
}
public static void invokeOnScope(final Project project, final PsiMethod method, final AnalysisScope scope) {
invokeOnScope(project, Collections.singleton(method), scope, false);
}
public static void invokeOnScope(final Project project, final Set<PsiMethod> methods, final AnalysisScope scope, boolean silent) {
final Map<PsiMethod, List<Match>> duplicates = new HashMap<PsiMethod, List<Match>>();
scope.accept(new PsiRecursiveElementVisitor() {
@Override public void visitFile(final PsiFile file) {
final ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator();
if (progressIndicator != null && progressIndicator.isCanceled()) return;
for (PsiMethod method : methods) {
final List<Match> matchList = hasDuplicates(file, method);
for (Iterator<Match> iterator = matchList.iterator(); iterator.hasNext(); ) {
Match match = iterator.next();
final PsiElement matchStart = match.getMatchStart();
final PsiElement matchEnd = match.getMatchEnd();
for (PsiMethod psiMethod : methods) {
if (PsiTreeUtil.isAncestor(psiMethod, matchStart, false) ||
PsiTreeUtil.isAncestor(psiMethod, matchEnd, false)) {
iterator.remove();
break;
}
}
}
if (!matchList.isEmpty()) {
List<Match> matches = duplicates.get(method);
if (matches == null) {
matches = new ArrayList<Match>();
duplicates.put(method, matches);
}
matches.addAll(matchList);
}
}
}
});
replaceDuplicate(project, duplicates, methods);
if (!silent) {
final Runnable nothingFoundRunnable = new Runnable() {
public void run() {
if (duplicates.isEmpty()) {
final String message = RefactoringBundle.message("idea.has.not.found.any.code.that.can.be.replaced.with.method.call",
ApplicationNamesInfo.getInstance().getProductName());
Messages.showInfoMessage(project, message, REFACTORING_NAME);
}
}
};
if (ApplicationManager.getApplication().isUnitTestMode()) {
nothingFoundRunnable.run();
} else {
ApplicationManager.getApplication().invokeLater(nothingFoundRunnable, ModalityState.NON_MODAL);
}
}
}
private static void replaceDuplicate(final Project project, final Map<PsiMethod, List<Match>> duplicates, final Set<PsiMethod> methods) {
LocalHistoryAction a = LocalHistory.getInstance().startAction(REFACTORING_NAME);
try {
final ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator();
if (progressIndicator != null && progressIndicator.isCanceled()) return;
final Runnable replaceRunnable = new Runnable() {
public void run() {
for (final PsiMethod method : methods) {
final List<Match> matches = duplicates.get(method);
if (matches == null) continue;
final int duplicatesNo = matches.size();
WindowManager.getInstance().getStatusBar(project).setInfo(getStatusMessage(duplicatesNo));
CommandProcessor.getInstance().executeCommand(project, new Runnable() {
public void run() {
PostprocessReformattingAspect.getInstance(project).postponeFormattingInside(new Runnable() {
public void run() {
DuplicatesImpl.invoke(project, new MethodDuplicatesMatchProvider(method, matches));
}
});
}
}, REFACTORING_NAME, REFACTORING_NAME);
WindowManager.getInstance().getStatusBar(project).setInfo("");
}
}
};
if (ApplicationManager.getApplication().isUnitTestMode()) {
replaceRunnable.run();
}
else {
ApplicationManager.getApplication().invokeLater(replaceRunnable, ModalityState.NON_MODAL);
}
}
finally {
a.finish();
}
}
public static List<Match> hasDuplicates(final PsiFile file, final PsiMethod method) {
final PsiCodeBlock body = method.getBody();
LOG.assertTrue(body != null);
final PsiStatement[] statements = body.getStatements();
PsiElement[] pattern = statements;
ReturnValue matchedReturnValue = null;
if (statements.length != 1 || !(statements[0] instanceof PsiReturnStatement)) {
final PsiStatement lastStatement = statements.length > 0 ? statements[statements.length - 1] : null;
if (lastStatement instanceof PsiReturnStatement) {
final PsiExpression returnValue = ((PsiReturnStatement)lastStatement).getReturnValue();
if (returnValue instanceof PsiReferenceExpression) {
final PsiElement resolved = ((PsiReferenceExpression)returnValue).resolve();
if (resolved instanceof PsiVariable) {
pattern = new PsiElement[statements.length - 1];
System.arraycopy(statements, 0, pattern, 0, statements.length - 1);
matchedReturnValue = new VariableReturnValue((PsiVariable)resolved);
}
}
}
} else {
final PsiExpression returnValue = ((PsiReturnStatement)statements[0]).getReturnValue();
if (returnValue != null) {
pattern = new PsiElement[]{returnValue};
}
}
final DuplicatesFinder duplicatesFinder =
new DuplicatesFinder(pattern,
new InputVariables(Arrays.asList(method.getParameterList().getParameters()), method.getProject(), new LocalSearchScope(pattern), false), matchedReturnValue,
new ArrayList<PsiVariable>());
return duplicatesFinder.findDuplicates(file);
}
static String getStatusMessage(final int duplicatesNo) {
return RefactoringBundle.message("method.duplicates.found.message", duplicatesNo);
}
private static void showErrorMessage(String message, Project project, Editor editor) {
CommonRefactoringUtil.showErrorHint(project, editor, message, REFACTORING_NAME, HelpID.METHOD_DUPLICATES);
}
public void invoke(@NotNull Project project, @NotNull PsiElement[] elements, DataContext dataContext) {
throw new UnsupportedOperationException();
}
private static class MethodDuplicatesMatchProvider implements MatchProvider {
private final PsiMethod myMethod;
private final List<Match> myDuplicates;
private MethodDuplicatesMatchProvider(PsiMethod method, List<Match> duplicates) {
myMethod = method;
myDuplicates = duplicates;
}
public PsiElement processMatch(Match match) throws IncorrectOperationException {
match.changeSignature(myMethod);
final PsiClass containingClass = myMethod.getContainingClass();
if (isEssentialStaticContextAbsent(match)) {
PsiUtil.setModifierProperty(myMethod, PsiModifier.STATIC, true);
}
final PsiElementFactory factory = JavaPsiFacade.getInstance(myMethod.getProject()).getElementFactory();
final boolean needQualifier = match.getInstanceExpression() != null;
final boolean needStaticQualifier = isExternal(match);
final boolean nameConflicts = nameConflicts(match);
@NonNls final String text = needQualifier || needStaticQualifier || nameConflicts
? "q." + myMethod.getName() + "()": myMethod.getName() + "()";
PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression)factory.createExpressionFromText(text, null);
methodCallExpression = (PsiMethodCallExpression)CodeStyleManager.getInstance(myMethod.getManager()).reformat(methodCallExpression);
final PsiParameter[] parameters = myMethod.getParameterList().getParameters();
for (final PsiParameter parameter : parameters) {
final List<PsiElement> parameterValue = match.getParameterValues(parameter);
if (parameterValue != null) {
for (PsiElement val : parameterValue) {
methodCallExpression.getArgumentList().add(val);
}
}
else {
methodCallExpression.getArgumentList().add(factory.createExpressionFromText(PsiTypesUtil.getDefaultValueOfType(parameter.getType()), parameter));
}
}
if (needQualifier || needStaticQualifier || nameConflicts) {
final PsiExpression qualifierExpression = methodCallExpression.getMethodExpression().getQualifierExpression();
LOG.assertTrue(qualifierExpression != null);
if (needQualifier) {
qualifierExpression.replace(match.getInstanceExpression());
} else if (needStaticQualifier || myMethod.hasModifierProperty(PsiModifier.STATIC)) {
qualifierExpression.replace(factory.createReferenceExpression(containingClass));
} else {
final PsiClass psiClass = PsiTreeUtil.getParentOfType(match.getMatchStart(), PsiClass.class);
if (psiClass != null && psiClass.isInheritor(containingClass, true)) {
qualifierExpression.replace(RefactoringUtil.createSuperExpression(containingClass.getManager(), psiClass));
} else {
qualifierExpression.replace(RefactoringUtil.createThisExpression(containingClass.getManager(), containingClass));
}
}
}
VisibilityUtil.escalateVisibility(myMethod, match.getMatchStart());
final PsiCodeBlock body = myMethod.getBody();
assert body != null;
final PsiStatement[] statements = body.getStatements();
if (statements[statements.length - 1] instanceof PsiReturnStatement) {
final PsiExpression value = ((PsiReturnStatement)statements[statements.length - 1]).getReturnValue();
if (value instanceof PsiReferenceExpression) {
final PsiElement var = ((PsiReferenceExpression)value).resolve();
if (var instanceof PsiVariable) {
match.replace(myMethod, methodCallExpression, (PsiVariable)var);
return methodCallExpression;
}
}
}
return match.replace(myMethod, methodCallExpression, null);
}
private boolean isExternal(final Match match) {
final PsiElement matchStart = match.getMatchStart();
final PsiClass containingClass = myMethod.getContainingClass();
if (PsiTreeUtil.isAncestor(containingClass, matchStart, false)) {
return false;
}
final PsiClass psiClass = PsiTreeUtil.getParentOfType(matchStart, PsiClass.class);
if (psiClass != null) {
if (InheritanceUtil.isInheritorOrSelf(psiClass, containingClass, true)) return false;
}
return true;
}
private boolean nameConflicts(Match match) {
PsiClass matchClass = PsiTreeUtil.getParentOfType(match.getMatchStart(), PsiClass.class);
while (matchClass != null && matchClass != myMethod.getContainingClass()) {
if (matchClass.findMethodsBySignature(myMethod, false).length > 0) {
return true;
}
matchClass = PsiTreeUtil.getParentOfType(matchClass, PsiClass.class);
}
return false;
}
private boolean isEssentialStaticContextAbsent(final Match match) {
if (!myMethod.hasModifierProperty(PsiModifier.STATIC)) {
final PsiExpression instanceExpression = match.getInstanceExpression();
if (instanceExpression != null) return false;
if (isExternal(match)) return true;
if (PsiTreeUtil.isAncestor(myMethod.getContainingClass(), match.getMatchStart(), false) && RefactoringUtil.isInStaticContext(match.getMatchStart(), myMethod.getContainingClass())) return true;
}
return false;
}
public List<Match> getDuplicates() {
return myDuplicates;
}
public boolean hasDuplicates() {
return myDuplicates.isEmpty();
}
@Nullable
public String getConfirmDuplicatePrompt(final Match match) {
final PsiElement matchStart = match.getMatchStart();
@Modifier String visibility = VisibilityUtil.getPossibleVisibility(myMethod, matchStart);
final boolean shouldBeStatic = isEssentialStaticContextAbsent(match);
final String signature = match.getChangedSignature(myMethod, myMethod.hasModifierProperty(PsiModifier.STATIC) || shouldBeStatic, visibility);
if (signature != null) {
return RefactoringBundle.message("replace.this.code.fragment.and.change.signature", signature);
}
final boolean needToEscalateVisibility = !PsiUtil.isAccessible(myMethod, matchStart, null);
if (needToEscalateVisibility) {
final String visibilityPresentation = VisibilityUtil.toPresentableText(visibility);
return shouldBeStatic
? RefactoringBundle.message("replace.this.code.fragment.and.make.method.static.visible", visibilityPresentation)
: RefactoringBundle.message("replace.this.code.fragment.and.make.method.visible", visibilityPresentation);
}
if (shouldBeStatic) {
return RefactoringBundle.message("replace.this.code.fragment.and.make.method.static");
}
return null;
}
@Override
public String getReplaceDuplicatesTitle(int idx, int size) {
return RefactoringBundle.message("process.methods.duplicates.title", idx, size, myMethod.getName());
}
}
}
| java/java-impl/src/com/intellij/refactoring/util/duplicates/MethodDuplicatesHandler.java | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.refactoring.util.duplicates;
import com.intellij.analysis.AnalysisScope;
import com.intellij.analysis.AnalysisUIOptions;
import com.intellij.analysis.BaseAnalysisActionDialog;
import com.intellij.history.LocalHistory;
import com.intellij.history.LocalHistoryAction;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ApplicationNamesInfo;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtil;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.impl.source.PostprocessReformattingAspect;
import com.intellij.psi.search.LocalSearchScope;
import com.intellij.psi.util.InheritanceUtil;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiTypesUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.refactoring.HelpID;
import com.intellij.refactoring.RefactoringActionHandler;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.extractMethod.InputVariables;
import com.intellij.refactoring.util.CommonRefactoringUtil;
import com.intellij.refactoring.util.RefactoringUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.VisibilityUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
/**
* @author dsl
*/
public class MethodDuplicatesHandler implements RefactoringActionHandler {
public static final String REFACTORING_NAME = RefactoringBundle.message("replace.method.code.duplicates.title");
private static final Logger LOG = Logger.getInstance("#" + MethodDuplicatesHandler.class.getName());
public void invoke(@NotNull final Project project, final Editor editor, PsiFile file, DataContext dataContext) {
final int offset = editor.getCaretModel().getOffset();
final PsiElement element = file.findElementAt(offset);
final PsiMethod method = PsiTreeUtil.getParentOfType(element, PsiMethod.class);
if (method == null) {
String message = RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("locate.caret.inside.a.method"));
showErrorMessage(message, project, editor);
return;
}
if (method.isConstructor()) {
String message = RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("replace.with.method.call.does.not.work.for.constructors"));
showErrorMessage(message, project, editor);
}
final PsiCodeBlock body = method.getBody();
if (body == null) {
String message = RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("method.does.not.have.a.body", method.getName()));
showErrorMessage(message, project, editor);
return;
}
final PsiStatement[] statements = body.getStatements();
if (statements.length == 0) {
String message = RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("method.has.an.empty.body", method.getName()));
showErrorMessage(message, project, editor);
return;
}
final AnalysisScope scope = new AnalysisScope(file);
final Module module = ModuleUtil.findModuleForPsiElement(file);
final BaseAnalysisActionDialog dlg = new BaseAnalysisActionDialog(RefactoringBundle.message("replace.method.duplicates.scope.chooser.title", REFACTORING_NAME),
RefactoringBundle.message("replace.method.duplicates.scope.chooser.message"),
project, scope, module != null ? module.getName() : null, false,
AnalysisUIOptions.getInstance(project), element);
dlg.show();
if (dlg.isOK()) {
ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() {
public void run() {
ProgressManager.getInstance().getProgressIndicator().setIndeterminate(true);
invokeOnScope(project, method, dlg.getScope(AnalysisUIOptions.getInstance(project), scope, project, module));
}
}, "Locate method duplicates", true, project) ;
}
}
public static void invokeOnScope(final Project project, final PsiMethod method, final AnalysisScope scope) {
invokeOnScope(project, Collections.singleton(method), scope, false);
}
public static void invokeOnScope(final Project project, final Set<PsiMethod> methods, final AnalysisScope scope, boolean silent) {
final Map<PsiMethod, List<Match>> duplicates = new HashMap<PsiMethod, List<Match>>();
scope.accept(new PsiRecursiveElementVisitor() {
@Override public void visitFile(final PsiFile file) {
final ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator();
if (progressIndicator != null && progressIndicator.isCanceled()) return;
for (PsiMethod method : methods) {
final List<Match> matchList = hasDuplicates(file, method);
for (Iterator<Match> iterator = matchList.iterator(); iterator.hasNext(); ) {
Match match = iterator.next();
final PsiElement matchStart = match.getMatchStart();
final PsiElement matchEnd = match.getMatchEnd();
for (PsiMethod psiMethod : methods) {
if (PsiTreeUtil.isAncestor(psiMethod, matchStart, false) ||
PsiTreeUtil.isAncestor(psiMethod, matchEnd, false)) {
iterator.remove();
break;
}
}
}
if (!matchList.isEmpty()) {
List<Match> matches = duplicates.get(method);
if (matches == null) {
matches = new ArrayList<Match>();
duplicates.put(method, matches);
}
matches.addAll(matchList);
}
}
}
});
replaceDuplicate(project, duplicates, methods);
if (!silent) {
final Runnable nothingFoundRunnable = new Runnable() {
public void run() {
if (duplicates.isEmpty()) {
final String message = RefactoringBundle.message("idea.has.not.found.any.code.that.can.be.replaced.with.method.call",
ApplicationNamesInfo.getInstance().getProductName());
Messages.showInfoMessage(project, message, REFACTORING_NAME);
}
}
};
if (ApplicationManager.getApplication().isUnitTestMode()) {
nothingFoundRunnable.run();
} else {
ApplicationManager.getApplication().invokeLater(nothingFoundRunnable, ModalityState.NON_MODAL);
}
}
}
private static void replaceDuplicate(final Project project, final Map<PsiMethod, List<Match>> duplicates, final Set<PsiMethod> methods) {
LocalHistoryAction a = LocalHistory.getInstance().startAction(REFACTORING_NAME);
try {
final ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator();
if (progressIndicator != null && progressIndicator.isCanceled()) return;
final Runnable replaceRunnable = new Runnable() {
public void run() {
for (final PsiMethod method : methods) {
final List<Match> matches = duplicates.get(method);
if (matches == null) continue;
final int duplicatesNo = matches.size();
WindowManager.getInstance().getStatusBar(project).setInfo(getStatusMessage(duplicatesNo));
CommandProcessor.getInstance().executeCommand(project, new Runnable() {
public void run() {
PostprocessReformattingAspect.getInstance(project).postponeFormattingInside(new Runnable() {
public void run() {
DuplicatesImpl.invoke(project, new MethodDuplicatesMatchProvider(method, matches));
}
});
}
}, REFACTORING_NAME, REFACTORING_NAME);
WindowManager.getInstance().getStatusBar(project).setInfo("");
}
}
};
if (ApplicationManager.getApplication().isUnitTestMode()) {
replaceRunnable.run();
}
else {
ApplicationManager.getApplication().invokeLater(replaceRunnable, ModalityState.NON_MODAL);
}
}
finally {
a.finish();
}
}
public static List<Match> hasDuplicates(final PsiFile file, final PsiMethod method) {
final PsiCodeBlock body = method.getBody();
LOG.assertTrue(body != null);
final PsiStatement[] statements = body.getStatements();
PsiElement[] pattern = statements;
ReturnValue matchedReturnValue = null;
if (statements.length != 1 || !(statements[0] instanceof PsiReturnStatement)) {
final PsiStatement lastStatement = statements[statements.length - 1];
if (lastStatement instanceof PsiReturnStatement) {
final PsiExpression returnValue = ((PsiReturnStatement)lastStatement).getReturnValue();
if (returnValue instanceof PsiReferenceExpression) {
final PsiElement resolved = ((PsiReferenceExpression)returnValue).resolve();
if (resolved instanceof PsiVariable) {
pattern = new PsiElement[statements.length - 1];
System.arraycopy(statements, 0, pattern, 0, statements.length - 1);
matchedReturnValue = new VariableReturnValue((PsiVariable)resolved);
}
}
}
} else {
final PsiExpression returnValue = ((PsiReturnStatement)statements[0]).getReturnValue();
if (returnValue != null) {
pattern = new PsiElement[]{returnValue};
}
}
final DuplicatesFinder duplicatesFinder =
new DuplicatesFinder(pattern,
new InputVariables(Arrays.asList(method.getParameterList().getParameters()), method.getProject(), new LocalSearchScope(pattern), false), matchedReturnValue,
new ArrayList<PsiVariable>());
return duplicatesFinder.findDuplicates(file);
}
static String getStatusMessage(final int duplicatesNo) {
return RefactoringBundle.message("method.duplicates.found.message", duplicatesNo);
}
private static void showErrorMessage(String message, Project project, Editor editor) {
CommonRefactoringUtil.showErrorHint(project, editor, message, REFACTORING_NAME, HelpID.METHOD_DUPLICATES);
}
public void invoke(@NotNull Project project, @NotNull PsiElement[] elements, DataContext dataContext) {
throw new UnsupportedOperationException();
}
private static class MethodDuplicatesMatchProvider implements MatchProvider {
private final PsiMethod myMethod;
private final List<Match> myDuplicates;
private MethodDuplicatesMatchProvider(PsiMethod method, List<Match> duplicates) {
myMethod = method;
myDuplicates = duplicates;
}
public PsiElement processMatch(Match match) throws IncorrectOperationException {
match.changeSignature(myMethod);
final PsiClass containingClass = myMethod.getContainingClass();
if (isEssentialStaticContextAbsent(match)) {
PsiUtil.setModifierProperty(myMethod, PsiModifier.STATIC, true);
}
final PsiElementFactory factory = JavaPsiFacade.getInstance(myMethod.getProject()).getElementFactory();
final boolean needQualifier = match.getInstanceExpression() != null;
final boolean needStaticQualifier = isExternal(match);
final boolean nameConflicts = nameConflicts(match);
@NonNls final String text = needQualifier || needStaticQualifier || nameConflicts
? "q." + myMethod.getName() + "()": myMethod.getName() + "()";
PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression)factory.createExpressionFromText(text, null);
methodCallExpression = (PsiMethodCallExpression)CodeStyleManager.getInstance(myMethod.getManager()).reformat(methodCallExpression);
final PsiParameter[] parameters = myMethod.getParameterList().getParameters();
for (final PsiParameter parameter : parameters) {
final List<PsiElement> parameterValue = match.getParameterValues(parameter);
if (parameterValue != null) {
for (PsiElement val : parameterValue) {
methodCallExpression.getArgumentList().add(val);
}
}
else {
methodCallExpression.getArgumentList().add(factory.createExpressionFromText(PsiTypesUtil.getDefaultValueOfType(parameter.getType()), parameter));
}
}
if (needQualifier || needStaticQualifier || nameConflicts) {
final PsiExpression qualifierExpression = methodCallExpression.getMethodExpression().getQualifierExpression();
LOG.assertTrue(qualifierExpression != null);
if (needQualifier) {
qualifierExpression.replace(match.getInstanceExpression());
} else if (needStaticQualifier || myMethod.hasModifierProperty(PsiModifier.STATIC)) {
qualifierExpression.replace(factory.createReferenceExpression(containingClass));
} else {
final PsiClass psiClass = PsiTreeUtil.getParentOfType(match.getMatchStart(), PsiClass.class);
if (psiClass != null && psiClass.isInheritor(containingClass, true)) {
qualifierExpression.replace(RefactoringUtil.createSuperExpression(containingClass.getManager(), psiClass));
} else {
qualifierExpression.replace(RefactoringUtil.createThisExpression(containingClass.getManager(), containingClass));
}
}
}
VisibilityUtil.escalateVisibility(myMethod, match.getMatchStart());
final PsiCodeBlock body = myMethod.getBody();
assert body != null;
final PsiStatement[] statements = body.getStatements();
if (statements[statements.length - 1] instanceof PsiReturnStatement) {
final PsiExpression value = ((PsiReturnStatement)statements[statements.length - 1]).getReturnValue();
if (value instanceof PsiReferenceExpression) {
final PsiElement var = ((PsiReferenceExpression)value).resolve();
if (var instanceof PsiVariable) {
match.replace(myMethod, methodCallExpression, (PsiVariable)var);
return methodCallExpression;
}
}
}
return match.replace(myMethod, methodCallExpression, null);
}
private boolean isExternal(final Match match) {
final PsiElement matchStart = match.getMatchStart();
final PsiClass containingClass = myMethod.getContainingClass();
if (PsiTreeUtil.isAncestor(containingClass, matchStart, false)) {
return false;
}
final PsiClass psiClass = PsiTreeUtil.getParentOfType(matchStart, PsiClass.class);
if (psiClass != null) {
if (InheritanceUtil.isInheritorOrSelf(psiClass, containingClass, true)) return false;
}
return true;
}
private boolean nameConflicts(Match match) {
PsiClass matchClass = PsiTreeUtil.getParentOfType(match.getMatchStart(), PsiClass.class);
while (matchClass != null && matchClass != myMethod.getContainingClass()) {
if (matchClass.findMethodsBySignature(myMethod, false).length > 0) {
return true;
}
matchClass = PsiTreeUtil.getParentOfType(matchClass, PsiClass.class);
}
return false;
}
private boolean isEssentialStaticContextAbsent(final Match match) {
if (!myMethod.hasModifierProperty(PsiModifier.STATIC)) {
final PsiExpression instanceExpression = match.getInstanceExpression();
if (instanceExpression != null) return false;
if (isExternal(match)) return true;
if (PsiTreeUtil.isAncestor(myMethod.getContainingClass(), match.getMatchStart(), false) && RefactoringUtil.isInStaticContext(match.getMatchStart(), myMethod.getContainingClass())) return true;
}
return false;
}
public List<Match> getDuplicates() {
return myDuplicates;
}
public boolean hasDuplicates() {
return myDuplicates.isEmpty();
}
@Nullable
public String getConfirmDuplicatePrompt(final Match match) {
final PsiElement matchStart = match.getMatchStart();
@Modifier String visibility = VisibilityUtil.getPossibleVisibility(myMethod, matchStart);
final boolean shouldBeStatic = isEssentialStaticContextAbsent(match);
final String signature = match.getChangedSignature(myMethod, myMethod.hasModifierProperty(PsiModifier.STATIC) || shouldBeStatic, visibility);
if (signature != null) {
return RefactoringBundle.message("replace.this.code.fragment.and.change.signature", signature);
}
final boolean needToEscalateVisibility = !PsiUtil.isAccessible(myMethod, matchStart, null);
if (needToEscalateVisibility) {
final String visibilityPresentation = VisibilityUtil.toPresentableText(visibility);
return shouldBeStatic
? RefactoringBundle.message("replace.this.code.fragment.and.make.method.static.visible", visibilityPresentation)
: RefactoringBundle.message("replace.this.code.fragment.and.make.method.visible", visibilityPresentation);
}
if (shouldBeStatic) {
return RefactoringBundle.message("replace.this.code.fragment.and.make.method.static");
}
return null;
}
@Override
public String getReplaceDuplicatesTitle(int idx, int size) {
return RefactoringBundle.message("process.methods.duplicates.title", idx, size, myMethod.getName());
}
}
}
| EA-28869 - AIOOBE: MethodDuplicatesHandler.hasDuplicates
| java/java-impl/src/com/intellij/refactoring/util/duplicates/MethodDuplicatesHandler.java | EA-28869 - AIOOBE: MethodDuplicatesHandler.hasDuplicates | <ide><path>ava/java-impl/src/com/intellij/refactoring/util/duplicates/MethodDuplicatesHandler.java
<ide> PsiElement[] pattern = statements;
<ide> ReturnValue matchedReturnValue = null;
<ide> if (statements.length != 1 || !(statements[0] instanceof PsiReturnStatement)) {
<del> final PsiStatement lastStatement = statements[statements.length - 1];
<add> final PsiStatement lastStatement = statements.length > 0 ? statements[statements.length - 1] : null;
<ide> if (lastStatement instanceof PsiReturnStatement) {
<ide> final PsiExpression returnValue = ((PsiReturnStatement)lastStatement).getReturnValue();
<ide> if (returnValue instanceof PsiReferenceExpression) { |
|
Java | apache-2.0 | 4bc84f5c8de1230a7f7af59f5291a3938c6baee1 | 0 | markwoon/pathvisio,PathVisio/pathvisio,markwoon/pathvisio,markwoon/pathvisio,PathVisio/pathvisio,PathVisio/pathvisio,markwoon/pathvisio,PathVisio/pathvisio | // PathVisio,
// a tool for data visualization and analysis using Biological Pathways
// Copyright 2006-2007 BiGCaT Bioinformatics
//
// 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.pathvisio;
/**
* Global Project-wide Constants
*/
public class Globals
{
public static final String APPLICATION_NAME = "PathVisio";
public static final String HELP_URL = "http://www.pathvisio.org/Help_1.1";
// for inclusion in certain error messages.
public static final String DEVELOPER_EMAIL = "[email protected]";
public static final String SERVER_NAME = "WikiPathways.org";
}
| src/core/org/pathvisio/Globals.java | // PathVisio,
// a tool for data visualization and analysis using Biological Pathways
// Copyright 2006-2007 BiGCaT Bioinformatics
//
// 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.pathvisio;
/**
* Global Project-wide Constants
*/
public class Globals
{
public static final String APPLICATION_NAME = "PathVisio";
public static final String HELP_URL = "http://wiki.bigcat.unimaas.nl/pathvisio/Help";
// for inclusion in certain error messages.
public static final String DEVELOPER_EMAIL = "[email protected]";
public static final String SERVER_NAME = "WikiPathways.org";
}
| Started new Help page for pv 1.1
| src/core/org/pathvisio/Globals.java | Started new Help page for pv 1.1 | <ide><path>rc/core/org/pathvisio/Globals.java
<ide> public class Globals
<ide> {
<ide> public static final String APPLICATION_NAME = "PathVisio";
<del> public static final String HELP_URL = "http://wiki.bigcat.unimaas.nl/pathvisio/Help";
<add> public static final String HELP_URL = "http://www.pathvisio.org/Help_1.1";
<ide> // for inclusion in certain error messages.
<ide> public static final String DEVELOPER_EMAIL = "[email protected]";
<ide> public static final String SERVER_NAME = "WikiPathways.org"; |
|
Java | agpl-3.0 | 895cb28f179c10cb6cca471b6617fbbb601d65c4 | 0 | bio4j/bio4j | /*
* Copyright (C) 2010-2011 "Bio4j"
*
* This file is part of Bio4j
*
* Bio4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.era7.bioinfo.bio4j.blueprints.model.nodes;
import com.era7.bioinfo.bio4j.blueprints.model.nodes.citation.*;
import com.era7.bioinfo.bio4j.blueprints.model.nodes.reactome.ReactomeTermNode;
import com.era7.bioinfo.bio4j.blueprints.model.nodes.refseq.GenomeElementNode;
import com.era7.bioinfo.bio4j.blueprints.model.relationships.citation.article.ArticleProteinCitationRel;
import com.era7.bioinfo.bio4j.blueprints.model.relationships.citation.book.BookProteinCitationRel;
import com.era7.bioinfo.bio4j.blueprints.model.relationships.citation.onarticle.OnlineArticleProteinCitationRel;
import com.era7.bioinfo.bio4j.blueprints.model.relationships.citation.patent.PatentProteinCitationRel;
import com.era7.bioinfo.bio4j.blueprints.model.relationships.citation.submission.SubmissionProteinCitationRel;
import com.era7.bioinfo.bio4j.blueprints.model.relationships.citation.thesis.ThesisProteinCitationRel;
import com.era7.bioinfo.bio4j.blueprints.model.relationships.citation.uo.UnpublishedObservationProteinCitationRel;
import com.era7.bioinfo.bio4j.blueprints.model.relationships.comment.DomainCommentRel;
import com.era7.bioinfo.bio4j.blueprints.model.relationships.comment.FunctionCommentRel;
import com.era7.bioinfo.bio4j.blueprints.model.relationships.comment.PathwayCommentRel;
import com.era7.bioinfo.bio4j.blueprints.model.relationships.comment.SimilarityCommentRel;
import com.era7.bioinfo.bio4j.blueprints.model.relationships.features.ActiveSiteFeatureRel;
import com.era7.bioinfo.bio4j.blueprints.model.relationships.features.SignalPeptideFeatureRel;
import com.era7.bioinfo.bio4j.blueprints.model.relationships.features.SpliceVariantFeatureRel;
import com.era7.bioinfo.bio4j.blueprints.model.relationships.features.TransmembraneRegionFeatureRel;
import com.era7.bioinfo.bio4j.blueprints.model.relationships.protein.*;
import com.era7.bioinfo.bio4j.blueprints.model.relationships.uniref.UniRef100MemberRel;
import com.era7.bioinfo.bio4j.blueprints.model.relationships.uniref.UniRef50MemberRel;
import com.era7.bioinfo.bio4j.blueprints.model.relationships.uniref.UniRef90MemberRel;
import com.tinkerpop.blueprints.Direction;
import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Vertex;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/**
* Uniprot proteins
*
* @author Pablo Pareja Tobes <[email protected]>
*/
public class ProteinNode extends BasicVertex {
public static final String NODE_TYPE = ProteinNode.class.getCanonicalName();
public static final String NAME_PROPERTY = "protein_name";
public static final String FULL_NAME_PROPERTY = "protein_full_name";
public static final String SHORT_NAME_PROPERTY = "protein_short_name";
public static final String ACCESSION_PROPERTY = "protein_accession";
public static final String SEQUENCE_PROPERTY = "protein_sequence";
public static final String MASS_PROPERTY = "protein_mass";
public static final String LENGTH_PROPERTY = "protein_length";
public static final String MODIFIED_DATE_PROPERTY = "protein_modified_date";
public static final String GENE_NAMES_PROPERTY = "protein_gene_names";
public static final String ALTERNATIVE_ACCESSIONS_PROPERTY = "protein_alternative_accessions";
//---------------------DB CROSS REFERENCES----------------------------------------
public static final String ENSEMBL_REFERENCES_PROPERTY = "protein_ensembl_references";
public static final String PIR_REFERENCES_PROPERTY = "protein_pir_references";
public static final String KEGG_REFERENCES_PROPERTY = "protein_kegg_references";
public static final String EMBL_REFERENCES_PROPERTY = "protein_embl_references";
public static final String REFSEQ_REFERENCES_PROPERTY = "protein_refseq_references";
public static final String ARRAY_EXPRESS_REFERENCES_PROPERTY = "protein_array_express_references";
public static final String UNIGENE_REFERENCES_PROPERTY = "protein_unigene_references";
public static final String ENSEMBL_PLANTS_REFERENCES_PROPERTY = "protein_ensembl_plants_references";
public static final String DBASE_ECOLI_REFERENCES_PROPERTY = "protein_2dbase_ecoli_references";
public static final String AARHUS_GHENT_2DPAGE_REFERENCES_PROPERTY = "protein_aarhus_ghent_2dpage_references";
public static final String AGD_REFERENCES_PROPERTY = "protein_agd_references";
public static final String ALLERGOME_REFERENCES_PROPERTY = "protein_allergome_references";
public static final String ANU_2DPAGE_REFERENCES_PROPERTY = "protein_anu_2dpage_references";
public static final String ARACHNOSERVER_REFERENCES_PROPERTY = "protein_arachnoserver_references";
public static final String BGEE_REFERENCES_PROPERTY = "protein_bgee_references";
public static final String BINDING_DB_REFERENCES_PROPERTY = "protein_binding_db_references";
public static final String BIOCYC_REFERENCES_PROPERTY = "protein_biocyc_references";
public static final String BRENDA_REFERENCES_PROPERTY = "protein_brenda_references";
public static final String CAZY_REFERENCES_PROPERTY = "protein_cazy_references";
public static final String CGD_REFERENCES_PROPERTY = "protein_cgd_references";
public static final String CHEMBL_REFERENCES_PROPERTY = "protein_chembl_references";
public static final String CLEANEX_REFERENCES_PROPERTY = "protein_cleanex_references";
public static final String COMPLUYEAST_2DPAGE_REFERENCES_PROPERTY = "protein_compluyeast_2dpage_references";
public static final String CONOSERVER_REFERENCES_PROPERTY = "protein_conoserver_references";
public static final String CORNEA_2DPAGE_REFERENCES_PROPERTY = "protein_cornea_2dpage_references";
public static final String CTD_REFERENCES_PROPERTY = "protein_ctd_references";
public static final String CYGD_REFERENCES_PROPERTY = "protein_cygd_references";
public static final String DBSNP_REFERENCES_PROPERTY = "protein_dbsnp_references";
public static final String DDBJ_REFERENCES_PROPERTY = "protein_ddbj_references";
public static final String DICTY_BASE_REFERENCES_PROPERTY = "protein_dicty_base_references";
public static final String DIP_REFERENCES_PROPERTY = "protein_dip_references";
public static final String DISPROT_REFERENCES_PROPERTY = "protein_disprot_references";
public static final String DMDM_REFERENCES_PROPERTY = "protein_dmdm_references";
public static final String DNASU_REFERENCES_PROPERTY = "protein_dnasu_references";
public static final String DOSAC_COBS_2DPAGE_REFERENCES_PROPERTY = "protein_dosac_cobs_2dpage_references";
public static final String DRUGBANK_REFERENCES_PROPERTY = "protein_drugbank_references";
public static final String ECHOBASE_REFERENCES_PROPERTY = "protein_echobase_references";
public static final String ECOGENE_REFERENCES_PROPERTY = "protein_ecogene_references";
public static final String EGGNOG_REFERENCES_PROPERTY = "protein_eggnog_references";
public static final String ENSEMBL_BACTERIA_REFERENCES_PROPERTY = "protein_ensembl_bacteria_references";
public static final String ENSEMBL_FUNGI_REFERENCES_PROPERTY = "protein_ensembl_fungi_references";
public static final String ENSEMBL_METAZOA_REFERENCES_PROPERTY = "protein_ensembl_metazoa_references";
public static final String ENSEMBL_PROTISTS_REFERENCES_PROPERTY = "protein_ensembl_protists_references";
public static final String EUHCVDB_REFERENCES_PROPERTY = "protein_euhcvdb_references";
public static final String EUPATHDB_REFERENCES_PROPERTY = "protein_eupathdb_references";
public static final String EVOLUTIONARY_TRACE_REFERENCES_PROPERTY = "protein_evolutionary_trace_references";
public static final String FLYBASE_REFERENCES_PROPERTY = "protein_flybase_references";
public static final String GENATLAS_REFERENCES_PROPERTY = "protein_genatlas_references";
public static final String GENBANK_REFERENCES_PROPERTY = "protein_genbank_references";
public static final String GENE3D_REFERENCES_PROPERTY = "protein_gene3d_references";
public static final String GENECARDS_REFERENCES_PROPERTY = "protein_genecards_references";
public static final String GENEFARM_REFERENCES_PROPERTY = "protein_genefarm_references";
public static final String GENEID_REFERENCES_PROPERTY = "protein_geneid_references";
public static final String GENETREE_REFERENCES_PROPERTY = "protein_genetree_references";
public static final String GENEVESTIGATOR_REFERENCES_PROPERTY = "protein_genevestigator_references";
public static final String GENOLIST_REFERENCES_PROPERTY = "protein_genolist_references";
public static final String GENOME_REVIEWS_REFERENCES_PROPERTY = "protein_genome_reviews_references";
public static final String GENOME_RNAI_REFERENCES_PROPERTY = "protein_genome_rnai_references";
public static final String GERMONLINE_REFERENCES_PROPERTY = "protein_germonline_references";
public static final String GLYCOSUITEDB_REFERENCES_PROPERTY = "protein_glycosuitedb_references";
public static final String GPCRDB_REFERENCES_PROPERTY = "protein_gpcrdb_references";
public static final String GRAMENE_REFERENCES_PROPERTY = "protein_gramene_references";
public static final String HINVDB_REFERENCES_PROPERTY = "protein_hinvdb_references";
public static final String HAMAP_REFERENCES_PROPERTY = "protein_hamap_references";
public static final String HGNC_REFERENCES_PROPERTY = "protein_hgnc_references";
public static final String HOGENOM_REFERENCES_PROPERTY = "protein_hogenom_references";
public static final String HOVERGEN_REFERENCES_PROPERTY = "protein_hovergen_references";
public static final String HPA_REFERENCES_PROPERTY = "protein_hpa_references";
public static final String HSSP_REFERENCES_PROPERTY = "protein_hssp_references";
public static final String HUGE_REFERENCES_PROPERTY = "protein_huge_references";
public static final String IMGT_REFERENCES_PROPERTY = "protein_imgt_references";
public static final String INPARANOID_REFERENCES_PROPERTY = "protein_inparanoid_references";
public static final String INTACT_REFERENCES_PROPERTY = "protein_intact_references";
public static final String IPI_REFERENCES_PROPERTY = "protein_ipi_references";
public static final String KO_REFERENCES_PROPERTY = "protein_ko_references";
public static final String LEGIO_LIST_REFERENCES_PROPERTY = "protein_legio_list_references";
public static final String LEPROMA_REFERENCES_PROPERTY = "protein_leproma_references";
public static final String MAIZE_GDB_REFERENCES_PROPERTY = "protein_maize_gdb_references";
public static final String MEROPS_REFERENCES_PROPERTY = "protein_merops_references";
public static final String MGI_REFERENCES_PROPERTY = "protein_mgi_references";
public static final String MICADO_REFERENCES_PROPERTY = "protein_micado_references";
public static final String MIM_REFERENCES_PROPERTY = "protein_mim_references";
public static final String MINT_REFERENCES_PROPERTY = "protein_mint_references";
public static final String MODBASE_REFERENCES_PROPERTY = "protein_modbase_references";
public static final String MYCOCLAP_REFERENCES_PROPERTY = "protein_mycoclap_references";
public static final String NEXTBIO_REFERENCES_PROPERTY = "protein_nextbio_references";
public static final String NEXTPROT_REFERENCES_PROPERTY = "protein_nextprot_references";
public static final String OGP_REFERENCES_PROPERTY = "protein_ogp_references";
public static final String OMA_REFERENCES_PROPERTY = "protein_oma_references";
public static final String ORPHANET_REFERENCES_PROPERTY = "protein_orphanet_references";
public static final String ORTHODB_REFERENCES_PROPERTY = "protein_orthodb_references";
public static final String PANTHER_REFERENCES_PROPERTY = "protein_panther_references";
public static final String PATHWAY_INTERACTION_DB_REFERENCES_PROPERTY = "protein_pathway_interaction_db_references";
public static final String PATRIC_REFERENCES_PROPERTY = "protein_patric_references";
public static final String PAXDB_REFERENCES_PROPERTY = "protein_paxdb_references";
public static final String PDB_REFERENCES_PROPERTY = "protein_pdb_references";
public static final String PDBJ_REFERENCES_PROPERTY = "protein_pdbj_references";
public static final String PDBSUM_REFERENCES_PROPERTY = "protein_pdbsum_references";
public static final String PEPTIDE_ATLAS_REFERENCES_PROPERTY = "protein_peptide_atlas_references";
public static final String PHARMGKB_REFERENCES_PROPERTY = "protein_pharmgkb_references";
public static final String PHCI_2DPAGE_REFERENCES_PROPERTY = "protein_phci_2dpage_references";
public static final String PHOSPHOSITE_REFERENCES_PROPERTY = "protein_phosphosite_references";
public static final String PHOS_SITE_REFERENCES_PROPERTY = "protein_phos_site_references";
public static final String PHYLOME_DB_REFERENCES_PROPERTY = "protein_phylome_db_references";
public static final String PIRSF_REFERENCES_PROPERTY = "protein_pirsf_references";
public static final String PMAP_CUTDB_REFERENCES_PROPERTY = "protein_pmap_cutdb_references";
public static final String PMMA_2DPAGE_REFERENCES_PROPERTY = "protein_pmma_2dpage_references";
public static final String POMBASE_REFERENCES_PROPERTY = "protein_pombase_references";
public static final String PPTASEDB_REFERENCES_PROPERTY = "protein_pptasedb_references";
public static final String PRIDE_REFERENCES_PROPERTY = "protein_pride_references";
public static final String PRINTS_REFERENCES_PROPERTY = "protein_prints_references";
public static final String PRODOM_REFERENCES_PROPERTY = "protein_prodom_references";
public static final String PROMEX_REFERENCES_PROPERTY = "protein_promex_references";
public static final String PROSITE_REFERENCES_PROPERTY = "protein_prosite_references";
public static final String PROT_CLUST_DB_REFERENCES_PROPERTY = "protein_prot_clust_db_references";
public static final String PROTEIN_MODEL_PORTAL_REFERENCES_PROPERTY = "protein_model_portal_references";
public static final String PROTONET_REFERENCES_PROPERTY = "protein_protonet_references";
public static final String PSEUDO_CAP_REFERENCES_PROPERTY = "protein_pseudo_cap_references";
public static final String RAT_HEART_2DPAGE_REFERENCES_PROPERTY = "protein_rat_heart_2dpage_references";
public static final String RCSB_PDB_REFERENCES_PROPERTY = "protein_rcsb_pdb_references";
public static final String REBASE_REFERENCES_PROPERTY = "protein_rebase_references";
public static final String REPRODUCTION_2DPAGE_REFERENCES_PROPERTY = "protein_reproduction_2dpage_references";
public static final String RGD_REFERENCES_PROPERTY = "protein_rgd_references";
public static final String ROUGE_REFERENCES_PROPERTY = "protein_rouge_references";
public static final String SBKB_REFERENCES_PROPERTY = "protein_sbkb_references";
public static final String SGD_REFERENCES_PROPERTY = "protein_sgd_references";
public static final String SIENA_2DPAGE_REFERENCES_PROPERTY = "protein_siena_2dpage_references";
public static final String SMART_REFERENCES_PROPERTY = "protein_smart_references";
public static final String SMR_REFERENCES_PROPERTY = "protein_smr_references";
public static final String SOURCE_REFERENCES_PROPERTY = "protein_source_references";
public static final String STRING_REFERENCES_PROPERTY = "protein_string_references";
public static final String SUPFAM_REFERENCES_PROPERTY = "protein_supfam_references";
public static final String SWISS_2DPAGE_REFERENCES_PROPERTY = "protein_swiss_2dpage_references";
public static final String TAIR_REFERENCES_PROPERTY = "protein_tair_references";
public static final String TCDB_REFERENCES_PROPERTY = "protein_tcb_references";
public static final String TIGRFAMS_REFERENCES_PROPERTY = "protein_tigrfams_references";
public static final String TUBERCULIST_REFERENCES_PROPERTY = "protein_tuberculist_references";
public static final String UCD_2DPAGE_REFERENCES_PROPERTY = "protein_ucd_2dpage_references";
public static final String UCSC_REFERENCES_PROPERTY = "protein_ucsc_references";
public static final String VECTOR_BASE_REFERENCES_PROPERTY = "protein_vector_base_references";
public static final String WORLD_2DPAGE_REFERENCES_PROPERTY = "protein_world_2dpage_references";
public static final String WORM_BASE_REFERENCES_PROPERTY = "protein_worm_base_references";
public static final String XEN_BASE_REFERENCES_PROPERTY = "protein_xen_base_references";
public static final String ZFIN_REFERENCES_PROPERTY = "protein_zfin_references";
//-------------------------------------------------------------------------------------------------
public ProteinNode(Vertex v) {
super(v);
}
public String getName() {
return String.valueOf(vertex.getProperty(NAME_PROPERTY));
}
public String getFullName() {
return String.valueOf(vertex.getProperty(FULL_NAME_PROPERTY));
}
public String getShortName() {
return String.valueOf(vertex.getProperty(SHORT_NAME_PROPERTY));
}
public String getAccession() {
return String.valueOf(vertex.getProperty(ACCESSION_PROPERTY));
}
public String getSequence() {
return String.valueOf(vertex.getProperty(SEQUENCE_PROPERTY));
}
public String getEnsemblReferences() {
return String.valueOf(vertex.getProperty(ENSEMBL_REFERENCES_PROPERTY));
}
public String[] getEMBLFeferences() {
return (String[]) vertex.getProperty(EMBL_REFERENCES_PROPERTY);
}
public String[] getEnsemblPlantsReferences() {
return (String[]) vertex.getProperty(ENSEMBL_PLANTS_REFERENCES_PROPERTY);
}
public String[] getRefseqReferences() {
return (String[]) vertex.getProperty(REFSEQ_REFERENCES_PROPERTY);
}
public String[] getAlternativeAcessions() {
return (String[]) vertex.getProperty(ALTERNATIVE_ACCESSIONS_PROPERTY);
}
public String[] getPIRReferences() {
return (String[]) vertex.getProperty(PIR_REFERENCES_PROPERTY);
}
public String[] getKeggReferences() {
return (String[]) vertex.getProperty(KEGG_REFERENCES_PROPERTY);
}
public String[] getArrayExpressReferences() {
return (String[]) vertex.getProperty(ARRAY_EXPRESS_REFERENCES_PROPERTY);
}
public String[] getUniGeneReferences() {
return (String[]) vertex.getProperty(UNIGENE_REFERENCES_PROPERTY);
}
public String getModifiedDate() {
return String.valueOf(vertex.getProperty(MODIFIED_DATE_PROPERTY));
}
public float getMass() {
return Float.parseFloat(String.valueOf(vertex.getProperty(MASS_PROPERTY)));
}
public int getLength() {
return Integer.parseInt(String.valueOf(vertex.getProperty(LENGTH_PROPERTY)));
}
public String[] getGeneNames() {
return (String[]) vertex.getProperty(GENE_NAMES_PROPERTY);
}
public boolean isUniref50Representant() {
return !vertex.getEdges(Direction.IN, UniRef50MemberRel.NAME).iterator().hasNext();
}
public boolean isUniref90Representant() {
return !vertex.getEdges(Direction.IN, UniRef90MemberRel.NAME).iterator().hasNext();
}
public boolean isUniref100Representant() {
return !vertex.getEdges(Direction.IN, UniRef100MemberRel.NAME).iterator().hasNext();
}
public List<ProteinNode> getUniref50ClusterThisProteinBelongsTo() {
List<ProteinNode> list = new LinkedList<ProteinNode>();
if (isUniref50Representant()) {
list.add(this);
Iterator<Vertex> relIterator = vertex.getVertices(Direction.OUT, UniRef50MemberRel.NAME).iterator();
while (relIterator.hasNext()) {
list.add(new ProteinNode(relIterator.next()));
}
} else {
ProteinNode representant = new ProteinNode(vertex.getVertices(Direction.IN, UniRef50MemberRel.NAME).iterator().next());
return representant.getUniref50ClusterThisProteinBelongsTo();
}
return list;
}
public List<ProteinNode> getUniref90ClusterThisProteinBelongsTo() {
List<ProteinNode> list = new LinkedList<ProteinNode>();
if (isUniref90Representant()) {
list.add(this);
Iterator<Vertex> relIterator = vertex.getVertices(Direction.OUT, UniRef90MemberRel.NAME).iterator();
while (relIterator.hasNext()) {
list.add(new ProteinNode(relIterator.next()));
}
} else {
ProteinNode representant = new ProteinNode(vertex.getVertices(Direction.IN, UniRef90MemberRel.NAME).iterator().next());
return representant.getUniref90ClusterThisProteinBelongsTo();
}
return list;
}
public List<ProteinNode> getUniref100ClusterThisProteinBelongsTo() {
List<ProteinNode> list = new LinkedList<ProteinNode>();
if (isUniref100Representant()) {
list.add(this);
Iterator<Vertex> relIterator = vertex.getVertices(Direction.OUT, UniRef100MemberRel.NAME).iterator();
while (relIterator.hasNext()) {
list.add(new ProteinNode(relIterator.next()));
}
} else {
ProteinNode representant = new ProteinNode(vertex.getVertices(Direction.IN, UniRef100MemberRel.NAME).iterator().next());
return representant.getUniref100ClusterThisProteinBelongsTo();
}
return list;
}
public OrganismNode getOrganism() {
OrganismNode org = null;
Iterator<Vertex> iterator = vertex.getVertices(Direction.OUT, ProteinOrganismRel.NAME).iterator();
if (iterator.hasNext()) {
org = new OrganismNode(iterator.next());
}
return org;
}
public DatasetNode getDataset() {
DatasetNode dataset = null;
Iterator<Vertex> iterator = vertex.getVertices(Direction.OUT, ProteinDatasetRel.NAME).iterator();
if (iterator.hasNext()) {
dataset = new DatasetNode(iterator.next());
}
return dataset;
}
public List<GenomeElementNode> getGenomeElements() {
List<GenomeElementNode> list = new ArrayList<GenomeElementNode>();
Iterator<Vertex> iterator = vertex.getVertices(Direction.OUT, ProteinGenomeElementRel.NAME).iterator();
while (iterator.hasNext()) {
list.add(new GenomeElementNode(iterator.next()));
}
return list;
}
public List<SubcellularLocationNode> getSubcellularLocations() {
List<SubcellularLocationNode> list = new ArrayList<SubcellularLocationNode>();
Iterator<Vertex> iterator = vertex.getVertices(Direction.OUT, ProteinSubcellularLocationRel.NAME).iterator();
while (iterator.hasNext()) {
list.add(new SubcellularLocationNode(iterator.next()));
}
return list;
}
public List<InterproNode> getInterpro() {
List<InterproNode> interpros = new ArrayList<InterproNode>();
Iterator<Vertex> iterator = vertex.getVertices(Direction.OUT, ProteinInterproRel.NAME).iterator();
while (iterator.hasNext()) {
InterproNode interpro = new InterproNode(iterator.next());
interpros.add(interpro);
}
return interpros;
}
public List<PfamNode> getPfamTerms() {
List<PfamNode> pfamTerms = new ArrayList<PfamNode>();
Iterator<Vertex> iterator = vertex.getVertices(Direction.OUT, ProteinPfamRel.NAME).iterator();
while (iterator.hasNext()) {
PfamNode interpro = new PfamNode(iterator.next());
pfamTerms.add(interpro);
}
return pfamTerms;
}
public List<ReactomeTermNode> getReactomeTerms() {
List<ReactomeTermNode> list = new LinkedList<ReactomeTermNode>();
Iterator<Vertex> iterator = vertex.getVertices(Direction.OUT, ProteinReactomeRel.NAME).iterator();
while (iterator.hasNext()) {
ReactomeTermNode reactomeTerm = new ReactomeTermNode(iterator.next());
list.add(reactomeTerm);
}
return list;
}
public List<EnzymeNode> getProteinEnzymaticActivity() {
List<EnzymeNode> list = new LinkedList<EnzymeNode>();
Iterator<Vertex> iterator = vertex.getVertices(Direction.OUT, ProteinEnzymaticActivityRel.NAME).iterator();
while (iterator.hasNext()) {
EnzymeNode enzyme = new EnzymeNode(iterator.next());
list.add(enzyme);
}
return list;
}
public List<GoTermNode> getGOAnnotations() {
List<GoTermNode> list = new ArrayList<GoTermNode>();
Iterator<Vertex> iterator = vertex.getVertices(Direction.OUT, ProteinGoRel.NAME).iterator();
while (iterator.hasNext()) {
GoTermNode goTerm = new GoTermNode(iterator.next());
list.add(goTerm);
}
return list;
}
public List<KeywordNode> getKeywords() {
List<KeywordNode> keywords = new ArrayList<KeywordNode>();
Iterator<Vertex> iterator = vertex.getVertices(Direction.OUT, ProteinKeywordRel.NAME).iterator();
while (iterator.hasNext()) {
KeywordNode keyword = new KeywordNode(iterator.next());
keywords.add(keyword);
}
return keywords;
}
public List<SignalPeptideFeatureRel> getSignalPeptideFeature() {
List<SignalPeptideFeatureRel> list = new ArrayList<SignalPeptideFeatureRel>();
Iterator<Edge> iterator = vertex.getEdges(Direction.OUT, SignalPeptideFeatureRel.NAME).iterator();
while (iterator.hasNext()) {
SignalPeptideFeatureRel rel = new SignalPeptideFeatureRel(iterator.next());
list.add(rel);
}
return list;
}
public List<SpliceVariantFeatureRel> getSpliceVariantFeature() {
List<SpliceVariantFeatureRel> list = new ArrayList<SpliceVariantFeatureRel>();
Iterator<Edge> iterator = vertex.getEdges(Direction.OUT, SpliceVariantFeatureRel.NAME).iterator();
while (iterator.hasNext()) {
SpliceVariantFeatureRel rel = new SpliceVariantFeatureRel(iterator.next());
list.add(rel);
}
return list;
}
public List<TransmembraneRegionFeatureRel> getTransmembraneRegionFeature() {
List<TransmembraneRegionFeatureRel> list = new ArrayList<TransmembraneRegionFeatureRel>();
Iterator<Edge> iterator = vertex.getEdges(Direction.OUT, TransmembraneRegionFeatureRel.NAME).iterator();
while (iterator.hasNext()) {
TransmembraneRegionFeatureRel rel = new TransmembraneRegionFeatureRel(iterator.next());
list.add(rel);
}
return list;
}
public List<ActiveSiteFeatureRel> getActiveSiteFeature() {
List<ActiveSiteFeatureRel> list = new ArrayList<ActiveSiteFeatureRel>();
Iterator<Edge> iterator = vertex.getEdges(Direction.OUT, ActiveSiteFeatureRel.NAME).iterator();
while (iterator.hasNext()) {
ActiveSiteFeatureRel rel = new ActiveSiteFeatureRel(iterator.next());
list.add(rel);
}
return list;
}
public List<FunctionCommentRel> getFunctionComment() {
List<FunctionCommentRel> list = new ArrayList<FunctionCommentRel>();
Iterator<Edge> iterator = vertex.getEdges(Direction.OUT, FunctionCommentRel.NAME).iterator();
while (iterator.hasNext()) {
FunctionCommentRel rel = new FunctionCommentRel(iterator.next());
list.add(rel);
}
return list;
}
public List<PathwayCommentRel> getPathwayComment() {
List<PathwayCommentRel> list = new ArrayList<PathwayCommentRel>();
Iterator<Edge> iterator = vertex.getEdges(Direction.OUT, PathwayCommentRel.NAME).iterator();
while (iterator.hasNext()) {
PathwayCommentRel rel = new PathwayCommentRel(iterator.next());
list.add(rel);
}
return list;
}
public List<DomainCommentRel> getDomainComment() {
List<DomainCommentRel> list = new ArrayList<DomainCommentRel>();
Iterator<Edge> iterator = vertex.getEdges(Direction.OUT, DomainCommentRel.NAME).iterator();
while (iterator.hasNext()) {
DomainCommentRel rel = new DomainCommentRel(iterator.next());
list.add(rel);
}
return list;
}
public List<SimilarityCommentRel> getSimilarityComment() {
List<SimilarityCommentRel> list = new ArrayList<SimilarityCommentRel>();
Iterator<Edge> iterator = vertex.getEdges(Direction.OUT, SimilarityCommentRel.NAME).iterator();
while (iterator.hasNext()) {
SimilarityCommentRel rel = new SimilarityCommentRel(iterator.next());
list.add(rel);
}
return list;
}
/**
* Protein-protein outgoing interactions
*
* @return
*/
public List<ProteinProteinInteractionRel> getProteinOutgoingInteractions() {
List<ProteinProteinInteractionRel> list = new ArrayList<ProteinProteinInteractionRel>();
Iterator<Edge> iterator = vertex.getEdges(Direction.OUT, ProteinProteinInteractionRel.NAME).iterator();
while (iterator.hasNext()) {
list.add(new ProteinProteinInteractionRel(iterator.next()));
}
return list;
}
/**
* Protein-protein incoming interactions
*
* @return
*/
public List<ProteinProteinInteractionRel> getProteinIncomingInteractions() {
List<ProteinProteinInteractionRel> list = new ArrayList<ProteinProteinInteractionRel>();
Iterator<Edge> iterator = vertex.getEdges(Direction.IN, ProteinProteinInteractionRel.NAME).iterator();
while (iterator.hasNext()) {
list.add(new ProteinProteinInteractionRel(iterator.next()));
}
return list;
}
/**
* Protein-Isoform outgoing interactions
*
* @return
*/
public List<ProteinIsoformInteractionRel> getIsoformOutgoingInteractions() {
List<ProteinIsoformInteractionRel> list = new ArrayList<ProteinIsoformInteractionRel>();
Iterator<Edge> iterator = vertex.getEdges(Direction.OUT, ProteinIsoformInteractionRel.NAME).iterator();
while (iterator.hasNext()) {
list.add(new ProteinIsoformInteractionRel(iterator.next()));
}
return list;
}
/**
* Protein-Isoform incoming interactions
*
* @return
*/
public List<ProteinIsoformInteractionRel> getIsoformIncomingInteractions() {
List<ProteinIsoformInteractionRel> list = new ArrayList<ProteinIsoformInteractionRel>();
Iterator<Edge> iterator = vertex.getEdges(Direction.IN, ProteinIsoformInteractionRel.NAME).iterator();
while (iterator.hasNext()) {
list.add(new ProteinIsoformInteractionRel(iterator.next()));
}
return list;
}
//---------------------------------------------------------------------------------------------
//-------------------------------------CITATIONS-----------------------------------------------
//---------------------------------------------------------------------------------------------
/**
* Protein article citations
*
* @return
*/
public List<ArticleNode> getArticleCitations() {
List<ArticleNode> list = new ArrayList<ArticleNode>();
Iterator<Vertex> iterator = vertex.getVertices(Direction.IN, ArticleProteinCitationRel.NAME).iterator();
while (iterator.hasNext()) {
list.add(new ArticleNode(iterator.next()));
}
return list;
}
/**
* Protein submission citations
*
* @return
*/
public List<SubmissionNode> getSubmissionCitations() {
List<SubmissionNode> list = new ArrayList<SubmissionNode>();
Iterator<Vertex> iterator = vertex.getVertices(Direction.IN, SubmissionProteinCitationRel.NAME).iterator();
while (iterator.hasNext()) {
list.add(new SubmissionNode(iterator.next()));
}
return list;
}
/**
* Protein Online article citations
*
* @return
*/
public List<OnlineArticleNode> getOnlineArticleCitations() {
List<OnlineArticleNode> list = new ArrayList<OnlineArticleNode>();
Iterator<Vertex> iterator = vertex.getVertices(Direction.IN, OnlineArticleProteinCitationRel.NAME).iterator();
while (iterator.hasNext()) {
list.add(new OnlineArticleNode(iterator.next()));
}
return list;
}
/**
* Protein Book citations
*
* @return
*/
public List<BookNode> getBookCitations() {
List<BookNode> list = new ArrayList<BookNode>();
Iterator<Vertex> iterator = vertex.getVertices(Direction.IN, BookProteinCitationRel.NAME).iterator();
while (iterator.hasNext()) {
list.add(new BookNode(iterator.next()));
}
return list;
}
/**
* Protein patent citations
*
* @return
*/
public List<PatentNode> getPatentCitations() {
List<PatentNode> list = new ArrayList<PatentNode>();
Iterator<Vertex> iterator = vertex.getVertices(Direction.IN, PatentProteinCitationRel.NAME).iterator();
while (iterator.hasNext()) {
list.add(new PatentNode(iterator.next()));
}
return list;
}
/**
* Protein thesis citations
*
* @return
*/
public List<ThesisNode> getThesisCitations() {
List<ThesisNode> list = new ArrayList<ThesisNode>();
Iterator<Vertex> iterator = vertex.getVertices(Direction.IN, ThesisProteinCitationRel.NAME).iterator();
while (iterator.hasNext()) {
list.add(new ThesisNode(iterator.next()));
}
return list;
}
/**
* Protein unpublished observations citations
*
* @return
*/
public List<UnpublishedObservationNode> getUnpublishedObservationsCitations() {
List<UnpublishedObservationNode> list = new ArrayList<UnpublishedObservationNode>();
Iterator<Vertex> iterator = vertex.getVertices(Direction.IN, UnpublishedObservationProteinCitationRel.NAME).iterator();
while (iterator.hasNext()) {
list.add(new UnpublishedObservationNode(iterator.next()));
}
return list;
}
//---------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------
public void setName(String value) {
vertex.setProperty(NAME_PROPERTY, value);
}
public void setFullName(String value) {
vertex.setProperty(FULL_NAME_PROPERTY, value);
}
public void setShortName(String value) {
vertex.setProperty(SHORT_NAME_PROPERTY, value);
}
public void setAccession(String value) {
vertex.setProperty(ACCESSION_PROPERTY, value);
}
public void setSequence(String value) {
vertex.setProperty(SEQUENCE_PROPERTY, value);
}
public void setModifiedDate(String value) {
vertex.setProperty(MODIFIED_DATE_PROPERTY, value);
}
public void setMass(float value) {
vertex.setProperty(MASS_PROPERTY, value);
}
public void setLength(int value) {
vertex.setProperty(LENGTH_PROPERTY, value);
}
public void setGeneNames(String[] value) {
vertex.setProperty(GENE_NAMES_PROPERTY, value);
}
public void setEnsemblReferences(String[] value) {
vertex.setProperty(ENSEMBL_REFERENCES_PROPERTY, value);
}
public void setKeggReferences(String[] value) {
vertex.setProperty(KEGG_REFERENCES_PROPERTY, value);
}
public void setPIRReferences(String[] value) {
vertex.setProperty(PIR_REFERENCES_PROPERTY, value);
}
public void setEMBLreferences(String[] value) {
vertex.setProperty(EMBL_REFERENCES_PROPERTY, value);
}
public void setEnsemblPlantsReferences(String[] value) {
vertex.setProperty(ENSEMBL_PLANTS_REFERENCES_PROPERTY, value);
}
public void setRefseqReferences(String[] value) {
vertex.setProperty(REFSEQ_REFERENCES_PROPERTY, value);
}
public void setAlternativeAccessions(String[] value) {
vertex.setProperty(ALTERNATIVE_ACCESSIONS_PROPERTY, value);
}
public void setArrayExpressReferences(String[] value) {
vertex.setProperty(ARRAY_EXPRESS_REFERENCES_PROPERTY, value);
}
public void setUniGeneReferences(String[] value) {
vertex.setProperty(UNIGENE_REFERENCES_PROPERTY, value);
}
public void setDBaseEcoliReferences(String[] value) {
vertex.setProperty(DBASE_ECOLI_REFERENCES_PROPERTY, value);
}
public void setAarhusGhent2DPageReferences(String[] value) {
vertex.setProperty(AARHUS_GHENT_2DPAGE_REFERENCES_PROPERTY, value);
}
public void setAGDReferences(String[] value) {
vertex.setProperty(AGD_REFERENCES_PROPERTY, value);
}
public void setAllergomeReferences(String[] value) {
vertex.setProperty(ALLERGOME_REFERENCES_PROPERTY, value);
}
public void setAnu2DPageReferences(String[] value) {
vertex.setProperty(ANU_2DPAGE_REFERENCES_PROPERTY, value);
}
public void setArachnoserverReferences(String[] value) {
vertex.setProperty(ARACHNOSERVER_REFERENCES_PROPERTY, value);
}
public void setBGeeReferences(String[] value) {
vertex.setProperty(BGEE_REFERENCES_PROPERTY, value);
}
public void setBindingDBReferences(String[] value) {
vertex.setProperty(BINDING_DB_REFERENCES_PROPERTY, value);
}
public void setBiocycReferences(String[] value) {
vertex.setProperty(BIOCYC_REFERENCES_PROPERTY, value);
}
public void setBrendaReferences(String[] value) {
vertex.setProperty(BRENDA_REFERENCES_PROPERTY, value);
}
public void setCazyReferences(String[] value) {
vertex.setProperty(CAZY_REFERENCES_PROPERTY, value);
}
public void setCGDReferences(String[] value) {
vertex.setProperty(CGD_REFERENCES_PROPERTY, value);
}
public void setCHEmblReferences(String[] value) {
vertex.setProperty(CHEMBL_REFERENCES_PROPERTY, value);
}
public void setCleanexReferences(String[] value) {
vertex.setProperty(CLEANEX_REFERENCES_PROPERTY, value);
}
public void setCompluYeastReferences(String[] value) {
vertex.setProperty(COMPLUYEAST_2DPAGE_REFERENCES_PROPERTY, value);
}
public void setConserverReferences(String[] value) {
vertex.setProperty(CONOSERVER_REFERENCES_PROPERTY, value);
}
public void setCornea2DPageReferences(String[] value) {
vertex.setProperty(CORNEA_2DPAGE_REFERENCES_PROPERTY, value);
}
public void setCTDReferences(String[] value) {
vertex.setProperty(CTD_REFERENCES_PROPERTY, value);
}
public void setCYGDReferences(String[] value) {
vertex.setProperty(CYGD_REFERENCES_PROPERTY, value);
}
public void setDBSNPReferences(String[] value) {
vertex.setProperty(DBSNP_REFERENCES_PROPERTY, value);
}
public void setDDBJReferences(String[] value) {
vertex.setProperty(DDBJ_REFERENCES_PROPERTY, value);
}
public void setDictyBaseReferences(String[] value) {
vertex.setProperty(DICTY_BASE_REFERENCES_PROPERTY, value);
}
public void setDIPReferences(String[] value) {
vertex.setProperty(DIP_REFERENCES_PROPERTY, value);
}
public void setDisprotReferences(String[] value) {
vertex.setProperty(DISPROT_REFERENCES_PROPERTY, value);
}
public void setDMDMReferences(String[] value) {
vertex.setProperty(DMDM_REFERENCES_PROPERTY, value);
}
public void setDnasuReferences(String[] value) {
vertex.setProperty(DNASU_REFERENCES_PROPERTY, value);
}
public void setDosacCobs2DPageReferences(String[] value) {
vertex.setProperty(DOSAC_COBS_2DPAGE_REFERENCES_PROPERTY, value);
}
public void setDrugbankReferences(String[] value) {
vertex.setProperty(DRUGBANK_REFERENCES_PROPERTY, value);
}
public void setEchoBaseReferences(String[] value) {
vertex.setProperty(ECHOBASE_REFERENCES_PROPERTY, value);
}
public void setEcogeneReferences(String[] value) {
vertex.setProperty(ECOGENE_REFERENCES_PROPERTY, value);
}
public void setEggnogReferences(String[] value) {
vertex.setProperty(EGGNOG_REFERENCES_PROPERTY, value);
}
public void setEnsemblBacteriaReferences(String[] value) {
vertex.setProperty(ENSEMBL_BACTERIA_REFERENCES_PROPERTY, value);
}
public void setEnsemblFungiReferences(String[] value) {
vertex.setProperty(ENSEMBL_FUNGI_REFERENCES_PROPERTY, value);
}
public void setEnsemblMetazoaReferences(String[] value) {
vertex.setProperty(ENSEMBL_METAZOA_REFERENCES_PROPERTY, value);
}
public void setEnsemblProtistsReferences(String[] value) {
vertex.setProperty(ENSEMBL_PROTISTS_REFERENCES_PROPERTY, value);
}
public void setEuhcvDBReferences(String[] value) {
vertex.setProperty(EUHCVDB_REFERENCES_PROPERTY, value);
}
public void setEupathDBReferences(String[] value) {
vertex.setProperty(EUPATHDB_REFERENCES_PROPERTY, value);
}
public void setEvolutionaryTraceReferences(String[] value) {
vertex.setProperty(EVOLUTIONARY_TRACE_REFERENCES_PROPERTY, value);
}
public void setFlyBaseReferences(String[] value) {
vertex.setProperty(FLYBASE_REFERENCES_PROPERTY, value);
}
public void setGenAtlasReferences(String[] value) {
vertex.setProperty(GENATLAS_REFERENCES_PROPERTY, value);
}
public void setGenBankReferences(String[] value) {
vertex.setProperty(GENBANK_REFERENCES_PROPERTY, value);
}
public void setGene3DReferences(String[] value) {
vertex.setProperty(GENE3D_REFERENCES_PROPERTY, value);
}
public void setGeneCardsReferences(String[] value) {
vertex.setProperty(GENECARDS_REFERENCES_PROPERTY, value);
}
public void setGeneFarmReferences(String[] value) {
vertex.setProperty(GENEFARM_REFERENCES_PROPERTY, value);
}
public void setGeneIDReferences(String[] value) {
vertex.setProperty(GENEID_REFERENCES_PROPERTY, value);
}
public void setGeneTreeReferences(String[] value) {
vertex.setProperty(GENETREE_REFERENCES_PROPERTY, value);
}
public void setGenevestigatorReferences(String[] value) {
vertex.setProperty(GENEVESTIGATOR_REFERENCES_PROPERTY, value);
}
public void setGenolistReferences(String[] value) {
vertex.setProperty(GENOLIST_REFERENCES_PROPERTY, value);
}
public void setGenomeReviewsReferences(String[] value) {
vertex.setProperty(GENOME_REVIEWS_REFERENCES_PROPERTY, value);
}
public void setGenomeRNAIReferences(String[] value) {
vertex.setProperty(GENOME_RNAI_REFERENCES_PROPERTY, value);
}
public void setGermOnlineReferences(String[] value) {
vertex.setProperty(GERMONLINE_REFERENCES_PROPERTY, value);
}
public void setGlycoSuiteDBReferences(String[] value) {
vertex.setProperty(GLYCOSUITEDB_REFERENCES_PROPERTY, value);
}
public void setGPCRDBReferences(String[] value) {
vertex.setProperty(GPCRDB_REFERENCES_PROPERTY, value);
}
public void setGrameneReferences(String[] value) {
vertex.setProperty(GRAMENE_REFERENCES_PROPERTY, value);
}
public void setHINVDBReferences(String[] value) {
vertex.setProperty(HINVDB_REFERENCES_PROPERTY, value);
}
public void setHamapReferences(String[] value) {
vertex.setProperty(HAMAP_REFERENCES_PROPERTY, value);
}
public void setHGNCReferences(String[] value) {
vertex.setProperty(HGNC_REFERENCES_PROPERTY, value);
}
public void setHogenomReferences(String[] value) {
vertex.setProperty(HOGENOM_REFERENCES_PROPERTY, value);
}
public void setHovergenReferences(String[] value) {
vertex.setProperty(HOVERGEN_REFERENCES_PROPERTY, value);
}
public void setHpaReferences(String[] value) {
vertex.setProperty(HPA_REFERENCES_PROPERTY, value);
}
public void setHsspReferences(String[] value) {
vertex.setProperty(HSSP_REFERENCES_PROPERTY, value);
}
public void setHugeReferences(String[] value) {
vertex.setProperty(HUGE_REFERENCES_PROPERTY, value);
}
public void setIMGTReferences(String[] value) {
vertex.setProperty(IMGT_REFERENCES_PROPERTY, value);
}
public void setINPARANOIDReferences(String[] value) {
vertex.setProperty(INPARANOID_REFERENCES_PROPERTY, value);
}
public void setIntactReferences(String[] value) {
vertex.setProperty(INTACT_REFERENCES_PROPERTY, value);
}
public void setIPIReferences(String[] value) {
vertex.setProperty(IPI_REFERENCES_PROPERTY, value);
}
public void setKOReferences(String[] value) {
vertex.setProperty(KO_REFERENCES_PROPERTY, value);
}
public void setLegioListReferences(String[] value) {
vertex.setProperty(LEGIO_LIST_REFERENCES_PROPERTY, value);
}
public void setLepromaReferences(String[] value) {
vertex.setProperty(LEPROMA_REFERENCES_PROPERTY, value);
}
public void setMaizeGDBReferences(String[] value) {
vertex.setProperty(MAIZE_GDB_REFERENCES_PROPERTY, value);
}
public void setMeropsReferences(String[] value) {
vertex.setProperty(MEROPS_REFERENCES_PROPERTY, value);
}
public void setMGIReferences(String[] value) {
vertex.setProperty(MGI_REFERENCES_PROPERTY, value);
}
public void setMicadoReferences(String[] value) {
vertex.setProperty(MICADO_REFERENCES_PROPERTY, value);
}
public void setMIMReferences(String[] value) {
vertex.setProperty(MIM_REFERENCES_PROPERTY, value);
}
public void setMINTReferences(String[] value) {
vertex.setProperty(MINT_REFERENCES_PROPERTY, value);
}
public void setModbaseReferences(String[] value) {
vertex.setProperty(MODBASE_REFERENCES_PROPERTY, value);
}
public void setMycoclapReferences(String[] value) {
vertex.setProperty(MYCOCLAP_REFERENCES_PROPERTY, value);
}
public void setNextbioReferences(String[] value) {
vertex.setProperty(NEXTBIO_REFERENCES_PROPERTY, value);
}
public void setNextprotoReferences(String[] value) {
vertex.setProperty(NEXTPROT_REFERENCES_PROPERTY, value);
}
public void setOGPReferences(String[] value) {
vertex.setProperty(OGP_REFERENCES_PROPERTY, value);
}
public void setOMAReferences(String[] value) {
vertex.setProperty(OMA_REFERENCES_PROPERTY, value);
}
public void setOrphanetReferences(String[] value) {
vertex.setProperty(ORPHANET_REFERENCES_PROPERTY, value);
}
public void setOrthoDBReferences(String[] value) {
vertex.setProperty(ORTHODB_REFERENCES_PROPERTY, value);
}
public void setPantherReferences(String[] value) {
vertex.setProperty(PANTHER_REFERENCES_PROPERTY, value);
}
public void setPathwayInteractionDBReferences(String[] value) {
vertex.setProperty(PATHWAY_INTERACTION_DB_REFERENCES_PROPERTY, value);
}
public void setPatricReferences(String[] value) {
vertex.setProperty(PATRIC_REFERENCES_PROPERTY, value);
}
public void setPaxDBReferences(String[] value) {
vertex.setProperty(PAXDB_REFERENCES_PROPERTY, value);
}
public void setPDBReferences(String[] value) {
vertex.setProperty(PDB_REFERENCES_PROPERTY, value);
}
public void setPDBJReferences(String[] value) {
vertex.setProperty(PDBJ_REFERENCES_PROPERTY, value);
}
public void setPDBSumReferences(String[] value) {
vertex.setProperty(PDBSUM_REFERENCES_PROPERTY, value);
}
public void setPeptideAtlasReferences(String[] value) {
vertex.setProperty(PEPTIDE_ATLAS_REFERENCES_PROPERTY, value);
}
public void setPharmGKBReferences(String[] value) {
vertex.setProperty(PHARMGKB_REFERENCES_PROPERTY, value);
}
public void setPHCI_2DPageReferences(String[] value) {
vertex.setProperty(PHCI_2DPAGE_REFERENCES_PROPERTY, value);
}
public void setPhosphositeReferences(String[] value) {
vertex.setProperty(PHOSPHOSITE_REFERENCES_PROPERTY, value);
}
public void setPhosSiteReferences(String[] value) {
vertex.setProperty(PHOS_SITE_REFERENCES_PROPERTY, value);
}
public void setPhylomeReferences(String[] value) {
vertex.setProperty(PHYLOME_DB_REFERENCES_PROPERTY, value);
}
public void setPirsfReferences(String[] value) {
vertex.setProperty(PIRSF_REFERENCES_PROPERTY, value);
}
public void setPmapReferences(String[] value) {
vertex.setProperty(PMAP_CUTDB_REFERENCES_PROPERTY, value);
}
public void setPMMA2DPageReferences(String[] value) {
vertex.setProperty(PMMA_2DPAGE_REFERENCES_PROPERTY, value);
}
public void setPomBaseReferences(String[] value) {
vertex.setProperty(POMBASE_REFERENCES_PROPERTY, value);
}
public void setPPTaseDBReferences(String[] value) {
vertex.setProperty(PPTASEDB_REFERENCES_PROPERTY, value);
}
public void setPrideReferences(String[] value) {
vertex.setProperty(PRIDE_REFERENCES_PROPERTY, value);
}
public void setPrintsReferences(String[] value) {
vertex.setProperty(PRINTS_REFERENCES_PROPERTY, value);
}
public void setProdomReferences(String[] value) {
vertex.setProperty(PRODOM_REFERENCES_PROPERTY, value);
}
public void setPromexReferences(String[] value) {
vertex.setProperty(PROMEX_REFERENCES_PROPERTY, value);
}
public void setPrositeReferences(String[] value) {
vertex.setProperty(PROSITE_REFERENCES_PROPERTY, value);
}
public void setProtClustDBReferences(String[] value) {
vertex.setProperty(PROT_CLUST_DB_REFERENCES_PROPERTY, value);
}
public void setProteinModelPortalReferences(String[] value) {
vertex.setProperty(PROTEIN_MODEL_PORTAL_REFERENCES_PROPERTY, value);
}
public void setProtonetReferences(String[] value) {
vertex.setProperty(PROTONET_REFERENCES_PROPERTY, value);
}
public void setPseudoCapReferences(String[] value) {
vertex.setProperty(PSEUDO_CAP_REFERENCES_PROPERTY, value);
}
public void setRatHeart2DPageReferences(String[] value) {
vertex.setProperty(RAT_HEART_2DPAGE_REFERENCES_PROPERTY, value);
}
public void setRCSBPDBReferences(String[] value) {
vertex.setProperty(RCSB_PDB_REFERENCES_PROPERTY, value);
}
public void setRebaseReferences(String[] value) {
vertex.setProperty(REBASE_REFERENCES_PROPERTY, value);
}
public void setReproduction2DPageReferences(String[] value) {
vertex.setProperty(REPRODUCTION_2DPAGE_REFERENCES_PROPERTY, value);
}
public void setRGDReferences(String[] value) {
vertex.setProperty(RGD_REFERENCES_PROPERTY, value);
}
public void setRougeReferences(String[] value) {
vertex.setProperty(ROUGE_REFERENCES_PROPERTY, value);
}
public void setSBKBReferences(String[] value) {
vertex.setProperty(SBKB_REFERENCES_PROPERTY, value);
}
public void setSGDReferences(String[] value) {
vertex.setProperty(SGD_REFERENCES_PROPERTY, value);
}
public void setSiena2DPageReferences(String[] value) {
vertex.setProperty(SIENA_2DPAGE_REFERENCES_PROPERTY, value);
}
public void setSmartReferences(String[] value) {
vertex.setProperty(SMART_REFERENCES_PROPERTY, value);
}
public void setSMRReferences(String[] value) {
vertex.setProperty(SMR_REFERENCES_PROPERTY, value);
}
public void setSourceReferences(String[] value) {
vertex.setProperty(SOURCE_REFERENCES_PROPERTY, value);
}
public void setStringReferences(String[] value) {
vertex.setProperty(STRING_REFERENCES_PROPERTY, value);
}
public void setSupfamReferences(String[] value) {
vertex.setProperty(SUPFAM_REFERENCES_PROPERTY, value);
}
public void setSwiss2DPageReferences(String[] value) {
vertex.setProperty(SWISS_2DPAGE_REFERENCES_PROPERTY, value);
}
public void setTairReferences(String[] value) {
vertex.setProperty(TAIR_REFERENCES_PROPERTY, value);
}
public void setTCDBReferences(String[] value) {
vertex.setProperty(TCDB_REFERENCES_PROPERTY, value);
}
public void setTIGRFAMSReferences(String[] value) {
vertex.setProperty(TIGRFAMS_REFERENCES_PROPERTY, value);
}
public void setTuberculistReferences(String[] value) {
vertex.setProperty(TUBERCULIST_REFERENCES_PROPERTY, value);
}
public void setUCD2DPageReferences(String[] value) {
vertex.setProperty(UCD_2DPAGE_REFERENCES_PROPERTY, value);
}
public void setUCSCReferences(String[] value) {
vertex.setProperty(UCSC_REFERENCES_PROPERTY, value);
}
public void setVectorBaseReferences(String[] value) {
vertex.setProperty(VECTOR_BASE_REFERENCES_PROPERTY, value);
}
public void setWorld2DPageReferences(String[] value) {
vertex.setProperty(WORLD_2DPAGE_REFERENCES_PROPERTY, value);
}
public void setWormBaseReferences(String[] value) {
vertex.setProperty(WORM_BASE_REFERENCES_PROPERTY, value);
}
public void setXenBaseReferences(String[] value) {
vertex.setProperty(XEN_BASE_REFERENCES_PROPERTY, value);
}
public void setZFINReferences(String[] value) {
vertex.setProperty(ZFIN_REFERENCES_PROPERTY, value);
}
}
| src/main/java/com/era7/bioinfo/bio4j/blueprints/model/nodes/ProteinNode.java | /*
* Copyright (C) 2010-2011 "Bio4j"
*
* This file is part of Bio4j
*
* Bio4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.era7.bioinfo.bio4j.blueprints.model.nodes;
import com.era7.bioinfo.bio4j.blueprints.model.nodes.citation.*;
import com.era7.bioinfo.bio4j.blueprints.model.nodes.reactome.ReactomeTermNode;
import com.era7.bioinfo.bio4j.blueprints.model.nodes.refseq.GenomeElementNode;
import com.era7.bioinfo.bio4j.blueprints.model.relationships.citation.article.ArticleProteinCitationRel;
import com.era7.bioinfo.bio4j.blueprints.model.relationships.citation.book.BookProteinCitationRel;
import com.era7.bioinfo.bio4j.blueprints.model.relationships.citation.onarticle.OnlineArticleProteinCitationRel;
import com.era7.bioinfo.bio4j.blueprints.model.relationships.citation.patent.PatentProteinCitationRel;
import com.era7.bioinfo.bio4j.blueprints.model.relationships.citation.submission.SubmissionProteinCitationRel;
import com.era7.bioinfo.bio4j.blueprints.model.relationships.citation.thesis.ThesisProteinCitationRel;
import com.era7.bioinfo.bio4j.blueprints.model.relationships.citation.uo.UnpublishedObservationProteinCitationRel;
import com.era7.bioinfo.bio4j.blueprints.model.relationships.comment.DomainCommentRel;
import com.era7.bioinfo.bio4j.blueprints.model.relationships.comment.FunctionCommentRel;
import com.era7.bioinfo.bio4j.blueprints.model.relationships.comment.PathwayCommentRel;
import com.era7.bioinfo.bio4j.blueprints.model.relationships.comment.SimilarityCommentRel;
import com.era7.bioinfo.bio4j.blueprints.model.relationships.features.ActiveSiteFeatureRel;
import com.era7.bioinfo.bio4j.blueprints.model.relationships.features.SignalPeptideFeatureRel;
import com.era7.bioinfo.bio4j.blueprints.model.relationships.features.SpliceVariantFeatureRel;
import com.era7.bioinfo.bio4j.blueprints.model.relationships.features.TransmembraneRegionFeatureRel;
import com.era7.bioinfo.bio4j.blueprints.model.relationships.protein.*;
import com.era7.bioinfo.bio4j.blueprints.model.relationships.uniref.UniRef100MemberRel;
import com.era7.bioinfo.bio4j.blueprints.model.relationships.uniref.UniRef50MemberRel;
import com.era7.bioinfo.bio4j.blueprints.model.relationships.uniref.UniRef90MemberRel;
import com.tinkerpop.blueprints.Direction;
import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Vertex;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/**
* Uniprot proteins
*
* @author Pablo Pareja Tobes <[email protected]>
*/
public class ProteinNode extends BasicVertex {
public static final String NODE_TYPE = ProteinNode.class.getCanonicalName();
public static final String NAME_PROPERTY = "protein_name";
public static final String FULL_NAME_PROPERTY = "protein_full_name";
public static final String SHORT_NAME_PROPERTY = "protein_short_name";
public static final String ACCESSION_PROPERTY = "protein_accession";
public static final String SEQUENCE_PROPERTY = "protein_sequence";
public static final String MASS_PROPERTY = "protein_mass";
public static final String LENGTH_PROPERTY = "protein_length";
public static final String MODIFIED_DATE_PROPERTY = "protein_modified_date";
public static final String GENE_NAMES_PROPERTY = "protein_gene_names";
public static final String ALTERNATIVE_ACCESSIONS_PROPERTY = "protein_alternative_accessions";
//---------------------DB CROSS REFERENCES----------------------------------------
public static final String ENSEMBL_REFERENCES_PROPERTY = "protein_ensembl_references";
public static final String PIR_REFERENCES_PROPERTY = "protein_pir_references";
public static final String KEGG_REFERENCES_PROPERTY = "protein_kegg_references";
public static final String EMBL_REFERENCES_PROPERTY = "protein_embl_references";
public static final String REFSEQ_REFERENCES_PROPERTY = "protein_refseq_references";
public static final String ARRAY_EXPRESS_REFERENCES_PROPERTY = "protein_array_express_references";
public static final String UNIGENE_REFERENCES_PROPERTY = "protein_unigene_references";
public static final String ENSEMBL_PLANTS_REFERENCES_PROPERTY = "protein_ensembl_plants_references";
public static final String DBASE_ECOLI_REFERENCES_PROPERTY = "protein_2dbase_ecoli_references";
public static final String AARHUS_GHENT_2DPAGE_REFERENCES_PROPERTY = "protein_aarhus_ghent_2dpage_references";
public static final String AGD_REFERENCES_PROPERTY = "protein_agd_references";
public static final String ALLERGOME_REFERENCES_PROPERTY = "protein_allergome_references";
public static final String ANU_2DPAGE_REFERENCES_PROPERTY = "protein_anu_2dpage_references";
public static final String ARACHNOSERVER_REFERENCES_PROPERTY = "protein_arachnoserver_references";
public static final String BGEE_REFERENCES_PROPERTY = "protein_bgee_references";
public static final String BINDING_DB_REFERENCES_PROPERTY = "protein_binding_db_references";
public static final String BIOCYC_REFERENCES_PROPERTY = "protein_biocyc_references";
public static final String BRENDA_REFERENCES_PROPERTY = "protein_brenda_references";
public static final String CAZY_REFERENCES_PROPERTY = "protein_cazy_references";
public static final String CGD_REFERENCES_PROPERTY = "protein_cgd_references";
public static final String CHEMBL_REFERENCES_PROPERTY = "protein_chembl_references";
public static final String CLEANEX_REFERENCES_PROPERTY = "protein_cleanex_references";
public static final String COMPLUYEAST_2DPAGE_REFERENCES_PROPERTY = "protein_compluyeast_2dpage_references";
public static final String CONOSERVER_REFERENCES_PROPERTY = "protein_conoserver_references";
public static final String CORNEA_2DPAGE_REFERENCES_PROPERTY = "protein_cornea_2dpage_references";
public static final String CTD_REFERENCES_PROPERTY = "protein_ctd_references";
public static final String CYGD_REFERENCES_PROPERTY = "protein_cygd_references";
public static final String DBSNP_REFERENCES_PROPERTY = "protein_dbsnp_references";
public static final String DDBJ_REFERENCES_PROPERTY = "protein_ddbj_references";
public static final String DICTY_BASE_REFERENCES_PROPERTY = "protein_dicty_base_references";
public static final String DIP_REFERENCES_PROPERTY = "protein_dip_references";
public static final String DISPROT_REFERENCES_PROPERTY = "protein_disprot_references";
public static final String DMDM_REFERENCES_PROPERTY = "protein_dmdm_references";
public static final String DNASU_REFERENCES_PROPERTY = "protein_dnasu_references";
public static final String DOSAC_COBS_2DPAGE_REFERENCES_PROPERTY = "protein_dosac_cobs_2dpage_references";
public static final String DRUGBANK_REFERENCES_PROPERTY = "protein_drugbank_references";
public static final String ECHOBASE_REFERENCES_PROPERTY = "protein_echobase_references";
public static final String ECOGENE_REFERENCES_PROPERTY = "protein_ecogene_references";
public static final String EGGNOG_REFERENCES_PROPERTY = "protein_eggnog_references";
public static final String ENSEMBL_BACTERIA_REFERENCES_PROPERTY = "protein_ensembl_bacteria_references";
public static final String ENSEMBL_FUNGI_REFERENCES_PROPERTY = "protein_ensembl_fungi_references";
public static final String ENSEMBL_METAZOA_REFERENCES_PROPERTY = "protein_ensembl_metazoa_references";
public static final String ENSEMBL_PROTISTS_REFERENCES_PROPERTY = "protein_ensembl_protists_references";
public static final String EUHCVDB_REFERENCES_PROPERTY = "protein_euhcvdb_references";
public static final String EUPATHDB_REFERENCES_PROPERTY = "protein_eupathdb_references";
public static final String EVOLUTIONARY_TRACE_REFERENCES_PROPERTY = "protein_evolutionary_trace_references";
public static final String FLYBASE_REFERENCES_PROPERTY = "protein_flybase_references";
public static final String GENATLAS_REFERENCES_PROPERTY = "protein_genatlas_references";
public static final String GENBANK_REFERENCES_PROPERTY = "protein_genbank_references";
public static final String GENE3D_REFERENCES_PROPERTY = "protein_gene3d_references";
public static final String GENECARDS_REFERENCES_PROPERTY = "protein_genecards_references";
public static final String GENEFARM_REFERENCES_PROPERTY = "protein_genefarm_references";
public static final String GENEID_REFERENCES_PROPERTY = "protein_geneid_references";
public static final String GENETREE_REFERENCES_PROPERTY = "protein_genetree_references";
public static final String GENEVESTIGATOR_REFERENCES_PROPERTY = "protein_genevestigator_references";
public static final String GENOLIST_REFERENCES_PROPERTY = "protein_genolist_references";
public static final String GENOME_REVIEWS_REFERENCES_PROPERTY = "protein_genome_reviews_references";
public static final String GENOME_RNAI_REFERENCES_PROPERTY = "protein_genome_rnai_references";
public static final String GERMONLINE_REFERENCES_PROPERTY = "protein_germonline_references";
public static final String GLYCOSUITEDB_REFERENCES_PROPERTY = "protein_glycosuitedb_references";
public static final String GPCRDB_REFERENCES_PROPERTY = "protein_gpcrdb_references";
public static final String GRAMENE_REFERENCES_PROPERTY = "protein_gramene_references";
public static final String HINVDB_REFERENCES_PROPERTY = "protein_hinvdb_references";
public static final String HAMAP_REFERENCES_PROPERTY = "protein_hamap_references";
public static final String HGNC_REFERENCES_PROPERTY = "protein_hgnc_references";
public static final String HOGENOM_REFERENCES_PROPERTY = "protein_hogenom_references";
public static final String HOVERGEN_REFERENCES_PROPERTY = "protein_hovergen_references";
public static final String HPA_REFERENCES_PROPERTY = "protein_hpa_references";
public static final String HSSP_REFERENCES_PROPERTY = "protein_hssp_references";
public static final String HUGE_REFERENCES_PROPERTY = "protein_huge_references";
public static final String IMGT_REFERENCES_PROPERTY = "protein_imgt_references";
public static final String INPARANOID_REFERENCES_PROPERTY = "protein_inparanoid_references";
public static final String INTACT_REFERENCES_PROPERTY = "protein_intact_references";
public static final String IPI_REFERENCES_PROPERTY = "protein_ipi_references";
public static final String KO_REFERENCES_PROPERTY = "protein_ko_references";
public static final String LEGIO_LIST_REFERENCES_PROPERTY = "protein_legio_list_references";
public static final String LEPROMA_REFERENCES_PROPERTY = "protein_leproma_references";
public static final String MAIZE_GDB_REFERENCES_PROPERTY = "protein_maize_gdb_references";
public static final String MEROPS_REFERENCES_PROPERTY = "protein_merops_references";
public static final String MGI_REFERENCES_PROPERTY = "protein_mgi_references";
public static final String MICADO_REFERENCES_PROPERTY = "protein_micado_references";
public static final String MIM_REFERENCES_PROPERTY = "protein_mim_references";
public static final String MINT_REFERENCES_PROPERTY = "protein_mint_references";
public static final String MODBASE_REFERENCES_PROPERTY = "protein_modbase_references";
public static final String MYCOCLAP_REFERENCES_PROPERTY = "protein_mycoclap_references";
public static final String NEXTBIO_REFERENCES_PROPERTY = "protein_nextbio_references";
public static final String NEXTPROT_REFERENCES_PROPERTY = "protein_nextprot_references";
public static final String OGP_REFERENCES_PROPERTY = "protein_ogp_references";
public static final String OMA_REFERENCES_PROPERTY = "protein_oma_references";
public static final String ORPHANET_REFERENCES_PROPERTY = "protein_orphanet_references";
public static final String ORTHODB_REFERENCES_PROPERTY = "protein_orthodb_references";
public static final String PANTHER_REFERENCES_PROPERTY = "protein_panther_references";
public static final String PATHWAY_INTERACTION_DB_REFERENCES_PROPERTY = "protein_pathway_interaction_db_references";
public static final String PATRIC_REFERENCES_PROPERTY = "protein_patric_references";
public static final String PAXDB_REFERENCES_PROPERTY = "protein_paxdb_references";
public static final String PDB_REFERENCES_PROPERTY = "protein_pdb_references";
public static final String PDBJ_REFERENCES_PROPERTY = "protein_pdbj_references";
public static final String PDBSUM_REFERENCES_PROPERTY = "protein_pdbsum_references";
public static final String PEPTIDE_ATLAS_REFERENCES_PROPERTY = "protein_peptide_atlas_references";
public static final String PHARMGKB_REFERENCES_PROPERTY = "protein_pharmgkb_references";
public static final String PHCI_2DPAGE_REFERENCES_PROPERTY = "protein_phci_2dpage_references";
public static final String PHOSPHOSITE_REFERENCES_PROPERTY = "protein_phosphosite_references";
public static final String PHOS_SITE_REFERENCES_PROPERTY = "protein_phos_site_references";
public static final String PHYLOME_DB_REFERENCES_PROPERTY = "protein_phylome_db_references";
public static final String PIRSF_REFERENCES_PROPERTY = "protein_pirsf_references";
public static final String PMAP_CUTDB_REFERENCES_PROPERTY = "protein_pmap_cutdb_references";
public static final String PMMA_2DPAGE_REFERENCES_PROPERTY = "protein_pmma_2dpage_references";
public static final String POMBASE_REFERENCES_PROPERTY = "protein_pombase_references";
public static final String PPTASEDB_REFERENCES_PROPERTY = "protein_pptasedb_references";
public static final String PRIDE_REFERENCES_PROPERTY = "protein_pride_references";
public static final String PRINTS_REFERENCES_PROPERTY = "protein_prints_references";
public static final String PRODOM_REFERENCES_PROPERTY = "protein_prodom_references";
public static final String PROMEX_REFERENCES_PROPERTY = "protein_promex_references";
public static final String PROSITE_REFERENCES_PROPERTY = "protein_prosite_references";
public static final String PROT_CLUST_DB_REFERENCES_PROPERTY = "protein_prot_clust_db_references";
public static final String PROTEIN_MODEL_PORTAL_REFERENCES_PROPERTY = "protein_model_portal_references";
public static final String PROTONET_REFERENCES_PROPERTY = "protein_protonet_references";
public static final String PSEUDO_CAP_REFERENCES_PROPERTY = "protein_pseudo_cap_references";
public static final String RAT_HEART_2DPAGE_REFERENCES_PROPERTY = "protein_rat_heart_2dpage_references";
public static final String RCSB_PDB_REFERENCES_PROPERTY = "protein_rcsb_pdb_references";
public static final String REBASE_REFERENCES_PROPERTY = "protein_rebase_references";
public static final String REPRODUCTION_2DPAGE_REFERENCES_PROPERTY = "protein_reproduction_2dpage_references";
public static final String RGD_REFERENCES_PROPERTY = "protein_rgd_references";
public static final String ROUGE_REFERENCES_PROPERTY = "protein_rouge_references";
public static final String SBKB_REFERENCES_PROPERTY = "protein_sbkb_references";
public static final String SGD_REFERENCES_PROPERTY = "protein_sgd_references";
public static final String SIENA_2DPAGE_REFERENCES_PROPERTY = "protein_siena_2dpage_references";
public static final String SMART_REFERENCES_PROPERTY = "protein_smart_references";
public static final String SMR_REFERENCES_PROPERTY = "protein_smr_references";
public static final String SOURCE_REFERENCES_PROPERTY = "protein_source_references";
public static final String STRING_REFERENCES_PROPERTY = "protein_string_references";
public static final String SUPFAM_REFERENCES_PROPERTY = "protein_supfam_references";
public static final String SWISS_2DPAGE_REFERENCES_PROPERTY = "protein_swiss_2dpage_references";
public static final String TAIR_REFERENCES_PROPERTY = "protein_tair_references";
public static final String TCDB_REFERENCES_PROPERTY = "protein_tcb_references";
public static final String TIGRFAMS_REFERENCES_PROPERTY = "protein_tigrfams_references";
public static final String TUBERCULIST_REFERENCES_PROPERTY = "protein_tuberculist_references";
public static final String UCD_2DPAGE_REFERENCES_PROPERTY = "protein_ucd_2dpage_references";
public static final String UCSC_REFERENCES_PROPERTY = "protein_ucsc_references";
public static final String VECTOR_BASE_REFERENCES_PROPERTY = "protein_vector_base_references";
public static final String WORLD_2DPAGE_REFERENCES_PROPERTY = "protein_world_2dpage_references";
public static final String WORM_BASE_REFERENCES_PROPERTY = "protein_worm_base_references";
public static final String XEN_BASE_REFERENCES_PROPERTY = "protein_xen_base_references";
public static final String ZFIN_REFERENCES_PROPERTY = "protein_zfin_references";
//-------------------------------------------------------------------------------------------------
public ProteinNode(Vertex v) {
super(v);
}
public String getName() {
return String.valueOf(vertex.getProperty(NAME_PROPERTY));
}
public String getFullName() {
return String.valueOf(vertex.getProperty(FULL_NAME_PROPERTY));
}
public String getShortName() {
return String.valueOf(vertex.getProperty(SHORT_NAME_PROPERTY));
}
public String getAccession() {
return String.valueOf(vertex.getProperty(ACCESSION_PROPERTY));
}
public String getSequence() {
return String.valueOf(vertex.getProperty(SEQUENCE_PROPERTY));
}
public String getEnsemblReferences() {
return String.valueOf(vertex.getProperty(ENSEMBL_REFERENCES_PROPERTY));
}
public String[] getEMBLFeferences() {
return (String[]) vertex.getProperty(EMBL_REFERENCES_PROPERTY);
}
public String[] getEnsemblPlantsReferences() {
return (String[]) vertex.getProperty(ENSEMBL_PLANTS_REFERENCES_PROPERTY);
}
public String[] getRefseqReferences() {
return (String[]) vertex.getProperty(REFSEQ_REFERENCES_PROPERTY);
}
public String[] getAlternativeAcessions() {
return (String[]) vertex.getProperty(ALTERNATIVE_ACCESSIONS_PROPERTY);
}
public String[] getPIRReferences() {
return (String[]) vertex.getProperty(PIR_REFERENCES_PROPERTY);
}
public String[] getKeggReferences() {
return (String[]) vertex.getProperty(KEGG_REFERENCES_PROPERTY);
}
public String[] getArrayExpressReferences() {
return (String[]) vertex.getProperty(ARRAY_EXPRESS_REFERENCES_PROPERTY);
}
public String[] getUniGeneReferences() {
return (String[]) vertex.getProperty(UNIGENE_REFERENCES_PROPERTY);
}
public String getModifiedDate() {
return String.valueOf(vertex.getProperty(MODIFIED_DATE_PROPERTY));
}
public float getMass() {
return Float.parseFloat(String.valueOf(vertex.getProperty(MASS_PROPERTY)));
}
public int getLength() {
return Integer.parseInt(String.valueOf(vertex.getProperty(LENGTH_PROPERTY)));
}
public String[] getGeneNames() {
return (String[]) vertex.getProperty(GENE_NAMES_PROPERTY);
}
public boolean isUniref50Representant() {
return !vertex.getEdges(Direction.IN, UniRef50MemberRel.NAME).iterator().hasNext();
}
public boolean isUniref90Representant() {
return !vertex.getEdges(Direction.IN, UniRef90MemberRel.NAME).iterator().hasNext();
}
public boolean isUniref100Representant() {
return !vertex.getEdges(Direction.IN, UniRef100MemberRel.NAME).iterator().hasNext();
}
public List<ProteinNode> getUniref50ClusterThisProteinBelongsTo() {
List<ProteinNode> list = new LinkedList<ProteinNode>();
if (isUniref50Representant()) {
list.add(this);
Iterator<Vertex> relIterator = vertex.getVertices(Direction.OUT, UniRef50MemberRel.NAME).iterator();
while (relIterator.hasNext()) {
list.add(new ProteinNode(relIterator.next()));
}
} else {
ProteinNode representant = new ProteinNode(vertex.getVertices(Direction.IN, UniRef50MemberRel.NAME).iterator().next());
return representant.getUniref50ClusterThisProteinBelongsTo();
}
return list;
}
public List<ProteinNode> getUniref90ClusterThisProteinBelongsTo() {
List<ProteinNode> list = new LinkedList<ProteinNode>();
if (isUniref90Representant()) {
list.add(this);
Iterator<Vertex> relIterator = vertex.getVertices(Direction.OUT, UniRef90MemberRel.NAME).iterator();
while (relIterator.hasNext()) {
list.add(new ProteinNode(relIterator.next()));
}
} else {
ProteinNode representant = new ProteinNode(vertex.getVertices(Direction.IN, UniRef90MemberRel.NAME).iterator().next());
return representant.getUniref90ClusterThisProteinBelongsTo();
}
return list;
}
public List<ProteinNode> getUniref100ClusterThisProteinBelongsTo() {
List<ProteinNode> list = new LinkedList<ProteinNode>();
if (isUniref100Representant()) {
list.add(this);
Iterator<Vertex> relIterator = vertex.getVertices(Direction.OUT, UniRef100MemberRel.NAME).iterator();
while (relIterator.hasNext()) {
list.add(new ProteinNode(relIterator.next()));
}
} else {
ProteinNode representant = new ProteinNode(vertex.getVertices(Direction.IN, UniRef100MemberRel.NAME).iterator().next());
return representant.getUniref100ClusterThisProteinBelongsTo();
}
return list;
}
public OrganismNode getOrganism() {
OrganismNode org = null;
Iterator<Vertex> iterator = vertex.getVertices(Direction.OUT, ProteinOrganismRel.NAME).iterator();
if (iterator.hasNext()) {
org = new OrganismNode(iterator.next());
}
return org;
}
public DatasetNode getDataset() {
DatasetNode dataset = null;
Iterator<Vertex> iterator = vertex.getVertices(Direction.OUT, ProteinDatasetRel.NAME).iterator();
if (iterator.hasNext()) {
dataset = new DatasetNode(iterator.next());
}
return dataset;
}
public List<GenomeElementNode> getGenomeElements() {
List<GenomeElementNode> list = new ArrayList<GenomeElementNode>();
Iterator<Vertex> iterator = vertex.getVertices(Direction.OUT, ProteinGenomeElementRel.NAME).iterator();
while (iterator.hasNext()) {
list.add(new GenomeElementNode(iterator.next()));
}
return list;
}
public List<SubcellularLocationNode> getSubcellularLocations() {
List<SubcellularLocationNode> list = new ArrayList<SubcellularLocationNode>();
Iterator<Vertex> iterator = vertex.getVertices(Direction.OUT, ProteinSubcellularLocationRel.NAME).iterator();
while (iterator.hasNext()) {
list.add(new SubcellularLocationNode(iterator.next()));
}
return list;
}
public List<InterproNode> getInterpro() {
List<InterproNode> interpros = new ArrayList<InterproNode>();
Iterator<Vertex> iterator = vertex.getVertices(Direction.OUT, ProteinInterproRel.NAME).iterator();
while (iterator.hasNext()) {
InterproNode interpro = new InterproNode(iterator.next());
interpros.add(interpro);
}
return interpros;
}
public List<PfamNode> getPfamTerms() {
List<PfamNode> pfamTerms = new ArrayList<PfamNode>();
Iterator<Vertex> iterator = vertex.getVertices(Direction.OUT, ProteinPfamRel.NAME).iterator();
while (iterator.hasNext()) {
PfamNode interpro = new PfamNode(iterator.next());
pfamTerms.add(interpro);
}
return pfamTerms;
}
public List<ReactomeTermNode> getReactomeTerms() {
List<ReactomeTermNode> list = new LinkedList<ReactomeTermNode>();
Iterator<Vertex> iterator = vertex.getVertices(Direction.OUT, ProteinReactomeRel.NAME).iterator();
while (iterator.hasNext()) {
ReactomeTermNode reactomeTerm = new ReactomeTermNode(iterator.next());
list.add(reactomeTerm);
}
return list;
}
public List<EnzymeNode> getProteinEnzymaticActivity() {
List<EnzymeNode> list = new LinkedList<EnzymeNode>();
Iterator<Vertex> iterator = vertex.getVertices(Direction.OUT, ProteinEnzymaticActivityRel.NAME).iterator();
while (iterator.hasNext()) {
EnzymeNode enzyme = new EnzymeNode(iterator.next());
list.add(enzyme);
}
return list;
}
public List<GoTermNode> getGOAnnotations() {
List<GoTermNode> list = new ArrayList<GoTermNode>();
Iterator<Vertex> iterator = vertex.getVertices(Direction.OUT, ProteinGoRel.NAME).iterator();
while (iterator.hasNext()) {
GoTermNode goTerm = new GoTermNode(iterator.next());
list.add(goTerm);
}
return list;
}
public List<KeywordNode> getKeywords() {
List<KeywordNode> keywords = new ArrayList<KeywordNode>();
Iterator<Vertex> iterator = vertex.getVertices(Direction.OUT, ProteinKeywordRel.NAME).iterator();
while (iterator.hasNext()) {
KeywordNode keyword = new KeywordNode(iterator.next());
keywords.add(keyword);
}
return keywords;
}
public List<SignalPeptideFeatureRel> getSignalPeptideFeature() {
List<SignalPeptideFeatureRel> list = new ArrayList<SignalPeptideFeatureRel>();
Iterator<Edge> iterator = vertex.getEdges(Direction.OUT, SignalPeptideFeatureRel.NAME).iterator();
while (iterator.hasNext()) {
SignalPeptideFeatureRel rel = new SignalPeptideFeatureRel(iterator.next());
list.add(rel);
}
return list;
}
public List<SpliceVariantFeatureRel> getSpliceVariantFeature() {
List<SpliceVariantFeatureRel> list = new ArrayList<SpliceVariantFeatureRel>();
Iterator<Edge> iterator = vertex.getEdges(Direction.OUT, SpliceVariantFeatureRel.NAME).iterator();
while (iterator.hasNext()) {
SpliceVariantFeatureRel rel = new SpliceVariantFeatureRel(iterator.next());
list.add(rel);
}
return list;
}
public List<TransmembraneRegionFeatureRel> getTransmembraneRegionFeature() {
List<TransmembraneRegionFeatureRel> list = new ArrayList<TransmembraneRegionFeatureRel>();
Iterator<Edge> iterator = vertex.getEdges(Direction.OUT, TransmembraneRegionFeatureRel.NAME).iterator();
while (iterator.hasNext()) {
TransmembraneRegionFeatureRel rel = new TransmembraneRegionFeatureRel(iterator.next());
list.add(rel);
}
return list;
}
public List<ActiveSiteFeatureRel> getActiveSiteFeature() {
List<ActiveSiteFeatureRel> list = new ArrayList<ActiveSiteFeatureRel>();
Iterator<Edge> iterator = vertex.getEdges(Direction.OUT, ActiveSiteFeatureRel.NAME).iterator();
while (iterator.hasNext()) {
ActiveSiteFeatureRel rel = new ActiveSiteFeatureRel(iterator.next());
list.add(rel);
}
return list;
}
public List<FunctionCommentRel> getFunctionComment() {
List<FunctionCommentRel> list = new ArrayList<FunctionCommentRel>();
Iterator<Edge> iterator = vertex.getEdges(Direction.OUT, FunctionCommentRel.NAME).iterator();
while (iterator.hasNext()) {
FunctionCommentRel rel = new FunctionCommentRel(iterator.next());
list.add(rel);
}
return list;
}
public List<PathwayCommentRel> getPathwayComment() {
List<PathwayCommentRel> list = new ArrayList<PathwayCommentRel>();
Iterator<Edge> iterator = vertex.getEdges(Direction.OUT, PathwayCommentRel.NAME).iterator();
while (iterator.hasNext()) {
PathwayCommentRel rel = new PathwayCommentRel(iterator.next());
list.add(rel);
}
return list;
}
public List<DomainCommentRel> getDomainComment() {
List<DomainCommentRel> list = new ArrayList<DomainCommentRel>();
Iterator<Edge> iterator = vertex.getEdges(Direction.OUT, DomainCommentRel.NAME).iterator();
while (iterator.hasNext()) {
DomainCommentRel rel = new DomainCommentRel(iterator.next());
list.add(rel);
}
return list;
}
public List<SimilarityCommentRel> getSimilarityComment() {
List<SimilarityCommentRel> list = new ArrayList<SimilarityCommentRel>();
Iterator<Edge> iterator = vertex.getEdges(Direction.OUT, SimilarityCommentRel.NAME).iterator();
while (iterator.hasNext()) {
SimilarityCommentRel rel = new SimilarityCommentRel(iterator.next());
list.add(rel);
}
return list;
}
/**
* Protein-protein outgoing interactions
*
* @return
*/
public List<ProteinProteinInteractionRel> getProteinOutgoingInteractions() {
List<ProteinProteinInteractionRel> list = new ArrayList<ProteinProteinInteractionRel>();
Iterator<Edge> iterator = vertex.getEdges(Direction.OUT, ProteinProteinInteractionRel.NAME).iterator();
while (iterator.hasNext()) {
list.add(new ProteinProteinInteractionRel(iterator.next()));
}
return list;
}
/**
* Protein-protein incoming interactions
*
* @return
*/
public List<ProteinProteinInteractionRel> getProteinIncomingInteractions() {
List<ProteinProteinInteractionRel> list = new ArrayList<ProteinProteinInteractionRel>();
Iterator<Edge> iterator = vertex.getEdges(Direction.IN, ProteinProteinInteractionRel.NAME).iterator();
while (iterator.hasNext()) {
list.add(new ProteinProteinInteractionRel(iterator.next()));
}
return list;
}
/**
* Protein-Isoform outgoing interactions
*
* @return
*/
public List<ProteinIsoformInteractionRel> getIsoformOutgoingInteractions() {
List<ProteinIsoformInteractionRel> list = new ArrayList<ProteinIsoformInteractionRel>();
Iterator<Edge> iterator = vertex.getEdges(Direction.OUT, ProteinIsoformInteractionRel.NAME).iterator();
while (iterator.hasNext()) {
list.add(new ProteinIsoformInteractionRel(iterator.next()));
}
return list;
}
/**
* Protein-Isoform incoming interactions
*
* @return
*/
public List<ProteinIsoformInteractionRel> getIsoformIncomingInteractions() {
List<ProteinIsoformInteractionRel> list = new ArrayList<ProteinIsoformInteractionRel>();
Iterator<Edge> iterator = vertex.getEdges(Direction.IN, ProteinIsoformInteractionRel.NAME).iterator();
while (iterator.hasNext()) {
list.add(new ProteinIsoformInteractionRel(iterator.next()));
}
return list;
}
//---------------------------------------------------------------------------------------------
//-------------------------------------CITATIONS-----------------------------------------------
//---------------------------------------------------------------------------------------------
/**
* Protein article citations
*
* @return
*/
public List<ArticleNode> getArticleCitations() {
List<ArticleNode> list = new ArrayList<ArticleNode>();
Iterator<Vertex> iterator = vertex.getVertices(Direction.IN, ArticleProteinCitationRel.NAME).iterator();
while (iterator.hasNext()) {
list.add(new ArticleNode(iterator.next()));
}
return list;
}
/**
* Protein submission citations
*
* @return
*/
public List<SubmissionNode> getSubmissionCitations() {
List<SubmissionNode> list = new ArrayList<SubmissionNode>();
Iterator<Vertex> iterator = vertex.getVertices(Direction.IN, SubmissionProteinCitationRel.NAME).iterator();
while (iterator.hasNext()) {
list.add(new SubmissionNode(iterator.next()));
}
return list;
}
/**
* Protein Online article citations
*
* @return
*/
public List<OnlineArticleNode> getOnlineArticleCitations() {
List<OnlineArticleNode> list = new ArrayList<OnlineArticleNode>();
Iterator<Vertex> iterator = vertex.getVertices(Direction.IN, OnlineArticleProteinCitationRel.NAME).iterator();
while (iterator.hasNext()) {
list.add(new OnlineArticleNode(iterator.next()));
}
return list;
}
/**
* Protein Book citations
*
* @return
*/
public List<BookNode> getBookCitations() {
List<BookNode> list = new ArrayList<BookNode>();
Iterator<Vertex> iterator = vertex.getVertices(Direction.IN, BookProteinCitationRel.NAME).iterator();
while (iterator.hasNext()) {
list.add(new BookNode(iterator.next()));
}
return list;
}
/**
* Protein patent citations
*
* @return
*/
public List<PatentNode> getPatentCitations() {
List<PatentNode> list = new ArrayList<PatentNode>();
Iterator<Vertex> iterator = vertex.getVertices(Direction.IN, PatentProteinCitationRel.NAME).iterator();
while (iterator.hasNext()) {
list.add(new PatentNode(iterator.next()));
}
return list;
}
/**
* Protein thesis citations
*
* @return
*/
public List<ThesisNode> getThesisCitations() {
List<ThesisNode> list = new ArrayList<ThesisNode>();
Iterator<Vertex> iterator = vertex.getVertices(Direction.IN, ThesisProteinCitationRel.NAME).iterator();
while (iterator.hasNext()) {
list.add(new ThesisNode(iterator.next()));
}
return list;
}
/**
* Protein unpublished observations citations
*
* @return
*/
public List<UnpublishedObservationNode> getUnpublishedObservationsCitations() {
List<UnpublishedObservationNode> list = new ArrayList<UnpublishedObservationNode>();
Iterator<Vertex> iterator = vertex.getVertices(Direction.IN, UnpublishedObservationProteinCitationRel.NAME).iterator();
while (iterator.hasNext()) {
list.add(new UnpublishedObservationNode(iterator.next()));
}
return list;
}
//---------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------
public void setName(String value) {
vertex.setProperty(NAME_PROPERTY, value);
}
public void setFullName(String value) {
vertex.setProperty(FULL_NAME_PROPERTY, value);
}
public void setShortName(String value) {
vertex.setProperty(SHORT_NAME_PROPERTY, value);
}
public void setAccession(String value) {
vertex.setProperty(ACCESSION_PROPERTY, value);
}
public void setSequence(String value) {
vertex.setProperty(SEQUENCE_PROPERTY, value);
}
public void setModifiedDate(String value) {
vertex.setProperty(MODIFIED_DATE_PROPERTY, value);
}
public void setMass(float value) {
vertex.setProperty(MASS_PROPERTY, value);
}
public void setLength(int value) {
vertex.setProperty(LENGTH_PROPERTY, value);
}
public void setGeneNames(String[] value) {
vertex.setProperty(GENE_NAMES_PROPERTY, value);
}
public void setEnsemblReferences(String[] value) {
vertex.setProperty(ENSEMBL_REFERENCES_PROPERTY, value);
}
public void setKeggReferences(String[] value) {
vertex.setProperty(KEGG_REFERENCES_PROPERTY, value);
}
public void setPIRReferences(String[] value) {
vertex.setProperty(PIR_REFERENCES_PROPERTY, value);
}
public void setEMBLreferences(String[] value) {
vertex.setProperty(EMBL_REFERENCES_PROPERTY, value);
}
public void setEnsemblPlantsReferences(String[] value) {
vertex.setProperty(ENSEMBL_PLANTS_REFERENCES_PROPERTY, value);
}
public void setRefseqReferences(String[] value) {
vertex.setProperty(REFSEQ_REFERENCES_PROPERTY, value);
}
public void setAlternativeAccessions(String[] value) {
vertex.setProperty(ALTERNATIVE_ACCESSIONS_PROPERTY, value);
}
public void setArrayExpressReferences(String[] value) {
vertex.setProperty(ARRAY_EXPRESS_REFERENCES_PROPERTY, value);
}
public void setUniGeneReferences(String[] value) {
vertex.setProperty(UNIGENE_REFERENCES_PROPERTY, value);
}
public void setDBaseEcoliReferences(String[] value) {
vertex.setProperty(DBASE_ECOLI_REFERENCES_PROPERTY, value);
}
public void setAarhusGhent2DPageReferences(String[] value) {
vertex.setProperty(AARHUS_GHENT_2DPAGE_REFERENCES_PROPERTY, value);
}
public void setAGDReferences(String[] value) {
vertex.setProperty(AGD_REFERENCES_PROPERTY, value);
}
public void setAllergomeReferences(String[] value) {
vertex.setProperty(ALLERGOME_REFERENCES_PROPERTY, value);
}
public void setAnu2DPageReferences(String[] value) {
vertex.setProperty(ANU_2DPAGE_REFERENCES_PROPERTY, value);
}
public void setArachnoserverReferences(String[] value) {
vertex.setProperty(ARACHNOSERVER_REFERENCES_PROPERTY, value);
}
public void setBGeeReferences(String[] value) {
vertex.setProperty(BGEE_REFERENCES_PROPERTY, value);
}
public void setBindingDBReferences(String[] value) {
vertex.setProperty(BINDING_DB_REFERENCES_PROPERTY, value);
}
public void setBiocycReferences(String[] value) {
vertex.setProperty(BIOCYC_REFERENCES_PROPERTY, value);
}
public void setBrendaReferences(String[] value) {
vertex.setProperty(BRENDA_REFERENCES_PROPERTY, value);
}
public void setCazyReferences(String[] value) {
vertex.setProperty(CAZY_REFERENCES_PROPERTY, value);
}
public void setCGDReferences(String[] value) {
vertex.setProperty(CGD_REFERENCES_PROPERTY, value);
}
public void setCHEmblReferences(String[] value) {
vertex.setProperty(CHEMBL_REFERENCES_PROPERTY, value);
}
public void setCleanexReferences(String[] value) {
vertex.setProperty(CLEANEX_REFERENCES_PROPERTY, value);
}
public void setCompluYeastReferences(String[] value) {
vertex.setProperty(COMPLUYEAST_2DPAGE_REFERENCES_PROPERTY, value);
}
public void setConserverReferences(String[] value) {
vertex.setProperty(CONOSERVER_REFERENCES_PROPERTY, value);
}
public void setCornea2DPageReferences(String[] value) {
vertex.setProperty(CORNEA_2DPAGE_REFERENCES_PROPERTY, value);
}
public void setCTDReferences(String[] value) {
vertex.setProperty(CTD_REFERENCES_PROPERTY, value);
}
public void setCYGDReferences(String[] value) {
vertex.setProperty(CYGD_REFERENCES_PROPERTY, value);
}
public void setDBSNPReferences(String[] value) {
vertex.setProperty(DBSNP_REFERENCES_PROPERTY, value);
}
public void setDDBJReferences(String[] value) {
vertex.setProperty(DDBJ_REFERENCES_PROPERTY, value);
}
public void setDictyBaseReferences(String[] value) {
vertex.setProperty(DICTY_BASE_REFERENCES_PROPERTY, value);
}
public void setDIPReferences(String[] value) {
vertex.setProperty(DIP_REFERENCES_PROPERTY, value);
}
public void setDisprotReferences(String[] value) {
vertex.setProperty(DISPROT_REFERENCES_PROPERTY, value);
}
public void setDMDMReferences(String[] value) {
vertex.setProperty(DMDM_REFERENCES_PROPERTY, value);
}
public void setDnasuReferences(String[] value) {
vertex.setProperty(DNASU_REFERENCES_PROPERTY, value);
}
public void setDosacCobs2DPageReferences(String[] value) {
vertex.setProperty(DOSAC_COBS_2DPAGE_REFERENCES_PROPERTY, value);
}
public void setDrugbankReferences(String[] value) {
vertex.setProperty(DRUGBANK_REFERENCES_PROPERTY, value);
}
public void setEchoBaseReferences(String[] value) {
vertex.setProperty(ECHOBASE_REFERENCES_PROPERTY, value);
}
public void setEcogeneReferences(String[] value) {
vertex.setProperty(ECOGENE_REFERENCES_PROPERTY, value);
}
public void setEggnogReferences(String[] value) {
vertex.setProperty(EGGNOG_REFERENCES_PROPERTY, value);
}
public void setEnsemblBacteriaReferences(String[] value) {
vertex.setProperty(ENSEMBL_BACTERIA_REFERENCES_PROPERTY, value);
}
public void setEnsemblFungiReferences(String[] value) {
vertex.setProperty(ENSEMBL_FUNGI_REFERENCES_PROPERTY, value);
}
public void setEnsemblMetazoaReferences(String[] value) {
vertex.setProperty(ENSEMBL_METAZOA_REFERENCES_PROPERTY, value);
}
public void setEnsemblProtistsReferences(String[] value) {
vertex.setProperty(ENSEMBL_PROTISTS_REFERENCES_PROPERTY, value);
}
public void setEuhcvDBReferences(String[] value) {
vertex.setProperty(EUHCVDB_REFERENCES_PROPERTY, value);
}
public void setEupathDBReferences(String[] value) {
vertex.setProperty(EUPATHDB_REFERENCES_PROPERTY, value);
}
public void setEvolutionaryTraceReferences(String[] value) {
vertex.setProperty(EVOLUTIONARY_TRACE_REFERENCES_PROPERTY, value);
}
public void setFlyBaseReferences(String[] value) {
vertex.setProperty(FLYBASE_REFERENCES_PROPERTY, value);
}
public void setGenAtlasReferences(String[] value) {
vertex.setProperty(GENATLAS_REFERENCES_PROPERTY, value);
}
public void setGenBankReferences(String[] value) {
vertex.setProperty(GENBANK_REFERENCES_PROPERTY, value);
}
public void setGene3DReferences(String[] value) {
vertex.setProperty(GENE3D_REFERENCES_PROPERTY, value);
}
public void setGeneCardsReferences(String[] value) {
vertex.setProperty(GENECARDS_REFERENCES_PROPERTY, value);
}
public void setGeneFarmReferences(String[] value) {
vertex.setProperty(GENEFARM_REFERENCES_PROPERTY, value);
}
public void setGeneIDReferences(String[] value) {
vertex.setProperty(GENEID_REFERENCES_PROPERTY, value);
}
public void setGeneTreeReferences(String[] value) {
vertex.setProperty(GENETREE_REFERENCES_PROPERTY, value);
}
public void setGenevestigatorReferences(String[] value) {
vertex.setProperty(GENEVESTIGATOR_REFERENCES_PROPERTY, value);
}
public void setGenolistReferences(String[] value) {
vertex.setProperty(GENOLIST_REFERENCES_PROPERTY, value);
}
public void setGenomeReviewsReferences(String[] value) {
vertex.setProperty(GENOME_REVIEWS_REFERENCES_PROPERTY, value);
}
public void setGenomeRNAIReferences(String[] value) {
vertex.setProperty(GENOME_RNAI_REFERENCES_PROPERTY, value);
}
public void setGermOnlineReferences(String[] value) {
vertex.setProperty(GERMONLINE_REFERENCES_PROPERTY, value);
}
public void setGlycoSuiteDBReferences(String[] value) {
vertex.setProperty(GLYCOSUITEDB_REFERENCES_PROPERTY, value);
}
public void setGPCRDBReferences(String[] value) {
vertex.setProperty(GPCRDB_REFERENCES_PROPERTY, value);
}
public void setGrameneReferences(String[] value) {
vertex.setProperty(GRAMENE_REFERENCES_PROPERTY, value);
}
public void setHINVDBReferences(String[] value) {
vertex.setProperty(HINVDB_REFERENCES_PROPERTY, value);
}
public void setHamapReferences(String[] value) {
vertex.setProperty(HAMAP_REFERENCES_PROPERTY, value);
}
public void setHGNCReferences(String[] value) {
vertex.setProperty(HGNC_REFERENCES_PROPERTY, value);
}
public void setHogenomReferences(String[] value) {
vertex.setProperty(HOGENOM_REFERENCES_PROPERTY, value);
}
public void setHovergenReferences(String[] value) {
vertex.setProperty(HOVERGEN_REFERENCES_PROPERTY, value);
}
public void setHpaReferences(String[] value) {
vertex.setProperty(HPA_REFERENCES_PROPERTY, value);
}
public void setHsspReferences(String[] value) {
vertex.setProperty(HSSP_REFERENCES_PROPERTY, value);
}
public void setHugeReferences(String[] value) {
vertex.setProperty(HUGE_REFERENCES_PROPERTY, value);
}
public void setIMGTReferences(String[] value) {
vertex.setProperty(IMGT_REFERENCES_PROPERTY, value);
}
public void setINPARANOIDReferences(String[] value) {
vertex.setProperty(INPARANOID_REFERENCES_PROPERTY, value);
}
public void setIntactReferences(String[] value) {
vertex.setProperty(INTACT_REFERENCES_PROPERTY, value);
}
public void setIPIReferences(String[] value) {
vertex.setProperty(IPI_REFERENCES_PROPERTY, value);
}
public void setKOReferences(String[] value) {
vertex.setProperty(KO_REFERENCES_PROPERTY, value);
}
public void setLegioListReferences(String[] value) {
vertex.setProperty(LEGIO_LIST_REFERENCES_PROPERTY, value);
}
public void setLepromaReferences(String[] value) {
vertex.setProperty(LEPROMA_REFERENCES_PROPERTY, value);
}
public void setMaizeGDBReferences(String[] value) {
vertex.setProperty(MAIZE_GDB_REFERENCES_PROPERTY, value);
}
public void setMeropsReferences(String[] value) {
vertex.setProperty(MEROPS_REFERENCES_PROPERTY, value);
}
public void setMGIReferences(String[] value) {
vertex.setProperty(MGI_REFERENCES_PROPERTY, value);
}
public static final String MICADO_REFERENCES_PROPERTY = "protein_micado_references";
public static final String MIM_REFERENCES_PROPERTY = "protein_mim_references";
public static final String MINT_REFERENCES_PROPERTY = "protein_mint_references";
public static final String MODBASE_REFERENCES_PROPERTY = "protein_modbase_references";
public static final String MYCOCLAP_REFERENCES_PROPERTY = "protein_mycoclap_references";
public static final String NEXTBIO_REFERENCES_PROPERTY = "protein_nextbio_references";
public static final String NEXTPROT_REFERENCES_PROPERTY = "protein_nextprot_references";
public static final String OGP_REFERENCES_PROPERTY = "protein_ogp_references";
public static final String OMA_REFERENCES_PROPERTY = "protein_oma_references";
public static final String ORPHANET_REFERENCES_PROPERTY = "protein_orphanet_references";
public static final String ORTHODB_REFERENCES_PROPERTY = "protein_orthodb_references";
public static final String PANTHER_REFERENCES_PROPERTY = "protein_panther_references";
public static final String PATHWAY_INTERACTION_DB_REFERENCES_PROPERTY = "protein_pathway_interaction_db_references";
public static final String PATRIC_REFERENCES_PROPERTY = "protein_patric_references";
public static final String PAXDB_REFERENCES_PROPERTY = "protein_paxdb_references";
public static final String PDB_REFERENCES_PROPERTY = "protein_pdb_references";
public static final String PDBJ_REFERENCES_PROPERTY = "protein_pdbj_references";
public static final String PDBSUM_REFERENCES_PROPERTY = "protein_pdbsum_references";
public static final String PEPTIDE_ATLAS_REFERENCES_PROPERTY = "protein_peptide_atlas_references";
public static final String PHARMGKB_REFERENCES_PROPERTY = "protein_pharmgkb_references";
public static final String PHCI_2DPAGE_REFERENCES_PROPERTY = "protein_phci_2dpage_references";
public static final String PHOSPHOSITE_REFERENCES_PROPERTY = "protein_phosphosite_references";
public static final String PHOS_SITE_REFERENCES_PROPERTY = "protein_phos_site_references";
public static final String PHYLOME_DB_REFERENCES_PROPERTY = "protein_phylome_db_references";
public static final String PIRSF_REFERENCES_PROPERTY = "protein_pirsf_references";
public static final String PMAP_CUTDB_REFERENCES_PROPERTY = "protein_pmap_cutdb_references";
public static final String PMMA_2DPAGE_REFERENCES_PROPERTY = "protein_pmma_2dpage_references";
public static final String POMBASE_REFERENCES_PROPERTY = "protein_pombase_references";
public static final String PPTASEDB_REFERENCES_PROPERTY = "protein_pptasedb_references";
public static final String PRIDE_REFERENCES_PROPERTY = "protein_pride_references";
public static final String PRINTS_REFERENCES_PROPERTY = "protein_prints_references";
public static final String PRODOM_REFERENCES_PROPERTY = "protein_prodom_references";
public static final String PROMEX_REFERENCES_PROPERTY = "protein_promex_references";
public static final String PROSITE_REFERENCES_PROPERTY = "protein_prosite_references";
public static final String PROT_CLUST_DB_REFERENCES_PROPERTY = "protein_prot_clust_db_references";
public static final String PROTEIN_MODEL_PORTAL_REFERENCES_PROPERTY = "protein_model_portal_references";
public static final String PROTONET_REFERENCES_PROPERTY = "protein_protonet_references";
public static final String PSEUDO_CAP_REFERENCES_PROPERTY = "protein_pseudo_cap_references";
public static final String RAT_HEART_2DPAGE_REFERENCES_PROPERTY = "protein_rat_heart_2dpage_references";
public static final String RCSB_PDB_REFERENCES_PROPERTY = "protein_rcsb_pdb_references";
public static final String REBASE_REFERENCES_PROPERTY = "protein_rebase_references";
public static final String REPRODUCTION_2DPAGE_REFERENCES_PROPERTY = "protein_reproduction_2dpage_references";
public static final String RGD_REFERENCES_PROPERTY = "protein_rgd_references";
public static final String ROUGE_REFERENCES_PROPERTY = "protein_rouge_references";
public static final String SBKB_REFERENCES_PROPERTY = "protein_sbkb_references";
public static final String SGD_REFERENCES_PROPERTY = "protein_sgd_references";
public static final String SIENA_2DPAGE_REFERENCES_PROPERTY = "protein_siena_2dpage_references";
public static final String SMART_REFERENCES_PROPERTY = "protein_smart_references";
public static final String SMR_REFERENCES_PROPERTY = "protein_smr_references";
public static final String SOURCE_REFERENCES_PROPERTY = "protein_source_references";
public static final String STRING_REFERENCES_PROPERTY = "protein_string_references";
public static final String SUPFAM_REFERENCES_PROPERTY = "protein_supfam_references";
public static final String SWISS_2DPAGE_REFERENCES_PROPERTY = "protein_swiss_2dpage_references";
public static final String TAIR_REFERENCES_PROPERTY = "protein_tair_references";
public static final String TCDB_REFERENCES_PROPERTY = "protein_tcb_references";
public static final String TIGRFAMS_REFERENCES_PROPERTY = "protein_tigrfams_references";
public static final String TUBERCULIST_REFERENCES_PROPERTY = "protein_tuberculist_references";
public static final String UCD_2DPAGE_REFERENCES_PROPERTY = "protein_ucd_2dpage_references";
public static final String UCSC_REFERENCES_PROPERTY = "protein_ucsc_references";
public static final String VECTOR_BASE_REFERENCES_PROPERTY = "protein_vector_base_references";
public static final String WORLD_2DPAGE_REFERENCES_PROPERTY = "protein_world_2dpage_references";
public static final String WORM_BASE_REFERENCES_PROPERTY = "protein_worm_base_references";
public static final String XEN_BASE_REFERENCES_PROPERTY = "protein_xen_base_references";
public static final String ZFIN_REFERENCES_PROPERTY = "protein_zfin_references";
}
| making progress on integration of all external DB refs from Uniprot
| src/main/java/com/era7/bioinfo/bio4j/blueprints/model/nodes/ProteinNode.java | making progress on integration of all external DB refs from Uniprot | <ide><path>rc/main/java/com/era7/bioinfo/bio4j/blueprints/model/nodes/ProteinNode.java
<ide> vertex.setProperty(MGI_REFERENCES_PROPERTY, value);
<ide> }
<ide>
<del>
<del>
<del> public static final String MICADO_REFERENCES_PROPERTY = "protein_micado_references";
<del> public static final String MIM_REFERENCES_PROPERTY = "protein_mim_references";
<del> public static final String MINT_REFERENCES_PROPERTY = "protein_mint_references";
<del> public static final String MODBASE_REFERENCES_PROPERTY = "protein_modbase_references";
<del> public static final String MYCOCLAP_REFERENCES_PROPERTY = "protein_mycoclap_references";
<del> public static final String NEXTBIO_REFERENCES_PROPERTY = "protein_nextbio_references";
<del> public static final String NEXTPROT_REFERENCES_PROPERTY = "protein_nextprot_references";
<del> public static final String OGP_REFERENCES_PROPERTY = "protein_ogp_references";
<del> public static final String OMA_REFERENCES_PROPERTY = "protein_oma_references";
<del> public static final String ORPHANET_REFERENCES_PROPERTY = "protein_orphanet_references";
<del> public static final String ORTHODB_REFERENCES_PROPERTY = "protein_orthodb_references";
<del> public static final String PANTHER_REFERENCES_PROPERTY = "protein_panther_references";
<del> public static final String PATHWAY_INTERACTION_DB_REFERENCES_PROPERTY = "protein_pathway_interaction_db_references";
<del> public static final String PATRIC_REFERENCES_PROPERTY = "protein_patric_references";
<del> public static final String PAXDB_REFERENCES_PROPERTY = "protein_paxdb_references";
<del> public static final String PDB_REFERENCES_PROPERTY = "protein_pdb_references";
<del> public static final String PDBJ_REFERENCES_PROPERTY = "protein_pdbj_references";
<del> public static final String PDBSUM_REFERENCES_PROPERTY = "protein_pdbsum_references";
<del> public static final String PEPTIDE_ATLAS_REFERENCES_PROPERTY = "protein_peptide_atlas_references";
<del> public static final String PHARMGKB_REFERENCES_PROPERTY = "protein_pharmgkb_references";
<del> public static final String PHCI_2DPAGE_REFERENCES_PROPERTY = "protein_phci_2dpage_references";
<del> public static final String PHOSPHOSITE_REFERENCES_PROPERTY = "protein_phosphosite_references";
<del> public static final String PHOS_SITE_REFERENCES_PROPERTY = "protein_phos_site_references";
<del> public static final String PHYLOME_DB_REFERENCES_PROPERTY = "protein_phylome_db_references";
<del> public static final String PIRSF_REFERENCES_PROPERTY = "protein_pirsf_references";
<del> public static final String PMAP_CUTDB_REFERENCES_PROPERTY = "protein_pmap_cutdb_references";
<del> public static final String PMMA_2DPAGE_REFERENCES_PROPERTY = "protein_pmma_2dpage_references";
<del> public static final String POMBASE_REFERENCES_PROPERTY = "protein_pombase_references";
<del> public static final String PPTASEDB_REFERENCES_PROPERTY = "protein_pptasedb_references";
<del> public static final String PRIDE_REFERENCES_PROPERTY = "protein_pride_references";
<del> public static final String PRINTS_REFERENCES_PROPERTY = "protein_prints_references";
<del> public static final String PRODOM_REFERENCES_PROPERTY = "protein_prodom_references";
<del> public static final String PROMEX_REFERENCES_PROPERTY = "protein_promex_references";
<del> public static final String PROSITE_REFERENCES_PROPERTY = "protein_prosite_references";
<del> public static final String PROT_CLUST_DB_REFERENCES_PROPERTY = "protein_prot_clust_db_references";
<del> public static final String PROTEIN_MODEL_PORTAL_REFERENCES_PROPERTY = "protein_model_portal_references";
<del> public static final String PROTONET_REFERENCES_PROPERTY = "protein_protonet_references";
<del> public static final String PSEUDO_CAP_REFERENCES_PROPERTY = "protein_pseudo_cap_references";
<del> public static final String RAT_HEART_2DPAGE_REFERENCES_PROPERTY = "protein_rat_heart_2dpage_references";
<del> public static final String RCSB_PDB_REFERENCES_PROPERTY = "protein_rcsb_pdb_references";
<del> public static final String REBASE_REFERENCES_PROPERTY = "protein_rebase_references";
<del> public static final String REPRODUCTION_2DPAGE_REFERENCES_PROPERTY = "protein_reproduction_2dpage_references";
<del> public static final String RGD_REFERENCES_PROPERTY = "protein_rgd_references";
<del> public static final String ROUGE_REFERENCES_PROPERTY = "protein_rouge_references";
<del> public static final String SBKB_REFERENCES_PROPERTY = "protein_sbkb_references";
<del> public static final String SGD_REFERENCES_PROPERTY = "protein_sgd_references";
<del> public static final String SIENA_2DPAGE_REFERENCES_PROPERTY = "protein_siena_2dpage_references";
<del> public static final String SMART_REFERENCES_PROPERTY = "protein_smart_references";
<del> public static final String SMR_REFERENCES_PROPERTY = "protein_smr_references";
<del> public static final String SOURCE_REFERENCES_PROPERTY = "protein_source_references";
<del> public static final String STRING_REFERENCES_PROPERTY = "protein_string_references";
<del> public static final String SUPFAM_REFERENCES_PROPERTY = "protein_supfam_references";
<del> public static final String SWISS_2DPAGE_REFERENCES_PROPERTY = "protein_swiss_2dpage_references";
<del> public static final String TAIR_REFERENCES_PROPERTY = "protein_tair_references";
<del> public static final String TCDB_REFERENCES_PROPERTY = "protein_tcb_references";
<del> public static final String TIGRFAMS_REFERENCES_PROPERTY = "protein_tigrfams_references";
<del> public static final String TUBERCULIST_REFERENCES_PROPERTY = "protein_tuberculist_references";
<del> public static final String UCD_2DPAGE_REFERENCES_PROPERTY = "protein_ucd_2dpage_references";
<del> public static final String UCSC_REFERENCES_PROPERTY = "protein_ucsc_references";
<del> public static final String VECTOR_BASE_REFERENCES_PROPERTY = "protein_vector_base_references";
<del> public static final String WORLD_2DPAGE_REFERENCES_PROPERTY = "protein_world_2dpage_references";
<del> public static final String WORM_BASE_REFERENCES_PROPERTY = "protein_worm_base_references";
<del> public static final String XEN_BASE_REFERENCES_PROPERTY = "protein_xen_base_references";
<del> public static final String ZFIN_REFERENCES_PROPERTY = "protein_zfin_references";
<add> public void setMicadoReferences(String[] value) {
<add> vertex.setProperty(MICADO_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setMIMReferences(String[] value) {
<add> vertex.setProperty(MIM_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setMINTReferences(String[] value) {
<add> vertex.setProperty(MINT_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setModbaseReferences(String[] value) {
<add> vertex.setProperty(MODBASE_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setMycoclapReferences(String[] value) {
<add> vertex.setProperty(MYCOCLAP_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setNextbioReferences(String[] value) {
<add> vertex.setProperty(NEXTBIO_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setNextprotoReferences(String[] value) {
<add> vertex.setProperty(NEXTPROT_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setOGPReferences(String[] value) {
<add> vertex.setProperty(OGP_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setOMAReferences(String[] value) {
<add> vertex.setProperty(OMA_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setOrphanetReferences(String[] value) {
<add> vertex.setProperty(ORPHANET_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setOrthoDBReferences(String[] value) {
<add> vertex.setProperty(ORTHODB_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setPantherReferences(String[] value) {
<add> vertex.setProperty(PANTHER_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setPathwayInteractionDBReferences(String[] value) {
<add> vertex.setProperty(PATHWAY_INTERACTION_DB_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setPatricReferences(String[] value) {
<add> vertex.setProperty(PATRIC_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setPaxDBReferences(String[] value) {
<add> vertex.setProperty(PAXDB_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setPDBReferences(String[] value) {
<add> vertex.setProperty(PDB_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setPDBJReferences(String[] value) {
<add> vertex.setProperty(PDBJ_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setPDBSumReferences(String[] value) {
<add> vertex.setProperty(PDBSUM_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setPeptideAtlasReferences(String[] value) {
<add> vertex.setProperty(PEPTIDE_ATLAS_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setPharmGKBReferences(String[] value) {
<add> vertex.setProperty(PHARMGKB_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setPHCI_2DPageReferences(String[] value) {
<add> vertex.setProperty(PHCI_2DPAGE_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setPhosphositeReferences(String[] value) {
<add> vertex.setProperty(PHOSPHOSITE_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setPhosSiteReferences(String[] value) {
<add> vertex.setProperty(PHOS_SITE_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setPhylomeReferences(String[] value) {
<add> vertex.setProperty(PHYLOME_DB_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setPirsfReferences(String[] value) {
<add> vertex.setProperty(PIRSF_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setPmapReferences(String[] value) {
<add> vertex.setProperty(PMAP_CUTDB_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setPMMA2DPageReferences(String[] value) {
<add> vertex.setProperty(PMMA_2DPAGE_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setPomBaseReferences(String[] value) {
<add> vertex.setProperty(POMBASE_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setPPTaseDBReferences(String[] value) {
<add> vertex.setProperty(PPTASEDB_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setPrideReferences(String[] value) {
<add> vertex.setProperty(PRIDE_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setPrintsReferences(String[] value) {
<add> vertex.setProperty(PRINTS_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setProdomReferences(String[] value) {
<add> vertex.setProperty(PRODOM_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setPromexReferences(String[] value) {
<add> vertex.setProperty(PROMEX_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setPrositeReferences(String[] value) {
<add> vertex.setProperty(PROSITE_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setProtClustDBReferences(String[] value) {
<add> vertex.setProperty(PROT_CLUST_DB_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setProteinModelPortalReferences(String[] value) {
<add> vertex.setProperty(PROTEIN_MODEL_PORTAL_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setProtonetReferences(String[] value) {
<add> vertex.setProperty(PROTONET_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setPseudoCapReferences(String[] value) {
<add> vertex.setProperty(PSEUDO_CAP_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setRatHeart2DPageReferences(String[] value) {
<add> vertex.setProperty(RAT_HEART_2DPAGE_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setRCSBPDBReferences(String[] value) {
<add> vertex.setProperty(RCSB_PDB_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setRebaseReferences(String[] value) {
<add> vertex.setProperty(REBASE_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setReproduction2DPageReferences(String[] value) {
<add> vertex.setProperty(REPRODUCTION_2DPAGE_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setRGDReferences(String[] value) {
<add> vertex.setProperty(RGD_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setRougeReferences(String[] value) {
<add> vertex.setProperty(ROUGE_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setSBKBReferences(String[] value) {
<add> vertex.setProperty(SBKB_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setSGDReferences(String[] value) {
<add> vertex.setProperty(SGD_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setSiena2DPageReferences(String[] value) {
<add> vertex.setProperty(SIENA_2DPAGE_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setSmartReferences(String[] value) {
<add> vertex.setProperty(SMART_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setSMRReferences(String[] value) {
<add> vertex.setProperty(SMR_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setSourceReferences(String[] value) {
<add> vertex.setProperty(SOURCE_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setStringReferences(String[] value) {
<add> vertex.setProperty(STRING_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setSupfamReferences(String[] value) {
<add> vertex.setProperty(SUPFAM_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setSwiss2DPageReferences(String[] value) {
<add> vertex.setProperty(SWISS_2DPAGE_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setTairReferences(String[] value) {
<add> vertex.setProperty(TAIR_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setTCDBReferences(String[] value) {
<add> vertex.setProperty(TCDB_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setTIGRFAMSReferences(String[] value) {
<add> vertex.setProperty(TIGRFAMS_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setTuberculistReferences(String[] value) {
<add> vertex.setProperty(TUBERCULIST_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setUCD2DPageReferences(String[] value) {
<add> vertex.setProperty(UCD_2DPAGE_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setUCSCReferences(String[] value) {
<add> vertex.setProperty(UCSC_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setVectorBaseReferences(String[] value) {
<add> vertex.setProperty(VECTOR_BASE_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setWorld2DPageReferences(String[] value) {
<add> vertex.setProperty(WORLD_2DPAGE_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setWormBaseReferences(String[] value) {
<add> vertex.setProperty(WORM_BASE_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setXenBaseReferences(String[] value) {
<add> vertex.setProperty(XEN_BASE_REFERENCES_PROPERTY, value);
<add> }
<add>
<add> public void setZFINReferences(String[] value) {
<add> vertex.setProperty(ZFIN_REFERENCES_PROPERTY, value);
<add> }
<add>
<add>
<ide> } |
|
Java | apache-2.0 | 873f4547bde97cb4e86dcc0ea5eb6580662fe838 | 0 | marklogic/java-client-api,marklogic/java-client-api,marklogic/java-client-api,marklogic/java-client-api,marklogic/java-client-api | /*
* Copyright (c) 2021 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.functionaltest;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.xml.parsers.ParserConfigurationException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.xml.sax.SAXException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.marklogic.client.DatabaseClient;
import com.marklogic.client.DatabaseClientFactory;
import com.marklogic.client.DatabaseClientFactory.Authentication;
import com.marklogic.client.DatabaseClientFactory.DigestAuthContext;
import com.marklogic.client.admin.ExtensionMetadata;
import com.marklogic.client.admin.ExtensionMetadata.ScriptLanguage;
import com.marklogic.client.admin.MethodType;
import com.marklogic.client.admin.ResourceExtensionsManager;
import com.marklogic.client.admin.ResourceExtensionsManager.MethodParameters;
import com.marklogic.client.document.DocumentManager;
import com.marklogic.client.document.DocumentWriteSet;
import com.marklogic.client.expression.PlanBuilder;
import com.marklogic.client.expression.PlanBuilder.ExportablePlan;
import com.marklogic.client.expression.PlanBuilder.ModifyPlan;
import com.marklogic.client.io.DocumentMetadataHandle;
import com.marklogic.client.io.FileHandle;
import com.marklogic.client.io.InputStreamHandle;
import com.marklogic.client.io.JacksonHandle;
import com.marklogic.client.row.RowManager;
import com.marklogic.client.type.PlanAggregateColSeq;
import com.marklogic.client.type.PlanColumn;
import com.marklogic.client.type.PlanExprColSeq;
import com.marklogic.client.type.PlanValueOption;
public class TestOpticOnLiterals extends BasicJavaClientREST {
private static String dbName = "TestOpticOnLiteralsDB";
private static String schemadbName = "TestOpticOnLiteralsSchemaDB";
private static String[] fNames = { "TestOpticOnLiteralsDB-1" };
private static String[] schemafNames = { "TestOpticOnLiteralsSchemaDB-1" };
private static DatabaseClient client;
private static DatabaseClient clientRes;
private static String datasource = "src/test/java/com/marklogic/client/functionaltest/data/optics/";
private static Map<String, Object>[] literals1 = new HashMap[5];
private static Map<String, Object>[] literals2 = new HashMap[4];
private static Map<String, Object>[] storeInformation = new HashMap[4];
private static Map<String, Object>[] internetSales = new HashMap[4];
private static ResourceExtensionsManager resourceMgr;
private static String resourceName = "OpticsJSResourceModule";
@BeforeClass
public static void setUp() throws KeyManagementException, NoSuchAlgorithmException, Exception
{
System.out.println("In TestOpticOnLiterals setup");
DatabaseClient schemaDBclient = null;
configureRESTServer(dbName, fNames);
// Add new range elements into this array
String[][] rangeElements = {
// { scalar-type, namespace-uri, localname, collation,
// range-value-positions, invalid-values }
// If there is a need to add additional fields, then add them to the end
// of each array
// and pass empty strings ("") into an array where the additional field
// does not have a value.
// For example : as in namespace, collections below.
// Add new RangeElementIndex as an array below.
{ "string", "", "city", "http://marklogic.com/collation/", "false", "reject" },
{ "int", "", "popularity", "", "false", "reject" },
{ "double", "", "distance", "", "false", "reject" },
{ "date", "", "date", "", "false", "reject" },
{ "string", "", "cityName", "http://marklogic.com/collation/", "false", "reject" },
{ "string", "", "cityTeam", "http://marklogic.com/collation/", "false", "reject" },
{ "long", "", "cityPopulation", "", "false", "reject" }
};
// Insert the range indices
addRangeElementIndex(dbName, rangeElements);
// Insert word lexicon.
ObjectMapper mapper = new ObjectMapper();
ObjectNode mainNode = mapper.createObjectNode();
ArrayNode childArray = mapper.createArrayNode();
ObjectNode childNodeObject = mapper.createObjectNode();
childNodeObject.put("namespace-uri", "http://marklogic.com/collation/");
childNodeObject.put("localname", "city");
childNodeObject.put("collation", "http://marklogic.com/collation/");
childArray.add(childNodeObject);
mainNode.withArray("element-word-lexicon").add(childArray);
setDatabaseProperties(dbName, "element-word-lexicon", mainNode);
// Add geo element index.
addGeospatialElementIndexes(dbName, "latLonPoint", "", "wgs84", "point", false, "reject");
// Enable triple index.
enableTripleIndex(dbName);
waitForServerRestart();
// Enable collection lexicon.
enableCollectionLexicon(dbName);
// Enable uri lexicon.
setDatabaseProperties(dbName, "uri-lexicon", true);
// Create schema database
createDB(schemadbName);
createForest(schemafNames[0], schemadbName);
// Set the schemadbName database as the Schema database.
setDatabaseProperties(dbName, "schema-database", schemadbName);
createUserRolesWithPrevilages("opticRole", "xdbc:eval", "xdbc:eval-in", "xdmp:eval-in", "any-uri", "xdbc:invoke");
createRESTUser("opticUser", "0pt1c", "tde-admin", "tde-view", "opticRole", "rest-admin", "rest-writer",
"rest-reader", "rest-extension-user", "manage-user");
if (IsSecurityEnabled()) {
schemaDBclient = getDatabaseClientOnDatabase(getRestServerHostName(), getRestServerPort(), schemadbName, "opticUser", "0pt1c", getConnType());
client = getDatabaseClient("opticUser", "0pt1c", getConnType());
}
else {
schemaDBclient = DatabaseClientFactory.newClient(getRestServerHostName(), getRestServerPort(), schemadbName, new DigestAuthContext("opticUser", "0pt1c"));
client = DatabaseClientFactory.newClient(getRestServerHostName(), getRestServerPort(), new DigestAuthContext("opticUser", "0pt1c"));
}
// Install the TDE templates
// loadFileToDB(client, filename, docURI, collection, document format)
loadFileToDB(schemaDBclient, "masterDetail.tdex", "/optic/view/test/masterDetail.tdex", "XML", new String[] { "http://marklogic.com/xdmp/tde" });
loadFileToDB(schemaDBclient, "masterDetail2.tdej", "/optic/view/test/masterDetail2.tdej", "JSON", new String[] { "http://marklogic.com/xdmp/tde" });
loadFileToDB(schemaDBclient, "masterDetail3.tdej", "/optic/view/test/masterDetail3.tdej", "JSON", new String[] { "http://marklogic.com/xdmp/tde" });
loadFileToDB(schemaDBclient, "masterDetail4.tdej", "/optic/view/test/masterDetail4.tdej", "JSON", new String[] { "http://marklogic.com/xdmp/tde" });
// Load XML data files.
loadFileToDB(client, "masterDetail.xml", "/optic/view/test/masterDetail.xml", "XML", new String[] { "/optic/view/test" });
loadFileToDB(client, "playerTripleSet.xml", "/optic/triple/test/playerTripleSet.xml", "XML", new String[] { "/optic/player/triple/test" });
loadFileToDB(client, "teamTripleSet.xml", "/optic/triple/test/teamTripleSet.xml", "XML", new String[] { "/optic/team/triple/test" });
loadFileToDB(client, "otherPlayerTripleSet.xml", "/optic/triple/test/otherPlayerTripleSet.xml", "XML", new String[] { "/optic/other/player/triple/test" });
loadFileToDB(client, "doc4.xml", "/optic/lexicon/test/doc4.xml", "XML", new String[] { "/optic/lexicon/test" });
loadFileToDB(client, "doc5.xml", "/optic/lexicon/test/doc5.xml", "XML", new String[] { "/optic/lexicon/test" });
// Load JSON data files.
loadFileToDB(client, "masterDetail2.json", "/optic/view/test/masterDetail2.json", "JSON", new String[] { "/optic/view/test" });
loadFileToDB(client, "masterDetail3.json", "/optic/view/test/masterDetail3.json", "JSON", new String[] { "/optic/view/test" });
loadFileToDB(client, "masterDetail4.json", "/optic/view/test/masterDetail4.json", "JSON", new String[] { "/optic/view/test" });
loadFileToDB(client, "masterDetail5.json", "/optic/view/test/masterDetail5.json", "JSON", new String[] { "/optic/view/test" });
loadFileToDB(client, "doc1.json", "/optic/lexicon/test/doc1.json", "JSON", new String[] { "/other/coll1", "/other/coll2" });
loadFileToDB(client, "doc2.json", "/optic/lexicon/test/doc2.json", "JSON", new String[] { "/optic/lexicon/test" });
loadFileToDB(client, "doc3.json", "/optic/lexicon/test/doc3.json", "JSON", new String[] { "/optic/lexicon/test" });
loadFileToDB(client, "city1.json", "/optic/lexicon/test/city1.json", "JSON", new String[] { "/optic/lexicon/test" });
loadFileToDB(client, "city2.json", "/optic/lexicon/test/city2.json", "JSON", new String[] { "/optic/lexicon/test" });
loadFileToDB(client, "city3.json", "/optic/lexicon/test/city3.json", "JSON", new String[] { "/optic/lexicon/test" });
loadFileToDB(client, "city4.json", "/optic/lexicon/test/city4.json", "JSON", new String[] { "/optic/lexicon/test" });
loadFileToDB(client, "city5.json", "/optic/lexicon/test/city5.json", "JSON", new String[] { "/optic/lexicon/test" });
Map<String, Object> row = new HashMap<>();
row.put("rowId", 1);
row.put("colorId", 1);
row.put("desc", "ball");
literals1[0] = row;
row = new HashMap<>();
row.put("rowId", 2);
row.put("colorId", 2);
row.put("desc", "square");
literals1[1] = row;
row = new HashMap<>();
row.put("rowId", 3);
row.put("colorId", 1);
row.put("desc", "box");
literals1[2] = row;
row = new HashMap<>();
row.put("rowId", 4);
row.put("colorId", 1);
row.put("desc", "hoop");
literals1[3] = row;
row = new HashMap<>();
row.put("rowId", 5);
row.put("colorId", 5);
row.put("desc", "circle");
literals1[4] = row;
row = new HashMap<>();
row.put("colorId", 1);
row.put("colorDesc", "red");
literals2[0] = row;
row = new HashMap<>();
row.put("colorId", 2);
row.put("colorDesc", "blue");
literals2[1] = row;
row = new HashMap<>();
row.put("colorId", 3);
row.put("colorDesc", "black");
literals2[2] = row;
row = new HashMap<>();
row.put("colorId", 4);
row.put("colorDesc", "yellow");
literals2[3] = row;
// Fill up storeInformation Map
row = new HashMap<>();
row.put("storeName", "Los Angeles");
row.put("sales", 1500);
row.put("txnDate", "Jan-05-1999");
storeInformation[0] = row;
row = new HashMap<>();
row.put("storeName", "San Diego");
row.put("sales", 250);
row.put("txnDate", "Jan-07-1999");
storeInformation[1] = row;
row = new HashMap<>();
row.put("storeName", "Los Angeles");
row.put("sales", 300);
row.put("txnDate", "Jan-08-1999");
storeInformation[2] = row;
row = new HashMap<>();
row.put("storeName", "Boston");
row.put("sales", 700);
row.put("txnDate", "Jan-08-1999");
storeInformation[3] = row;
// Fill up internetSales Map
row = new HashMap<>();
row.put("txnDate", "Jan-07-1999");
row.put("sales", 250);
row.put("sales", 1500);
internetSales[0] = row;
row = new HashMap<>();
row.put("txnDate", "Jan-10-1999");
row.put("sales", 535);
row.put("storeName", "San Diego");
internetSales[1] = row;
row = new HashMap<>();
row.put("txnDate", "Jan-11-1999");
row.put("sales", 320);
row.put("storeName", "Los Angeles");
internetSales[2] = row;
row = new HashMap<>();
row.put("txnDate", "Jan-12-1999");
row.put("sales", 750);
row.put("storeName", "Boston");
internetSales[3] = row;
// Install JavaScript modules into REST Server module database to support
// Map and Reduce tests.
createUserRolesWithPrevilages("test-eval", "xdbc:eval", "xdbc:eval-in", "xdmp:eval-in", "any-uri", "xdbc:invoke");
createRESTUser("eval-user", "x", "test-eval", "rest-admin", "rest-writer", "rest-reader");
clientRes = getDatabaseClient("eval-user", "x", getConnType());
resourceMgr = clientRes.newServerConfigManager().newResourceExtensionsManager();
ExtensionMetadata resextMetadata = new ExtensionMetadata();
resextMetadata.setTitle("BasicJSTest");
resextMetadata.setDescription("Testing resource extension for java script");
System.out.println(resextMetadata.getScriptLanguage());
resextMetadata.setScriptLanguage(ScriptLanguage.JAVASCRIPT);
System.out.println(resextMetadata.getScriptLanguage());
resextMetadata.setVersion("1.0");
MethodParameters getParams = new MethodParameters(MethodType.GET);
getParams.add("row", "xs:string?");
FileInputStream myStream = new FileInputStream("src/test/java/com/marklogic/client/functionaltest/data/OpticsTestJSResource.js");
InputStreamHandle handle = new InputStreamHandle(myStream);
handle.set(myStream);
resourceMgr.writeServices(resourceName, handle, resextMetadata, getParams);
Thread.sleep(10000);
schemaDBclient.release();
}
/**
* Write document using DOMHandle
*
* @param client
* @param filename
* @param uri
* @param type
* @throws IOException
* @throws ParserConfigurationException
* @throws SAXException
*/
public static void loadFileToDB(DatabaseClient client, String filename, String uri, String type, String[] collections) throws IOException, ParserConfigurationException,
SAXException
{
// create doc manager
DocumentManager docMgr = null;
docMgr = documentMgrSelector(client, docMgr, type);
File file = new File(datasource + filename);
// create a handle on the content
FileHandle handle = new FileHandle(file);
handle.set(file);
DocumentMetadataHandle metadataHandle = new DocumentMetadataHandle();
for (String coll : collections)
metadataHandle.getCollections().addAll(coll.toString());
// write the document content
DocumentWriteSet writeset = docMgr.newWriteSet();
writeset.addDefault(metadataHandle);
writeset.add(uri, handle);
docMgr.write(writeset);
System.out.println("Write " + uri + " to database");
}
/**
* Function to select and create document manager based on the type
*
* @param client
* @param docMgr
* @param type
* @return
*/
public static DocumentManager documentMgrSelector(DatabaseClient client, DocumentManager docMgr, String type) {
// create doc manager
switch (type) {
case "XML":
docMgr = client.newXMLDocumentManager();
break;
case "Text":
docMgr = client.newTextDocumentManager();
break;
case "JSON":
docMgr = client.newJSONDocumentManager();
break;
case "Binary":
docMgr = client.newBinaryDocumentManager();
break;
case "JAXB":
docMgr = client.newXMLDocumentManager();
break;
default:
System.out.println("Invalid type");
break;
}
return docMgr;
}
/*
* 1) Test join inner 2) Test join inner with qualifier 3) Test join and
* multiple order by 4) Test multple inner joins
*/
@Test
public void testJoinInner() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException
{
System.out.println("In testJoinInner method");
// Create a new Plan.
RowManager rowMgr = client.newRowManager();
PlanBuilder p = rowMgr.newPlanBuilder();
// plans from literals
ModifyPlan plan1 = p.fromLiterals(literals1);
ModifyPlan plan2 = p.fromLiterals(literals2);
ModifyPlan output = plan1.joinInner(plan2).orderBy(p.asc(p.col("rowId")));
JacksonHandle jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(output, jacksonHandle);
JsonNode jsonBindingsNodes = jacksonHandle.get().path("rows");
// Should have 4 nodes returned.
assertEquals("Four nodes not returned from testJoinInner method", 4, jsonBindingsNodes.size());
JsonNode node = jsonBindingsNodes.path(0);
assertEquals("Row 1 rowId value incorrect", "1", node.path("rowId").path("value").asText());
assertEquals("Row 1 desc value incorrect", "ball", node.path("desc").path("value").asText());
assertEquals("Row 1 colorDesc value incorrect", "red", node.path("colorDesc").path("value").asText());
node = jsonBindingsNodes.path(3);
assertEquals("Row 4 rowId value incorrect", "4", node.path("rowId").path("value").asText());
assertEquals("Row 4 desc value incorrect", "hoop", node.path("desc").path("value").asText());
assertEquals("Row 4 colorDesc value incorrect", "red", node.path("colorDesc").path("value").asText());
// Join inner with qualifier
ModifyPlan plan3 = p.fromLiterals(literals1, "table1");
ModifyPlan plan4 = p.fromLiterals(literals2, "table2");
ModifyPlan outputQualifier = plan3.joinInner(plan4)
.where(p.eq(p.viewCol("table1", "colorId"), p.viewCol("table2", "colorId")))
.orderBy(p.desc(p.viewCol("table1", "rowId")));
jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(outputQualifier, jacksonHandle);
jsonBindingsNodes = jacksonHandle.get().path("rows");
node = jsonBindingsNodes.path(3);
assertEquals("Row 1 table1.rowId value incorrect", "1", node.path("table1.rowId").path("value").asText());
assertEquals("Row 1 table1.desc value incorrect", "ball", node.path("table1.desc").path("value").asText());
assertEquals("Row 1 table2.colorDesc value incorrect", "red", node.path("table2.colorDesc").path("value").asText());
node = jsonBindingsNodes.path(0);
assertEquals("Row 4 table1.rowId value incorrect", "4", node.path("table1.rowId").path("value").asText());
assertEquals("Row 4 table1.desc value incorrect", "hoop", node.path("table1.desc").path("value").asText());
assertEquals("Row 4 table2.colorDesc value incorrect", "red", node.path("table2.colorDesc").path("value").asText());
// Test join and multiple order by
ModifyPlan plan5 = p.fromLiterals(literals1, "myItem");
ModifyPlan plan6 = p.fromLiterals(literals2, "myColor");
PlanColumn descCol = p.viewCol("myItem", "desc");
PlanColumn itemColorIdCol = p.viewCol("myItem", "colorId");
PlanColumn colorIdCol = p.viewCol("myColor", "colorId");
ModifyPlan outputMultiOrder = plan5.joinInner(plan6, p.on(itemColorIdCol, colorIdCol))
.select(descCol, colorIdCol)
.orderBy(p.sortKeySeq(colorIdCol, descCol));
jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(outputMultiOrder, jacksonHandle);
jsonBindingsNodes = jacksonHandle.get().path("rows");
// Should have 4 nodes returned.
assertEquals("Four nodes not returned from testJoinInner method - multiple order by", 4, jsonBindingsNodes.size());
node = jsonBindingsNodes.path(0);
assertEquals("Row 1 myItem.desc value incorrect", "ball", node.path("myItem.desc").path("value").asText());
assertEquals("Row 1 myColor.colorId value incorrect", "1", node.path("myColor.colorId").path("value").asText());
node = jsonBindingsNodes.path(1);
assertEquals("Row 2 myItem.desc value incorrect", "box", node.path("myItem.desc").path("value").asText());
assertEquals("Row 2 myColor.colorId value incorrect", "1", node.path("myColor.colorId").path("value").asText());
node = jsonBindingsNodes.path(2);
assertEquals("Row 3 myItem.desc value incorrect", "hoop", node.path("myItem.desc").path("value").asText());
assertEquals("Row 3 myColor.colorId value incorrect", "1", node.path("myColor.colorId").path("value").asText());
node = jsonBindingsNodes.path(3);
assertEquals("Row 4 myItem.desc value incorrect", "square", node.path("myItem.desc").path("value").asText());
assertEquals("Row 4 myColor.colorId value incorrect", "2", node.path("myColor.colorId").path("value").asText());
// Test multple inner joins
Map<String, Object>[] literals3 = new HashMap[4];
Map<String, Object> row = new HashMap<>();
row = new HashMap<>();
row.put("color", "red");
row.put("ref", "rose");
literals3[0] = row;
row = new HashMap<>();
row.put("color", "blue");
row.put("ref", "water");
literals3[1] = row;
row = new HashMap<>();
row.put("color", "black");
row.put("ref", "bag");
literals3[2] = row;
row = new HashMap<>();
row.put("color", "yellow");
row.put("ref", "moon");
literals3[3] = row;
ModifyPlan plan7 = p.fromLiterals(literals3, "myRef");
PlanColumn colorDescCol = p.viewCol("myColor", "colorDesc");
PlanColumn refColorCol = p.viewCol("myRef", "color");
PlanColumn refCol = p.viewCol("myRef", "ref");
ModifyPlan outputMultiJoin = plan5.joinInner(plan6, p.on(itemColorIdCol, colorIdCol))
.joinInner(plan7, p.on(colorDescCol, refColorCol))
.select(descCol, colorIdCol, refCol)
.orderBy(p.sortKeySeq(colorIdCol, descCol));
jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(outputMultiJoin, jacksonHandle);
jsonBindingsNodes = jacksonHandle.get().path("rows");
// Should have 4 nodes returned.
assertEquals("Four nodes not returned from testJoinInner method - multiple joins", 4, jsonBindingsNodes.size());
node = jsonBindingsNodes.path(0);
assertEquals("Row 1 myItem.desc value incorrect", "ball", node.path("myItem.desc").path("value").asText());
assertEquals("Row 1 myColor.colorId value incorrect", "1", node.path("myColor.colorId").path("value").asText());
assertEquals("Row 1 myRef.ref value incorrect", "rose", node.path("myRef.ref").path("value").asText());
node = jsonBindingsNodes.path(1);
assertEquals("Row 2 myItem.desc value incorrect", "box", node.path("myItem.desc").path("value").asText());
assertEquals("Row 2 myColor.colorId value incorrect", "1", node.path("myColor.colorId").path("value").asText());
assertEquals("Row 2 myRef.ref value incorrect", "rose", node.path("myRef.ref").path("value").asText());
node = jsonBindingsNodes.path(2);
assertEquals("Row 3 myItem.desc value incorrect", "hoop", node.path("myItem.desc").path("value").asText());
assertEquals("Row 3 myColor.colorId value incorrect", "1", node.path("myColor.colorId").path("value").asText());
assertEquals("Row 3 myRef.ref value incorrect", "rose", node.path("myRef.ref").path("value").asText());
node = jsonBindingsNodes.path(3);
assertEquals("Row 4 myItem.desc value incorrect", "square", node.path("myItem.desc").path("value").asText());
assertEquals("Row 4 myColor.colorId value incorrect", "2", node.path("myColor.colorId").path("value").asText());
assertEquals("Row 4 myRef.ref value incorrect", "water", node.path("myRef.ref").path("value").asText());
}
/*
* Test join left outer
*/
@Test
public void testJoinLeftOuter() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException
{
System.out.println("In testJoinLeftOuter method");
// Create a new Plan.
RowManager rowMgr = client.newRowManager();
PlanBuilder p = rowMgr.newPlanBuilder();
// plans from literals
ModifyPlan plan1 = p.fromLiterals(literals1);
ModifyPlan plan2 = p.fromLiterals(literals2);
ModifyPlan output = plan1.joinLeftOuter(plan2)
.orderBy(p.col("rowId"));
JacksonHandle jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(output, jacksonHandle);
JsonNode jsonBindingsNodes = jacksonHandle.get().path("rows");
// Should have 5 nodes returned.
assertEquals("Five nodes not returned from testJoinLeftOuter method", 5, jsonBindingsNodes.size());
JsonNode node = jsonBindingsNodes.path(0);
assertEquals("Row 1 rowId value incorrect", "1", node.path("rowId").path("value").asText());
assertEquals("Row 1 desc value incorrect", "ball", node.path("desc").path("value").asText());
assertEquals("Row 1 colorDesc value incorrect", "red", node.path("colorDesc").path("value").asText());
node = jsonBindingsNodes.path(3);
assertEquals("Row 4 rowId value incorrect", "4", node.path("rowId").path("value").asText());
assertEquals("Row 4 desc value incorrect", "hoop", node.path("desc").path("value").asText());
assertEquals("Row 4 colorDesc value incorrect", "red", node.path("colorDesc").path("value").asText());
node = jsonBindingsNodes.path(4);
assertEquals("Row 5 rowId value incorrect", "5", node.path("rowId").path("value").asText());
assertEquals("Row 5 desc value incorrect", "circle", node.path("desc").path("value").asText());
assertFalse("Row 5 colorDesc should be null", node.path("colorDesc").isNull());
// To verify issue 1055.
FileHandle fh = new FileHandle();
rowMgr.resultDoc(output, fh);
File file = fh.get();
String fileContents = convertFileToString(file);
ObjectMapper mapper = new ObjectMapper();
JsonNode fromFile = mapper.readTree(file).path("rows");
System.out.println(fileContents);
assertEquals("Five nodes not returned from testJoinLeftOuter method", 5, fromFile.size());
JsonNode nodeFile = fromFile.path(0);
assertEquals("Row 1 rowId value incorrect", "1", nodeFile.path("rowId").path("value").asText());
assertEquals("Row 1 desc value incorrect", "ball", nodeFile.path("desc").path("value").asText());
assertEquals("Row 1 colorDesc value incorrect", "red", nodeFile.path("colorDesc").path("value").asText());
}
/*
* Test group-by max
*/
@Test
public void testGroupByMax() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException
{
System.out.println("In testGroupByMax method");
// Create a new Plan.
RowManager rowMgr = client.newRowManager();
PlanBuilder p = rowMgr.newPlanBuilder();
// plans from literals
ModifyPlan plan1 = p.fromLiterals(literals1);
ModifyPlan output = plan1.groupBy(p.col("colorId"), p.max("new_color_id", "colorId"));
JacksonHandle jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(output, jacksonHandle);
JsonNode jsonBindingsNodes = jacksonHandle.get().path("rows");
// Should have 3 nodes returned.
assertEquals("Three nodes not returned from testJoinLeftOuter method", 3, jsonBindingsNodes.size());
JsonNode node = jsonBindingsNodes.path(0);
assertEquals("Row 1 colorId value incorrect", "1", node.path("colorId").path("value").asText());
assertEquals("Row 1 new_color_id value incorrect", "1", node.path("new_color_id").path("value").asText());
node = jsonBindingsNodes.path(1);
assertEquals("Row 2 colorId value incorrect", "2", node.path("colorId").path("value").asText());
assertEquals("Row 2 new_color_id value incorrect", "2", node.path("new_color_id").path("value").asText());
node = jsonBindingsNodes.path(2);
assertEquals("Row 3 colorId value incorrect", "5", node.path("colorId").path("value").asText());
assertEquals("Row 3 new_color_id value incorrect", "5", node.path("new_color_id").path("value").asText());
}
/*
* Test where limit and select Test limit with 0 length
*/
@Test
public void testOffsetAndLimit() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException
{
System.out.println("In testOffsetAndLimit method");
// Create a new Plan.
RowManager rowMgr = client.newRowManager();
PlanBuilder p = rowMgr.newPlanBuilder();
// plans from literals
ModifyPlan plan1 = p.fromLiterals(literals1);
ModifyPlan plan2 = p.fromLiterals(literals2);
ModifyPlan output = plan1.joinInner(plan2)
.where(p.eq(p.col("colorId"), p.xs.intVal(1)))
.offsetLimit(1, 3)
.select(p.colSeq("rowId", "desc", "colorId", "colorDesc"));
JacksonHandle jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(output, jacksonHandle);
JsonNode jsonBindingsNodes = jacksonHandle.get().path("rows");
// Should have 2 nodes returned.
assertEquals("Two nodes not returned from testOffsetAndLimit method", 2, jsonBindingsNodes.size());
JsonNode node = jsonBindingsNodes.path(0);
assertEquals("Row 1 rowId value incorrect", "3", node.path("rowId").path("value").asText());
assertEquals("Row 1 desc value incorrect", "box", node.path("desc").path("value").asText());
assertEquals("Row 1 colorId value incorrect", "1", node.path("colorId").path("value").asText());
assertEquals("Row 1 colorDesc value incorrect", "red", node.path("colorDesc").path("value").asText());
node = jsonBindingsNodes.path(1);
assertEquals("Row 2 rowId value incorrect", "4", node.path("rowId").path("value").asText());
assertEquals("Row 2 desc value incorrect", "hoop", node.path("desc").path("value").asText());
assertEquals("Row 2 colorId value incorrect", "1", node.path("colorId").path("value").asText());
assertEquals("Row 2 colorDesc value incorrect", "red", node.path("colorDesc").path("value").asText());
// limit with 0 length
ModifyPlan outputLimit = plan1.joinInner(plan2)
.where(p.eq(p.col("colorId"), p.xs.intVal(1)))
.limit(0)
.select(p.colSeq("rowId", "desc", "colorId", "colorDesc"));
jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
StringBuilder str = new StringBuilder();
try {
rowMgr.resultDoc(outputLimit, jacksonHandle);
} catch (Exception ex) {
str.append(ex.getMessage());
System.out.println("Exception message is " + str.toString());
}
// Should have OPTIC-INVALARGS exceptions.
assertTrue("Exceptions not found", str.toString().contains("OPTIC-INVALARGS"));
assertTrue("Exceptions not found", str.toString().contains("Invalid arguments: limit must be a positive number: 0"));
}
/*
* Test arithmetic expression
*/
@Test
public void testArithmeticExpression() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException
{
System.out.println("In testArithmeticExpression method");
// Create a new Plan.
RowManager rowMgr = client.newRowManager();
PlanBuilder p = rowMgr.newPlanBuilder();
// plans from literals
ModifyPlan plan1 = p.fromLiterals(literals1);
ModifyPlan plan2 = p.fromLiterals(literals2);
ModifyPlan output =
plan1.joinInner(plan2)
.select(
p.col("rowId"),
p.col("desc"),
p.col("colorId"),
p.col("colorDesc"),
p.as("added", p.add(p.col("rowId"), p.col("colorId"), p.xs.intVal(10))),
p.as("subtracted", p.subtract(p.col("colorId"), p.col("rowId"))),
p.as("negSubtracted", p.subtract(p.col("colorId"), p.col("rowId"))),
p.as("divided", p.divide(p.col("colorId"), p.col("rowId"))),
p.as("multiplied", p.multiply(p.col("colorId"), p.col("rowId"), p.xs.floatVal(0.6f))),
p.as("colDefined", p.isDefined(p.col("added"))),
p.as("colNotDefined", p.isDefined(p.col("negSubtracted"))),
p.as("colNotDefinedNegate", p.not(p.isDefined(p.col("negSubtracted")))),
p.as("caseExpr",
p.caseExpr(
p.when(p.eq(p.col("rowId"), p.xs.intVal(1)), p.xs.string("foo")),
p.when(p.eq(p.col("rowId"), p.xs.intVal(2)), p.xs.string("baz")),
p.when(p.eq(p.col("rowId"), p.xs.intVal(3)), p.xs.string("rat")),
p.elseExpr(p.xs.string("bar"))
)
)
)
.orderBy(p.sortKeySeq(p.col("rowId")));
JacksonHandle jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(output, jacksonHandle);
JsonNode jsonBindingsNodes = jacksonHandle.get().path("rows");
// Should have 4 nodes returned.
assertEquals("Four nodes not returned from testArithmeticExpression method", 4, jsonBindingsNodes.size());
JsonNode node = jsonBindingsNodes.path(0);
assertEquals("Row 1 rowId value incorrect", "1", node.path("rowId").path("value").asText());
assertEquals("Row 1 colorDesc value incorrect", "red", node.path("colorDesc").path("value").asText());
assertEquals("Row 1 added value incorrect", "12", node.path("added").path("value").asText());
assertEquals("Row 1 subtracted value incorrect", "0", node.path("subtracted").path("value").asText());
assertEquals("Row 1 divided value incorrect", "1", node.path("divided").path("value").asText());
assertEquals("Row 1 multiplied value incorrect", "0.600000023841858", node.path("multiplied").path("value").asText());
assertEquals("Row 1 caseExpr value incorrect", "foo", node.path("caseExpr").path("value").asText());
node = jsonBindingsNodes.path(1);
assertEquals("Row 2 caseExpr value incorrect", "baz", node.path("caseExpr").path("value").asText());
node = jsonBindingsNodes.path(2);
assertEquals("Row 3 caseExpr value incorrect", "rat", node.path("caseExpr").path("value").asText());
node = jsonBindingsNodes.path(3);
assertEquals("Row 4 rowId value incorrect", "4", node.path("rowId").path("value").asText());
assertEquals("Row 4 colorDesc value incorrect", "red", node.path("colorDesc").path("value").asText());
assertEquals("Row 4 added value incorrect", "15", node.path("added").path("value").asText());
assertEquals("Row 4 subtracted value incorrect", "-3", node.path("subtracted").path("value").asText());
assertEquals("Row 4 divided value incorrect", "0.25", node.path("divided").path("value").asText());
assertEquals("Row 4 multiplied value incorrect", "2.400000095367432", node.path("multiplied").path("value").asText());
assertEquals("Row 4 caseExpr value incorrect", "bar", node.path("caseExpr").path("value").asText());
}
/*
* Test join inner doc on json and xml documents
*/
@Test
public void testJoinInnerDocOnJson() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException
{
System.out.println("In testJoinInnerDocOnJson method");
// Create a new Plan.
RowManager rowMgr = client.newRowManager();
PlanBuilder p = rowMgr.newPlanBuilder();
Map<String, Object>[] literals3 = new HashMap[4];
Map<String, Object> row = new HashMap<>();
row.put("id", 1);
row.put("val", 2);
row.put("uri", "/optic/lexicon/test/doc1.json");
literals3[0] = row;
row = new HashMap<>();
row.put("id", 2);
row.put("val", 4);
row.put("uri", "/optic/test/not/a/real/doc.nada");
literals3[1] = row;
row = new HashMap<>();
row.put("id", 3);
row.put("val", 6);
row.put("uri", "/optic/lexicon/test/doc3.json");
literals3[2] = row;
row = new HashMap<>();
row.put("id", 4);
row.put("val", 8);
row.put("uri", "/optic/lexicon/test/doc4.xml");
literals3[3] = row;
// TEST 16 - join inner doc with xpath traversing down and multiple values
// on json
ModifyPlan output = p.fromLiterals(literals3)
.joinDoc(p.col("doc"), p.col("uri"))
.select(
p.col("id"),
p.col("val"),
p.col("uri"),
p.as("nodes", p.xpath("doc", "/location/latLonPair/(lat|long)")))
.where(p.isDefined(p.col("nodes")))
.orderBy(p.asc("id"));
JacksonHandle jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(output, jacksonHandle);
JsonNode jsonBindingsNodes = jacksonHandle.get().path("rows");
// Should have 2 nodes returned.
assertEquals("Two nodes not returned from testJoinInnerDocOnJson method", 2, jsonBindingsNodes.size());
JsonNode node = jsonBindingsNodes.path(0);
assertEquals("Row 1 id value incorrect", "1", node.path("id").path("value").asText());
assertEquals("Row 1 val value incorrect", "2", node.path("val").path("value").asText());
assertEquals("Row 1 uri value incorrect", "/optic/lexicon/test/doc1.json", node.path("uri").path("value").asText());
node = jsonBindingsNodes.path(1);
assertEquals("Row 2 id value incorrect", "3", node.path("id").path("value").asText());
assertEquals("Row 2 val value incorrect", "6", node.path("val").path("value").asText());
assertEquals("Row 2 uri value incorrect", "/optic/lexicon/test/doc3.json", node.path("uri").path("value").asText());
// Verify TEST 17 - join inner doc with xpath accessing attribute on xml
ModifyPlan output17 = p.fromLiterals(literals3)
.joinDoc(p.col("doc"), p.col("uri"))
.select(
p.col("id"),
p.col("val"),
p.col("uri"),
p.as("nodes", p.xpath("doc", "/doc/distance/@direction")))
.where(p.isDefined(p.col("nodes")))
.orderBy(p.asc("id"));
JacksonHandle jacksonHandle17 = new JacksonHandle();
jacksonHandle17.setMimetype("application/json");
rowMgr.resultDoc(output17, jacksonHandle17);
JsonNode jsonBindingsNodes17 = jacksonHandle17.get().path("rows");
// Should have 1 node returned.
assertEquals("One node not returned from testJoinInnerDocOnJson method", 1, jsonBindingsNodes17.size());
JsonNode node17 = jsonBindingsNodes17.path(0);
assertEquals("Row 1 id value incorrect", "4", node17.path("id").path("value").asText());
assertEquals("Row 1 val value incorrect", "8", node17.path("val").path("value").asText());
assertEquals("Row 1 uri value incorrect", "/optic/lexicon/test/doc4.xml", node17.path("uri").path("value").asText());
assertEquals("Row 1 nodes value incorrect", "east", node17.path("nodes").path("value").asText());
// Verify TEST 18 - join inner doc with xpath traversing down and multiple
// values on xml
ModifyPlan output18 = p.fromLiterals(literals3)
.joinDoc(p.col("doc"), p.col("uri"))
.select(
p.col("id"),
p.col("val"),
p.col("uri"),
p.as("nodes", p.xpath("doc", "/doc/location/latLonPair/(lat|long)/text()")))
.where(p.isDefined(p.col("nodes")))
.orderBy(p.asc("id"));
JacksonHandle jacksonHandle18 = new JacksonHandle();
jacksonHandle18.setMimetype("application/json");
rowMgr.resultDoc(output18, jacksonHandle18);
JsonNode jsonBindingsNodes18 = jacksonHandle18.get().path("rows");
// Should have 1 node returned.
assertEquals("One node not returned from testJoinInnerDocOnJson method", 1, jsonBindingsNodes18.size());
JsonNode node18 = jsonBindingsNodes18.path(0);
assertEquals("Row 1 id value incorrect", "4", node18.path("id").path("value").asText());
assertEquals("Row 1 val value incorrect", "8", node18.path("val").path("value").asText());
assertEquals("Row 1 uri value incorrect", "/optic/lexicon/test/doc4.xml", node18.path("uri").path("value").asText());
assertEquals("Row 1 nodes value incorrect", "39.90", node18.path("nodes").path("value").get(0).asText());
assertEquals("Row 1 nodes value incorrect", "116.40", node18.path("nodes").path("value").get(1).asText());
// Verify TEST 19 - join inner doc with traversing up xpath on json
ModifyPlan output19 = p.fromLiterals(literals3)
.joinDoc(p.col("doc"), p.col("uri"))
.select(
p.col("id"),
p.col("val"),
p.col("uri"),
p.as("nodes", p.fn.string(p.xpath("doc", "//city"))))
.where(p.isDefined(p.col("nodes")))
.orderBy(p.asc("id"));
JacksonHandle jacksonHandle19 = new JacksonHandle();
jacksonHandle19.setMimetype("application/json");
rowMgr.resultDoc(output19, jacksonHandle19);
JsonNode jsonBindingsNodes19 = jacksonHandle19.get().path("rows");
// Should have 3 nodes returned.
assertEquals("Three nodes not returned from testJoinInnerDocOnJson method", 3, jsonBindingsNodes19.size());
JsonNode node19 = jsonBindingsNodes19.path(0);
assertEquals("Row 1 id value incorrect", "1", node19.path("id").path("value").asText());
assertEquals("Row 1 val value incorrect", "2", node19.path("val").path("value").asText());
assertEquals("Row 1 uri value incorrect", "/optic/lexicon/test/doc1.json", node19.path("uri").path("value").asText());
assertEquals("Row 1 nodes value incorrect", "london", node19.path("nodes").path("value").asText());
node19 = jsonBindingsNodes19.path(1);
assertEquals("Row 2 id value incorrect", "3", node19.path("id").path("value").asText());
assertEquals("Row 2 val value incorrect", "6", node19.path("val").path("value").asText());
assertEquals("Row 2 uri value incorrect", "/optic/lexicon/test/doc3.json", node19.path("uri").path("value").asText());
assertEquals("Row 2 nodes value incorrect", "new jersey", node19.path("nodes").path("value").asText());
node19 = jsonBindingsNodes19.path(2);
assertEquals("Row 2 id value incorrect", "4", node19.path("id").path("value").asText());
assertEquals("Row 2 val value incorrect", "8", node19.path("val").path("value").asText());
assertEquals("Row 2 uri value incorrect", "/optic/lexicon/test/doc4.xml", node19.path("uri").path("value").asText());
assertEquals("Row 2 nodes value incorrect", "beijing", node19.path("nodes").path("value").asText());
// Verify TEST 15 - join inner doc with xpath accessing attribute on xml
ModifyPlan output15 = p.fromLiterals(literals3)
.joinDoc(p.col("doc"), p.col("uri"))
.select(
p.col("id"),
p.col("val"),
p.col("uri"),
p.as("nodes", p.xpath("doc", "/doc/city")))
.where(p.isDefined(p.col("nodes")))
.orderBy(p.asc("id"));
JacksonHandle jacksonHandle15 = new JacksonHandle();
jacksonHandle15.setMimetype("application/json");
rowMgr.resultDoc(output15, jacksonHandle15);
JsonNode jsonBindingsNodes15 = jacksonHandle15.get().path("rows");
// Should have 1 node returned.
assertEquals("One node not returned from testJoinInnerDocOnJson method", 1, jsonBindingsNodes15.size());
JsonNode node20 = jsonBindingsNodes15.path(0);
assertEquals("Row 1 id value incorrect", "4", node20.path("id").path("value").asText());
assertEquals("Row 1 val value incorrect", "8", node20.path("val").path("value").asText());
assertEquals("Row 1 uri value incorrect", "/optic/lexicon/test/doc4.xml", node20.path("uri").path("value").asText());
assertEquals("Row 1 nodes value incorrect", "<city>beijing</city>", node20.path("nodes").path("value").asText());
// Verify TEST 21 - join inner doc with traversing deep xpath on json and
// xml
ModifyPlan output21 = p.fromLiterals(literals3)
.joinDoc(p.col("doc"), p.col("uri"))
.select(
p.col("id"),
p.col("val"),
p.col("uri"),
p.as("nodes", p.fn.number(p.xpath("doc", "//lat"))))
.where(p.isDefined(p.col("nodes")))
.orderBy(p.asc("id"));
JacksonHandle jacksonHandle21 = new JacksonHandle();
jacksonHandle21.setMimetype("application/json");
rowMgr.resultDoc(output21, jacksonHandle21);
JsonNode jsonBindingsNodes21 = jacksonHandle21.get().path("rows");
// Should have 3 nodes returned.
assertEquals("Three nodes not returned from testJoinInnerDocOnJson method", 3, jsonBindingsNodes21.size());
JsonNode node21 = jsonBindingsNodes21.path(0);
assertEquals("Row 1 id value incorrect", "1", node21.path("id").path("value").asText());
assertEquals("Row 1 val value incorrect", "2", node21.path("val").path("value").asText());
assertEquals("Row 1 uri value incorrect", "/optic/lexicon/test/doc1.json", node21.path("uri").path("value").asText());
assertEquals("Row 1 nodes value incorrect", "51.5", node21.path("nodes").path("value").asText());
node21 = jsonBindingsNodes21.path(1);
assertEquals("Row 1 id value incorrect", "3", node21.path("id").path("value").asText());
assertEquals("Row 1 val value incorrect", "6", node21.path("val").path("value").asText());
assertEquals("Row 1 uri value incorrect", "/optic/lexicon/test/doc3.json", node21.path("uri").path("value").asText());
assertEquals("Row 1 nodes value incorrect", "40.72", node21.path("nodes").path("value").asText());
node21 = jsonBindingsNodes21.path(2);
assertEquals("Row 1 id value incorrect", "4", node21.path("id").path("value").asText());
assertEquals("Row 1 val value incorrect", "8", node21.path("val").path("value").asText());
assertEquals("Row 1 uri value incorrect", "/optic/lexicon/test/doc4.xml", node21.path("uri").path("value").asText());
assertEquals("Row 1 nodes value incorrect", "39.9", node21.path("nodes").path("value").asText());
}
/*
* Test group-by without aggregate
*/
@Test
public void testGroupbyWithoutAggregate() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException
{
System.out.println("In testGroupbyWithoutAggregate method");
// Create a new Plan.
RowManager rowMgr = client.newRowManager();
PlanBuilder p = rowMgr.newPlanBuilder();
// plans from literals
ModifyPlan plan1 = p.fromLiterals(literals1);
ModifyPlan output = plan1.groupBy(p.col("colorId")).orderBy(p.col("colorId"));
JacksonHandle jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(output, jacksonHandle);
JsonNode jsonBindingsNodes = jacksonHandle.get().path("rows");
// Should have 3 nodes returned.
assertEquals("Three nodes not returned from testGroupbyWithoutAggregate method", 3, jsonBindingsNodes.size());
assertEquals("Row 1 colorId value incorrect", "1", jsonBindingsNodes.path(0).path("colorId").path("value").asText());
assertEquals("Row 2 colorId value incorrect", "2", jsonBindingsNodes.path(1).path("colorId").path("value").asText());
assertEquals("Row 3 colorId value incorrect", "5", jsonBindingsNodes.path(2).path("colorId").path("value").asText());
}
/*
* Test union with whereDistinct
*/
@Test
public void testUnionWithWhereDistinct() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException
{
System.out.println("In testUnionWithWhereDistinct method");
// Create a new Plan.
RowManager rowMgr = client.newRowManager();
PlanBuilder p = rowMgr.newPlanBuilder();
// plans from literals
ModifyPlan plan1 = p.fromLiterals(literals1);
ModifyPlan plan2 = p.fromLiterals(literals2);
ModifyPlan output = plan1.union(plan2).whereDistinct().orderBy(p.sortKeySeq(p.col("rowId"), p.col("colorId")));
JacksonHandle jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(output, jacksonHandle);
JsonNode jsonBindingsNodes = jacksonHandle.get().path("rows");
// Should have 9 nodes returned.
assertEquals("Nine nodes not returned from testUnionWithWhereDistinct method", 9, jsonBindingsNodes.size());
assertEquals("Row 1 colorId value incorrect", "1", jsonBindingsNodes.path(0).path("colorId").path("value").asText());
assertEquals("Row 1 colorDesc value incorrect", "null", jsonBindingsNodes.path(0).path("colorDesc").path("value").asText());
assertEquals("Row 2 colorId value incorrect", "2", jsonBindingsNodes.path(1).path("colorId").path("value").asText());
assertEquals("Row 2 colorDesc value incorrect", "null", jsonBindingsNodes.path(1).path("colorDesc").path("value").asText());
assertEquals("Row 6 desc value incorrect", "null", jsonBindingsNodes.path(5).path("desc").path("value").asText());
assertEquals("Row 6 rowId value incorrect", "null", jsonBindingsNodes.path(5).path("rowId").path("value").asText());
assertEquals("Row 9 desc value incorrect", "null", jsonBindingsNodes.path(8).path("desc").path("value").asText());
assertEquals("Row 9 colorId value incorrect", "4", jsonBindingsNodes.path(8).path("colorId").path("value").asText());
}
/*
* Test intersect
*/
@Test
public void testIntersect() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException
{
System.out.println("In testIntersect method");
// Create a new Plan.
RowManager rowMgr = client.newRowManager();
PlanBuilder p = rowMgr.newPlanBuilder();
// plans from literals
ModifyPlan plan1 = p.fromLiterals(storeInformation);
ModifyPlan plan2 = p.fromLiterals(internetSales);
ModifyPlan output = plan1.select(p.col("txnDate"))
.intersect(plan2.select(p.col("txnDate")));
JacksonHandle jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(output, jacksonHandle);
JsonNode jsonBindingsNodes = jacksonHandle.get().path("rows");
// Should have 1 node returned.
assertEquals("One node not returned from testIntersect method", 1, jsonBindingsNodes.size());
assertEquals("Row 1 txnDate value incorrect", "Jan-07-1999", jsonBindingsNodes.path(0).path("txnDate").path("value").asText());
}
/*
* Test except
*/
@Test
public void testExcept() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException
{
System.out.println("In testExcept method");
// Create a new Plan.
RowManager rowMgr = client.newRowManager();
PlanBuilder p = rowMgr.newPlanBuilder();
// plans from literals
ModifyPlan plan1 = p.fromLiterals(storeInformation);
ModifyPlan plan2 = p.fromLiterals(internetSales);
ModifyPlan output = plan1.select(p.colSeq("txnDate"))
.except(plan2.select(p.colSeq("txnDate")));
JacksonHandle jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(output, jacksonHandle);
JsonNode jsonBindingsNodes = jacksonHandle.get().path("rows");
// Should have 3 nodes returned.
assertEquals("Three nodes not returned from testExcept method", 3, jsonBindingsNodes.size());
assertEquals("Row 1 txnDate value incorrect", "Jan-05-1999", jsonBindingsNodes.path(0).path("txnDate").path("value").asText());
assertEquals("Row 2 txnDate value incorrect", "Jan-08-1999", jsonBindingsNodes.path(1).path("txnDate").path("value").asText());
assertEquals("Row 3 txnDate value incorrect", "Jan-08-1999", jsonBindingsNodes.path(2).path("txnDate").path("value").asText());
}
/*
* Test arrayAggregate, sequenceAggregate and aggregate with distinct and
* duplicate options
*/
@Test
public void testAggregateSeq() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException
{
System.out.println("In testAggregateSeq method");
RowManager rowMgr = client.newRowManager();
PlanBuilder p = rowMgr.newPlanBuilder();
// Create a new Map for literals.
Map<String, Object> row = new HashMap<>();
Map<String, Object>[] fooLiteral = new HashMap[6];
Map<String, Object>[] purpleLiteral = new HashMap[6];
Map<String, Object>[] ballLiteral = new HashMap[6];
row.put("rowId", 1);
row.put("colorId", 1);
row.put("desc", "ball");
fooLiteral[0] = row;
row = new HashMap<>();
row.put("rowId", 1);
row.put("colorId", 3);
row.put("desc", "foo");
fooLiteral[1] = row;
row = new HashMap<>();
row.put("rowId", 2);
row.put("colorId", 2);
row.put("desc", "square");
fooLiteral[2] = row;
row = new HashMap<>();
row.put("rowId", 3);
row.put("colorId", 1);
row.put("desc", "box");
fooLiteral[3] = row;
row = new HashMap<>();
row.put("rowId", 4);
row.put("colorId", 1);
row.put("desc", "hoop");
fooLiteral[4] = row;
row = new HashMap<>();
row.put("rowId", 5);
row.put("colorId", 5);
row.put("desc", "circle");
fooLiteral[5] = row;
row = new HashMap<>();
row.put("colorId", 1);
row.put("colorDesc", "red");
purpleLiteral[0] = row;
// Add another red color
purpleLiteral[1] = row;
row = new HashMap<>();
row.put("colorId", 1);
row.put("colorDesc", "purple");
purpleLiteral[2] = row;
row = new HashMap<>();
row.put("colorId", 2);
row.put("colorDesc", "blue");
purpleLiteral[3] = row;
row = new HashMap<>();
row.put("colorId", 3);
row.put("colorDesc", "black");
purpleLiteral[4] = row;
row = new HashMap<>();
row.put("colorId", 4);
row.put("colorDesc", "yellow");
purpleLiteral[5] = row;
row = new HashMap<>();
row.put("rowId", 1);
row.put("colorId", 1);
row.put("desc", "ball");
ballLiteral[0] = row;
row = new HashMap<>();
row.put("rowId", 1);
row.put("colorId", 3);
row.put("desc", "ball");
ballLiteral[1] = row;
row = new HashMap<>();
row.put("rowId", 2);
row.put("colorId", 2);
row.put("desc", "square");
ballLiteral[2] = row;
row = new HashMap<>();
row.put("rowId", 3);
row.put("colorId", 1);
row.put("desc", "box");
ballLiteral[3] = row;
row = new HashMap<>();
row.put("rowId", 4);
row.put("colorId", 1);
row.put("desc", "hoop");
ballLiteral[4] = row;
row = new HashMap<>();
row.put("rowId", 5);
row.put("colorId", 5);
row.put("desc", "circle");
ballLiteral[5] = row;
// plans from literals
ModifyPlan plan1 = p.fromLiterals(fooLiteral, "myItem");
ModifyPlan plan2 = p.fromLiterals(purpleLiteral, "myColor");
PlanColumn rowIdExp = p.viewCol("myItem", "rowId");
PlanColumn itemColorIdCol = p.viewCol("myItem", "colorId");
PlanColumn colorIdCol = p.viewCol("myColor", "colorId");
ModifyPlan outputAgg = plan1.joinInner(plan2, p.on(itemColorIdCol, colorIdCol))
.groupBy(rowIdExp, p.arrayAggregate("colorIdArray", "colorDesc"))
.orderBy(p.sortKeySeq(p.col("rowId")));
JacksonHandle jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(outputAgg, jacksonHandle);
JsonNode jsonBindingsNodes = jacksonHandle.get().path("rows");
// Should have 4 nodes returned.
assertEquals("Four nodes not returned from testAggregateSeq method", 4, jsonBindingsNodes.size());
assertEquals("Row 1 myItem.rowId value incorrect", "1", jsonBindingsNodes.path(0).path("myItem.rowId").path("value").asText());
assertEquals("Row 1 colorIdArray length value incorrect", 4, jsonBindingsNodes.path(0).path("colorIdArray").path("value").size());
assertEquals("Row 2 colorIdArray array 1 value incorrect", "blue", jsonBindingsNodes.path(1).path("colorIdArray").path("value").path(0).asText());
// sequenceAggregate
ModifyPlan outputSeqAgg = plan1.joinInner(plan2, p.on(itemColorIdCol, colorIdCol))
.groupBy(rowIdExp, p.sequenceAggregate("colorIdArray", "colorDesc"))
.orderBy(p.sortKeySeq(p.col("rowId")));
jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(outputSeqAgg, jacksonHandle);
jsonBindingsNodes = jacksonHandle.get().path("rows");
// Should have 4 nodes returned.
assertEquals("Four nodes not returned from testAggregateSeq method", 4, jsonBindingsNodes.size());
assertEquals("Row 1 myItem.rowId value incorrect", "1", jsonBindingsNodes.path(0).path("myItem.rowId").path("value").asText());
assertEquals("Row 1 colorIdArray length value incorrect", 4, jsonBindingsNodes.path(0).path("colorIdArray").path("value").size());
assertEquals("Row 2 colorIdArray array 1 value incorrect", "blue", jsonBindingsNodes.path(1).path("colorIdArray").path("value").asText());
// TEST 37 - aggregate with distinct option
// plans from literals
ModifyPlan plan3 = p.fromLiterals(ballLiteral);
ModifyPlan plan4 = p.fromLiterals(literals2);
// Verify DISTINCT
PlanAggregateColSeq aggColSeq = p.aggregateSeq(p.count("descAgg", "desc", PlanValueOption.DISTINCT));
PlanExprColSeq colSeq = p.colSeq("rowId");
ModifyPlan outputCountDist = plan3.joinInner(plan4)
.groupBy(colSeq, aggColSeq)
.orderBy(p.sortKeySeq(p.col("rowId")));
jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(outputCountDist, jacksonHandle);
jsonBindingsNodes = jacksonHandle.get().path("rows");
// Should have 4 nodes returned.
assertEquals("Four node not returned from testAggregateSeq method", 4, jsonBindingsNodes.size());
assertEquals("Row 1 rowId value incorrect", "1", jsonBindingsNodes.path(0).path("rowId").path("value").asText());
assertEquals("Row 1 descAgg value incorrect", 1, jsonBindingsNodes.path(0).path("descAgg").path("value").asInt());
assertEquals("Row 1 rowId value incorrect", "4", jsonBindingsNodes.path(3).path("rowId").path("value").asText());
assertEquals("Row 1 descAgg value incorrect", 1, jsonBindingsNodes.path(3).path("descAgg").path("value").asInt());
// aggregate with duplicate option
PlanAggregateColSeq aggColSeqDup = p.aggregateSeq(p.count("descAgg", "desc", PlanValueOption.DUPLICATE));
PlanExprColSeq colSeqDup = p.colSeq("rowId");
ModifyPlan outputCountDup = plan3.joinInner(plan4)
.groupBy(colSeqDup, aggColSeqDup)
.orderBy(p.sortKeySeq(p.col("rowId")));
jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(outputCountDup, jacksonHandle);
JsonNode jsonBindingsNodesDup = jacksonHandle.get().path("rows");
// Should have 4 nodes returned. Duplicate values are included.
assertEquals("Four node not returned from testAggregateSeq method", 4, jsonBindingsNodesDup.size());
assertEquals("Row 1 rowId value incorrect", "1", jsonBindingsNodesDup.path(0).path("rowId").path("value").asText());
assertEquals("Row 1 descAgg value incorrect", 2, jsonBindingsNodesDup.path(0).path("descAgg").path("value").asInt());
assertEquals("Row 1 rowId value incorrect", "4", jsonBindingsNodesDup.path(3).path("rowId").path("value").asText());
assertEquals("Row 1 descAgg value incorrect", 1, jsonBindingsNodesDup.path(3).path("descAgg").path("value").asInt());
}
/*
* Test date time builtin functions
*/
@Ignore
public void testBuiltInFns() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException
{
System.out.println("In testBuiltInFns method");
// Create a new Plan.
RowManager rowMgr = client.newRowManager();
PlanBuilder p = rowMgr.newPlanBuilder();
// plans from literals
ModifyPlan plan1 = p.fromLiterals(literals1, "myItem");
ModifyPlan plan2 = p.fromLiterals(literals2, "myColor");
PlanColumn descCol = p.viewCol("myItem", "desc");
PlanColumn itemColorIdCol = p.viewCol("myItem", "colorId");
PlanColumn colorIdCol = p.viewCol("myColor", "colorId");
/*
* XsDateExpr curDate = p.fn.currentDate(); XsTimeExpr curTime =
* p.fn.currentTime(); SqlGenericDateTimeExpr sqlcurTime =
* (SqlGenericDateTimeExpr) curTime; double sqlHr = p.sql.hours(sqlcurTime);
*
* PlanColumn log10 = p.math.log10(sqlHr); ModifyPlan output =
* plan1.joinInner(plan2, p.on(itemColorIdCol, colorIdCol)) .select(
* p.as("currentDate", p.fn.currentDate()), p.as("curDate", curDate),
* p.as("currentTime", p.fn.currentTime()), p.as("curTime", curTime),
* p.as("upperCase", p.fn.upperCase(p.col("desc"))), p.as("semNum",
* p.sem.isLiteral(p.col("desc"))), p.as("sqlHours",
* p.sql.hours(sqlcurTime)), p.as("sqlHr", sqlHr), p.as("mathLog10",
* p.math.log10(p.col("sqlHours"))), p.as("log10", log10) )
* .orderBy(p.col("upperCase"));
*/
// TODO Wait until Erik H comes back on this to discuss the recent changes
// to SQL types.
JacksonHandle jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
// rowMgr.resultDoc(output, jacksonHandle);
JsonNode jsonBindingsNodes = jacksonHandle.get().path("rows");
// Should have 2 nodes returned.
assertEquals("Two nodes not returned from testExcept method", 3, jsonBindingsNodes.size());
}
/*
* Test invalid rowdef
*/
@Test
public void testInvalidDefinitions() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException
{
System.out.println("In testInvalidDefinitions method");
// Create a new Plan.
RowManager rowMgr = client.newRowManager();
PlanBuilder p = rowMgr.newPlanBuilder();
// plans from literals
ModifyPlan plan1 = p.fromLiterals(literals1);
ModifyPlan plan2 = p.fromLiterals(literals2);
ModifyPlan output = plan1.joinInner(plan2)
.where(p.eq(p.col("colorId"), p.xs.intVal(1)))
.select(p.colSeq("rowIdRef", "desc", "colorId", "colorDesc"));
JacksonHandle jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
StringBuilder str = new StringBuilder();
try {
rowMgr.resultDoc(output, jacksonHandle);
} catch (Exception ex) {
str.append(ex.getMessage());
System.out.println("Exception message is " + str.toString());
}
// Should have SQL-NOCOLUMN exceptions.
assertTrue("Exceptions not found", str.toString().contains("SQL-NOCOLUMN"));
assertTrue("Exceptions not found", str.toString().contains("Column not found: rowIdRef"));
// invalid viewCol
ModifyPlan outputExtCol = plan1.joinInner(plan2)
.where(p.eq(p.viewCol("invalid_view", "colorId"), p.xs.intVal(1)))
.offsetLimit(1, 3);
str = new StringBuilder();
try {
rowMgr.resultDoc(outputExtCol, jacksonHandle);
} catch (Exception ex) {
str.append(ex.getMessage());
System.out.println("Exception message is " + str.toString());
}
// Should have SQL-NOCOLUMN exceptions.
assertTrue("Exceptions not found", str.toString().contains("SQL-NOCOLUMN"));
assertTrue("Exceptions not found", str.toString().contains("Column not found: invalid_view.colorId"));
}
/*
* Test offsetLimit with negative offset
*/
@Test
public void testNegativeOffset() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException
{
System.out.println("In testNegativeOffset method");
// Create a new Plan.
RowManager rowMgr = client.newRowManager();
PlanBuilder p = rowMgr.newPlanBuilder();
// plans from literals
ModifyPlan plan1 = p.fromLiterals(literals1);
ModifyPlan plan2 = p.fromLiterals(literals2);
ModifyPlan output = plan1.joinInner(plan2)
.where(p.eq(p.col("colorId"), p.xs.intVal(1)))
.offsetLimit(-1, 1)
.select(p.colSeq("rowId", "desc", "colorId", "colorDesc"));
JacksonHandle jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
StringBuilder str = new StringBuilder();
try {
rowMgr.resultDoc(output, jacksonHandle);
} catch (Exception ex) {
str.append(ex.getMessage());
System.out.println("Exception message is " + str.toString());
}
// Should have OPTIC-INVALARGS exceptions.
assertTrue("Exceptions not found", str.toString().contains("OPTIC-INVALARGS"));
assertTrue("Exceptions not found", str.toString().contains("Invalid arguments: offset must be a non-negative number: -1"));
}
/*
* Test invalid qualifier
*/
@Test
public void testInvalidQualifier() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException
{
System.out.println("In testInvalidQualifier method");
// Create a new Plan.
RowManager rowMgr = client.newRowManager();
PlanBuilder p = rowMgr.newPlanBuilder();
// plans from literals
ModifyPlan plan1 = p.fromLiterals(literals1, "table1");
ModifyPlan plan2 = p.fromLiterals(literals2, "table2");
ModifyPlan output = plan1.joinInner(plan2)
.where(p.eq(p.viewCol("table1_Invalid", "colorId"), p.viewCol("table2", "colorId")))
.orderBy(p.desc(p.viewCol("table1", "rowId")));
JacksonHandle jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
StringBuilder str = new StringBuilder();
try {
rowMgr.resultDoc(output, jacksonHandle);
} catch (Exception ex) {
str.append(ex.getMessage());
System.out.println("Exception message is " + str.toString());
}
// Should have OPTIC-INVALARGS exceptions.
assertTrue("Exceptions not found", str.toString().contains("SQL-NOCOLUMN"));
assertTrue("Exceptions not found", str.toString().contains("Column not found: table1_Invalid.colorId"));
}
/*
* Test Map function Uses JS function colorIdMapper installed in the REST
* server module database.
*/
@Test
public void testMapFunction() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException
{
System.out.println("In testMapFunction method");
Map<String, Object>[] literalsM1 = new HashMap[5];
Map<String, Object>[] literalsM2 = new HashMap[4];
Map<String, Object> row = new HashMap<>();
row.put("rowId", 1);
row.put("colorId_shape", 1);
row.put("desc", "ball");
literalsM1[0] = row;
row = new HashMap<>();
row.put("rowId", 2);
row.put("colorId_shape", 2);
row.put("desc", "square");
literalsM1[1] = row;
row = new HashMap<>();
row.put("rowId", 3);
row.put("colorId_shape", 1);
row.put("desc", "box");
literalsM1[2] = row;
row = new HashMap<>();
row.put("rowId", 4);
row.put("colorId_shape", 1);
row.put("desc", "hoop");
literalsM1[3] = row;
row = new HashMap<>();
row.put("rowId", 5);
row.put("colorId_shape", 5);
row.put("desc", "circle");
literalsM1[4] = row;
// Assemble literalsM2
row = new HashMap<>();
row.put("colorId", 1);
row.put("colorDesc", "red");
literalsM2[0] = row;
row = new HashMap<>();
row.put("colorId", 2);
row.put("colorDesc", "blue");
literalsM2[1] = row;
row = new HashMap<>();
row.put("colorId", 3);
row.put("colorDesc", "black");
literalsM2[2] = row;
row = new HashMap<>();
row.put("colorId", 4);
row.put("colorDesc", "yellow");
literalsM2[3] = row;
RowManager rowMgr = client.newRowManager();
PlanBuilder p = rowMgr.newPlanBuilder();
// plans from literals
ModifyPlan plan1 = p.fromLiterals(literalsM1);
ModifyPlan plan2 = p.fromLiterals(literalsM2);
ExportablePlan output = plan1.joinInner(plan2, p.on(p.col("colorId_shape"), p.col("colorId")))
.select(
p.as("rowId", p.col("rowId")),
p.as("description", p.col("desc")),
p.as("myColorId", p.col("colorId"))
)
.orderBy(p.asc("rowId"))
.map(p.resolveFunction(p.xs.QName("colorIdMapper"), "/marklogic.rest.resource/OpticsJSResourceModule/assets/resource.sjs"));
JacksonHandle jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(output, jacksonHandle);
JsonNode jsonBindingsNodes = jacksonHandle.get().path("rows");
// Should have 4 node returned.
assertEquals("Four nodes not returned from testMapFunction method", 4, jsonBindingsNodes.size());
assertEquals("Row 1 rowId value incorrect", "1", jsonBindingsNodes.path(0).path("rowId").path("value").asText());
assertEquals("Row 1 myColorId value incorrect", "RED ROBIN", jsonBindingsNodes.path(0).path("myColorId").path("value").asText());
assertEquals("Row 1 description value incorrect", "ball", jsonBindingsNodes.path(0).path("description").path("value").asText());
assertEquals("Row 2 rowId value incorrect", "2", jsonBindingsNodes.path(1).path("rowId").path("value").asText());
assertEquals("Row 2 myColorId value incorrect", "BLUE JAY", jsonBindingsNodes.path(1).path("myColorId").path("value").asText());
assertEquals("Row 2 description value incorrect", "square", jsonBindingsNodes.path(1).path("description").path("value").asText());
assertEquals("Row 3 rowId value incorrect", "4", jsonBindingsNodes.path(3).path("rowId").path("value").asText());
assertEquals("Row 3 myColorId value incorrect", "RED ROBIN", jsonBindingsNodes.path(3).path("myColorId").path("value").asText());
assertEquals("Row 3 description value incorrect", "hoop", jsonBindingsNodes.path(3).path("description").path("value").asText());
}
/*
* Test Reduce function Uses JS function fibReducer installed in the REST
* server module database.
*/
@Test
public void testReduceFunction() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException
{
System.out.println("In testReduceFunction method");
Map<String, Object>[] literalsM1 = new HashMap[5];
Map<String, Object>[] literalsM2 = new HashMap[4];
Map<String, Object> row = new HashMap<>();
row.put("rowId", 1);
row.put("colorId_shape", 1);
row.put("desc", "ball");
literalsM1[0] = row;
row = new HashMap<>();
row.put("rowId", 2);
row.put("colorId_shape", 2);
row.put("desc", "square");
literalsM1[1] = row;
row = new HashMap<>();
row.put("rowId", 3);
row.put("colorId_shape", 1);
row.put("desc", "box");
literalsM1[2] = row;
row = new HashMap<>();
row.put("rowId", 4);
row.put("colorId_shape", 1);
row.put("desc", "hoop");
literalsM1[3] = row;
row = new HashMap<>();
row.put("rowId", 5);
row.put("colorId_shape", 5);
row.put("desc", "circle");
literalsM1[4] = row;
// Assemble literalsM2
row = new HashMap<>();
row.put("colorId", 1);
row.put("colorDesc", "red");
literalsM2[0] = row;
row = new HashMap<>();
row.put("colorId", 2);
row.put("colorDesc", "blue");
literalsM2[1] = row;
row = new HashMap<>();
row.put("colorId", 3);
row.put("colorDesc", "black");
literalsM2[2] = row;
row = new HashMap<>();
row.put("colorId", 4);
row.put("colorDesc", "yellow");
literalsM2[3] = row;
RowManager rowMgr = client.newRowManager();
PlanBuilder p = rowMgr.newPlanBuilder();
// plans from literals
ModifyPlan plan1 = p.fromLiterals(literalsM1);
ModifyPlan plan2 = p.fromLiterals(literalsM2);
ExportablePlan output = plan1.joinInner(plan2, p.on(p.col("colorId_shape"), p.col("colorId")))
.select(
p.as("myRowId", p.col("rowId"))
)
.orderBy(p.asc("myRowId"))
.reduce(p.resolveFunction(p.xs.QName("fibReducer"), "/marklogic.rest.resource/OpticsJSResourceModule/assets/resource.sjs"));
JacksonHandle jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(output, jacksonHandle);
JsonNode jsonBindingsNodes = jacksonHandle.get().path("rows");
// Should have 4 node returned.
assertEquals("Four nodes not returned from testMapFunction method", 4, jsonBindingsNodes.size());
assertEquals("Row 1 rowId value incorrect", "1", jsonBindingsNodes.path(0).path("myRowId").path("value").asText());
assertEquals("Row 1 myColorId value incorrect", "0", jsonBindingsNodes.path(0).path("i").path("value").asText());
assertEquals("Row 1 description value incorrect", "0", jsonBindingsNodes.path(0).path("fib").path("value").asText());
assertEquals("Row 2 rowId value incorrect", "2", jsonBindingsNodes.path(1).path("myRowId").path("value").asText());
assertEquals("Row 2 myColorId value incorrect", "1", jsonBindingsNodes.path(1).path("i").path("value").asText());
assertEquals("Row 2 description value incorrect", "1", jsonBindingsNodes.path(1).path("fib").path("value").asText());
assertEquals("Row 3 rowId value incorrect", "4", jsonBindingsNodes.path(3).path("myRowId").path("value").asText());
assertEquals("Row 3 myColorId value incorrect", "3", jsonBindingsNodes.path(3).path("i").path("value").asText());
assertEquals("Row 3 description value incorrect", "2", jsonBindingsNodes.path(3).path("fib").path("value").asText());
}
/*
* Test existJoin with literals
*/
@Test
public void testExistJoin() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException {
System.out.println("In testExistJoin method");
Map<String, Object>[] colLiteral = new HashMap[7];
Map<String, Object>[] invLiteral = new HashMap[6];
Map<String, Object> row = new HashMap<>();
row.put("rowId", 1);
row.put("colorId", 1);
row.put("desc", "ball");
row.put("colorDesc", "red");
invLiteral[0] = row;
row = new HashMap<>();
row.put("rowId", 2);
row.put("colorId", 2);
row.put("desc", "square");
row.put("colorDesc", "blue");
invLiteral[1] = row;
row = new HashMap<>();
row.put("rowId", 3);
row.put("colorId", 1);
row.put("desc", "box");
row.put("colorDesc", "red");
invLiteral[2] = row;
row = new HashMap<>();
row.put("rowId", 4);
row.put("colorId", 3);
row.put("desc", "hoop");
row.put("colorDesc", "black");
invLiteral[3] = row;
row = new HashMap<>();
row.put("rowId", 5);
row.put("colorId", 4);
row.put("desc", "circle");
row.put("colorDesc", "yellow");
invLiteral[4] = row;
row = new HashMap<>();
row.put("rowId", 6);
row.put("colorId", 5);
row.put("desc", "car");
row.put("colorDesc", "YELLOW");
invLiteral[5] = row;
row = new HashMap<>();
row.put("colorId", 1);
row.put("colorDesc", "red");
colLiteral[0] = row;
row = new HashMap<>();
row.put("colorId", 2);
row.put("colorDesc", "blue");
colLiteral[1] = row;
row = new HashMap<>();
row.put("colorId", 3);
row.put("colorDesc", "black");
colLiteral[2] = row;
row = new HashMap<>();
row.put("colorId", 4);
row.put("colorDesc", "yellow");
colLiteral[3] = row;
row = new HashMap<>();
row.put("colorId", 5);
row.put("colorDesc", "YELLOW");
colLiteral[4] = row;
row = new HashMap<>();
row.put("colorId", 6);
row.put("colorDesc", "Yellow");
colLiteral[5] = row;
row = new HashMap<>();
row.put("colorId", 7);
row.put("colorDesc", "yellowish");
colLiteral[6] = row;
ArrayList<String> exptdExists = new ArrayList<String>();
exptdExists.add("red");
exptdExists.add("black");
exptdExists.add("blue");
exptdExists.add("yellow");
exptdExists.add("YELLOW");
Collections.sort(exptdExists);
// Create a new Plan.
RowManager rowMgr = client.newRowManager();
PlanBuilder p = rowMgr.newPlanBuilder();
// plans from literals
ModifyPlan plan1 = p.fromLiterals(colLiteral, "table1");
ModifyPlan plan2 = p.fromLiterals(invLiteral, "table2");
ModifyPlan existsOutput = plan1.existsJoin(plan2, p.on(p.viewCol("table1", "colorDesc"), p.viewCol("table2", "colorDesc")));
JacksonHandle jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(existsOutput, jacksonHandle);
JsonNode jsonBindingsNodes = jacksonHandle.get().path("rows");
ArrayList<String> existColorList = new ArrayList<String>();
existColorList.add(jsonBindingsNodes.path(0).path("table1.colorDesc").path("value").asText());
existColorList.add(jsonBindingsNodes.path(1).path("table1.colorDesc").path("value").asText());
existColorList.add(jsonBindingsNodes.path(2).path("table1.colorDesc").path("value").asText());
existColorList.add(jsonBindingsNodes.path(3).path("table1.colorDesc").path("value").asText());
existColorList.add(jsonBindingsNodes.path(4).path("table1.colorDesc").path("value").asText());
Collections.sort(existColorList);
assertTrue("Error while return from existsJoin", existColorList.equals(exptdExists));
// existJoin with literals - without on parameters
ModifyPlan existsNoOptionsOutput = plan2.existsJoin(plan1).orderBy(p.desc(p.col("desc")));
jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(existsNoOptionsOutput, jacksonHandle);
jsonBindingsNodes = jacksonHandle.get().path("rows");
assertEquals("Element 1 desc value incorrect", "square", jsonBindingsNodes.path(0).path("table2.desc").path("value").asText());
assertEquals("Element 3 desc value incorrect", "circle", jsonBindingsNodes.path(2).path("table2.desc").path("value").asText());
assertEquals("Element 6 desc value incorrect", "ball", jsonBindingsNodes.path(5).path("table2.desc").path("value").asText());
// not exists join
ModifyPlan notExistsOutput = plan1.notExistsJoin(plan2, p.on(p.viewCol("table1", "colorDesc"), p.viewCol("table2", "colorDesc")));
jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(notExistsOutput, jacksonHandle);
jsonBindingsNodes = jacksonHandle.get().path("rows");
ArrayList<String> exptdNotExists = new ArrayList<String>();
exptdNotExists.add("Yellow");
exptdNotExists.add("yellowish");
Collections.sort(exptdNotExists);
ArrayList<String> notExistColorList = new ArrayList<String>();
notExistColorList.add(jsonBindingsNodes.path(0).path("table1.colorDesc").path("value").asText());
notExistColorList.add(jsonBindingsNodes.path(1).path("table1.colorDesc").path("value").asText());
Collections.sort(notExistColorList);
assertTrue("Error while return from notExistsJoin", notExistColorList.equals(exptdNotExists));
}
/*
* Test facetBy and bucketGroups
*/
@Test
public void testFacetByWithBucketGroups() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException {
System.out.println("In testFacetByWithBucketGroups method");
Map<String, Object>[] invLiteral = new HashMap[17];
Map<String, Object>[] colLiteral = new HashMap[6];
Map<String, Object> row = new HashMap<>();
row = new HashMap<>();
row.put("rowId", 1); row.put("colorId", 1); row.put("desc", "ball");
invLiteral[0] = row;
row = new HashMap<>();
row.put("rowId", 2); row.put("colorId", 2); row.put("desc", "square");
invLiteral[1] = row;
row = new HashMap<>();
row.put("rowId", 3); row.put("colorId", 1); row.put("desc", "box");
invLiteral[2] = row;
row = new HashMap<>();
row.put("rowId", 4); row.put("colorId", 1); row.put("desc", "hoop");
invLiteral[3] = row;
row = new HashMap<>();
row.put("rowId", 5); row.put("colorId", 5); row.put("desc", "circle");
invLiteral[4] = row;
row = new HashMap<>();
row.put("rowId", 6); row.put("colorId", 1); row.put("desc", "key");
invLiteral[5] = row;
row = new HashMap<>();
row.put("rowId", 7); row.put("colorId", 1); row.put("desc", "cup");
invLiteral[6] = row;
row = new HashMap<>();
row.put("rowId", 8); row.put("colorId", 1); row.put("desc", "bike");
invLiteral[7] = row;
row = new HashMap<>();
row.put("rowId", 9); row.put("colorId", 3); row.put("desc", "car");
invLiteral[8] = row;
row = new HashMap<>();
row.put("rowId", 10); row.put("colorId", 3); row.put("desc", "cart");
invLiteral[9] = row;
row = new HashMap<>();
row.put("rowId", 11); row.put("colorId", 4); row.put("desc", "cupholder");
invLiteral[10] = row;
row = new HashMap<>();
row.put("rowId", 12); row.put("colorId", 2); row.put("desc", "scooter");
invLiteral[11] = row;
row = new HashMap<>();
row.put("rowId", 13); row.put("colorId", 5); row.put("desc", "hat");
invLiteral[12] = row;
row = new HashMap<>();
row.put("rowId", 14); row.put("colorId", 3); row.put("desc", "booster");
invLiteral[13] = row;
row = new HashMap<>();
row.put("rowId", 15); row.put("colorId", 3); row.put("desc", "knapsack");
invLiteral[14] = row;
row = new HashMap<>();
row.put("rowId", 16); row.put("colorId", 1); row.put("desc", "hovercraft");
invLiteral[15] = row;
row = new HashMap<>();
row.put("rowId", 17); row.put("colorId", 6); row.put("desc", "dice");
invLiteral[16] = row;
row = new HashMap<>();
row.put("colorId", 1);
row.put("colorDesc", "red");
colLiteral[0] = row;
row = new HashMap<>();
row.put("colorId", 2);
row.put("colorDesc", "blue");
colLiteral[1] = row;
row = new HashMap<>();
row.put("colorId", 3);
row.put("colorDesc", "black");
colLiteral[2] = row;
row = new HashMap<>();
row.put("colorId", 4);
row.put("colorDesc", "yellow");
colLiteral[3] = row;
row = new HashMap<>();
row.put("colorId", 5);
row.put("colorDesc", "white");
colLiteral[4] = row;
row = new HashMap<>();
row.put("colorId", 6);
row.put("colorDesc", "grey");
colLiteral[5] = row;
// Create a new Plan.
RowManager rowMgr = client.newRowManager();
PlanBuilder p = rowMgr.newPlanBuilder();
// plans from literals
ModifyPlan plan1 = p.fromLiterals(invLiteral, "table1");
ModifyPlan plan2 = p.fromLiterals(colLiteral, "table2");
ModifyPlan output1 = plan1.joinInner(plan2)
.where(p.eq(p.viewCol("table1","colorId"), p.viewCol("table2","colorId")))
.facetBy(p.namedGroupSeq(p.bucketGroup(p.xs.string("colorBucket"), p.viewCol("table1","colorId"), p.xs.integerSeq(2, 4) )));
JacksonHandle jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(output1, jacksonHandle);
JsonNode colorBucketNodes = jacksonHandle.get().path("rows");
assertEquals("Bucket group 1 count value incorrect", "9", colorBucketNodes.path(0).path("colorBucket").path("value").path(0).path("count").asText());
assertEquals("Bucket group 2 count value incorrect", "5", colorBucketNodes.path(0).path("colorBucket").path("value").path(1).path("count").asText());
assertEquals("Bucket group 3 count value incorrect", "3", colorBucketNodes.path(0).path("colorBucket").path("value").path(2).path("count").asText());
// outside range
ModifyPlan output2 = plan1.joinInner(plan2)
.where(p.eq(p.viewCol("table1","colorId"), p.viewCol("table2","colorId")))
.facetBy(p.namedGroupSeq(p.bucketGroup(p.xs.string("colorBucket"), p.viewCol("table1","colorId"), p.xs.integerSeq(-1, 0) )));
jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(output2, jacksonHandle);
JsonNode colorBucketNodesNoRange = jacksonHandle.get().path("rows");
assertEquals("Bucket group 1 count value incorrect", "17", colorBucketNodesNoRange.path(0).path("colorBucket").path("value").path(0).path("count").asText());
// string range
ModifyPlan output3 = plan1.joinInner(plan2)
.where(p.eq(p.viewCol("table1","colorId"), p.viewCol("table2","colorId")))
.facetBy(p.namedGroupSeq(p.bucketGroup(p.xs.string("descBucket"), p.col("desc"), p.xs.stringSeq("ball", "dice"))));
jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(output3, jacksonHandle);
JsonNode descBucketNodesStringRange = jacksonHandle.get().path("rows");
assertEquals("Bucket group 1 count value incorrect", "1", descBucketNodesStringRange.path(0).path("descBucket").path("value").path(0).path("count").asText());
assertEquals("Bucket group 2 count value incorrect", "9", descBucketNodesStringRange.path(0).path("descBucket").path("value").path(1).path("count").asText());
assertEquals("Bucket group 3 count value incorrect", "7", descBucketNodesStringRange.path(0).path("descBucket").path("value").path(2).path("count").asText());
//bucket group negative test
ModifyPlan output4 = plan1.joinInner(plan2)
.where(p.eq(p.viewCol("table1","colorId"), p.viewCol("table2","colorId")))
.facetBy(p.namedGroupSeq(p.bucketGroup(p.xs.string("colorBucket"), p.viewCol("table1","colorId"), p.xs.integerSeq(1, 0) )));
jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
try {
rowMgr.resultDoc(output4, jacksonHandle);
} catch (Exception ex) {
assertTrue("Incorrect error/exception message", ex.getMessage().contains("failed to apply resource at rows: Internal Server Error"));
}
}
@AfterClass
public static void tearDownAfterClass() throws Exception
{
System.out.println("In tear down");
// Delete the services.
resourceMgr.deleteServices(resourceName);
// Delete the temp schema DB after resetting the Schema DB on content DB.
// Else delete fails.
deleteUserRole("opticRole");
deleteRESTUser("opticUser");
setDatabaseProperties(dbName, "schema-database", dbName);
deleteDB(schemadbName);
deleteForest(schemafNames[0]);
// release client
clientRes.release();
client.release();
cleanupRESTServer(dbName, fNames);
deleteRESTUser("eval-user");
deleteUserRole("test-eval");
}
}
| marklogic-client-api-functionaltests/src/test/java/com/marklogic/client/functionaltest/TestOpticOnLiterals.java | /*
* Copyright (c) 2021 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.functionaltest;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.xml.parsers.ParserConfigurationException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.xml.sax.SAXException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.marklogic.client.DatabaseClient;
import com.marklogic.client.DatabaseClientFactory;
import com.marklogic.client.DatabaseClientFactory.Authentication;
import com.marklogic.client.DatabaseClientFactory.DigestAuthContext;
import com.marklogic.client.admin.ExtensionMetadata;
import com.marklogic.client.admin.ExtensionMetadata.ScriptLanguage;
import com.marklogic.client.admin.MethodType;
import com.marklogic.client.admin.ResourceExtensionsManager;
import com.marklogic.client.admin.ResourceExtensionsManager.MethodParameters;
import com.marklogic.client.document.DocumentManager;
import com.marklogic.client.document.DocumentWriteSet;
import com.marklogic.client.expression.PlanBuilder;
import com.marklogic.client.expression.PlanBuilder.ExportablePlan;
import com.marklogic.client.expression.PlanBuilder.ModifyPlan;
import com.marklogic.client.io.DocumentMetadataHandle;
import com.marklogic.client.io.FileHandle;
import com.marklogic.client.io.InputStreamHandle;
import com.marklogic.client.io.JacksonHandle;
import com.marklogic.client.row.RowManager;
import com.marklogic.client.type.PlanAggregateColSeq;
import com.marklogic.client.type.PlanColumn;
import com.marklogic.client.type.PlanExprColSeq;
import com.marklogic.client.type.PlanValueOption;
public class TestOpticOnLiterals extends BasicJavaClientREST {
private static String dbName = "TestOpticOnLiteralsDB";
private static String schemadbName = "TestOpticOnLiteralsSchemaDB";
private static String[] fNames = { "TestOpticOnLiteralsDB-1" };
private static String[] schemafNames = { "TestOpticOnLiteralsSchemaDB-1" };
private static DatabaseClient client;
private static DatabaseClient clientRes;
private static String datasource = "src/test/java/com/marklogic/client/functionaltest/data/optics/";
private static Map<String, Object>[] literals1 = new HashMap[5];
private static Map<String, Object>[] literals2 = new HashMap[4];
private static Map<String, Object>[] storeInformation = new HashMap[4];
private static Map<String, Object>[] internetSales = new HashMap[4];
private static ResourceExtensionsManager resourceMgr;
private static String resourceName = "OpticsJSResourceModule";
@BeforeClass
public static void setUp() throws KeyManagementException, NoSuchAlgorithmException, Exception
{
System.out.println("In TestOpticOnLiterals setup");
DatabaseClient schemaDBclient = null;
configureRESTServer(dbName, fNames);
// Add new range elements into this array
String[][] rangeElements = {
// { scalar-type, namespace-uri, localname, collation,
// range-value-positions, invalid-values }
// If there is a need to add additional fields, then add them to the end
// of each array
// and pass empty strings ("") into an array where the additional field
// does not have a value.
// For example : as in namespace, collections below.
// Add new RangeElementIndex as an array below.
{ "string", "", "city", "http://marklogic.com/collation/", "false", "reject" },
{ "int", "", "popularity", "", "false", "reject" },
{ "double", "", "distance", "", "false", "reject" },
{ "date", "", "date", "", "false", "reject" },
{ "string", "", "cityName", "http://marklogic.com/collation/", "false", "reject" },
{ "string", "", "cityTeam", "http://marklogic.com/collation/", "false", "reject" },
{ "long", "", "cityPopulation", "", "false", "reject" }
};
// Insert the range indices
addRangeElementIndex(dbName, rangeElements);
// Insert word lexicon.
ObjectMapper mapper = new ObjectMapper();
ObjectNode mainNode = mapper.createObjectNode();
ArrayNode childArray = mapper.createArrayNode();
ObjectNode childNodeObject = mapper.createObjectNode();
childNodeObject.put("namespace-uri", "http://marklogic.com/collation/");
childNodeObject.put("localname", "city");
childNodeObject.put("collation", "http://marklogic.com/collation/");
childArray.add(childNodeObject);
mainNode.withArray("element-word-lexicon").add(childArray);
setDatabaseProperties(dbName, "element-word-lexicon", mainNode);
// Add geo element index.
addGeospatialElementIndexes(dbName, "latLonPoint", "", "wgs84", "point", false, "reject");
// Enable triple index.
enableTripleIndex(dbName);
waitForServerRestart();
// Enable collection lexicon.
enableCollectionLexicon(dbName);
// Enable uri lexicon.
setDatabaseProperties(dbName, "uri-lexicon", true);
// Create schema database
createDB(schemadbName);
createForest(schemafNames[0], schemadbName);
// Set the schemadbName database as the Schema database.
setDatabaseProperties(dbName, "schema-database", schemadbName);
createUserRolesWithPrevilages("opticRole", "xdbc:eval", "xdbc:eval-in", "xdmp:eval-in", "any-uri", "xdbc:invoke");
createRESTUser("opticUser", "0pt1c", "tde-admin", "tde-view", "opticRole", "rest-admin", "rest-writer",
"rest-reader", "rest-extension-user", "manage-user");
if (IsSecurityEnabled()) {
schemaDBclient = getDatabaseClientOnDatabase(getRestServerHostName(), getRestServerPort(), schemadbName, "opticUser", "0pt1c", getConnType());
client = getDatabaseClient("opticUser", "0pt1c", getConnType());
}
else {
schemaDBclient = DatabaseClientFactory.newClient(getRestServerHostName(), getRestServerPort(), schemadbName, new DigestAuthContext("opticUser", "0pt1c"));
client = DatabaseClientFactory.newClient(getRestServerHostName(), getRestServerPort(), new DigestAuthContext("opticUser", "0pt1c"));
}
// Install the TDE templates
// loadFileToDB(client, filename, docURI, collection, document format)
loadFileToDB(schemaDBclient, "masterDetail.tdex", "/optic/view/test/masterDetail.tdex", "XML", new String[] { "http://marklogic.com/xdmp/tde" });
loadFileToDB(schemaDBclient, "masterDetail2.tdej", "/optic/view/test/masterDetail2.tdej", "JSON", new String[] { "http://marklogic.com/xdmp/tde" });
loadFileToDB(schemaDBclient, "masterDetail3.tdej", "/optic/view/test/masterDetail3.tdej", "JSON", new String[] { "http://marklogic.com/xdmp/tde" });
loadFileToDB(schemaDBclient, "masterDetail4.tdej", "/optic/view/test/masterDetail4.tdej", "JSON", new String[] { "http://marklogic.com/xdmp/tde" });
// Load XML data files.
loadFileToDB(client, "masterDetail.xml", "/optic/view/test/masterDetail.xml", "XML", new String[] { "/optic/view/test" });
loadFileToDB(client, "playerTripleSet.xml", "/optic/triple/test/playerTripleSet.xml", "XML", new String[] { "/optic/player/triple/test" });
loadFileToDB(client, "teamTripleSet.xml", "/optic/triple/test/teamTripleSet.xml", "XML", new String[] { "/optic/team/triple/test" });
loadFileToDB(client, "otherPlayerTripleSet.xml", "/optic/triple/test/otherPlayerTripleSet.xml", "XML", new String[] { "/optic/other/player/triple/test" });
loadFileToDB(client, "doc4.xml", "/optic/lexicon/test/doc4.xml", "XML", new String[] { "/optic/lexicon/test" });
loadFileToDB(client, "doc5.xml", "/optic/lexicon/test/doc5.xml", "XML", new String[] { "/optic/lexicon/test" });
// Load JSON data files.
loadFileToDB(client, "masterDetail2.json", "/optic/view/test/masterDetail2.json", "JSON", new String[] { "/optic/view/test" });
loadFileToDB(client, "masterDetail3.json", "/optic/view/test/masterDetail3.json", "JSON", new String[] { "/optic/view/test" });
loadFileToDB(client, "masterDetail4.json", "/optic/view/test/masterDetail4.json", "JSON", new String[] { "/optic/view/test" });
loadFileToDB(client, "masterDetail5.json", "/optic/view/test/masterDetail5.json", "JSON", new String[] { "/optic/view/test" });
loadFileToDB(client, "doc1.json", "/optic/lexicon/test/doc1.json", "JSON", new String[] { "/other/coll1", "/other/coll2" });
loadFileToDB(client, "doc2.json", "/optic/lexicon/test/doc2.json", "JSON", new String[] { "/optic/lexicon/test" });
loadFileToDB(client, "doc3.json", "/optic/lexicon/test/doc3.json", "JSON", new String[] { "/optic/lexicon/test" });
loadFileToDB(client, "city1.json", "/optic/lexicon/test/city1.json", "JSON", new String[] { "/optic/lexicon/test" });
loadFileToDB(client, "city2.json", "/optic/lexicon/test/city2.json", "JSON", new String[] { "/optic/lexicon/test" });
loadFileToDB(client, "city3.json", "/optic/lexicon/test/city3.json", "JSON", new String[] { "/optic/lexicon/test" });
loadFileToDB(client, "city4.json", "/optic/lexicon/test/city4.json", "JSON", new String[] { "/optic/lexicon/test" });
loadFileToDB(client, "city5.json", "/optic/lexicon/test/city5.json", "JSON", new String[] { "/optic/lexicon/test" });
Map<String, Object> row = new HashMap<>();
row.put("rowId", 1);
row.put("colorId", 1);
row.put("desc", "ball");
literals1[0] = row;
row = new HashMap<>();
row.put("rowId", 2);
row.put("colorId", 2);
row.put("desc", "square");
literals1[1] = row;
row = new HashMap<>();
row.put("rowId", 3);
row.put("colorId", 1);
row.put("desc", "box");
literals1[2] = row;
row = new HashMap<>();
row.put("rowId", 4);
row.put("colorId", 1);
row.put("desc", "hoop");
literals1[3] = row;
row = new HashMap<>();
row.put("rowId", 5);
row.put("colorId", 5);
row.put("desc", "circle");
literals1[4] = row;
row = new HashMap<>();
row.put("colorId", 1);
row.put("colorDesc", "red");
literals2[0] = row;
row = new HashMap<>();
row.put("colorId", 2);
row.put("colorDesc", "blue");
literals2[1] = row;
row = new HashMap<>();
row.put("colorId", 3);
row.put("colorDesc", "black");
literals2[2] = row;
row = new HashMap<>();
row.put("colorId", 4);
row.put("colorDesc", "yellow");
literals2[3] = row;
// Fill up storeInformation Map
row = new HashMap<>();
row.put("storeName", "Los Angeles");
row.put("sales", 1500);
row.put("txnDate", "Jan-05-1999");
storeInformation[0] = row;
row = new HashMap<>();
row.put("storeName", "San Diego");
row.put("sales", 250);
row.put("txnDate", "Jan-07-1999");
storeInformation[1] = row;
row = new HashMap<>();
row.put("storeName", "Los Angeles");
row.put("sales", 300);
row.put("txnDate", "Jan-08-1999");
storeInformation[2] = row;
row = new HashMap<>();
row.put("storeName", "Boston");
row.put("sales", 700);
row.put("txnDate", "Jan-08-1999");
storeInformation[3] = row;
// Fill up internetSales Map
row = new HashMap<>();
row.put("txnDate", "Jan-07-1999");
row.put("sales", 250);
row.put("sales", 1500);
internetSales[0] = row;
row = new HashMap<>();
row.put("txnDate", "Jan-10-1999");
row.put("sales", 535);
row.put("storeName", "San Diego");
internetSales[1] = row;
row = new HashMap<>();
row.put("txnDate", "Jan-11-1999");
row.put("sales", 320);
row.put("storeName", "Los Angeles");
internetSales[2] = row;
row = new HashMap<>();
row.put("txnDate", "Jan-12-1999");
row.put("sales", 750);
row.put("storeName", "Boston");
internetSales[3] = row;
// Install JavaScript modules into REST Server module database to support
// Map and Reduce tests.
createUserRolesWithPrevilages("test-eval", "xdbc:eval", "xdbc:eval-in", "xdmp:eval-in", "any-uri", "xdbc:invoke");
createRESTUser("eval-user", "x", "test-eval", "rest-admin", "rest-writer", "rest-reader");
clientRes = getDatabaseClient("eval-user", "x", getConnType());
resourceMgr = clientRes.newServerConfigManager().newResourceExtensionsManager();
ExtensionMetadata resextMetadata = new ExtensionMetadata();
resextMetadata.setTitle("BasicJSTest");
resextMetadata.setDescription("Testing resource extension for java script");
System.out.println(resextMetadata.getScriptLanguage());
resextMetadata.setScriptLanguage(ScriptLanguage.JAVASCRIPT);
System.out.println(resextMetadata.getScriptLanguage());
resextMetadata.setVersion("1.0");
MethodParameters getParams = new MethodParameters(MethodType.GET);
getParams.add("row", "xs:string?");
FileInputStream myStream = new FileInputStream("src/test/java/com/marklogic/client/functionaltest/data/OpticsTestJSResource.js");
InputStreamHandle handle = new InputStreamHandle(myStream);
handle.set(myStream);
resourceMgr.writeServices(resourceName, handle, resextMetadata, getParams);
Thread.sleep(10000);
schemaDBclient.release();
}
/**
* Write document using DOMHandle
*
* @param client
* @param filename
* @param uri
* @param type
* @throws IOException
* @throws ParserConfigurationException
* @throws SAXException
*/
public static void loadFileToDB(DatabaseClient client, String filename, String uri, String type, String[] collections) throws IOException, ParserConfigurationException,
SAXException
{
// create doc manager
DocumentManager docMgr = null;
docMgr = documentMgrSelector(client, docMgr, type);
File file = new File(datasource + filename);
// create a handle on the content
FileHandle handle = new FileHandle(file);
handle.set(file);
DocumentMetadataHandle metadataHandle = new DocumentMetadataHandle();
for (String coll : collections)
metadataHandle.getCollections().addAll(coll.toString());
// write the document content
DocumentWriteSet writeset = docMgr.newWriteSet();
writeset.addDefault(metadataHandle);
writeset.add(uri, handle);
docMgr.write(writeset);
System.out.println("Write " + uri + " to database");
}
/**
* Function to select and create document manager based on the type
*
* @param client
* @param docMgr
* @param type
* @return
*/
public static DocumentManager documentMgrSelector(DatabaseClient client, DocumentManager docMgr, String type) {
// create doc manager
switch (type) {
case "XML":
docMgr = client.newXMLDocumentManager();
break;
case "Text":
docMgr = client.newTextDocumentManager();
break;
case "JSON":
docMgr = client.newJSONDocumentManager();
break;
case "Binary":
docMgr = client.newBinaryDocumentManager();
break;
case "JAXB":
docMgr = client.newXMLDocumentManager();
break;
default:
System.out.println("Invalid type");
break;
}
return docMgr;
}
/*
* 1) Test join inner 2) Test join inner with qualifier 3) Test join and
* multiple order by 4) Test multple inner joins
*/
@Test
public void testJoinInner() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException
{
System.out.println("In testJoinInner method");
// Create a new Plan.
RowManager rowMgr = client.newRowManager();
PlanBuilder p = rowMgr.newPlanBuilder();
// plans from literals
ModifyPlan plan1 = p.fromLiterals(literals1);
ModifyPlan plan2 = p.fromLiterals(literals2);
ModifyPlan output = plan1.joinInner(plan2).orderBy(p.asc(p.col("rowId")));
JacksonHandle jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(output, jacksonHandle);
JsonNode jsonBindingsNodes = jacksonHandle.get().path("rows");
// Should have 4 nodes returned.
assertEquals("Four nodes not returned from testJoinInner method", 4, jsonBindingsNodes.size());
JsonNode node = jsonBindingsNodes.path(0);
assertEquals("Row 1 rowId value incorrect", "1", node.path("rowId").path("value").asText());
assertEquals("Row 1 desc value incorrect", "ball", node.path("desc").path("value").asText());
assertEquals("Row 1 colorDesc value incorrect", "red", node.path("colorDesc").path("value").asText());
node = jsonBindingsNodes.path(3);
assertEquals("Row 4 rowId value incorrect", "4", node.path("rowId").path("value").asText());
assertEquals("Row 4 desc value incorrect", "hoop", node.path("desc").path("value").asText());
assertEquals("Row 4 colorDesc value incorrect", "red", node.path("colorDesc").path("value").asText());
// Join inner with qualifier
ModifyPlan plan3 = p.fromLiterals(literals1, "table1");
ModifyPlan plan4 = p.fromLiterals(literals2, "table2");
ModifyPlan outputQualifier = plan3.joinInner(plan4)
.where(p.eq(p.viewCol("table1", "colorId"), p.viewCol("table2", "colorId")))
.orderBy(p.desc(p.viewCol("table1", "rowId")));
jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(outputQualifier, jacksonHandle);
jsonBindingsNodes = jacksonHandle.get().path("rows");
node = jsonBindingsNodes.path(3);
assertEquals("Row 1 table1.rowId value incorrect", "1", node.path("table1.rowId").path("value").asText());
assertEquals("Row 1 table1.desc value incorrect", "ball", node.path("table1.desc").path("value").asText());
assertEquals("Row 1 table2.colorDesc value incorrect", "red", node.path("table2.colorDesc").path("value").asText());
node = jsonBindingsNodes.path(0);
assertEquals("Row 4 table1.rowId value incorrect", "4", node.path("table1.rowId").path("value").asText());
assertEquals("Row 4 table1.desc value incorrect", "hoop", node.path("table1.desc").path("value").asText());
assertEquals("Row 4 table2.colorDesc value incorrect", "red", node.path("table2.colorDesc").path("value").asText());
// Test join and multiple order by
ModifyPlan plan5 = p.fromLiterals(literals1, "myItem");
ModifyPlan plan6 = p.fromLiterals(literals2, "myColor");
PlanColumn descCol = p.viewCol("myItem", "desc");
PlanColumn itemColorIdCol = p.viewCol("myItem", "colorId");
PlanColumn colorIdCol = p.viewCol("myColor", "colorId");
ModifyPlan outputMultiOrder = plan5.joinInner(plan6, p.on(itemColorIdCol, colorIdCol))
.select(descCol, colorIdCol)
.orderBy(p.sortKeySeq(colorIdCol, descCol));
jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(outputMultiOrder, jacksonHandle);
jsonBindingsNodes = jacksonHandle.get().path("rows");
// Should have 4 nodes returned.
assertEquals("Four nodes not returned from testJoinInner method - multiple order by", 4, jsonBindingsNodes.size());
node = jsonBindingsNodes.path(0);
assertEquals("Row 1 myItem.desc value incorrect", "ball", node.path("myItem.desc").path("value").asText());
assertEquals("Row 1 myColor.colorId value incorrect", "1", node.path("myColor.colorId").path("value").asText());
node = jsonBindingsNodes.path(1);
assertEquals("Row 2 myItem.desc value incorrect", "box", node.path("myItem.desc").path("value").asText());
assertEquals("Row 2 myColor.colorId value incorrect", "1", node.path("myColor.colorId").path("value").asText());
node = jsonBindingsNodes.path(2);
assertEquals("Row 3 myItem.desc value incorrect", "hoop", node.path("myItem.desc").path("value").asText());
assertEquals("Row 3 myColor.colorId value incorrect", "1", node.path("myColor.colorId").path("value").asText());
node = jsonBindingsNodes.path(3);
assertEquals("Row 4 myItem.desc value incorrect", "square", node.path("myItem.desc").path("value").asText());
assertEquals("Row 4 myColor.colorId value incorrect", "2", node.path("myColor.colorId").path("value").asText());
// Test multple inner joins
Map<String, Object>[] literals3 = new HashMap[4];
Map<String, Object> row = new HashMap<>();
row = new HashMap<>();
row.put("color", "red");
row.put("ref", "rose");
literals3[0] = row;
row = new HashMap<>();
row.put("color", "blue");
row.put("ref", "water");
literals3[1] = row;
row = new HashMap<>();
row.put("color", "black");
row.put("ref", "bag");
literals3[2] = row;
row = new HashMap<>();
row.put("color", "yellow");
row.put("ref", "moon");
literals3[3] = row;
ModifyPlan plan7 = p.fromLiterals(literals3, "myRef");
PlanColumn colorDescCol = p.viewCol("myColor", "colorDesc");
PlanColumn refColorCol = p.viewCol("myRef", "color");
PlanColumn refCol = p.viewCol("myRef", "ref");
ModifyPlan outputMultiJoin = plan5.joinInner(plan6, p.on(itemColorIdCol, colorIdCol))
.joinInner(plan7, p.on(colorDescCol, refColorCol))
.select(descCol, colorIdCol, refCol)
.orderBy(p.sortKeySeq(colorIdCol, descCol));
jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(outputMultiJoin, jacksonHandle);
jsonBindingsNodes = jacksonHandle.get().path("rows");
// Should have 4 nodes returned.
assertEquals("Four nodes not returned from testJoinInner method - multiple joins", 4, jsonBindingsNodes.size());
node = jsonBindingsNodes.path(0);
assertEquals("Row 1 myItem.desc value incorrect", "ball", node.path("myItem.desc").path("value").asText());
assertEquals("Row 1 myColor.colorId value incorrect", "1", node.path("myColor.colorId").path("value").asText());
assertEquals("Row 1 myRef.ref value incorrect", "rose", node.path("myRef.ref").path("value").asText());
node = jsonBindingsNodes.path(1);
assertEquals("Row 2 myItem.desc value incorrect", "box", node.path("myItem.desc").path("value").asText());
assertEquals("Row 2 myColor.colorId value incorrect", "1", node.path("myColor.colorId").path("value").asText());
assertEquals("Row 2 myRef.ref value incorrect", "rose", node.path("myRef.ref").path("value").asText());
node = jsonBindingsNodes.path(2);
assertEquals("Row 3 myItem.desc value incorrect", "hoop", node.path("myItem.desc").path("value").asText());
assertEquals("Row 3 myColor.colorId value incorrect", "1", node.path("myColor.colorId").path("value").asText());
assertEquals("Row 3 myRef.ref value incorrect", "rose", node.path("myRef.ref").path("value").asText());
node = jsonBindingsNodes.path(3);
assertEquals("Row 4 myItem.desc value incorrect", "square", node.path("myItem.desc").path("value").asText());
assertEquals("Row 4 myColor.colorId value incorrect", "2", node.path("myColor.colorId").path("value").asText());
assertEquals("Row 4 myRef.ref value incorrect", "water", node.path("myRef.ref").path("value").asText());
}
/*
* Test join left outer
*/
@Test
public void testJoinLeftOuter() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException
{
System.out.println("In testJoinLeftOuter method");
// Create a new Plan.
RowManager rowMgr = client.newRowManager();
PlanBuilder p = rowMgr.newPlanBuilder();
// plans from literals
ModifyPlan plan1 = p.fromLiterals(literals1);
ModifyPlan plan2 = p.fromLiterals(literals2);
ModifyPlan output = plan1.joinLeftOuter(plan2)
.orderBy(p.col("rowId"));
JacksonHandle jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(output, jacksonHandle);
JsonNode jsonBindingsNodes = jacksonHandle.get().path("rows");
// Should have 5 nodes returned.
assertEquals("Five nodes not returned from testJoinLeftOuter method", 5, jsonBindingsNodes.size());
JsonNode node = jsonBindingsNodes.path(0);
assertEquals("Row 1 rowId value incorrect", "1", node.path("rowId").path("value").asText());
assertEquals("Row 1 desc value incorrect", "ball", node.path("desc").path("value").asText());
assertEquals("Row 1 colorDesc value incorrect", "red", node.path("colorDesc").path("value").asText());
node = jsonBindingsNodes.path(3);
assertEquals("Row 4 rowId value incorrect", "4", node.path("rowId").path("value").asText());
assertEquals("Row 4 desc value incorrect", "hoop", node.path("desc").path("value").asText());
assertEquals("Row 4 colorDesc value incorrect", "red", node.path("colorDesc").path("value").asText());
node = jsonBindingsNodes.path(4);
assertEquals("Row 5 rowId value incorrect", "5", node.path("rowId").path("value").asText());
assertEquals("Row 5 desc value incorrect", "circle", node.path("desc").path("value").asText());
assertFalse("Row 5 colorDesc should be null", node.path("colorDesc").isNull());
// To verify issue 1055.
FileHandle fh = new FileHandle();
rowMgr.resultDoc(output, fh);
File file = fh.get();
String fileContents = convertFileToString(file);
ObjectMapper mapper = new ObjectMapper();
JsonNode fromFile = mapper.readTree(file).path("rows");
System.out.println(fileContents);
assertEquals("Five nodes not returned from testJoinLeftOuter method", 5, fromFile.size());
JsonNode nodeFile = fromFile.path(0);
assertEquals("Row 1 rowId value incorrect", "1", nodeFile.path("rowId").path("value").asText());
assertEquals("Row 1 desc value incorrect", "ball", nodeFile.path("desc").path("value").asText());
assertEquals("Row 1 colorDesc value incorrect", "red", nodeFile.path("colorDesc").path("value").asText());
}
/*
* Test group-by max
*/
@Test
public void testGroupByMax() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException
{
System.out.println("In testGroupByMax method");
// Create a new Plan.
RowManager rowMgr = client.newRowManager();
PlanBuilder p = rowMgr.newPlanBuilder();
// plans from literals
ModifyPlan plan1 = p.fromLiterals(literals1);
ModifyPlan output = plan1.groupBy(p.col("colorId"), p.max("new_color_id", "colorId"));
JacksonHandle jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(output, jacksonHandle);
JsonNode jsonBindingsNodes = jacksonHandle.get().path("rows");
// Should have 3 nodes returned.
assertEquals("Three nodes not returned from testJoinLeftOuter method", 3, jsonBindingsNodes.size());
JsonNode node = jsonBindingsNodes.path(0);
assertEquals("Row 1 colorId value incorrect", "1", node.path("colorId").path("value").asText());
assertEquals("Row 1 new_color_id value incorrect", "1", node.path("new_color_id").path("value").asText());
node = jsonBindingsNodes.path(1);
assertEquals("Row 2 colorId value incorrect", "2", node.path("colorId").path("value").asText());
assertEquals("Row 2 new_color_id value incorrect", "2", node.path("new_color_id").path("value").asText());
node = jsonBindingsNodes.path(2);
assertEquals("Row 3 colorId value incorrect", "5", node.path("colorId").path("value").asText());
assertEquals("Row 3 new_color_id value incorrect", "5", node.path("new_color_id").path("value").asText());
}
/*
* Test where limit and select Test limit with 0 length
*/
@Test
public void testOffsetAndLimit() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException
{
System.out.println("In testOffsetAndLimit method");
// Create a new Plan.
RowManager rowMgr = client.newRowManager();
PlanBuilder p = rowMgr.newPlanBuilder();
// plans from literals
ModifyPlan plan1 = p.fromLiterals(literals1);
ModifyPlan plan2 = p.fromLiterals(literals2);
ModifyPlan output = plan1.joinInner(plan2)
.where(p.eq(p.col("colorId"), p.xs.intVal(1)))
.offsetLimit(1, 3)
.select(p.colSeq("rowId", "desc", "colorId", "colorDesc"));
JacksonHandle jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(output, jacksonHandle);
JsonNode jsonBindingsNodes = jacksonHandle.get().path("rows");
// Should have 2 nodes returned.
assertEquals("Two nodes not returned from testOffsetAndLimit method", 2, jsonBindingsNodes.size());
JsonNode node = jsonBindingsNodes.path(0);
assertEquals("Row 1 rowId value incorrect", "3", node.path("rowId").path("value").asText());
assertEquals("Row 1 desc value incorrect", "box", node.path("desc").path("value").asText());
assertEquals("Row 1 colorId value incorrect", "1", node.path("colorId").path("value").asText());
assertEquals("Row 1 colorDesc value incorrect", "red", node.path("colorDesc").path("value").asText());
node = jsonBindingsNodes.path(1);
assertEquals("Row 2 rowId value incorrect", "4", node.path("rowId").path("value").asText());
assertEquals("Row 2 desc value incorrect", "hoop", node.path("desc").path("value").asText());
assertEquals("Row 2 colorId value incorrect", "1", node.path("colorId").path("value").asText());
assertEquals("Row 2 colorDesc value incorrect", "red", node.path("colorDesc").path("value").asText());
// limit with 0 length
ModifyPlan outputLimit = plan1.joinInner(plan2)
.where(p.eq(p.col("colorId"), p.xs.intVal(1)))
.limit(0)
.select(p.colSeq("rowId", "desc", "colorId", "colorDesc"));
jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
StringBuilder str = new StringBuilder();
try {
rowMgr.resultDoc(outputLimit, jacksonHandle);
} catch (Exception ex) {
str.append(ex.getMessage());
System.out.println("Exception message is " + str.toString());
}
// Should have OPTIC-INVALARGS exceptions.
assertTrue("Exceptions not found", str.toString().contains("OPTIC-INVALARGS"));
assertTrue("Exceptions not found", str.toString().contains("Invalid arguments: limit must be a positive number: 0"));
}
/*
* Test arithmetic expression
*/
@Test
public void testArithmeticExpression() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException
{
System.out.println("In testArithmeticExpression method");
// Create a new Plan.
RowManager rowMgr = client.newRowManager();
PlanBuilder p = rowMgr.newPlanBuilder();
// plans from literals
ModifyPlan plan1 = p.fromLiterals(literals1);
ModifyPlan plan2 = p.fromLiterals(literals2);
ModifyPlan output =
plan1.joinInner(plan2)
.select(
p.col("rowId"),
p.col("desc"),
p.col("colorId"),
p.col("colorDesc"),
p.as("added", p.add(p.col("rowId"), p.col("colorId"), p.xs.intVal(10))),
p.as("subtracted", p.subtract(p.col("colorId"), p.col("rowId"))),
p.as("negSubtracted", p.subtract(p.col("colorId"), p.col("rowId"))),
p.as("divided", p.divide(p.col("colorId"), p.col("rowId"))),
p.as("multiplied", p.multiply(p.col("colorId"), p.col("rowId"), p.xs.floatVal(0.6f))),
p.as("colDefined", p.isDefined(p.col("added"))),
p.as("colNotDefined", p.isDefined(p.col("negSubtracted"))),
p.as("colNotDefinedNegate", p.not(p.isDefined(p.col("negSubtracted")))),
p.as("caseExpr",
p.caseExpr(
p.when(p.eq(p.col("rowId"), p.xs.intVal(1)), p.xs.string("foo")),
p.when(p.eq(p.col("rowId"), p.xs.intVal(2)), p.xs.string("baz")),
p.when(p.eq(p.col("rowId"), p.xs.intVal(3)), p.xs.string("rat")),
p.elseExpr(p.xs.string("bar"))
)
)
)
.orderBy(p.sortKeySeq(p.col("rowId")));
JacksonHandle jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(output, jacksonHandle);
JsonNode jsonBindingsNodes = jacksonHandle.get().path("rows");
// Should have 4 nodes returned.
assertEquals("Four nodes not returned from testArithmeticExpression method", 4, jsonBindingsNodes.size());
JsonNode node = jsonBindingsNodes.path(0);
assertEquals("Row 1 rowId value incorrect", "1", node.path("rowId").path("value").asText());
assertEquals("Row 1 colorDesc value incorrect", "red", node.path("colorDesc").path("value").asText());
assertEquals("Row 1 added value incorrect", "12", node.path("added").path("value").asText());
assertEquals("Row 1 subtracted value incorrect", "0", node.path("subtracted").path("value").asText());
assertEquals("Row 1 divided value incorrect", "1", node.path("divided").path("value").asText());
assertEquals("Row 1 multiplied value incorrect", "0.600000023841858", node.path("multiplied").path("value").asText());
assertEquals("Row 1 caseExpr value incorrect", "foo", node.path("caseExpr").path("value").asText());
node = jsonBindingsNodes.path(1);
assertEquals("Row 2 caseExpr value incorrect", "baz", node.path("caseExpr").path("value").asText());
node = jsonBindingsNodes.path(2);
assertEquals("Row 3 caseExpr value incorrect", "rat", node.path("caseExpr").path("value").asText());
node = jsonBindingsNodes.path(3);
assertEquals("Row 4 rowId value incorrect", "4", node.path("rowId").path("value").asText());
assertEquals("Row 4 colorDesc value incorrect", "red", node.path("colorDesc").path("value").asText());
assertEquals("Row 4 added value incorrect", "15", node.path("added").path("value").asText());
assertEquals("Row 4 subtracted value incorrect", "-3", node.path("subtracted").path("value").asText());
assertEquals("Row 4 divided value incorrect", "0.25", node.path("divided").path("value").asText());
assertEquals("Row 4 multiplied value incorrect", "2.400000095367432", node.path("multiplied").path("value").asText());
assertEquals("Row 4 caseExpr value incorrect", "bar", node.path("caseExpr").path("value").asText());
}
/*
* Test join inner doc on json and xml documents
*/
@Test
public void testJoinInnerDocOnJson() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException
{
System.out.println("In testJoinInnerDocOnJson method");
// Create a new Plan.
RowManager rowMgr = client.newRowManager();
PlanBuilder p = rowMgr.newPlanBuilder();
Map<String, Object>[] literals3 = new HashMap[4];
Map<String, Object> row = new HashMap<>();
row.put("id", 1);
row.put("val", 2);
row.put("uri", "/optic/lexicon/test/doc1.json");
literals3[0] = row;
row = new HashMap<>();
row.put("id", 2);
row.put("val", 4);
row.put("uri", "/optic/test/not/a/real/doc.nada");
literals3[1] = row;
row = new HashMap<>();
row.put("id", 3);
row.put("val", 6);
row.put("uri", "/optic/lexicon/test/doc3.json");
literals3[2] = row;
row = new HashMap<>();
row.put("id", 4);
row.put("val", 8);
row.put("uri", "/optic/lexicon/test/doc4.xml");
literals3[3] = row;
// TEST 16 - join inner doc with xpath traversing down and multiple values
// on json
ModifyPlan output = p.fromLiterals(literals3)
.joinDoc(p.col("doc"), p.col("uri"))
.select(
p.col("id"),
p.col("val"),
p.col("uri"),
p.as("nodes", p.xpath("doc", "/location/latLonPair/(lat|long)")))
.where(p.isDefined(p.col("nodes")))
.orderBy(p.asc("id"));
JacksonHandle jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(output, jacksonHandle);
JsonNode jsonBindingsNodes = jacksonHandle.get().path("rows");
// Should have 2 nodes returned.
assertEquals("Two nodes not returned from testJoinInnerDocOnJson method", 2, jsonBindingsNodes.size());
JsonNode node = jsonBindingsNodes.path(0);
assertEquals("Row 1 id value incorrect", "1", node.path("id").path("value").asText());
assertEquals("Row 1 val value incorrect", "2", node.path("val").path("value").asText());
assertEquals("Row 1 uri value incorrect", "/optic/lexicon/test/doc1.json", node.path("uri").path("value").asText());
node = jsonBindingsNodes.path(1);
assertEquals("Row 2 id value incorrect", "3", node.path("id").path("value").asText());
assertEquals("Row 2 val value incorrect", "6", node.path("val").path("value").asText());
assertEquals("Row 2 uri value incorrect", "/optic/lexicon/test/doc3.json", node.path("uri").path("value").asText());
// Verify TEST 17 - join inner doc with xpath accessing attribute on xml
ModifyPlan output17 = p.fromLiterals(literals3)
.joinDoc(p.col("doc"), p.col("uri"))
.select(
p.col("id"),
p.col("val"),
p.col("uri"),
p.as("nodes", p.xpath("doc", "/doc/distance/@direction")))
.where(p.isDefined(p.col("nodes")))
.orderBy(p.asc("id"));
JacksonHandle jacksonHandle17 = new JacksonHandle();
jacksonHandle17.setMimetype("application/json");
rowMgr.resultDoc(output17, jacksonHandle17);
JsonNode jsonBindingsNodes17 = jacksonHandle17.get().path("rows");
// Should have 1 node returned.
assertEquals("One node not returned from testJoinInnerDocOnJson method", 1, jsonBindingsNodes17.size());
JsonNode node17 = jsonBindingsNodes17.path(0);
assertEquals("Row 1 id value incorrect", "4", node17.path("id").path("value").asText());
assertEquals("Row 1 val value incorrect", "8", node17.path("val").path("value").asText());
assertEquals("Row 1 uri value incorrect", "/optic/lexicon/test/doc4.xml", node17.path("uri").path("value").asText());
assertEquals("Row 1 nodes value incorrect", "east", node17.path("nodes").path("value").asText());
// Verify TEST 18 - join inner doc with xpath traversing down and multiple
// values on xml
ModifyPlan output18 = p.fromLiterals(literals3)
.joinDoc(p.col("doc"), p.col("uri"))
.select(
p.col("id"),
p.col("val"),
p.col("uri"),
p.as("nodes", p.xpath("doc", "/doc/location/latLonPair/(lat|long)/text()")))
.where(p.isDefined(p.col("nodes")))
.orderBy(p.asc("id"));
JacksonHandle jacksonHandle18 = new JacksonHandle();
jacksonHandle18.setMimetype("application/json");
rowMgr.resultDoc(output18, jacksonHandle18);
JsonNode jsonBindingsNodes18 = jacksonHandle18.get().path("rows");
// Should have 1 node returned.
assertEquals("One node not returned from testJoinInnerDocOnJson method", 1, jsonBindingsNodes18.size());
JsonNode node18 = jsonBindingsNodes18.path(0);
assertEquals("Row 1 id value incorrect", "4", node18.path("id").path("value").asText());
assertEquals("Row 1 val value incorrect", "8", node18.path("val").path("value").asText());
assertEquals("Row 1 uri value incorrect", "/optic/lexicon/test/doc4.xml", node18.path("uri").path("value").asText());
assertEquals("Row 1 nodes value incorrect", "39.90", node18.path("nodes").path("value").get(0).asText());
assertEquals("Row 1 nodes value incorrect", "116.40", node18.path("nodes").path("value").get(1).asText());
// Verify TEST 19 - join inner doc with traversing up xpath on json
ModifyPlan output19 = p.fromLiterals(literals3)
.joinDoc(p.col("doc"), p.col("uri"))
.select(
p.col("id"),
p.col("val"),
p.col("uri"),
p.as("nodes", p.fn.string(p.xpath("doc", "//city"))))
.where(p.isDefined(p.col("nodes")))
.orderBy(p.asc("id"));
JacksonHandle jacksonHandle19 = new JacksonHandle();
jacksonHandle19.setMimetype("application/json");
rowMgr.resultDoc(output19, jacksonHandle19);
JsonNode jsonBindingsNodes19 = jacksonHandle19.get().path("rows");
// Should have 3 nodes returned.
assertEquals("Three nodes not returned from testJoinInnerDocOnJson method", 3, jsonBindingsNodes19.size());
JsonNode node19 = jsonBindingsNodes19.path(0);
assertEquals("Row 1 id value incorrect", "1", node19.path("id").path("value").asText());
assertEquals("Row 1 val value incorrect", "2", node19.path("val").path("value").asText());
assertEquals("Row 1 uri value incorrect", "/optic/lexicon/test/doc1.json", node19.path("uri").path("value").asText());
assertEquals("Row 1 nodes value incorrect", "london", node19.path("nodes").path("value").asText());
node19 = jsonBindingsNodes19.path(1);
assertEquals("Row 2 id value incorrect", "3", node19.path("id").path("value").asText());
assertEquals("Row 2 val value incorrect", "6", node19.path("val").path("value").asText());
assertEquals("Row 2 uri value incorrect", "/optic/lexicon/test/doc3.json", node19.path("uri").path("value").asText());
assertEquals("Row 2 nodes value incorrect", "new jersey", node19.path("nodes").path("value").asText());
node19 = jsonBindingsNodes19.path(2);
assertEquals("Row 2 id value incorrect", "4", node19.path("id").path("value").asText());
assertEquals("Row 2 val value incorrect", "8", node19.path("val").path("value").asText());
assertEquals("Row 2 uri value incorrect", "/optic/lexicon/test/doc4.xml", node19.path("uri").path("value").asText());
assertEquals("Row 2 nodes value incorrect", "beijing", node19.path("nodes").path("value").asText());
// Verify TEST 15 - join inner doc with xpath accessing attribute on xml
ModifyPlan output15 = p.fromLiterals(literals3)
.joinDoc(p.col("doc"), p.col("uri"))
.select(
p.col("id"),
p.col("val"),
p.col("uri"),
p.as("nodes", p.xpath("doc", "/doc/city")))
.where(p.isDefined(p.col("nodes")))
.orderBy(p.asc("id"));
JacksonHandle jacksonHandle15 = new JacksonHandle();
jacksonHandle15.setMimetype("application/json");
rowMgr.resultDoc(output15, jacksonHandle15);
JsonNode jsonBindingsNodes15 = jacksonHandle15.get().path("rows");
// Should have 1 node returned.
assertEquals("One node not returned from testJoinInnerDocOnJson method", 1, jsonBindingsNodes15.size());
JsonNode node20 = jsonBindingsNodes15.path(0);
assertEquals("Row 1 id value incorrect", "4", node20.path("id").path("value").asText());
assertEquals("Row 1 val value incorrect", "8", node20.path("val").path("value").asText());
assertEquals("Row 1 uri value incorrect", "/optic/lexicon/test/doc4.xml", node20.path("uri").path("value").asText());
assertEquals("Row 1 nodes value incorrect", "<city>beijing</city>", node20.path("nodes").path("value").asText());
// Verify TEST 21 - join inner doc with traversing deep xpath on json and
// xml
ModifyPlan output21 = p.fromLiterals(literals3)
.joinDoc(p.col("doc"), p.col("uri"))
.select(
p.col("id"),
p.col("val"),
p.col("uri"),
p.as("nodes", p.fn.number(p.xpath("doc", "//lat"))))
.where(p.isDefined(p.col("nodes")))
.orderBy(p.asc("id"));
JacksonHandle jacksonHandle21 = new JacksonHandle();
jacksonHandle21.setMimetype("application/json");
rowMgr.resultDoc(output21, jacksonHandle21);
JsonNode jsonBindingsNodes21 = jacksonHandle21.get().path("rows");
// Should have 3 nodes returned.
assertEquals("Three nodes not returned from testJoinInnerDocOnJson method", 3, jsonBindingsNodes21.size());
JsonNode node21 = jsonBindingsNodes21.path(0);
assertEquals("Row 1 id value incorrect", "1", node21.path("id").path("value").asText());
assertEquals("Row 1 val value incorrect", "2", node21.path("val").path("value").asText());
assertEquals("Row 1 uri value incorrect", "/optic/lexicon/test/doc1.json", node21.path("uri").path("value").asText());
assertEquals("Row 1 nodes value incorrect", "51.5", node21.path("nodes").path("value").asText());
node21 = jsonBindingsNodes21.path(1);
assertEquals("Row 1 id value incorrect", "3", node21.path("id").path("value").asText());
assertEquals("Row 1 val value incorrect", "6", node21.path("val").path("value").asText());
assertEquals("Row 1 uri value incorrect", "/optic/lexicon/test/doc3.json", node21.path("uri").path("value").asText());
assertEquals("Row 1 nodes value incorrect", "40.72", node21.path("nodes").path("value").asText());
node21 = jsonBindingsNodes21.path(2);
assertEquals("Row 1 id value incorrect", "4", node21.path("id").path("value").asText());
assertEquals("Row 1 val value incorrect", "8", node21.path("val").path("value").asText());
assertEquals("Row 1 uri value incorrect", "/optic/lexicon/test/doc4.xml", node21.path("uri").path("value").asText());
assertEquals("Row 1 nodes value incorrect", "39.9", node21.path("nodes").path("value").asText());
}
/*
* Test group-by without aggregate
*/
@Test
public void testGroupbyWithoutAggregate() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException
{
System.out.println("In testGroupbyWithoutAggregate method");
// Create a new Plan.
RowManager rowMgr = client.newRowManager();
PlanBuilder p = rowMgr.newPlanBuilder();
// plans from literals
ModifyPlan plan1 = p.fromLiterals(literals1);
ModifyPlan output = plan1.groupBy(p.col("colorId")).orderBy(p.col("colorId"));
JacksonHandle jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(output, jacksonHandle);
JsonNode jsonBindingsNodes = jacksonHandle.get().path("rows");
// Should have 3 nodes returned.
assertEquals("Three nodes not returned from testGroupbyWithoutAggregate method", 3, jsonBindingsNodes.size());
assertEquals("Row 1 colorId value incorrect", "1", jsonBindingsNodes.path(0).path("colorId").path("value").asText());
assertEquals("Row 2 colorId value incorrect", "2", jsonBindingsNodes.path(1).path("colorId").path("value").asText());
assertEquals("Row 3 colorId value incorrect", "5", jsonBindingsNodes.path(2).path("colorId").path("value").asText());
}
/*
* Test union with whereDistinct
*/
@Test
public void testUnionWithWhereDistinct() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException
{
System.out.println("In testUnionWithWhereDistinct method");
// Create a new Plan.
RowManager rowMgr = client.newRowManager();
PlanBuilder p = rowMgr.newPlanBuilder();
// plans from literals
ModifyPlan plan1 = p.fromLiterals(literals1);
ModifyPlan plan2 = p.fromLiterals(literals2);
ModifyPlan output = plan1.union(plan2).whereDistinct().orderBy(p.sortKeySeq(p.col("rowId"), p.col("colorId")));
JacksonHandle jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(output, jacksonHandle);
JsonNode jsonBindingsNodes = jacksonHandle.get().path("rows");
// Should have 9 nodes returned.
assertEquals("Nine nodes not returned from testUnionWithWhereDistinct method", 9, jsonBindingsNodes.size());
assertEquals("Row 1 colorId value incorrect", "1", jsonBindingsNodes.path(0).path("colorId").path("value").asText());
assertEquals("Row 1 colorDesc value incorrect", "null", jsonBindingsNodes.path(0).path("colorDesc").path("value").asText());
assertEquals("Row 2 colorId value incorrect", "2", jsonBindingsNodes.path(1).path("colorId").path("value").asText());
assertEquals("Row 2 colorDesc value incorrect", "null", jsonBindingsNodes.path(1).path("colorDesc").path("value").asText());
assertEquals("Row 6 desc value incorrect", "null", jsonBindingsNodes.path(5).path("desc").path("value").asText());
assertEquals("Row 6 rowId value incorrect", "null", jsonBindingsNodes.path(5).path("rowId").path("value").asText());
assertEquals("Row 9 desc value incorrect", "null", jsonBindingsNodes.path(8).path("desc").path("value").asText());
assertEquals("Row 9 colorId value incorrect", "4", jsonBindingsNodes.path(8).path("colorId").path("value").asText());
}
/*
* Test intersect
*/
@Test
public void testIntersect() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException
{
System.out.println("In testIntersect method");
// Create a new Plan.
RowManager rowMgr = client.newRowManager();
PlanBuilder p = rowMgr.newPlanBuilder();
// plans from literals
ModifyPlan plan1 = p.fromLiterals(storeInformation);
ModifyPlan plan2 = p.fromLiterals(internetSales);
ModifyPlan output = plan1.select(p.col("txnDate"))
.intersect(plan2.select(p.col("txnDate")));
JacksonHandle jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(output, jacksonHandle);
JsonNode jsonBindingsNodes = jacksonHandle.get().path("rows");
// Should have 1 node returned.
assertEquals("One node not returned from testIntersect method", 1, jsonBindingsNodes.size());
assertEquals("Row 1 txnDate value incorrect", "Jan-07-1999", jsonBindingsNodes.path(0).path("txnDate").path("value").asText());
}
/*
* Test except
*/
@Test
public void testExcept() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException
{
System.out.println("In testExcept method");
// Create a new Plan.
RowManager rowMgr = client.newRowManager();
PlanBuilder p = rowMgr.newPlanBuilder();
// plans from literals
ModifyPlan plan1 = p.fromLiterals(storeInformation);
ModifyPlan plan2 = p.fromLiterals(internetSales);
ModifyPlan output = plan1.select(p.colSeq("txnDate"))
.except(plan2.select(p.colSeq("txnDate")));
JacksonHandle jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(output, jacksonHandle);
JsonNode jsonBindingsNodes = jacksonHandle.get().path("rows");
// Should have 3 nodes returned.
assertEquals("Three nodes not returned from testExcept method", 3, jsonBindingsNodes.size());
assertEquals("Row 1 txnDate value incorrect", "Jan-05-1999", jsonBindingsNodes.path(0).path("txnDate").path("value").asText());
assertEquals("Row 2 txnDate value incorrect", "Jan-08-1999", jsonBindingsNodes.path(1).path("txnDate").path("value").asText());
assertEquals("Row 3 txnDate value incorrect", "Jan-08-1999", jsonBindingsNodes.path(2).path("txnDate").path("value").asText());
}
/*
* Test arrayAggregate, sequenceAggregate and aggregate with distinct and
* duplicate options
*/
@Test
public void testAggregateSeq() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException
{
System.out.println("In testAggregateSeq method");
RowManager rowMgr = client.newRowManager();
PlanBuilder p = rowMgr.newPlanBuilder();
// Create a new Map for literals.
Map<String, Object> row = new HashMap<>();
Map<String, Object>[] fooLiteral = new HashMap[6];
Map<String, Object>[] purpleLiteral = new HashMap[6];
Map<String, Object>[] ballLiteral = new HashMap[6];
row.put("rowId", 1);
row.put("colorId", 1);
row.put("desc", "ball");
fooLiteral[0] = row;
row = new HashMap<>();
row.put("rowId", 1);
row.put("colorId", 3);
row.put("desc", "foo");
fooLiteral[1] = row;
row = new HashMap<>();
row.put("rowId", 2);
row.put("colorId", 2);
row.put("desc", "square");
fooLiteral[2] = row;
row = new HashMap<>();
row.put("rowId", 3);
row.put("colorId", 1);
row.put("desc", "box");
fooLiteral[3] = row;
row = new HashMap<>();
row.put("rowId", 4);
row.put("colorId", 1);
row.put("desc", "hoop");
fooLiteral[4] = row;
row = new HashMap<>();
row.put("rowId", 5);
row.put("colorId", 5);
row.put("desc", "circle");
fooLiteral[5] = row;
row = new HashMap<>();
row.put("colorId", 1);
row.put("colorDesc", "red");
purpleLiteral[0] = row;
// Add another red color
purpleLiteral[1] = row;
row = new HashMap<>();
row.put("colorId", 1);
row.put("colorDesc", "purple");
purpleLiteral[2] = row;
row = new HashMap<>();
row.put("colorId", 2);
row.put("colorDesc", "blue");
purpleLiteral[3] = row;
row = new HashMap<>();
row.put("colorId", 3);
row.put("colorDesc", "black");
purpleLiteral[4] = row;
row = new HashMap<>();
row.put("colorId", 4);
row.put("colorDesc", "yellow");
purpleLiteral[5] = row;
row = new HashMap<>();
row.put("rowId", 1);
row.put("colorId", 1);
row.put("desc", "ball");
ballLiteral[0] = row;
row = new HashMap<>();
row.put("rowId", 1);
row.put("colorId", 3);
row.put("desc", "ball");
ballLiteral[1] = row;
row = new HashMap<>();
row.put("rowId", 2);
row.put("colorId", 2);
row.put("desc", "square");
ballLiteral[2] = row;
row = new HashMap<>();
row.put("rowId", 3);
row.put("colorId", 1);
row.put("desc", "box");
ballLiteral[3] = row;
row = new HashMap<>();
row.put("rowId", 4);
row.put("colorId", 1);
row.put("desc", "hoop");
ballLiteral[4] = row;
row = new HashMap<>();
row.put("rowId", 5);
row.put("colorId", 5);
row.put("desc", "circle");
ballLiteral[5] = row;
// plans from literals
ModifyPlan plan1 = p.fromLiterals(fooLiteral, "myItem");
ModifyPlan plan2 = p.fromLiterals(purpleLiteral, "myColor");
PlanColumn rowIdExp = p.viewCol("myItem", "rowId");
PlanColumn itemColorIdCol = p.viewCol("myItem", "colorId");
PlanColumn colorIdCol = p.viewCol("myColor", "colorId");
ModifyPlan outputAgg = plan1.joinInner(plan2, p.on(itemColorIdCol, colorIdCol))
.groupBy(rowIdExp, p.arrayAggregate("colorIdArray", "colorDesc"))
.orderBy(p.sortKeySeq(p.col("rowId")));
JacksonHandle jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(outputAgg, jacksonHandle);
JsonNode jsonBindingsNodes = jacksonHandle.get().path("rows");
// Should have 4 nodes returned.
assertEquals("Four nodes not returned from testAggregateSeq method", 4, jsonBindingsNodes.size());
assertEquals("Row 1 myItem.rowId value incorrect", "1", jsonBindingsNodes.path(0).path("myItem.rowId").path("value").asText());
assertEquals("Row 1 colorIdArray length value incorrect", 4, jsonBindingsNodes.path(0).path("colorIdArray").path("value").size());
assertEquals("Row 2 colorIdArray array 1 value incorrect", "blue", jsonBindingsNodes.path(1).path("colorIdArray").path("value").path(0).asText());
// sequenceAggregate
ModifyPlan outputSeqAgg = plan1.joinInner(plan2, p.on(itemColorIdCol, colorIdCol))
.groupBy(rowIdExp, p.sequenceAggregate("colorIdArray", "colorDesc"))
.orderBy(p.sortKeySeq(p.col("rowId")));
jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(outputSeqAgg, jacksonHandle);
jsonBindingsNodes = jacksonHandle.get().path("rows");
// Should have 4 nodes returned.
assertEquals("Four nodes not returned from testAggregateSeq method", 4, jsonBindingsNodes.size());
assertEquals("Row 1 myItem.rowId value incorrect", "1", jsonBindingsNodes.path(0).path("myItem.rowId").path("value").asText());
assertEquals("Row 1 colorIdArray length value incorrect", 4, jsonBindingsNodes.path(0).path("colorIdArray").path("value").size());
assertEquals("Row 2 colorIdArray array 1 value incorrect", "blue", jsonBindingsNodes.path(1).path("colorIdArray").path("value").asText());
// TEST 37 - aggregate with distinct option
// plans from literals
ModifyPlan plan3 = p.fromLiterals(ballLiteral);
ModifyPlan plan4 = p.fromLiterals(literals2);
// Verify DISTINCT
PlanAggregateColSeq aggColSeq = p.aggregateSeq(p.count("descAgg", "desc", PlanValueOption.DISTINCT));
PlanExprColSeq colSeq = p.colSeq("rowId");
ModifyPlan outputCountDist = plan3.joinInner(plan4)
.groupBy(colSeq, aggColSeq)
.orderBy(p.sortKeySeq(p.col("rowId")));
jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(outputCountDist, jacksonHandle);
jsonBindingsNodes = jacksonHandle.get().path("rows");
// Should have 4 nodes returned.
assertEquals("Four node not returned from testAggregateSeq method", 4, jsonBindingsNodes.size());
assertEquals("Row 1 rowId value incorrect", "1", jsonBindingsNodes.path(0).path("rowId").path("value").asText());
assertEquals("Row 1 descAgg value incorrect", 1, jsonBindingsNodes.path(0).path("descAgg").path("value").asInt());
assertEquals("Row 1 rowId value incorrect", "4", jsonBindingsNodes.path(3).path("rowId").path("value").asText());
assertEquals("Row 1 descAgg value incorrect", 1, jsonBindingsNodes.path(3).path("descAgg").path("value").asInt());
// aggregate with duplicate option
PlanAggregateColSeq aggColSeqDup = p.aggregateSeq(p.count("descAgg", "desc", PlanValueOption.DUPLICATE));
PlanExprColSeq colSeqDup = p.colSeq("rowId");
ModifyPlan outputCountDup = plan3.joinInner(plan4)
.groupBy(colSeqDup, aggColSeqDup)
.orderBy(p.sortKeySeq(p.col("rowId")));
jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(outputCountDup, jacksonHandle);
JsonNode jsonBindingsNodesDup = jacksonHandle.get().path("rows");
// Should have 4 nodes returned. Duplicate values are included.
assertEquals("Four node not returned from testAggregateSeq method", 4, jsonBindingsNodesDup.size());
assertEquals("Row 1 rowId value incorrect", "1", jsonBindingsNodesDup.path(0).path("rowId").path("value").asText());
assertEquals("Row 1 descAgg value incorrect", 2, jsonBindingsNodesDup.path(0).path("descAgg").path("value").asInt());
assertEquals("Row 1 rowId value incorrect", "4", jsonBindingsNodesDup.path(3).path("rowId").path("value").asText());
assertEquals("Row 1 descAgg value incorrect", 1, jsonBindingsNodesDup.path(3).path("descAgg").path("value").asInt());
}
/*
* Test date time builtin functions
*/
@Ignore
public void testBuiltInFns() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException
{
System.out.println("In testBuiltInFns method");
// Create a new Plan.
RowManager rowMgr = client.newRowManager();
PlanBuilder p = rowMgr.newPlanBuilder();
// plans from literals
ModifyPlan plan1 = p.fromLiterals(literals1, "myItem");
ModifyPlan plan2 = p.fromLiterals(literals2, "myColor");
PlanColumn descCol = p.viewCol("myItem", "desc");
PlanColumn itemColorIdCol = p.viewCol("myItem", "colorId");
PlanColumn colorIdCol = p.viewCol("myColor", "colorId");
/*
* XsDateExpr curDate = p.fn.currentDate(); XsTimeExpr curTime =
* p.fn.currentTime(); SqlGenericDateTimeExpr sqlcurTime =
* (SqlGenericDateTimeExpr) curTime; double sqlHr = p.sql.hours(sqlcurTime);
*
* PlanColumn log10 = p.math.log10(sqlHr); ModifyPlan output =
* plan1.joinInner(plan2, p.on(itemColorIdCol, colorIdCol)) .select(
* p.as("currentDate", p.fn.currentDate()), p.as("curDate", curDate),
* p.as("currentTime", p.fn.currentTime()), p.as("curTime", curTime),
* p.as("upperCase", p.fn.upperCase(p.col("desc"))), p.as("semNum",
* p.sem.isLiteral(p.col("desc"))), p.as("sqlHours",
* p.sql.hours(sqlcurTime)), p.as("sqlHr", sqlHr), p.as("mathLog10",
* p.math.log10(p.col("sqlHours"))), p.as("log10", log10) )
* .orderBy(p.col("upperCase"));
*/
// TODO Wait until Erik H comes back on this to discuss the recent changes
// to SQL types.
JacksonHandle jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
// rowMgr.resultDoc(output, jacksonHandle);
JsonNode jsonBindingsNodes = jacksonHandle.get().path("rows");
// Should have 2 nodes returned.
assertEquals("Two nodes not returned from testExcept method", 3, jsonBindingsNodes.size());
}
/*
* Test invalid rowdef
*/
@Test
public void testInvalidDefinitions() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException
{
System.out.println("In testInvalidDefinitions method");
// Create a new Plan.
RowManager rowMgr = client.newRowManager();
PlanBuilder p = rowMgr.newPlanBuilder();
// plans from literals
ModifyPlan plan1 = p.fromLiterals(literals1);
ModifyPlan plan2 = p.fromLiterals(literals2);
ModifyPlan output = plan1.joinInner(plan2)
.where(p.eq(p.col("colorId"), p.xs.intVal(1)))
.select(p.colSeq("rowIdRef", "desc", "colorId", "colorDesc"));
JacksonHandle jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
StringBuilder str = new StringBuilder();
try {
rowMgr.resultDoc(output, jacksonHandle);
} catch (Exception ex) {
str.append(ex.getMessage());
System.out.println("Exception message is " + str.toString());
}
// Should have SQL-NOCOLUMN exceptions.
assertTrue("Exceptions not found", str.toString().contains("SQL-NOCOLUMN"));
assertTrue("Exceptions not found", str.toString().contains("Column not found: rowIdRef"));
// invalid viewCol
ModifyPlan outputExtCol = plan1.joinInner(plan2)
.where(p.eq(p.viewCol("invalid_view", "colorId"), p.xs.intVal(1)))
.offsetLimit(1, 3);
str = new StringBuilder();
try {
rowMgr.resultDoc(outputExtCol, jacksonHandle);
} catch (Exception ex) {
str.append(ex.getMessage());
System.out.println("Exception message is " + str.toString());
}
// Should have SQL-NOCOLUMN exceptions.
assertTrue("Exceptions not found", str.toString().contains("SQL-NOCOLUMN"));
assertTrue("Exceptions not found", str.toString().contains("Column not found: invalid_view.colorId"));
}
/*
* Test offsetLimit with negative offset
*/
@Test
public void testNegativeOffset() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException
{
System.out.println("In testNegativeOffset method");
// Create a new Plan.
RowManager rowMgr = client.newRowManager();
PlanBuilder p = rowMgr.newPlanBuilder();
// plans from literals
ModifyPlan plan1 = p.fromLiterals(literals1);
ModifyPlan plan2 = p.fromLiterals(literals2);
ModifyPlan output = plan1.joinInner(plan2)
.where(p.eq(p.col("colorId"), p.xs.intVal(1)))
.offsetLimit(-1, 1)
.select(p.colSeq("rowId", "desc", "colorId", "colorDesc"));
JacksonHandle jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
StringBuilder str = new StringBuilder();
try {
rowMgr.resultDoc(output, jacksonHandle);
} catch (Exception ex) {
str.append(ex.getMessage());
System.out.println("Exception message is " + str.toString());
}
// Should have OPTIC-INVALARGS exceptions.
assertTrue("Exceptions not found", str.toString().contains("OPTIC-INVALARGS"));
assertTrue("Exceptions not found", str.toString().contains("Invalid arguments: offset must be a non-negative number: -1"));
}
/*
* Test invalid qualifier
*/
@Test
public void testInvalidQualifier() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException
{
System.out.println("In testInvalidQualifier method");
// Create a new Plan.
RowManager rowMgr = client.newRowManager();
PlanBuilder p = rowMgr.newPlanBuilder();
// plans from literals
ModifyPlan plan1 = p.fromLiterals(literals1, "table1");
ModifyPlan plan2 = p.fromLiterals(literals2, "table2");
ModifyPlan output = plan1.joinInner(plan2)
.where(p.eq(p.viewCol("table1_Invalid", "colorId"), p.viewCol("table2", "colorId")))
.orderBy(p.desc(p.viewCol("table1", "rowId")));
JacksonHandle jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
StringBuilder str = new StringBuilder();
try {
rowMgr.resultDoc(output, jacksonHandle);
} catch (Exception ex) {
str.append(ex.getMessage());
System.out.println("Exception message is " + str.toString());
}
// Should have OPTIC-INVALARGS exceptions.
assertTrue("Exceptions not found", str.toString().contains("SQL-NOCOLUMN"));
assertTrue("Exceptions not found", str.toString().contains("Column not found: table1_Invalid.colorId"));
}
/*
* Test Map function Uses JS function colorIdMapper installed in the REST
* server module database.
*/
@Test
public void testMapFunction() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException
{
System.out.println("In testMapFunction method");
Map<String, Object>[] literalsM1 = new HashMap[5];
Map<String, Object>[] literalsM2 = new HashMap[4];
Map<String, Object> row = new HashMap<>();
row.put("rowId", 1);
row.put("colorId_shape", 1);
row.put("desc", "ball");
literalsM1[0] = row;
row = new HashMap<>();
row.put("rowId", 2);
row.put("colorId_shape", 2);
row.put("desc", "square");
literalsM1[1] = row;
row = new HashMap<>();
row.put("rowId", 3);
row.put("colorId_shape", 1);
row.put("desc", "box");
literalsM1[2] = row;
row = new HashMap<>();
row.put("rowId", 4);
row.put("colorId_shape", 1);
row.put("desc", "hoop");
literalsM1[3] = row;
row = new HashMap<>();
row.put("rowId", 5);
row.put("colorId_shape", 5);
row.put("desc", "circle");
literalsM1[4] = row;
// Assemble literalsM2
row = new HashMap<>();
row.put("colorId", 1);
row.put("colorDesc", "red");
literalsM2[0] = row;
row = new HashMap<>();
row.put("colorId", 2);
row.put("colorDesc", "blue");
literalsM2[1] = row;
row = new HashMap<>();
row.put("colorId", 3);
row.put("colorDesc", "black");
literalsM2[2] = row;
row = new HashMap<>();
row.put("colorId", 4);
row.put("colorDesc", "yellow");
literalsM2[3] = row;
RowManager rowMgr = client.newRowManager();
PlanBuilder p = rowMgr.newPlanBuilder();
// plans from literals
ModifyPlan plan1 = p.fromLiterals(literalsM1);
ModifyPlan plan2 = p.fromLiterals(literalsM2);
ExportablePlan output = plan1.joinInner(plan2, p.on(p.col("colorId_shape"), p.col("colorId")))
.select(
p.as("rowId", p.col("rowId")),
p.as("description", p.col("desc")),
p.as("myColorId", p.col("colorId"))
)
.orderBy(p.asc("rowId"))
.map(p.resolveFunction(p.xs.QName("colorIdMapper"), "/marklogic.rest.resource/OpticsJSResourceModule/assets/resource.sjs"));
JacksonHandle jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(output, jacksonHandle);
JsonNode jsonBindingsNodes = jacksonHandle.get().path("rows");
// Should have 4 node returned.
assertEquals("Four nodes not returned from testMapFunction method", 4, jsonBindingsNodes.size());
assertEquals("Row 1 rowId value incorrect", "1", jsonBindingsNodes.path(0).path("rowId").path("value").asText());
assertEquals("Row 1 myColorId value incorrect", "RED ROBIN", jsonBindingsNodes.path(0).path("myColorId").path("value").asText());
assertEquals("Row 1 description value incorrect", "ball", jsonBindingsNodes.path(0).path("description").path("value").asText());
assertEquals("Row 2 rowId value incorrect", "2", jsonBindingsNodes.path(1).path("rowId").path("value").asText());
assertEquals("Row 2 myColorId value incorrect", "BLUE JAY", jsonBindingsNodes.path(1).path("myColorId").path("value").asText());
assertEquals("Row 2 description value incorrect", "square", jsonBindingsNodes.path(1).path("description").path("value").asText());
assertEquals("Row 3 rowId value incorrect", "4", jsonBindingsNodes.path(3).path("rowId").path("value").asText());
assertEquals("Row 3 myColorId value incorrect", "RED ROBIN", jsonBindingsNodes.path(3).path("myColorId").path("value").asText());
assertEquals("Row 3 description value incorrect", "hoop", jsonBindingsNodes.path(3).path("description").path("value").asText());
}
/*
* Test Reduce function Uses JS function fibReducer installed in the REST
* server module database.
*/
@Test
public void testReduceFunction() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException
{
System.out.println("In testReduceFunction method");
Map<String, Object>[] literalsM1 = new HashMap[5];
Map<String, Object>[] literalsM2 = new HashMap[4];
Map<String, Object> row = new HashMap<>();
row.put("rowId", 1);
row.put("colorId_shape", 1);
row.put("desc", "ball");
literalsM1[0] = row;
row = new HashMap<>();
row.put("rowId", 2);
row.put("colorId_shape", 2);
row.put("desc", "square");
literalsM1[1] = row;
row = new HashMap<>();
row.put("rowId", 3);
row.put("colorId_shape", 1);
row.put("desc", "box");
literalsM1[2] = row;
row = new HashMap<>();
row.put("rowId", 4);
row.put("colorId_shape", 1);
row.put("desc", "hoop");
literalsM1[3] = row;
row = new HashMap<>();
row.put("rowId", 5);
row.put("colorId_shape", 5);
row.put("desc", "circle");
literalsM1[4] = row;
// Assemble literalsM2
row = new HashMap<>();
row.put("colorId", 1);
row.put("colorDesc", "red");
literalsM2[0] = row;
row = new HashMap<>();
row.put("colorId", 2);
row.put("colorDesc", "blue");
literalsM2[1] = row;
row = new HashMap<>();
row.put("colorId", 3);
row.put("colorDesc", "black");
literalsM2[2] = row;
row = new HashMap<>();
row.put("colorId", 4);
row.put("colorDesc", "yellow");
literalsM2[3] = row;
RowManager rowMgr = client.newRowManager();
PlanBuilder p = rowMgr.newPlanBuilder();
// plans from literals
ModifyPlan plan1 = p.fromLiterals(literalsM1);
ModifyPlan plan2 = p.fromLiterals(literalsM2);
ExportablePlan output = plan1.joinInner(plan2, p.on(p.col("colorId_shape"), p.col("colorId")))
.select(
p.as("myRowId", p.col("rowId"))
)
.orderBy(p.asc("myRowId"))
.reduce(p.resolveFunction(p.xs.QName("fibReducer"), "/marklogic.rest.resource/OpticsJSResourceModule/assets/resource.sjs"));
JacksonHandle jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(output, jacksonHandle);
JsonNode jsonBindingsNodes = jacksonHandle.get().path("rows");
// Should have 4 node returned.
assertEquals("Four nodes not returned from testMapFunction method", 4, jsonBindingsNodes.size());
assertEquals("Row 1 rowId value incorrect", "1", jsonBindingsNodes.path(0).path("myRowId").path("value").asText());
assertEquals("Row 1 myColorId value incorrect", "0", jsonBindingsNodes.path(0).path("i").path("value").asText());
assertEquals("Row 1 description value incorrect", "0", jsonBindingsNodes.path(0).path("fib").path("value").asText());
assertEquals("Row 2 rowId value incorrect", "2", jsonBindingsNodes.path(1).path("myRowId").path("value").asText());
assertEquals("Row 2 myColorId value incorrect", "1", jsonBindingsNodes.path(1).path("i").path("value").asText());
assertEquals("Row 2 description value incorrect", "1", jsonBindingsNodes.path(1).path("fib").path("value").asText());
assertEquals("Row 3 rowId value incorrect", "4", jsonBindingsNodes.path(3).path("myRowId").path("value").asText());
assertEquals("Row 3 myColorId value incorrect", "3", jsonBindingsNodes.path(3).path("i").path("value").asText());
assertEquals("Row 3 description value incorrect", "2", jsonBindingsNodes.path(3).path("fib").path("value").asText());
}
/*
* Test existJoin with literals
*/
@Test
public void testExistJoin() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException {
System.out.println("In testExistJoin method");
Map<String, Object>[] colLiteral = new HashMap[7];
Map<String, Object>[] invLiteral = new HashMap[6];
Map<String, Object> row = new HashMap<>();
row.put("rowId", 1);
row.put("colorId", 1);
row.put("desc", "ball");
row.put("colorDesc", "red");
invLiteral[0] = row;
row = new HashMap<>();
row.put("rowId", 2);
row.put("colorId", 2);
row.put("desc", "square");
row.put("colorDesc", "blue");
invLiteral[1] = row;
row = new HashMap<>();
row.put("rowId", 3);
row.put("colorId", 1);
row.put("desc", "box");
row.put("colorDesc", "red");
invLiteral[2] = row;
row = new HashMap<>();
row.put("rowId", 4);
row.put("colorId", 3);
row.put("desc", "hoop");
row.put("colorDesc", "black");
invLiteral[3] = row;
row = new HashMap<>();
row.put("rowId", 5);
row.put("colorId", 4);
row.put("desc", "circle");
row.put("colorDesc", "yellow");
invLiteral[4] = row;
row = new HashMap<>();
row.put("rowId", 6);
row.put("colorId", 5);
row.put("desc", "car");
row.put("colorDesc", "YELLOW");
invLiteral[5] = row;
row = new HashMap<>();
row.put("colorId", 1);
row.put("colorDesc", "red");
colLiteral[0] = row;
row = new HashMap<>();
row.put("colorId", 2);
row.put("colorDesc", "blue");
colLiteral[1] = row;
row = new HashMap<>();
row.put("colorId", 3);
row.put("colorDesc", "black");
colLiteral[2] = row;
row = new HashMap<>();
row.put("colorId", 4);
row.put("colorDesc", "yellow");
colLiteral[3] = row;
row = new HashMap<>();
row.put("colorId", 5);
row.put("colorDesc", "YELLOW");
colLiteral[4] = row;
row = new HashMap<>();
row.put("colorId", 6);
row.put("colorDesc", "Yellow");
colLiteral[5] = row;
row = new HashMap<>();
row.put("colorId", 7);
row.put("colorDesc", "yellowish");
colLiteral[6] = row;
ArrayList<String> exptdExists = new ArrayList<String>();
exptdExists.add("red");
exptdExists.add("black");
exptdExists.add("blue");
exptdExists.add("yellow");
exptdExists.add("YELLOW");
Collections.sort(exptdExists);
// Create a new Plan.
RowManager rowMgr = client.newRowManager();
PlanBuilder p = rowMgr.newPlanBuilder();
// plans from literals
ModifyPlan plan1 = p.fromLiterals(colLiteral, "table1");
ModifyPlan plan2 = p.fromLiterals(invLiteral, "table2");
ModifyPlan existsOutput = plan1.existsJoin(plan2, p.on(p.viewCol("table1", "colorDesc"), p.viewCol("table2", "colorDesc")));
JacksonHandle jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(existsOutput, jacksonHandle);
JsonNode jsonBindingsNodes = jacksonHandle.get().path("rows");
ArrayList<String> existColorList = new ArrayList<String>();
existColorList.add(jsonBindingsNodes.path(0).path("table1.colorDesc").path("value").asText());
existColorList.add(jsonBindingsNodes.path(1).path("table1.colorDesc").path("value").asText());
existColorList.add(jsonBindingsNodes.path(2).path("table1.colorDesc").path("value").asText());
existColorList.add(jsonBindingsNodes.path(3).path("table1.colorDesc").path("value").asText());
existColorList.add(jsonBindingsNodes.path(4).path("table1.colorDesc").path("value").asText());
Collections.sort(existColorList);
assertTrue("Error while return from existsJoin", existColorList.equals(exptdExists));
// existJoin with literals - without on parameters
ModifyPlan existsNoOptionsOutput = plan2.existsJoin(plan1).orderBy(p.desc(p.col("desc")));
jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(existsNoOptionsOutput, jacksonHandle);
jsonBindingsNodes = jacksonHandle.get().path("rows");
assertEquals("Element 1 desc value incorrect", "square", jsonBindingsNodes.path(0).path("table2.desc").path("value").asText());
assertEquals("Element 3 desc value incorrect", "circle", jsonBindingsNodes.path(2).path("table2.desc").path("value").asText());
assertEquals("Element 6 desc value incorrect", "ball", jsonBindingsNodes.path(5).path("table2.desc").path("value").asText());
// not exists join
ModifyPlan notExistsOutput = plan1.notExistsJoin(plan2, p.on(p.viewCol("table1", "colorDesc"), p.viewCol("table2", "colorDesc")));
jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(notExistsOutput, jacksonHandle);
jsonBindingsNodes = jacksonHandle.get().path("rows");
ArrayList<String> exptdNotExists = new ArrayList<String>();
exptdNotExists.add("Yellow");
exptdNotExists.add("yellowish");
Collections.sort(exptdNotExists);
ArrayList<String> notExistColorList = new ArrayList<String>();
notExistColorList.add(jsonBindingsNodes.path(0).path("table1.colorDesc").path("value").asText());
notExistColorList.add(jsonBindingsNodes.path(1).path("table1.colorDesc").path("value").asText());
Collections.sort(notExistColorList);
assertTrue("Error while return from notExistsJoin", notExistColorList.equals(exptdNotExists));
}
/*
* Test facetBy and bucketGroups
*/
@Test
public void testFacetByWithBucketGroups() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException {
System.out.println("In testFacetByWithBucketGroups method");
Map<String, Object>[] invLiteral = new HashMap[17];
Map<String, Object>[] colLiteral = new HashMap[6];
Map<String, Object> row = new HashMap<>();
row = new HashMap<>();
row.put("rowId", 1); row.put("colorId", 1); row.put("desc", "ball");
invLiteral[0] = row;
row = new HashMap<>();
row.put("rowId", 2); row.put("colorId", 2); row.put("desc", "square");
invLiteral[1] = row;
row = new HashMap<>();
row.put("rowId", 3); row.put("colorId", 1); row.put("desc", "box");
invLiteral[2] = row;
row = new HashMap<>();
row.put("rowId", 4); row.put("colorId", 1); row.put("desc", "hoop");
invLiteral[3] = row;
row = new HashMap<>();
row.put("rowId", 5); row.put("colorId", 5); row.put("desc", "circle");
invLiteral[4] = row;
row = new HashMap<>();
row.put("rowId", 6); row.put("colorId", 1); row.put("desc", "key");
invLiteral[5] = row;
row = new HashMap<>();
row.put("rowId", 7); row.put("colorId", 1); row.put("desc", "cup");
invLiteral[6] = row;
row = new HashMap<>();
row.put("rowId", 8); row.put("colorId", 1); row.put("desc", "bike");
invLiteral[7] = row;
row = new HashMap<>();
row.put("rowId", 9); row.put("colorId", 3); row.put("desc", "car");
invLiteral[8] = row;
row = new HashMap<>();
row.put("rowId", 10); row.put("colorId", 3); row.put("desc", "cart");
invLiteral[9] = row;
row = new HashMap<>();
row.put("rowId", 11); row.put("colorId", 4); row.put("desc", "cupholder");
invLiteral[10] = row;
row = new HashMap<>();
row.put("rowId", 12); row.put("colorId", 2); row.put("desc", "scooter");
invLiteral[11] = row;
row = new HashMap<>();
row.put("rowId", 13); row.put("colorId", 5); row.put("desc", "hat");
invLiteral[12] = row;
row = new HashMap<>();
row.put("rowId", 14); row.put("colorId", 3); row.put("desc", "booster");
invLiteral[13] = row;
row = new HashMap<>();
row.put("rowId", 15); row.put("colorId", 3); row.put("desc", "knapsack");
invLiteral[14] = row;
row = new HashMap<>();
row.put("rowId", 16); row.put("colorId", 1); row.put("desc", "hovercraft");
invLiteral[15] = row;
row = new HashMap<>();
row.put("rowId", 17); row.put("colorId", 6); row.put("desc", "dice");
invLiteral[16] = row;
row = new HashMap<>();
row.put("colorId", 1);
row.put("colorDesc", "red");
colLiteral[0] = row;
row = new HashMap<>();
row.put("colorId", 2);
row.put("colorDesc", "blue");
colLiteral[1] = row;
row = new HashMap<>();
row.put("colorId", 3);
row.put("colorDesc", "black");
colLiteral[2] = row;
row = new HashMap<>();
row.put("colorId", 4);
row.put("colorDesc", "yellow");
colLiteral[3] = row;
row = new HashMap<>();
row.put("colorId", 5);
row.put("colorDesc", "white");
colLiteral[4] = row;
row = new HashMap<>();
row.put("colorId", 6);
row.put("colorDesc", "grey");
colLiteral[5] = row;
// Create a new Plan.
RowManager rowMgr = client.newRowManager();
PlanBuilder p = rowMgr.newPlanBuilder();
// plans from literals
ModifyPlan plan1 = p.fromLiterals(invLiteral, "table1");
ModifyPlan plan2 = p.fromLiterals(colLiteral, "table2");
ModifyPlan output1 = plan1.joinInner(plan2)
.where(p.eq(p.viewCol("table1","colorId"), p.viewCol("table2","colorId")))
.facetBy(p.namedGroupSeq(p.bucketGroup(p.xs.string("colorBucket"), p.viewCol("table1","colorId"), p.xs.integerSeq(2, 4) )));
JacksonHandle jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(output1, jacksonHandle);
JsonNode colorBucketNodes = jacksonHandle.get().path("rows");
assertEquals("Bucket group 1 count value incorrect", "9", colorBucketNodes.path(0).path("colorBucket").path("value").path(0).path("count").asText());
assertEquals("Bucket group 2 count value incorrect", "5", colorBucketNodes.path(0).path("colorBucket").path("value").path(1).path("count").asText());
assertEquals("Bucket group 3 count value incorrect", "3", colorBucketNodes.path(0).path("colorBucket").path("value").path(2).path("count").asText());
// outside range
ModifyPlan output2 = plan1.joinInner(plan2)
.where(p.eq(p.viewCol("table1","colorId"), p.viewCol("table2","colorId")))
.facetBy(p.namedGroupSeq(p.bucketGroup(p.xs.string("colorBucket"), p.viewCol("table1","colorId"), p.xs.integerSeq(-1, 0) )));
jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(output2, jacksonHandle);
JsonNode colorBucketNodesNoRange = jacksonHandle.get().path("rows");
assertEquals("Bucket group 1 count value incorrect", "17", colorBucketNodesNoRange.path(0).path("colorBucket").path("value").path(0).path("count").asText());
// string range
ModifyPlan output3 = plan1.joinInner(plan2)
.where(p.eq(p.viewCol("table1","colorId"), p.viewCol("table2","colorId")))
.facetBy(p.namedGroupSeq(p.bucketGroup(p.xs.string("descBucket"), p.col("desc"), p.xs.stringSeq("ball", "dice"))));
jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
rowMgr.resultDoc(output3, jacksonHandle);
JsonNode descBucketNodesStringRange = jacksonHandle.get().path("rows");
assertEquals("Bucket group 1 count value incorrect", "1", descBucketNodesStringRange.path(0).path("descBucket").path("value").path(0).path("count").asText());
assertEquals("Bucket group 2 count value incorrect", "9", descBucketNodesStringRange.path(0).path("descBucket").path("value").path(1).path("count").asText());
assertEquals("Bucket group 3 count value incorrect", "7", descBucketNodesStringRange.path(0).path("descBucket").path("value").path(2).path("count").asText());
//bucket group negative test
ModifyPlan output4 = plan1.joinInner(plan2)
.where(p.eq(p.viewCol("table1","colorId"), p.viewCol("table2","colorId")))
.facetBy(p.namedGroupSeq(p.bucketGroup(p.xs.string("colorBucket"), p.viewCol("table1","colorId"), p.xs.integerSeq(1, 0) )));
jacksonHandle = new JacksonHandle();
jacksonHandle.setMimetype("application/json");
try {
rowMgr.resultDoc(output4, jacksonHandle);
} catch (Exception ex) {
assertTrue("Incorrect error/exception message", ex.getMessage().contains("failed to apply resource at rows: Internal Server Error"));
}
System.out.println("End");
}
// @AfterClass
public static void tearDownAfterClass() throws Exception
{
System.out.println("In tear down");
// Delete the services.
resourceMgr.deleteServices(resourceName);
// Delete the temp schema DB after resetting the Schema DB on content DB.
// Else delete fails.
deleteUserRole("opticRole");
deleteRESTUser("opticUser");
setDatabaseProperties(dbName, "schema-database", dbName);
deleteDB(schemadbName);
deleteForest(schemafNames[0]);
// release client
clientRes.release();
client.release();
cleanupRESTServer(dbName, fNames);
deleteRESTUser("eval-user");
deleteUserRole("test-eval");
}
}
| Uncommented after class method
| marklogic-client-api-functionaltests/src/test/java/com/marklogic/client/functionaltest/TestOpticOnLiterals.java | Uncommented after class method | <ide><path>arklogic-client-api-functionaltests/src/test/java/com/marklogic/client/functionaltest/TestOpticOnLiterals.java
<ide> } catch (Exception ex) {
<ide> assertTrue("Incorrect error/exception message", ex.getMessage().contains("failed to apply resource at rows: Internal Server Error"));
<ide> }
<del>
<del> System.out.println("End");
<del> }
<del>
<del> // @AfterClass
<add> }
<add>
<add> @AfterClass
<ide> public static void tearDownAfterClass() throws Exception
<ide> {
<ide> System.out.println("In tear down"); |
|
Java | mit | 007cf407cc8fac1dd331bc02523ab02839f5a256 | 0 | earlwlkr/awesomeFb,earlwlkr/awesomeFb,earlwlkr/awesomeFb | package awesomefb;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
import java.net.UnknownHostException;
/**
* Created by earl on 5/25/2015.
*/
public class DatabaseManager {
private static DatabaseManager instance = null;
private DB database;
private DBCollection postsCollection;
private DBCollection usersCollection;
public static DatabaseManager getInstance() {
if (instance == null) {
try {
MongoClient mongoClient = new MongoClient();
DB db = mongoClient.getDB("awesomefb");
instance = new DatabaseManager(db);
} catch (UnknownHostException e) {
System.out.println(e.toString());
}
}
return instance;
}
protected DatabaseManager(DB database) {
this.database = database;
postsCollection = this.database.getCollection("posts");
usersCollection = this.database.getCollection("users");
postsCollection.drop();
usersCollection.drop();
}
public void insertPost(ExtractedPost post) {
postsCollection.insert(post.toDBObject());
}
public void insertUser(ExtractedUser user) {
usersCollection.insert(user.toDBObject());
}
}
| backend/src/main/java/awesomefb/DatabaseManager.java | package awesomefb;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
import java.net.UnknownHostException;
/**
* Created by earl on 5/25/2015.
*/
public class DatabaseManager {
private static DatabaseManager instance = null;
private DB database;
private DBCollection postsCollection;
private DBCollection usersCollection;
public static DatabaseManager getInstance() {
if (instance == null) {
try {
MongoClient mongoClient = new MongoClient();
DB db = mongoClient.getDB("awesomefb");
instance = new DatabaseManager(db);
} catch (UnknownHostException e) {
System.out.println(e.toString());
}
}
return instance;
}
protected DatabaseManager(DB database) {
this.database = database;
postsCollection = this.database.getCollection("posts");
usersCollection = this.database.getCollection("users");
postsCollection.drop();
usersCollection.drop();
}
public DBCollection getPostsCollection() {
return postsCollection;
}
public DBCollection getUsersCollection() {
return usersCollection;
}
}
| DatabaseManager class
| backend/src/main/java/awesomefb/DatabaseManager.java | DatabaseManager class | <ide><path>ackend/src/main/java/awesomefb/DatabaseManager.java
<ide> package awesomefb;
<ide>
<add>import com.mongodb.BasicDBObject;
<ide> import com.mongodb.DB;
<ide> import com.mongodb.DBCollection;
<ide> import com.mongodb.MongoClient;
<ide> usersCollection.drop();
<ide> }
<ide>
<del> public DBCollection getPostsCollection() {
<del> return postsCollection;
<add> public void insertPost(ExtractedPost post) {
<add> postsCollection.insert(post.toDBObject());
<ide> }
<ide>
<del> public DBCollection getUsersCollection() {
<del> return usersCollection;
<add> public void insertUser(ExtractedUser user) {
<add> usersCollection.insert(user.toDBObject());
<ide> }
<ide> } |
|
Java | mit | 307d4adfd6192697cebf7f34b1ab9aea362c3831 | 0 | HumBuch/HumBuch,HumBuch/HumBuch,HumBuch/HumBuch | package de.dhbw.humbuch.model.entity;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import de.dhbw.humbuch.model.entity.TeachingMaterial.Term;
@Entity
@Table(name="schoolYear")
public class SchoolYear implements de.dhbw.humbuch.model.entity.Entity, Serializable {
private static final long serialVersionUID = -3752454317452902743L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String year;
private Date fromDate;
private Date toDate;
private Date endFirstTerm;
private Date beginSecondTerm;
public SchoolYear() {}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public Date getFromDate() {
return fromDate;
}
public void setFromDate(Date fromDate) {
this.fromDate = fromDate;
}
public Date getToDate() {
return toDate;
}
public void setToDate(Date toDate) {
this.toDate = toDate;
}
public Date getEndFirstTerm() {
return endFirstTerm;
}
public void setEndFirstTerm(Date endFirstTerm) {
this.endFirstTerm = endFirstTerm;
}
public Date getBeginSecondTerm() {
return beginSecondTerm;
}
public void setBeginSecondTerm(Date beginSecondTerm) {
this.beginSecondTerm = beginSecondTerm;
}
public Term getCurrentTerm() {
if(getEndFirstTerm().after(new Date())) {
return Term.FIRST;
} else {
return Term.SECOND;
}
}
public static class Builder {
private final String year;
private final Date fromDate;
private final Date toDate;
private Date endFirstTerm;
private Date beginSecondTerm;
public Builder(String year, Date fromDate, Date toDate) {
this.year = year;
this.fromDate = fromDate;
this.toDate = toDate;
}
public Builder endFirstTerm(Date endFirstTerm) {
this.endFirstTerm = endFirstTerm;
return this;
}
public Builder beginSecondTerm(Date beginSecondTerm) {
this.beginSecondTerm = beginSecondTerm;
return this;
}
public SchoolYear build() {
return new SchoolYear(this);
}
}
private SchoolYear(Builder builder) {
this.year = builder.year;
this.fromDate = builder.fromDate;
this.toDate = builder.toDate;
this.endFirstTerm = builder.endFirstTerm;
this.beginSecondTerm = builder.beginSecondTerm;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof SchoolYear))
return false;
SchoolYear other = (SchoolYear) obj;
if (getId() != other.getId())
return false;
return true;
}
}
| src/main/java/de/dhbw/humbuch/model/entity/SchoolYear.java | package de.dhbw.humbuch.model.entity;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="schoolYear")
public class SchoolYear implements de.dhbw.humbuch.model.entity.Entity, Serializable {
private static final long serialVersionUID = -3752454317452902743L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String year;
private Date fromDate;
private Date toDate;
private Date endFirstTerm;
private Date beginSecondTerm;
public SchoolYear() {}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public Date getFromDate() {
return fromDate;
}
public void setFromDate(Date fromDate) {
this.fromDate = fromDate;
}
public Date getToDate() {
return toDate;
}
public void setToDate(Date toDate) {
this.toDate = toDate;
}
public Date getEndFirstTerm() {
return endFirstTerm;
}
public void setEndFirstTerm(Date endFirstTerm) {
this.endFirstTerm = endFirstTerm;
}
public Date getBeginSecondTerm() {
return beginSecondTerm;
}
public void setBeginSecondTerm(Date beginSecondTerm) {
this.beginSecondTerm = beginSecondTerm;
}
public int getCurrentTerm() {
if(getEndFirstTerm().after(new Date())) {
return new Integer(1);
} else {
return new Integer(2);
}
}
public static class Builder {
private final String year;
private final Date fromDate;
private final Date toDate;
private Date endFirstTerm;
private Date beginSecondTerm;
public Builder(String year, Date fromDate, Date toDate) {
this.year = year;
this.fromDate = fromDate;
this.toDate = toDate;
}
public Builder endFirstTerm(Date endFirstTerm) {
this.endFirstTerm = endFirstTerm;
return this;
}
public Builder beginSecondTerm(Date beginSecondTerm) {
this.beginSecondTerm = beginSecondTerm;
return this;
}
public SchoolYear build() {
return new SchoolYear(this);
}
}
private SchoolYear(Builder builder) {
this.year = builder.year;
this.fromDate = builder.fromDate;
this.toDate = builder.toDate;
this.endFirstTerm = builder.endFirstTerm;
this.beginSecondTerm = builder.beginSecondTerm;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof SchoolYear))
return false;
SchoolYear other = (SchoolYear) obj;
if (getId() != other.getId())
return false;
return true;
}
}
| SchoolYear entsprechend des neuen TeachingMaterial angepasst | src/main/java/de/dhbw/humbuch/model/entity/SchoolYear.java | SchoolYear entsprechend des neuen TeachingMaterial angepasst | <ide><path>rc/main/java/de/dhbw/humbuch/model/entity/SchoolYear.java
<ide> import javax.persistence.GenerationType;
<ide> import javax.persistence.Id;
<ide> import javax.persistence.Table;
<add>
<add>import de.dhbw.humbuch.model.entity.TeachingMaterial.Term;
<ide>
<ide> @Entity
<ide> @Table(name="schoolYear")
<ide> this.beginSecondTerm = beginSecondTerm;
<ide> }
<ide>
<del> public int getCurrentTerm() {
<add> public Term getCurrentTerm() {
<ide> if(getEndFirstTerm().after(new Date())) {
<del> return new Integer(1);
<add> return Term.FIRST;
<ide> } else {
<del> return new Integer(2);
<add> return Term.SECOND;
<ide> }
<ide> }
<ide> |
|
Java | mit | c1f9a44dc75bcbdc338b0b6da20e95d63d9a5543 | 0 | dbsoftcombr/dbsfaces,dbsoftcombr/dbsfaces,dbsoftcombr/dbsfaces | package br.com.dbsoft.ui.component.actioncontroller;
import br.com.dbsoft.message.DBSMessages;
import br.com.dbsoft.message.IDBSMessage;
import br.com.dbsoft.message.IDBSMessages;
import br.com.dbsoft.message.IDBSMessagesListener;
import br.com.dbsoft.ui.core.DBSMessagesFacesContext;
/**
* Controla a execução de um action possibilitando o envio de mensagens e a respectiva validação.
*
*/
public abstract class DBSActionController{
private IDBSMessages wBeforeMessages = new DBSMessages(true);
private IDBSMessages wAfterMessages = new DBSMessages(true);
private LocalListener wLocalListener = new LocalListener();
private String wMessageControlClientId = null;
private Boolean wOk = false;
/**
* @param pMessageControlClientId ClientId do componente que receberá as mensagens quando houver.
*/
public DBSActionController() {
wBeforeMessages.addMessagesListener(wLocalListener);
wAfterMessages.addMessagesListener(wLocalListener);
}
/**
* @param pMessageControlClientId ClientId do componente que receberá as mensagens quando houver.
*/
public DBSActionController(String pMessageControlClientId) {
this();
wMessageControlClientId = pMessageControlClientId;
}
/**
* Efetua a chamada para o processamento.</br>
* @return Outcome
*/
public final String execute(){
wOk = false;
if (canValidate()){
beforeExecute(wBeforeMessages);
}
if (canExecute()){
wOk = onExecute();
afterExecute(wAfterMessages);
}
sendMessages(wMessageControlClientId);
return getOutcome();
}
/**
* Retorna se execução foi finalizada com sucesso.
* @return
*/
public final boolean isOk(){
return wOk;
}
/**
* Evento disparado antes de executar o processamento existente em <b>onExecute</b>.</br>
* Este evento deve ser utilizado para enviar mensagens de validação ou confirmação anterior a execução.
* @param pMessagesToSend
*/
protected void beforeExecute(IDBSMessages pMessagesToSend){};
/**
* Evento disparado após a execusão do processamento existente em <b>onExecute</b>.</br>
* Este evento deve ser utilizado para enviar mensagens de erro ou informações gerados pela execução.
* @param pMessagesToSend
*/
protected void afterExecute(IDBSMessages pMessagesToSend){};
/**
* @return Página a ser direcionada após a finalização <b>com sucesso</b> do processamento e exibição de todas as mensagens.
*/
protected String getOutcome(){return null;};
/**
* Implementação do processamento que se deseja efetuar.
* @return Se o processamento foi executado com sucesso.
*/
protected abstract boolean onExecute();
/**
* Mensagens que serão exibidas antes da execução do processamento principal.
* @return
*/
protected final IDBSMessages getMessagesBeforeAction(){
return wBeforeMessages;
}
/**
* Mensagens que serão exibidas após a execução do processamento principal.
* @return
*/
protected final IDBSMessages getMessagesAfterAction(){
return wAfterMessages;
}
/**
* Se pode executar as rotinas de validação e confirmação anterior a execução.<br/>
* Dentro deste if, deve-se setar as mensagens utilizando <b>getMessagesBeforeAction().add</b>.
* @return
*/
protected final boolean canValidate(){
return wBeforeMessages.size() == 0;
}
/**
* Se pode executar o processamento desejado.<br/>
* Dentro deste if, deve-se implementar o processamento e
* setar as mensagens de erro ou finalização utilizando <b>getMessagesAfterAction().add</b>.
* @return
*/
protected final boolean canExecute(){
return !wBeforeMessages.hasMessages() && wAfterMessages.size() == 0;
}
/**
* Envia mensagens.
* @param pClientId
* @return
*/
protected final boolean sendMessages(String pClientId){
DBSMessagesFacesContext.sendMessages(pvGetMessages(), pClientId);
return pvCanRedirect();
}
private final boolean pvCanRedirect(){
boolean xRedirect = !wBeforeMessages.hasMessages() && !wAfterMessages.hasMessages();
if (xRedirect){
pvClearMessages();
}
return xRedirect;
}
private final IDBSMessages pvGetMessages(){
if (wBeforeMessages.hasMessages()){
return wBeforeMessages;
}else{
return wAfterMessages;
}
}
private final void pvClearMessages(){
wBeforeMessages.clear();
wAfterMessages.clear();
}
/**
* Classe local que receberá as chamadas dos eventos disparados pelas mensagens.<br/>
* Código foi implemetado localmente para iniciar o acesso <i>public</i>.
*/
private class LocalListener implements IDBSMessagesListener{
@Override
public void afterAddMessage(IDBSMessages pMessages, IDBSMessage pMessage) {}
@Override
public void afterRemoveMessage(IDBSMessages pMessages, String pMessageKey) {}
@Override
public void afterClearMessages(IDBSMessages pMessages) {}
@Override
public void afterMessageValidated(IDBSMessages pMessages, IDBSMessage pMessage){
//Excluir todas as mensagens para reiniciar todo o processo de controle das mensagens.
if (!pMessage.isMessageValidatedTrue() && pMessage.getMessageType().getIsError()){
pvClearMessages();
}
}
}
}
| src/main/java/br/com/dbsoft/ui/component/actioncontroller/DBSActionController.java | package br.com.dbsoft.ui.component.actioncontroller;
import br.com.dbsoft.message.DBSMessages;
import br.com.dbsoft.message.IDBSMessage;
import br.com.dbsoft.message.IDBSMessages;
import br.com.dbsoft.message.IDBSMessagesListener;
import br.com.dbsoft.ui.core.DBSMessagesFacesContext;
/**
* Controla a execução de um action possibilitando o envio de mensagens e a respectiva validação.
*
*/
public abstract class DBSActionController{
private IDBSMessages wBeforeMessages = new DBSMessages(true);
private IDBSMessages wAfterMessages = new DBSMessages(true);
private LocalListener wLocalListener = new LocalListener();
private String wMessageControlClientId = null;
private Boolean wOk = false;
/**
* @param pMessageControlClientId ClientId do componente que receberá as mensagens quando houver.
*/
public DBSActionController() {
wBeforeMessages.addMessagesListener(wLocalListener);
wAfterMessages.addMessagesListener(wLocalListener);
}
/**
* @param pMessageControlClientId ClientId do componente que receberá as mensagens quando houver.
*/
public DBSActionController(String pMessageControlClientId) {
this();
wMessageControlClientId = pMessageControlClientId;
}
/**
* Efetua a chamada para o processamento.</br>
* @return Outcome
*/
public final String execute(){
wOk = false;
if (canValidate()){
beforeExecute(wBeforeMessages);
}
if (canExecute()){
wOk = onExecute();
afterExecute(wAfterMessages);
}
sendMessages(wMessageControlClientId);
return getOutcome();
}
/**
* Retorna se execução foi finalizada com sucesso.
* @return
*/
public final boolean isOk(){
return wOk;
}
/**
* Evento disparado antes de executar o processamento existente em <b>onExecute</b>.</br>
* Este evento deve ser utilizado para enviar mensagens de validação ou confirmação anterior a execução.
* @param pMessages
*/
protected void beforeExecute(IDBSMessages pMessages){};
/**
* Evento disparado após a execusão do processamento existente em <b>onExecute</b>.</br>
* Este evento deve ser utilizado para enviar mensagens de erro ou informações gerados pela execução.
* @param pMessages
*/
protected void afterExecute(IDBSMessages pMessages){};
/**
* @return Página a ser direcionada após a finalização <b>com sucesso</b> do processamento e exibição de todas as mensagens.
*/
protected String getOutcome(){return null;};
/**
* Implementação do processamento que se deseja efetuar.
* @return Se o processamento foi executado com sucesso.
*/
protected abstract boolean onExecute();
/**
* Mensagens que serão exibidas antes da execução do processamento principal.
* @return
*/
protected final IDBSMessages getMessagesBeforeAction(){
return wBeforeMessages;
}
/**
* Mensagens que serão exibidas após a execução do processamento principal.
* @return
*/
protected final IDBSMessages getMessagesAfterAction(){
return wAfterMessages;
}
/**
* Se pode executar as rotinas de validação e confirmação anterior a execução.<br/>
* Dentro deste if, deve-se setar as mensagens utilizando <b>getMessagesBeforeAction().add</b>.
* @return
*/
protected final boolean canValidate(){
return wBeforeMessages.size() == 0;
}
/**
* Se pode executar o processamento desejado.<br/>
* Dentro deste if, deve-se implementar o processamento e
* setar as mensagens de erro ou finalização utilizando <b>getMessagesAfterAction().add</b>.
* @return
*/
protected final boolean canExecute(){
return !wBeforeMessages.hasMessages() && wAfterMessages.size() == 0;
}
/**
* Envia mensagens.
* @param pClientId
* @return
*/
protected final boolean sendMessages(String pClientId){
DBSMessagesFacesContext.sendMessages(pvGetMessages(), pClientId);
return pvCanRedirect();
}
private final boolean pvCanRedirect(){
boolean xRedirect = !wBeforeMessages.hasMessages() && !wAfterMessages.hasMessages();
if (xRedirect){
pvClearMessages();
}
return xRedirect;
}
private final IDBSMessages pvGetMessages(){
if (wBeforeMessages.hasMessages()){
return wBeforeMessages;
}else{
return wAfterMessages;
}
}
private final void pvClearMessages(){
wBeforeMessages.clear();
wAfterMessages.clear();
}
/**
* Classe local que receberá as chamadas dos eventos disparados pelas mensagens.<br/>
* Código foi implemetado localmente para iniciar o acesso <i>public</i>.
*/
private class LocalListener implements IDBSMessagesListener{
@Override
public void afterAddMessage(IDBSMessages pMessages, IDBSMessage pMessage) {}
@Override
public void afterRemoveMessage(IDBSMessages pMessages, String pMessageKey) {}
@Override
public void afterClearMessages(IDBSMessages pMessages) {}
@Override
public void afterMessageValidated(IDBSMessages pMessages, IDBSMessage pMessage){
//Excluir todas as mensagens para reiniciar todo o processo de controle das mensagens.
if (!pMessage.isMessageValidatedTrue() && pMessage.getMessageType().getIsError()){
pvClearMessages();
}
}
}
}
| Documentação | src/main/java/br/com/dbsoft/ui/component/actioncontroller/DBSActionController.java | Documentação | <ide><path>rc/main/java/br/com/dbsoft/ui/component/actioncontroller/DBSActionController.java
<ide> /**
<ide> * Evento disparado antes de executar o processamento existente em <b>onExecute</b>.</br>
<ide> * Este evento deve ser utilizado para enviar mensagens de validação ou confirmação anterior a execução.
<del> * @param pMessages
<add> * @param pMessagesToSend
<ide> */
<del> protected void beforeExecute(IDBSMessages pMessages){};
<add> protected void beforeExecute(IDBSMessages pMessagesToSend){};
<ide> /**
<ide> * Evento disparado após a execusão do processamento existente em <b>onExecute</b>.</br>
<ide> * Este evento deve ser utilizado para enviar mensagens de erro ou informações gerados pela execução.
<del> * @param pMessages
<add> * @param pMessagesToSend
<ide> */
<del> protected void afterExecute(IDBSMessages pMessages){};
<add> protected void afterExecute(IDBSMessages pMessagesToSend){};
<ide>
<ide> /**
<ide> * @return Página a ser direcionada após a finalização <b>com sucesso</b> do processamento e exibição de todas as mensagens. |
|
Java | apache-2.0 | 105b3b1d3496786cd85305e462d208edf66d1ca9 | 0 | apache/jackrabbit,apache/jackrabbit,apache/jackrabbit | /*
* Copyright 2004-2005 The Apache Software Foundation or its licensors,
* as applicable.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.core.xml;
import org.apache.jackrabbit.core.Constants;
import org.apache.jackrabbit.core.HierarchyManager;
import org.apache.jackrabbit.core.InternalValue;
import org.apache.jackrabbit.core.ItemId;
import org.apache.jackrabbit.core.MalformedPathException;
import org.apache.jackrabbit.core.NamespaceResolver;
import org.apache.jackrabbit.core.NoPrefixDeclaredException;
import org.apache.jackrabbit.core.NodeId;
import org.apache.jackrabbit.core.Path;
import org.apache.jackrabbit.core.PropertyId;
import org.apache.jackrabbit.core.QName;
import org.apache.jackrabbit.core.SessionImpl;
import org.apache.jackrabbit.core.WorkspaceImpl;
import org.apache.jackrabbit.core.nodetype.ChildNodeDef;
import org.apache.jackrabbit.core.nodetype.EffectiveNodeType;
import org.apache.jackrabbit.core.nodetype.NodeDefId;
import org.apache.jackrabbit.core.nodetype.NodeTypeRegistry;
import org.apache.jackrabbit.core.nodetype.PropDef;
import org.apache.jackrabbit.core.nodetype.PropDefId;
import org.apache.jackrabbit.core.state.ItemStateException;
import org.apache.jackrabbit.core.state.NoSuchItemStateException;
import org.apache.jackrabbit.core.state.NodeState;
import org.apache.jackrabbit.core.state.PropertyState;
import org.apache.jackrabbit.core.state.UpdatableItemStateManager;
import org.apache.jackrabbit.core.util.Base64;
import org.apache.jackrabbit.core.util.ReferenceChangeTracker;
import org.apache.jackrabbit.core.util.uuid.UUID;
import org.apache.log4j.Logger;
import javax.jcr.ItemExistsException;
import javax.jcr.PropertyType;
import javax.jcr.RepositoryException;
import javax.jcr.nodetype.ConstraintViolationException;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.Stack;
/**
* <code>WorkspaceImporter</code> ...
*/
public class WorkspaceImporter implements Importer, Constants {
private static Logger log = Logger.getLogger(WorkspaceImporter.class);
private final NodeState importTarget;
private final WorkspaceImpl wsp;
private final NodeTypeRegistry ntReg;
private final HierarchyManager hierMgr;
private final UpdatableItemStateManager stateMgr;
private final int uuidBehavior;
private boolean aborted;
private Stack parents;
/**
* helper object that keeps track of remapped uuid's and imported reference
* properties that might need correcting depending on the uuid mappings
*/
private final ReferenceChangeTracker refTracker;
/**
* Creates a <code>WorkspaceImporter</code> instance.
*
* @param importTarget
* @param wsp
* @param ntReg
* @param uuidBehavior
*/
public WorkspaceImporter(NodeState importTarget,
WorkspaceImpl wsp,
NodeTypeRegistry ntReg,
int uuidBehavior) {
this.importTarget = importTarget;
this.wsp = wsp;
this.ntReg = ntReg;
hierMgr = wsp.getHierarchyManager();
stateMgr = wsp.getItemStateManager();
this.uuidBehavior = uuidBehavior;
aborted = false;
refTracker = new ReferenceChangeTracker();
parents = new Stack();
parents.push(importTarget);
}
/**
* Failsafe translation of internal <code>ItemId</code> to JCR path for
* use in error messages etc.
*
* @param id id to translate
* @return JCR path
*/
private String resolveJCRPath(ItemId id) {
Path path;
try {
path = hierMgr.getPath(id);
} catch (RepositoryException re) {
log.error(id + ": failed to determine path to");
// return string representation if id as a fallback
return id.toString();
}
try {
return path.toJCRPath(((SessionImpl) wsp.getSession()).getNamespaceResolver());
} catch (NoPrefixDeclaredException npde) {
log.error("failed to convert " + path.toString() + " to JCR path.");
// return string representation of internal path as a fallback
return path.toString();
}
}
protected NodeState createNode(NodeState parent,
QName nodeName,
QName nodeTypeName,
QName[] mixinNames,
String uuid)
throws RepositoryException {
ChildNodeDef def =
wsp.findApplicableNodeDefinition(nodeName, nodeTypeName, parent);
return createNode(parent, nodeName, nodeTypeName, mixinNames, uuid, def);
}
protected NodeState createNode(NodeState parent,
QName nodeName,
QName nodeTypeName,
QName[] mixinNames,
String uuid,
ChildNodeDef def)
throws RepositoryException {
// check for name collisions with existing properties
if (parent.hasPropertyEntry(nodeName)) {
String msg = "there's already a property with name " + nodeName;
log.debug(msg);
throw new RepositoryException(msg);
}
// check for name collisions with existing nodes
if (!def.allowSameNameSibs() && parent.hasChildNodeEntry(nodeName)) {
NodeId id = new NodeId(parent.getChildNodeEntry(nodeName, 1).getUUID());
throw new ItemExistsException(resolveJCRPath(id));
}
if (uuid == null) {
// create new uuid
uuid = UUID.randomUUID().toString(); // create new version 4 uuid
}
if (nodeTypeName == null) {
// no primary node type specified,
// try default primary type from definition
nodeTypeName = def.getDefaultPrimaryType();
if (nodeTypeName == null) {
String msg = "an applicable node type could not be determined for "
+ nodeName;
log.debug(msg);
throw new ConstraintViolationException(msg);
}
}
NodeState node = stateMgr.createNew(uuid, nodeTypeName, parent.getUUID());
if (mixinNames != null && mixinNames.length > 0) {
node.setMixinTypeNames(new HashSet(Arrays.asList(mixinNames)));
}
node.setDefinitionId(new NodeDefId(def));
// now add new child node entry to parent
parent.addChildNodeEntry(nodeName, node.getUUID());
EffectiveNodeType ent = wsp.getEffectiveNodeType(node);
if (!node.getMixinTypeNames().isEmpty()) {
// create jcr:mixinTypes property
PropDef pd = ent.getApplicablePropertyDef(JCR_MIXINTYPES,
PropertyType.NAME, true);
createProperty(node, pd.getName(), pd.getRequiredType(), pd);
}
// add 'auto-create' properties defined in node type
PropDef[] pda = ent.getAutoCreatePropDefs();
for (int i = 0; i < pda.length; i++) {
PropDef pd = pda[i];
createProperty(node, pd.getName(), pd.getRequiredType(), pd);
}
// recursively add 'auto-create' child nodes defined in node type
ChildNodeDef[] nda = ent.getAutoCreateNodeDefs();
for (int i = 0; i < nda.length; i++) {
ChildNodeDef nd = nda[i];
createNode(node, nd.getName(), nd.getDefaultPrimaryType(),
null, null, nd);
}
return node;
}
protected PropertyState createProperty(NodeState parent,
QName propName,
int type,
int numValues)
throws RepositoryException {
// find applicable definition
PropDef def;
// multi- or single-valued property?
if (numValues == 1) {
// could be single- or multi-valued (n == 1)
try {
// try single-valued
def = wsp.findApplicablePropertyDefinition(propName,
type, false, parent);
} catch (ConstraintViolationException cve) {
// try multi-valued
def = wsp.findApplicablePropertyDefinition(propName,
type, true, parent);
}
} else {
// can only be multi-valued (n == 0 || n > 1)
def = wsp.findApplicablePropertyDefinition(propName,
type, true, parent);
}
return createProperty(parent, propName, type, def);
}
protected PropertyState createProperty(NodeState parent,
QName propName,
int type,
PropDef def)
throws RepositoryException {
// check for name collisions with existing child nodes
if (parent.hasChildNodeEntry(propName)) {
String msg = "there's already a child node with name " + propName;
log.debug(msg);
throw new RepositoryException(msg);
}
// create property
PropertyState prop = stateMgr.createNew(propName, parent.getUUID());
prop.setDefinitionId(new PropDefId(def));
if (def.getRequiredType() != PropertyType.UNDEFINED) {
prop.setType(def.getRequiredType());
} else if (type != PropertyType.UNDEFINED) {
prop.setType(type);
} else {
prop.setType(PropertyType.STRING);
}
prop.setMultiValued(def.isMultiple());
// compute system generated values if necessary
InternalValue[] genValues =
computeSystemGeneratedPropertyValues(parent, propName, def);
if (genValues != null) {
prop.setValues(genValues);
} else if (def.getDefaultValues() != null) {
prop.setValues(def.getDefaultValues());
}
// now add new property entry to parent
parent.addPropertyEntry(propName);
return prop;
}
/**
* Computes the values of well-known system (i.e. protected) properties.
* todo: duplicate code in NodeImpl: consolidate and delegate to NodeTypeInstanceHandler
*
* @param parent
* @param name
* @param def
* @return
* @throws RepositoryException
*/
protected InternalValue[] computeSystemGeneratedPropertyValues(NodeState parent,
QName name,
PropDef def)
throws RepositoryException {
InternalValue[] genValues = null;
/**
* todo: need to come up with some callback mechanism for applying system generated values
* (e.g. using a NodeTypeInstanceHandler interface)
*/
// compute system generated values
QName declaringNT = def.getDeclaringNodeType();
if (MIX_REFERENCEABLE.equals(declaringNT)) {
// mix:referenceable node type
if (JCR_UUID.equals(name)) {
// jcr:uuid property
genValues = new InternalValue[]{InternalValue.create(parent.getUUID())};
}
} else if (NT_BASE.equals(declaringNT)) {
// nt:base node type
if (JCR_PRIMARYTYPE.equals(name)) {
// jcr:primaryType property
genValues = new InternalValue[]{InternalValue.create(parent.getNodeTypeName())};
} else if (JCR_MIXINTYPES.equals(name)) {
// jcr:mixinTypes property
Set mixins = parent.getMixinTypeNames();
ArrayList values = new ArrayList(mixins.size());
Iterator iter = mixins.iterator();
while (iter.hasNext()) {
values.add(InternalValue.create((QName) iter.next()));
}
genValues = (InternalValue[]) values.toArray(new InternalValue[values.size()]);
}
} else if (NT_HIERARCHYNODE.equals(declaringNT)) {
// nt:hierarchyNode node type
if (JCR_CREATED.equals(name)) {
// jcr:created property
genValues = new InternalValue[]{InternalValue.create(Calendar.getInstance())};
}
} else if (NT_RESOURCE.equals(declaringNT)) {
// nt:resource node type
if (JCR_LASTMODIFIED.equals(name)) {
// jcr:lastModified property
genValues = new InternalValue[]{InternalValue.create(Calendar.getInstance())};
}
} else if (NT_VERSION.equals(declaringNT)) {
// nt:version node type
if (JCR_CREATED.equals(name)) {
// jcr:created property
genValues = new InternalValue[]{InternalValue.create(Calendar.getInstance())};
}
/*
// FIXME delegate to NodeTypeInstanceHandler
} else if (MIX_VERSIONABLE.equals(declaringNT)) {
// mix:versionable node type
if (JCR_VERSIONHISTORY.equals(name)) {
// jcr:versionHistory property
genValues = new InternalValue[]{InternalValue.create(new UUID(hist.getUUID()))};
} else if (JCR_BASEVERSION.equals(name)) {
// jcr:baseVersion property
genValues = new InternalValue[]{InternalValue.create(new UUID(hist.getRootVersion().getUUID()))};
} else if (JCR_ISCHECKEDOUT.equals(name)) {
// jcr:isCheckedOut property
genValues = new InternalValue[]{InternalValue.create(true)};
} else if (JCR_PREDECESSORS.equals(name)) {
// jcr:predecessors property
genValues = new InternalValue[]{InternalValue.create(new UUID(hist.getRootVersion().getUUID()))};
}
*/
}
return genValues;
}
/**
* Unlinks the specified target node from all its parents and recursively
* removes it including its properties and child nodes.
* <p/>
* <b>Precondition:</b> the state manager of this workspace needs to be in
* edit mode.
* todo duplicate code in WorkspaceImporter; consolidate in WorkspaceOperations class
*
* @param target
* @throws RepositoryException if an error occurs
*/
protected void removeNode(NodeState target)
throws RepositoryException {
// copy list to avoid ConcurrentModificationException
ArrayList parentUUIDs = new ArrayList(target.getParentUUIDs());
Iterator iter = parentUUIDs.iterator();
while (iter.hasNext()) {
String parentUUID = (String) iter.next();
NodeId parentId = new NodeId(parentUUID);
// unlink target node from this parent
unlinkNode(target, parentUUID);
// remove child node entries
NodeState parent;
try {
parent = (NodeState) stateMgr.getItemState(parentId);
} catch (ItemStateException ise) {
// should never get here...
String msg = "internal error: failed to retrieve parent state";
log.error(msg, ise);
throw new RepositoryException(msg, ise);
}
// use temp array to avoid ConcurrentModificationException
ArrayList tmp =
new ArrayList(parent.getChildNodeEntries(target.getUUID()));
// remove from tail to avoid problems with same-name siblings
for (int i = tmp.size() - 1; i >= 0; i--) {
NodeState.ChildNodeEntry entry = (NodeState.ChildNodeEntry) tmp.get(i);
parent.removeChildNodeEntry(entry.getName(), entry.getIndex());
}
// store parent
stateMgr.store(parent);
}
}
/**
* Unlinks the given target node from the specified parent i.e. removes
* <code>parentUUID</code> from its list of parents. If as a result
* the target node would be orphaned it will be recursively removed
* including its properties and child nodes.
* <p/>
* Note that the child node entry refering to <code>target</code> is
* <b><i>not</i></b> automatically removed from <code>target</code>'s
* parent denoted by <code>parentUUID</code>.
* <p/>
* <b>Precondition:</b> the state manager of this workspace needs to be in
* edit mode.
* todo duplicate code in WorkspaceImporter; consolidate in WorkspaceOperations class
*
* @param target
* @param parentUUID
* @throws RepositoryException if an error occurs
*/
private void unlinkNode(NodeState target, String parentUUID)
throws RepositoryException {
// check if this node state would be orphaned after unlinking it from parent
ArrayList parentUUIDs = new ArrayList(target.getParentUUIDs());
parentUUIDs.remove(parentUUID);
boolean orphaned = parentUUIDs.isEmpty();
if (orphaned) {
// remove child nodes
// use temp array to avoid ConcurrentModificationException
ArrayList tmp = new ArrayList(target.getChildNodeEntries());
// remove from tail to avoid problems with same-name siblings
for (int i = tmp.size() - 1; i >= 0; i--) {
NodeState.ChildNodeEntry entry = (NodeState.ChildNodeEntry) tmp.get(i);
NodeId nodeId = new NodeId(entry.getUUID());
try {
NodeState node = (NodeState) stateMgr.getItemState(nodeId);
// check if child node can be removed
// (access rights, locking & versioning status)
wsp.checkRemoveNode(node, (NodeId) target.getId(),
WorkspaceImpl.CHECK_ACCESS | WorkspaceImpl.CHECK_LOCK
| WorkspaceImpl.CHECK_VERSIONING);
// unlink child node (recursive)
unlinkNode(node, target.getUUID());
} catch (ItemStateException ise) {
String msg = "internal error: failed to retrieve state of "
+ nodeId;
log.debug(msg);
throw new RepositoryException(msg, ise);
}
// remove child node entry
target.removeChildNodeEntry(entry.getName(), entry.getIndex());
}
// remove properties
// use temp array to avoid ConcurrentModificationException
tmp = new ArrayList(target.getPropertyEntries());
// remove from tail to avoid problems with same-name siblings
for (int i = tmp.size() - 1; i >= 0; i--) {
NodeState.PropertyEntry entry = (NodeState.PropertyEntry) tmp.get(i);
PropertyId propId =
new PropertyId(target.getUUID(), entry.getName());
try {
PropertyState prop = (PropertyState) stateMgr.getItemState(propId);
// remove property entry
target.removePropertyEntry(propId.getName());
// destroy property state
stateMgr.destroy(prop);
} catch (ItemStateException ise) {
String msg = "internal error: failed to retrieve state of "
+ propId;
log.debug(msg);
throw new RepositoryException(msg, ise);
}
}
}
// now actually do unlink target state from specified parent state
// (i.e. remove uuid of parent state from target state's parent list)
target.removeParentUUID(parentUUID);
if (orphaned) {
// destroy target
stateMgr.destroy(target);
} else {
// store target
stateMgr.store(target);
}
}
protected NodeState resolveUUIDConflict(NodeState parent,
NodeState conflicting,
NodeInfo nodeInfo)
throws RepositoryException {
NodeState node;
if (uuidBehavior == IMPORT_UUID_CREATE_NEW) {
// create new with new uuid:
// check if new node can be added (check access rights &
// node type constraints only, assume locking & versioning status
// has already been checked on ancestor)
wsp.checkAddNode(parent, nodeInfo.getName(),
nodeInfo.getNodeTypeName(),
WorkspaceImpl.CHECK_ACCESS
| WorkspaceImpl.CHECK_CONSTRAINTS);
node = createNode(parent, nodeInfo.getName(),
nodeInfo.getNodeTypeName(), nodeInfo.getMixinNames(), null);
// remember uuid mapping
EffectiveNodeType ent = wsp.getEffectiveNodeType(node);
if (ent.includesNodeType(MIX_REFERENCEABLE)) {
refTracker.mappedUUID(nodeInfo.getUUID(), node.getUUID());
}
} else if (uuidBehavior == IMPORT_UUID_COLLISION_THROW) {
String msg = "a node with uuid " + nodeInfo.getUUID()
+ " already exists!";
log.debug(msg);
throw new ItemExistsException(msg);
} else if (uuidBehavior == IMPORT_UUID_COLLISION_REMOVE_EXISTING) {
// make sure conflicting node is not importTarget or an ancestor thereof
Path p0 = hierMgr.getPath(importTarget.getId());
Path p1 = hierMgr.getPath(conflicting.getId());
try {
if (p1.equals(p0) || p1.isAncestorOf(p0)) {
String msg = "cannot remove ancestor node";
log.debug(msg);
throw new RepositoryException(msg);
}
} catch (MalformedPathException mpe) {
// should never get here...
String msg = "internal error: failed to determine degree of relationship";
log.error(msg, mpe);
throw new RepositoryException(msg, mpe);
}
// remove conflicting:
// check if conflicting can be removed
// (access rights, node type constraints, locking & versioning status)
wsp.checkRemoveNode(conflicting,
WorkspaceImpl.CHECK_ACCESS
| WorkspaceImpl.CHECK_LOCK
| WorkspaceImpl.CHECK_VERSIONING
| WorkspaceImpl.CHECK_CONSTRAINTS);
// do remove conflicting (recursive)
removeNode(conflicting);
// create new with given uuid:
// check if new node can be added (check access rights &
// node type constraints only, assume locking & versioning status
// has already been checked on ancestor)
wsp.checkAddNode(parent, nodeInfo.getName(),
nodeInfo.getNodeTypeName(),
WorkspaceImpl.CHECK_ACCESS
| WorkspaceImpl.CHECK_CONSTRAINTS);
// do create new node
node = createNode(parent, nodeInfo.getName(),
nodeInfo.getNodeTypeName(), nodeInfo.getMixinNames(),
nodeInfo.getUUID());
} else if (uuidBehavior == IMPORT_UUID_COLLISION_REPLACE_EXISTING) {
if (conflicting.getParentUUID() == null) {
String msg = "root node cannot be replaced";
log.debug(msg);
throw new RepositoryException(msg);
}
// 'replace' current parent with parent of conflicting
NodeId parentId = new NodeId(conflicting.getParentUUID());
try {
parent = (NodeState) stateMgr.getItemState(parentId);
} catch (ItemStateException ise) {
// should never get here...
String msg = "internal error: failed to retrieve parent state";
log.error(msg, ise);
throw new RepositoryException(msg, ise);
}
// remove conflicting:
// check if conflicting can be removed
wsp.checkRemoveNode(conflicting,
WorkspaceImpl.CHECK_ACCESS
| WorkspaceImpl.CHECK_LOCK
| WorkspaceImpl.CHECK_VERSIONING
| WorkspaceImpl.CHECK_CONSTRAINTS);
// do remove conflicting (recursive)
removeNode(conflicting);
// create new with given uuid at same location as conflicting:
// check if new node can be added at other location
// (access rights, node type constraints, locking & versioning status)
wsp.checkAddNode(parent, nodeInfo.getName(),
nodeInfo.getNodeTypeName(),
WorkspaceImpl.CHECK_ACCESS
| WorkspaceImpl.CHECK_LOCK
| WorkspaceImpl.CHECK_VERSIONING
| WorkspaceImpl.CHECK_CONSTRAINTS);
// do create new node
node = createNode(parent, nodeInfo.getName(),
nodeInfo.getNodeTypeName(), nodeInfo.getMixinNames(),
nodeInfo.getUUID());
} else {
String msg = "unknown uuidBehavior: " + uuidBehavior;
log.debug(msg);
throw new RepositoryException(msg);
}
return node;
}
//-------------------------------------------------------------< Importer >
/**
* {@inheritDoc}
*/
public void start() throws RepositoryException {
try {
// start update operation
stateMgr.edit();
} catch (ItemStateException ise) {
aborted = true;
String msg = "internal error: failed to start update operation";
log.debug(msg);
throw new RepositoryException(msg, ise);
}
}
/**
* {@inheritDoc}
*/
public void startNode(NodeInfo nodeInfo, List propInfos,
NamespaceResolver nsContext)
throws RepositoryException {
if (aborted) {
// the import has been aborted, get outta here...
return;
}
boolean succeeded = false;
NodeState parent = null;
try {
// check sanity of workspace/session first
wsp.sanityCheck();
parent = (NodeState) parents.peek();
// process node
NodeState node = null;
String uuid = nodeInfo.getUUID();
QName nodeName = nodeInfo.getName();
QName ntName = nodeInfo.getNodeTypeName();
QName[] mixins = nodeInfo.getMixinNames();
if (parent == null) {
// parent node was skipped, skip this child node also
parents.push(null); // push null onto stack for skipped node
succeeded = true;
log.debug("skipping node " + nodeName);
return;
}
if (parent.hasChildNodeEntry(nodeName)) {
// a node with that name already exists...
NodeState.ChildNodeEntry entry =
parent.getChildNodeEntry(nodeName, 1);
NodeId idExisting = new NodeId(entry.getUUID());
NodeState existing = (NodeState) stateMgr.getItemState(idExisting);
ChildNodeDef def = ntReg.getNodeDef(existing.getDefinitionId());
if (!def.allowSameNameSibs()) {
// existing doesn't allow same-name siblings,
// check for potential conflicts
EffectiveNodeType entExisting =
wsp.getEffectiveNodeType(existing);
if (def.isProtected() && entExisting.includesNodeType(ntName)) {
// skip protected node
parents.push(null); // push null onto stack for skipped node
succeeded = true;
log.debug("skipping protected node "
+ resolveJCRPath(existing.getId()));
return;
}
if (def.isAutoCreate() && entExisting.includesNodeType(ntName)) {
// this node has already been auto-created,
// no need to create it
node = existing;
} else {
throw new ItemExistsException(resolveJCRPath(existing.getId()));
}
}
}
if (node == null) {
// there's no node with that name...
if (uuid == null) {
// no potential uuid conflict, always create new node
ChildNodeDef def =
wsp.findApplicableNodeDefinition(nodeName, ntName, parent);
if (def.isProtected()) {
// skip protected node
parents.push(null); // push null onto stack for skipped node
succeeded = true;
log.debug("skipping protected node " + nodeName);
return;
}
// check if new node can be added (check access rights &
// node type constraints only, assume locking & versioning status
// has already been checked on ancestor)
wsp.checkAddNode(parent, nodeName, ntName,
WorkspaceImpl.CHECK_ACCESS
| WorkspaceImpl.CHECK_CONSTRAINTS);
// do create new node
node = createNode(parent, nodeName, ntName, mixins, null, def);
} else {
// potential uuid conflict
NodeState conflicting;
try {
conflicting =
(NodeState) stateMgr.getItemState(new NodeId(uuid));
} catch (NoSuchItemStateException nsise) {
conflicting = null;
}
if (conflicting != null) {
// resolve uuid conflict
node = resolveUUIDConflict(parent, conflicting, nodeInfo);
} else {
// create new with given uuid
ChildNodeDef def =
wsp.findApplicableNodeDefinition(nodeName, ntName, parent);
if (def.isProtected()) {
// skip protected node
parents.push(null); // push null onto stack for skipped node
succeeded = true;
log.debug("skipping protected node " + nodeName);
return;
}
// check if new node can be added (check access rights &
// node type constraints only, assume locking & versioning status
// has already been checked on ancestor)
wsp.checkAddNode(parent, nodeName, ntName,
WorkspaceImpl.CHECK_ACCESS
| WorkspaceImpl.CHECK_CONSTRAINTS);
// do create new node
node = createNode(parent, nodeName, ntName, mixins, uuid, def);
}
}
}
// process properties
Iterator iter = propInfos.iterator();
while (iter.hasNext()) {
PropInfo pi = (PropInfo) iter.next();
QName propName = pi.getName();
TextValue[] tva = pi.getValues();
int type = pi.getType();
PropertyState prop = null;
PropDef def = null;
if (node.hasPropertyEntry(propName)) {
// a property with that name already exists...
PropertyId idExisting = new PropertyId(node.getUUID(), propName);
PropertyState existing =
(PropertyState) stateMgr.getItemState(idExisting);
def = ntReg.getPropDef(existing.getDefinitionId());
if (def.isProtected()) {
// skip protected property
log.debug("skipping protected property "
+ resolveJCRPath(idExisting));
continue;
}
if (def.isAutoCreate() && (existing.getType() == type
|| type == PropertyType.UNDEFINED)
&& def.isMultiple() == existing.isMultiValued()) {
// this property has already been auto-created,
// no need to create it
prop = existing;
} else {
throw new ItemExistsException(resolveJCRPath(existing.getId()));
}
}
if (prop == null) {
// there's no property with that name,
// find applicable definition
// multi- or single-valued property?
if (tva.length == 1) {
// could be single- or multi-valued (n == 1)
try {
// try single-valued
def = wsp.findApplicablePropertyDefinition(propName,
type, false, node);
} catch (ConstraintViolationException cve) {
// try multi-valued
def = wsp.findApplicablePropertyDefinition(propName,
type, true, node);
}
} else {
// can only be multi-valued (n == 0 || n > 1)
def = wsp.findApplicablePropertyDefinition(propName,
type, true, node);
}
if (def.isProtected()) {
// skip protected property
log.debug("skipping protected property " + propName);
continue;
}
// create new property
prop = createProperty(node, propName, type, def);
}
// check multi-valued characteristic
if ((tva.length == 0 || tva.length > 1) && !def.isMultiple()) {
throw new ConstraintViolationException(resolveJCRPath(prop.getId())
+ " is not multi-valued");
}
// convert serialized values to InternalValue objects
InternalValue[] iva = new InternalValue[tva.length];
int targetType = def.getRequiredType();
if (targetType == PropertyType.UNDEFINED) {
if (type == PropertyType.UNDEFINED) {
targetType = PropertyType.STRING;
} else {
targetType = type;
}
}
for (int i = 0; i < tva.length; i++) {
TextValue tv = tva[i];
if (targetType == PropertyType.BINARY) {
// base64 encoded BINARY type;
// decode using Reader
/*
// @todo decode to temp file and pass FileInputStream to InternalValue factory method
File tmpFile = null;
try {
tmpFile = File.createTempFile("bin", null);
FileOutputStream out = new FileOutputStream(tmpFile);
Base64.decode(tv.reader(), out);
out.close();
iva[i] = InternalValue.create(new FileInputStream(tmpFile));
} catch (IOException ioe) {
String msg = "failed to decode binary value";
log.debug(msg, ioe);
throw new RepositoryException(msg, ioe);
} finally {
// the temp file can be deleted because
// the InternalValue instance has spooled
// its contents
if (tmpFile != null) {
tmpFile.delete();
}
}
*/
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
Base64.decode(tv.reader(), baos);
// no need to close ByteArrayOutputStream
//baos.close();
iva[i] = InternalValue.create(new ByteArrayInputStream(baos.toByteArray()));
} catch (IOException ioe) {
String msg = "failed to decode binary value";
log.debug(msg, ioe);
throw new RepositoryException(msg, ioe);
}
} else {
// retrieve serialized value
String serValue;
try {
serValue = tv.retrieve();
} catch (IOException ioe) {
String msg = "failed to retrieve serialized value";
log.debug(msg, ioe);
throw new RepositoryException(msg, ioe);
}
// convert serialized value to InternalValue using
// current namespace context of xml document
iva[i] = InternalValue.create(serValue, targetType,
nsContext);
}
}
// set values
prop.setValues(iva);
// make sure node is valid according to its definition
wsp.validate(prop);
if (prop.getType() == PropertyType.REFERENCE) {
// store reference for later resolution
refTracker.processedReference(prop);
}
// store property
stateMgr.store(prop);
}
// store affected nodes
stateMgr.store(node);
stateMgr.store(parent);
// push current node onto stack of parents
parents.push(node);
succeeded = true;
} catch (ItemStateException ise) {
String msg = "internal error: failed to store state of "
+ resolveJCRPath(parent.getId());
log.debug(msg);
throw new RepositoryException(msg, ise);
} finally {
if (!succeeded) {
// update operation failed, cancel all modifications
aborted = true;
stateMgr.cancel();
}
}
}
/**
* {@inheritDoc}
*/
public void endNode(NodeInfo nodeInfo) throws RepositoryException {
if (aborted) {
// the import has been aborted, get outta here...
return;
}
NodeState node = (NodeState) parents.pop();
if (node == null) {
// node was skipped, nothing to do here
return;
}
boolean succeeded = false;
try {
// check sanity of workspace/session first
wsp.sanityCheck();
// make sure node is valid according to its definition
wsp.validate(node);
// we're done with that node, now store its state
stateMgr.store(node);
succeeded = true;
} finally {
if (!succeeded) {
// update operation failed, cancel all modifications
aborted = true;
stateMgr.cancel();
}
}
}
/**
* {@inheritDoc}
*/
public void end() throws RepositoryException {
if (aborted) {
// the import has been aborted, get outta here...
return;
}
boolean succeeded = false;
try {
// check sanity of workspace/session first
wsp.sanityCheck();
/**
* adjust references that refer to uuid's which have been mapped to
* newly gererated uuid's on import
*/
Iterator iter = refTracker.getProcessedReferences();
while (iter.hasNext()) {
PropertyState prop = (PropertyState) iter.next();
// being paranoid...
if (prop.getType() != PropertyType.REFERENCE) {
continue;
}
boolean modified = false;
InternalValue[] values = prop.getValues();
InternalValue[] newVals = new InternalValue[values.length];
for (int i = 0; i < values.length; i++) {
InternalValue val = values[i];
String original = ((UUID) val.internalValue()).toString();
String adjusted = refTracker.getMappedUUID(original);
if (adjusted != null) {
newVals[i] = InternalValue.create(UUID.fromString(adjusted));
modified = true;
} else {
// reference doesn't need adjusting, just copy old value
newVals[i] = val;
}
}
if (modified) {
prop.setValues(newVals);
stateMgr.store(prop);
}
}
refTracker.clear();
// make sure import target is valid according to its definition
wsp.validate(importTarget);
// finally store the state of the import target
// (the parent of the imported subtree)
stateMgr.store(importTarget);
succeeded = true;
} finally {
if (!succeeded) {
// update operation failed, cancel all modifications
aborted = true;
stateMgr.cancel();
}
}
if (!aborted) {
try {
// finish update
stateMgr.update();
} catch (ItemStateException ise) {
aborted = true;
String msg = "internal error: failed to finish update operation";
log.debug(msg);
throw new RepositoryException(msg, ise);
}
}
}
}
| src/java/org/apache/jackrabbit/core/xml/WorkspaceImporter.java | /*
* Copyright 2004-2005 The Apache Software Foundation or its licensors,
* as applicable.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.core.xml;
import org.apache.jackrabbit.core.Constants;
import org.apache.jackrabbit.core.HierarchyManager;
import org.apache.jackrabbit.core.InternalValue;
import org.apache.jackrabbit.core.ItemId;
import org.apache.jackrabbit.core.MalformedPathException;
import org.apache.jackrabbit.core.NamespaceResolver;
import org.apache.jackrabbit.core.NoPrefixDeclaredException;
import org.apache.jackrabbit.core.NodeId;
import org.apache.jackrabbit.core.Path;
import org.apache.jackrabbit.core.PropertyId;
import org.apache.jackrabbit.core.QName;
import org.apache.jackrabbit.core.SessionImpl;
import org.apache.jackrabbit.core.WorkspaceImpl;
import org.apache.jackrabbit.core.nodetype.ChildNodeDef;
import org.apache.jackrabbit.core.nodetype.EffectiveNodeType;
import org.apache.jackrabbit.core.nodetype.NodeDefId;
import org.apache.jackrabbit.core.nodetype.NodeTypeRegistry;
import org.apache.jackrabbit.core.nodetype.PropDef;
import org.apache.jackrabbit.core.nodetype.PropDefId;
import org.apache.jackrabbit.core.state.ItemStateException;
import org.apache.jackrabbit.core.state.NoSuchItemStateException;
import org.apache.jackrabbit.core.state.NodeState;
import org.apache.jackrabbit.core.state.PropertyState;
import org.apache.jackrabbit.core.state.UpdatableItemStateManager;
import org.apache.jackrabbit.core.util.Base64;
import org.apache.jackrabbit.core.util.ReferenceChangeTracker;
import org.apache.jackrabbit.core.util.uuid.UUID;
import org.apache.log4j.Logger;
import javax.jcr.ItemExistsException;
import javax.jcr.PropertyType;
import javax.jcr.RepositoryException;
import javax.jcr.nodetype.ConstraintViolationException;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.Stack;
/**
* <code>WorkspaceImporter</code> ...
*/
public class WorkspaceImporter implements Importer, Constants {
private static Logger log = Logger.getLogger(WorkspaceImporter.class);
private final NodeState importTarget;
private final WorkspaceImpl wsp;
private final NodeTypeRegistry ntReg;
private final HierarchyManager hierMgr;
private final UpdatableItemStateManager stateMgr;
private final int uuidBehavior;
private boolean aborted;
private Stack parents;
/**
* helper object that keeps track of remapped uuid's and imported reference
* properties that might need correcting depending on the uuid mappings
*/
private final ReferenceChangeTracker refTracker;
/**
* Creates a <code>WorkspaceImporter</code> instance.
*
* @param importTarget
* @param wsp
* @param ntReg
* @param uuidBehavior
*/
public WorkspaceImporter(NodeState importTarget,
WorkspaceImpl wsp,
NodeTypeRegistry ntReg,
int uuidBehavior) {
this.importTarget = importTarget;
this.wsp = wsp;
this.ntReg = ntReg;
hierMgr = wsp.getHierarchyManager();
stateMgr = wsp.getItemStateManager();
this.uuidBehavior = uuidBehavior;
aborted = false;
refTracker = new ReferenceChangeTracker();
parents = new Stack();
parents.push(importTarget);
}
/**
* Failsafe translation of internal <code>ItemId</code> to JCR path for
* use in error messages etc.
*
* @param id id to translate
* @return JCR path
*/
private String resolveJCRPath(ItemId id) {
Path path;
try {
path = hierMgr.getPath(id);
} catch (RepositoryException re) {
log.error(id + ": failed to determine path to");
// return string representation if id as a fallback
return id.toString();
}
try {
return path.toJCRPath(((SessionImpl) wsp.getSession()).getNamespaceResolver());
} catch (NoPrefixDeclaredException npde) {
log.error("failed to convert " + path.toString() + " to JCR path.");
// return string representation of internal path as a fallback
return path.toString();
}
}
protected NodeState createNode(NodeState parent,
QName nodeName,
QName nodeTypeName,
QName[] mixinNames,
String uuid)
throws RepositoryException {
ChildNodeDef def =
wsp.findApplicableNodeDefinition(nodeName, nodeTypeName, parent);
return createNode(parent, nodeName, nodeTypeName, mixinNames, uuid, def);
}
protected NodeState createNode(NodeState parent,
QName nodeName,
QName nodeTypeName,
QName[] mixinNames,
String uuid,
ChildNodeDef def)
throws RepositoryException {
// check for name collisions with existing properties
if (parent.hasPropertyEntry(nodeName)) {
String msg = "there's already a property with name " + nodeName;
log.debug(msg);
throw new RepositoryException(msg);
}
// check for name collisions with existing nodes
if (!def.allowSameNameSibs() && parent.hasChildNodeEntry(nodeName)) {
NodeId id = new NodeId(parent.getChildNodeEntry(nodeName, 1).getUUID());
throw new ItemExistsException(resolveJCRPath(id));
}
if (uuid == null) {
// create new uuid
uuid = UUID.randomUUID().toString(); // create new version 4 uuid
}
if (nodeTypeName == null) {
// no primary node type specified,
// try default primary type from definition
nodeTypeName = def.getDefaultPrimaryType();
if (nodeTypeName == null) {
String msg = "an applicable node type could not be determined for "
+ nodeName;
log.debug(msg);
throw new ConstraintViolationException(msg);
}
}
NodeState node = stateMgr.createNew(uuid, nodeTypeName, parent.getUUID());
if (mixinNames != null && mixinNames.length > 0) {
node.setMixinTypeNames(new HashSet(Arrays.asList(mixinNames)));
}
node.setDefinitionId(new NodeDefId(def));
// now add new child node entry to parent
parent.addChildNodeEntry(nodeName, node.getUUID());
EffectiveNodeType ent = wsp.getEffectiveNodeType(node);
if (!node.getMixinTypeNames().isEmpty()) {
// create jcr:mixinTypes property
PropDef pd = ent.getApplicablePropertyDef(JCR_MIXINTYPES,
PropertyType.NAME, true);
createProperty(node, pd.getName(), pd.getRequiredType(), pd);
}
// add 'auto-create' properties defined in node type
PropDef[] pda = ent.getAutoCreatePropDefs();
for (int i = 0; i < pda.length; i++) {
PropDef pd = pda[i];
createProperty(node, pd.getName(), pd.getRequiredType(), pd);
}
// recursively add 'auto-create' child nodes defined in node type
ChildNodeDef[] nda = ent.getAutoCreateNodeDefs();
for (int i = 0; i < nda.length; i++) {
ChildNodeDef nd = nda[i];
createNode(node, nd.getName(), nd.getDefaultPrimaryType(),
null, null, nd);
}
return node;
}
protected PropertyState createProperty(NodeState parent,
QName propName,
int type,
int numValues)
throws RepositoryException {
// find applicable definition
PropDef def;
// multi- or single-valued property?
if (numValues == 1) {
// could be single- or multi-valued (n == 1)
try {
// try single-valued
def = wsp.findApplicablePropertyDefinition(propName,
type, false, parent);
} catch (ConstraintViolationException cve) {
// try multi-valued
def = wsp.findApplicablePropertyDefinition(propName,
type, true, parent);
}
} else {
// can only be multi-valued (n == 0 || n > 1)
def = wsp.findApplicablePropertyDefinition(propName,
type, true, parent);
}
return createProperty(parent, propName, type, def);
}
protected PropertyState createProperty(NodeState parent,
QName propName,
int type,
PropDef def)
throws RepositoryException {
// check for name collisions with existing child nodes
if (parent.hasChildNodeEntry(propName)) {
String msg = "there's already a child node with name " + propName;
log.debug(msg);
throw new RepositoryException(msg);
}
// create property
PropertyState prop = stateMgr.createNew(propName, parent.getUUID());
prop.setDefinitionId(new PropDefId(def));
if (def.getRequiredType() != PropertyType.UNDEFINED) {
prop.setType(def.getRequiredType());
} else if (type != PropertyType.UNDEFINED) {
prop.setType(type);
} else {
prop.setType(PropertyType.STRING);
}
prop.setMultiValued(def.isMultiple());
// compute system generated values if necessary
InternalValue[] genValues =
computeSystemGeneratedPropertyValues(parent, propName, def);
if (genValues != null) {
prop.setValues(genValues);
} else if (def.getDefaultValues() != null) {
prop.setValues(def.getDefaultValues());
}
// now add new property entry to parent
parent.addPropertyEntry(propName);
return prop;
}
/**
* Computes the values of well-known system (i.e. protected) properties.
* todo: duplicate code in NodeImpl: consolidate and delegate to NodeTypeInstanceHandler
*
* @param parent
* @param name
* @param def
* @return
* @throws RepositoryException
*/
protected InternalValue[] computeSystemGeneratedPropertyValues(NodeState parent,
QName name,
PropDef def)
throws RepositoryException {
InternalValue[] genValues = null;
/**
* todo: need to come up with some callback mechanism for applying system generated values
* (e.g. using a NodeTypeInstanceHandler interface)
*/
// compute system generated values
QName declaringNT = def.getDeclaringNodeType();
if (MIX_REFERENCEABLE.equals(declaringNT)) {
// mix:referenceable node type
if (JCR_UUID.equals(name)) {
// jcr:uuid property
genValues = new InternalValue[]{InternalValue.create(parent.getUUID())};
}
} else if (NT_BASE.equals(declaringNT)) {
// nt:base node type
if (JCR_PRIMARYTYPE.equals(name)) {
// jcr:primaryType property
genValues = new InternalValue[]{InternalValue.create(parent.getNodeTypeName())};
} else if (JCR_MIXINTYPES.equals(name)) {
// jcr:mixinTypes property
Set mixins = parent.getMixinTypeNames();
ArrayList values = new ArrayList(mixins.size());
Iterator iter = mixins.iterator();
while (iter.hasNext()) {
values.add(InternalValue.create((QName) iter.next()));
}
genValues = (InternalValue[]) values.toArray(new InternalValue[values.size()]);
}
} else if (NT_HIERARCHYNODE.equals(declaringNT)) {
// nt:hierarchyNode node type
if (JCR_CREATED.equals(name)) {
// jcr:created property
genValues = new InternalValue[]{InternalValue.create(Calendar.getInstance())};
}
} else if (NT_RESOURCE.equals(declaringNT)) {
// nt:resource node type
if (JCR_LASTMODIFIED.equals(name)) {
// jcr:lastModified property
genValues = new InternalValue[]{InternalValue.create(Calendar.getInstance())};
}
} else if (NT_VERSION.equals(declaringNT)) {
// nt:version node type
if (JCR_CREATED.equals(name)) {
// jcr:created property
genValues = new InternalValue[]{InternalValue.create(Calendar.getInstance())};
}
/*
// FIXME delegate to NodeTypeInstanceHandler
} else if (MIX_VERSIONABLE.equals(declaringNT)) {
// mix:versionable node type
if (JCR_VERSIONHISTORY.equals(name)) {
// jcr:versionHistory property
genValues = new InternalValue[]{InternalValue.create(new UUID(hist.getUUID()))};
} else if (JCR_BASEVERSION.equals(name)) {
// jcr:baseVersion property
genValues = new InternalValue[]{InternalValue.create(new UUID(hist.getRootVersion().getUUID()))};
} else if (JCR_ISCHECKEDOUT.equals(name)) {
// jcr:isCheckedOut property
genValues = new InternalValue[]{InternalValue.create(true)};
} else if (JCR_PREDECESSORS.equals(name)) {
// jcr:predecessors property
genValues = new InternalValue[]{InternalValue.create(new UUID(hist.getRootVersion().getUUID()))};
}
*/
}
return genValues;
}
/**
* Unlinks the specified target node from all its parents and recursively
* removes it including its properties and child nodes.
* <p/>
* <b>Precondition:</b> the state manager of this workspace needs to be in
* edit mode.
* todo duplicate code in WorkspaceImporter; consolidate in WorkspaceOperations class
*
* @param target
* @throws RepositoryException if an error occurs
*/
protected void removeNode(NodeState target)
throws RepositoryException {
// copy list to avoid ConcurrentModificationException
ArrayList parentUUIDs = new ArrayList(target.getParentUUIDs());
Iterator iter = parentUUIDs.iterator();
while (iter.hasNext()) {
String parentUUID = (String) iter.next();
NodeId parentId = new NodeId(parentUUID);
// unlink target node from this parent
unlinkNodeState(target, parentUUID);
// remove child node entries
NodeState parent;
try {
parent = (NodeState) stateMgr.getItemState(parentId);
} catch (ItemStateException ise) {
// should never get here...
String msg = "internal error: failed to retrieve parent state";
log.error(msg, ise);
throw new RepositoryException(msg, ise);
}
// use temp array to avoid ConcurrentModificationException
ArrayList tmp =
new ArrayList(parent.getChildNodeEntries(target.getUUID()));
// remove from tail to avoid problems with same-name siblings
for (int i = tmp.size() - 1; i >= 0; i--) {
NodeState.ChildNodeEntry entry = (NodeState.ChildNodeEntry) tmp.get(i);
parent.removeChildNodeEntry(entry.getName(), entry.getIndex());
}
// store parent
stateMgr.store(parent);
}
}
/**
* Unlinks the given target node from the specified parent i.e. removes
* <code>parentUUID</code> from its list of parents. If as a result
* the target node would be orphaned it will be recursively removed
* including its properties and child nodes.
* <p/>
* Note that the child node entry refering to <code>target</code> is
* <b><i>not</i></b> automatically removed from <code>target</code>'s
* parent denoted by <code>parentUUID</code>.
* <p/>
* <b>Precondition:</b> the state manager of this workspace needs to be in
* edit mode.
* todo duplicate code in WorkspaceImporter; consolidate in WorkspaceOperations class
*
* @param target
* @param parentUUID
* @throws RepositoryException if an error occurs
*/
private void unlinkNodeState(NodeState target, String parentUUID)
throws RepositoryException {
// check if this node state would be orphaned after unlinking it from parent
ArrayList parentUUIDs = new ArrayList(target.getParentUUIDs());
parentUUIDs.remove(parentUUID);
boolean orphaned = parentUUIDs.isEmpty();
if (orphaned) {
// remove child nodes
// use temp array to avoid ConcurrentModificationException
ArrayList tmp = new ArrayList(target.getChildNodeEntries());
// remove from tail to avoid problems with same-name siblings
for (int i = tmp.size() - 1; i >= 0; i--) {
NodeState.ChildNodeEntry entry = (NodeState.ChildNodeEntry) tmp.get(i);
NodeId nodeId = new NodeId(entry.getUUID());
try {
NodeState nodeState = (NodeState) stateMgr.getItemState(nodeId);
// check if child node can be removed
// (access rights, locking & versioning status)
wsp.checkRemoveNode(nodeState, (NodeId) target.getId(),
WorkspaceImpl.CHECK_ACCESS | WorkspaceImpl.CHECK_LOCK
| WorkspaceImpl.CHECK_VERSIONING);
// unlink child node (recursive)
unlinkNodeState(nodeState, target.getUUID());
} catch (ItemStateException ise) {
String msg = "internal error: failed to retrieve state of "
+ nodeId;
log.debug(msg);
throw new RepositoryException(msg, ise);
}
// remove child node entry
target.removeChildNodeEntry(entry.getName(), entry.getIndex());
}
// remove properties
// use temp array to avoid ConcurrentModificationException
tmp = new ArrayList(target.getPropertyEntries());
// remove from tail to avoid problems with same-name siblings
for (int i = tmp.size() - 1; i >= 0; i--) {
NodeState.PropertyEntry entry = (NodeState.PropertyEntry) tmp.get(i);
PropertyId propId =
new PropertyId(target.getUUID(), entry.getName());
try {
PropertyState propState = (PropertyState) stateMgr.getItemState(propId);
// remove property entry
target.removePropertyEntry(propId.getName());
// destroy property state
stateMgr.destroy(propState);
} catch (ItemStateException ise) {
String msg = "internal error: failed to retrieve state of "
+ propId;
log.debug(msg);
throw new RepositoryException(msg, ise);
}
}
}
// now actually do unlink target state from specified parent state
// (i.e. remove uuid of parent state from target state's parent list)
target.removeParentUUID(parentUUID);
if (orphaned) {
// destroy target state
stateMgr.destroy(target);
} else {
// store target state
stateMgr.store(target);
}
}
protected NodeState resolveUUIDConflict(NodeState parent,
NodeState conflicting,
NodeInfo nodeInfo)
throws RepositoryException {
NodeState node;
if (uuidBehavior == IMPORT_UUID_CREATE_NEW) {
// create new with new uuid:
// check if new node can be added (check access rights &
// node type constraints only, assume locking & versioning status
// has already been checked on ancestor)
wsp.checkAddNode(parent, nodeInfo.getName(),
nodeInfo.getNodeTypeName(),
WorkspaceImpl.CHECK_ACCESS
| WorkspaceImpl.CHECK_CONSTRAINTS);
node = createNode(parent, nodeInfo.getName(),
nodeInfo.getNodeTypeName(), nodeInfo.getMixinNames(), null);
// remember uuid mapping
EffectiveNodeType ent = wsp.getEffectiveNodeType(node);
if (ent.includesNodeType(MIX_REFERENCEABLE)) {
refTracker.mappedUUID(nodeInfo.getUUID(), node.getUUID());
}
} else if (uuidBehavior == IMPORT_UUID_COLLISION_THROW) {
String msg = "a node with uuid " + nodeInfo.getUUID()
+ " already exists!";
log.debug(msg);
throw new ItemExistsException(msg);
} else if (uuidBehavior == IMPORT_UUID_COLLISION_REMOVE_EXISTING) {
// make sure conflicting node is not importTarget or an ancestor thereof
Path p0 = hierMgr.getPath(importTarget.getId());
Path p1 = hierMgr.getPath(conflicting.getId());
try {
if (p1.equals(p0) || p1.isAncestorOf(p0)) {
String msg = "cannot remove ancestor node";
log.debug(msg);
throw new RepositoryException(msg);
}
} catch (MalformedPathException mpe) {
// should never get here...
String msg = "internal error: failed to determine degree of relationship";
log.error(msg, mpe);
throw new RepositoryException(msg, mpe);
}
// remove conflicting:
// check if conflicting can be removed
// (access rights, node type constraints, locking & versioning status)
wsp.checkRemoveNode(conflicting,
WorkspaceImpl.CHECK_ACCESS
| WorkspaceImpl.CHECK_LOCK
| WorkspaceImpl.CHECK_VERSIONING
| WorkspaceImpl.CHECK_CONSTRAINTS);
// do remove conflicting (recursive)
removeNode(conflicting);
// create new with given uuid:
// check if new node can be added (check access rights &
// node type constraints only, assume locking & versioning status
// has already been checked on ancestor)
wsp.checkAddNode(parent, nodeInfo.getName(),
nodeInfo.getNodeTypeName(),
WorkspaceImpl.CHECK_ACCESS
| WorkspaceImpl.CHECK_CONSTRAINTS);
// do create new node
node = createNode(parent, nodeInfo.getName(),
nodeInfo.getNodeTypeName(), nodeInfo.getMixinNames(),
nodeInfo.getUUID());
} else if (uuidBehavior == IMPORT_UUID_COLLISION_REPLACE_EXISTING) {
if (conflicting.getParentUUID() == null) {
String msg = "root node cannot be replaced";
log.debug(msg);
throw new RepositoryException(msg);
}
// 'replace' current parent with parent of conflicting
NodeId parentId = new NodeId(conflicting.getParentUUID());
try {
parent = (NodeState) stateMgr.getItemState(parentId);
} catch (ItemStateException ise) {
// should never get here...
String msg = "internal error: failed to retrieve parent state";
log.error(msg, ise);
throw new RepositoryException(msg, ise);
}
// remove conflicting:
// check if conflicting can be removed
wsp.checkRemoveNode(conflicting,
WorkspaceImpl.CHECK_ACCESS
| WorkspaceImpl.CHECK_LOCK
| WorkspaceImpl.CHECK_VERSIONING
| WorkspaceImpl.CHECK_CONSTRAINTS);
// do remove conflicting (recursive)
removeNode(conflicting);
// create new with given uuid at same location as conflicting:
// check if new node can be added at other location
// (access rights, node type constraints, locking & versioning status)
wsp.checkAddNode(parent, nodeInfo.getName(),
nodeInfo.getNodeTypeName(),
WorkspaceImpl.CHECK_ACCESS
| WorkspaceImpl.CHECK_LOCK
| WorkspaceImpl.CHECK_VERSIONING
| WorkspaceImpl.CHECK_CONSTRAINTS);
// do create new node
node = createNode(parent, nodeInfo.getName(),
nodeInfo.getNodeTypeName(), nodeInfo.getMixinNames(),
nodeInfo.getUUID());
} else {
String msg = "unknown uuidBehavior: " + uuidBehavior;
log.debug(msg);
throw new RepositoryException(msg);
}
return node;
}
//-------------------------------------------------------------< Importer >
/**
* {@inheritDoc}
*/
public void start() throws RepositoryException {
try {
// start update operation
stateMgr.edit();
} catch (ItemStateException ise) {
aborted = true;
String msg = "internal error: failed to start update operation";
log.debug(msg);
throw new RepositoryException(msg, ise);
}
}
/**
* {@inheritDoc}
*/
public void startNode(NodeInfo nodeInfo, List propInfos,
NamespaceResolver nsContext)
throws RepositoryException {
if (aborted) {
// the import has been aborted, get outta here...
return;
}
boolean succeeded = false;
NodeState parent = null;
try {
// check sanity of workspace/session first
wsp.sanityCheck();
parent = (NodeState) parents.peek();
// process node
NodeState node = null;
String uuid = nodeInfo.getUUID();
QName nodeName = nodeInfo.getName();
QName ntName = nodeInfo.getNodeTypeName();
QName[] mixins = nodeInfo.getMixinNames();
if (parent == null) {
// parent node was skipped, skip this child node also
parents.push(null); // push null onto stack for skipped node
succeeded = true;
log.debug("skipping node " + nodeName);
return;
}
if (parent.hasChildNodeEntry(nodeName)) {
// a node with that name already exists...
NodeState.ChildNodeEntry entry =
parent.getChildNodeEntry(nodeName, 1);
NodeId idExisting = new NodeId(entry.getUUID());
NodeState existing = (NodeState) stateMgr.getItemState(idExisting);
ChildNodeDef def = ntReg.getNodeDef(existing.getDefinitionId());
if (!def.allowSameNameSibs()) {
// existing doesn't allow same-name siblings,
// check for potential conflicts
EffectiveNodeType entExisting =
wsp.getEffectiveNodeType(existing);
if (def.isProtected() && entExisting.includesNodeType(ntName)) {
// skip protected node
parents.push(null); // push null onto stack for skipped node
succeeded = true;
log.debug("skipping protected node "
+ resolveJCRPath(existing.getId()));
return;
}
if (def.isAutoCreate() && entExisting.includesNodeType(ntName)) {
// this node has already been auto-created,
// no need to create it
node = existing;
} else {
throw new ItemExistsException(resolveJCRPath(existing.getId()));
}
}
}
if (node == null) {
// there's no node with that name...
if (uuid == null) {
// no potential uuid conflict, always create new node
ChildNodeDef def =
wsp.findApplicableNodeDefinition(nodeName, ntName, parent);
if (def.isProtected()) {
// skip protected node
parents.push(null); // push null onto stack for skipped node
succeeded = true;
log.debug("skipping protected node " + nodeName);
return;
}
// check if new node can be added (check access rights &
// node type constraints only, assume locking & versioning status
// has already been checked on ancestor)
wsp.checkAddNode(parent, nodeName, ntName,
WorkspaceImpl.CHECK_ACCESS
| WorkspaceImpl.CHECK_CONSTRAINTS);
// do create new node
node = createNode(parent, nodeName, ntName, mixins, null, def);
} else {
// potential uuid conflict
NodeState conflicting;
try {
conflicting =
(NodeState) stateMgr.getItemState(new NodeId(uuid));
} catch (NoSuchItemStateException nsise) {
conflicting = null;
}
if (conflicting != null) {
// resolve uuid conflict
node = resolveUUIDConflict(parent, conflicting, nodeInfo);
} else {
// create new with given uuid
ChildNodeDef def =
wsp.findApplicableNodeDefinition(nodeName, ntName, parent);
if (def.isProtected()) {
// skip protected node
parents.push(null); // push null onto stack for skipped node
succeeded = true;
log.debug("skipping protected node " + nodeName);
return;
}
// check if new node can be added (check access rights &
// node type constraints only, assume locking & versioning status
// has already been checked on ancestor)
wsp.checkAddNode(parent, nodeName, ntName,
WorkspaceImpl.CHECK_ACCESS
| WorkspaceImpl.CHECK_CONSTRAINTS);
// do create new node
node = createNode(parent, nodeName, ntName, mixins, uuid, def);
}
}
}
// process properties
Iterator iter = propInfos.iterator();
while (iter.hasNext()) {
PropInfo pi = (PropInfo) iter.next();
QName propName = pi.getName();
TextValue[] tva = pi.getValues();
int type = pi.getType();
PropertyState prop = null;
PropDef def = null;
if (node.hasPropertyEntry(propName)) {
// a property with that name already exists...
PropertyId idExisting = new PropertyId(node.getUUID(), propName);
PropertyState existing =
(PropertyState) stateMgr.getItemState(idExisting);
def = ntReg.getPropDef(existing.getDefinitionId());
if (def.isProtected()) {
// skip protected property
log.debug("skipping protected property "
+ resolveJCRPath(idExisting));
continue;
}
if (def.isAutoCreate() && (existing.getType() == type
|| type == PropertyType.UNDEFINED)
&& def.isMultiple() == existing.isMultiValued()) {
// this property has already been auto-created,
// no need to create it
prop = existing;
} else {
throw new ItemExistsException(resolveJCRPath(existing.getId()));
}
}
if (prop == null) {
// there's no property with that name,
// find applicable definition
// multi- or single-valued property?
if (tva.length == 1) {
// could be single- or multi-valued (n == 1)
try {
// try single-valued
def = wsp.findApplicablePropertyDefinition(propName,
type, false, node);
} catch (ConstraintViolationException cve) {
// try multi-valued
def = wsp.findApplicablePropertyDefinition(propName,
type, true, node);
}
} else {
// can only be multi-valued (n == 0 || n > 1)
def = wsp.findApplicablePropertyDefinition(propName,
type, true, node);
}
if (def.isProtected()) {
// skip protected property
log.debug("skipping protected property " + propName);
continue;
}
// create new property
prop = createProperty(node, propName, type, def);
}
// check multi-valued characteristic
if ((tva.length == 0 || tva.length > 1) && !def.isMultiple()) {
throw new ConstraintViolationException(resolveJCRPath(prop.getId())
+ " is not multi-valued");
}
// convert serialized values to InternalValue objects
InternalValue[] iva = new InternalValue[tva.length];
int targetType = def.getRequiredType();
if (targetType == PropertyType.UNDEFINED) {
if (type == PropertyType.UNDEFINED) {
targetType = PropertyType.STRING;
} else {
targetType = type;
}
}
for (int i = 0; i < tva.length; i++) {
TextValue tv = tva[i];
if (targetType == PropertyType.BINARY) {
// base64 encoded BINARY type;
// decode using Reader
/*
// @todo decode to temp file and pass FileInputStream to InternalValue factory method
File tmpFile = null;
try {
tmpFile = File.createTempFile("bin", null);
FileOutputStream out = new FileOutputStream(tmpFile);
Base64.decode(tv.reader(), out);
out.close();
iva[i] = InternalValue.create(new FileInputStream(tmpFile));
} catch (IOException ioe) {
String msg = "failed to decode binary value";
log.debug(msg, ioe);
throw new RepositoryException(msg, ioe);
} finally {
// the temp file can be deleted because
// the InternalValue instance has spooled
// its contents
if (tmpFile != null) {
tmpFile.delete();
}
}
*/
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
Base64.decode(tv.reader(), baos);
// no need to close ByteArrayOutputStream
//baos.close();
iva[i] = InternalValue.create(new ByteArrayInputStream(baos.toByteArray()));
} catch (IOException ioe) {
String msg = "failed to decode binary value";
log.debug(msg, ioe);
throw new RepositoryException(msg, ioe);
}
} else {
// retrieve serialized value
String serValue;
try {
serValue = tv.retrieve();
} catch (IOException ioe) {
String msg = "failed to retrieve serialized value";
log.debug(msg, ioe);
throw new RepositoryException(msg, ioe);
}
// convert serialized value to InternalValue using
// current namespace context of xml document
iva[i] = InternalValue.create(serValue, targetType,
nsContext);
}
}
// set values
prop.setValues(iva);
// make sure node is valid according to its definition
wsp.validate(prop);
if (prop.getType() == PropertyType.REFERENCE) {
// store reference for later resolution
refTracker.processedReference(prop);
}
// store property
stateMgr.store(prop);
}
// store affected nodes
stateMgr.store(node);
stateMgr.store(parent);
// push current node onto stack of parents
parents.push(node);
succeeded = true;
} catch (ItemStateException ise) {
String msg = "internal error: failed to store state of "
+ resolveJCRPath(parent.getId());
log.debug(msg);
throw new RepositoryException(msg, ise);
} finally {
if (!succeeded) {
// update operation failed, cancel all modifications
aborted = true;
stateMgr.cancel();
}
}
}
/**
* {@inheritDoc}
*/
public void endNode(NodeInfo nodeInfo) throws RepositoryException {
if (aborted) {
// the import has been aborted, get outta here...
return;
}
NodeState node = (NodeState) parents.pop();
if (node == null) {
// node was skipped, nothing to do here
return;
}
boolean succeeded = false;
try {
// check sanity of workspace/session first
wsp.sanityCheck();
// make sure node is valid according to its definition
wsp.validate(node);
// we're done with that node, now store its state
stateMgr.store(node);
succeeded = true;
} finally {
if (!succeeded) {
// update operation failed, cancel all modifications
aborted = true;
stateMgr.cancel();
}
}
}
/**
* {@inheritDoc}
*/
public void end() throws RepositoryException {
if (aborted) {
// the import has been aborted, get outta here...
return;
}
boolean succeeded = false;
try {
// check sanity of workspace/session first
wsp.sanityCheck();
/**
* adjust references that refer to uuid's which have been mapped to
* newly gererated uuid's on import
*/
Iterator iter = refTracker.getProcessedReferences();
while (iter.hasNext()) {
PropertyState prop = (PropertyState) iter.next();
// being paranoid...
if (prop.getType() != PropertyType.REFERENCE) {
continue;
}
boolean modified = false;
InternalValue[] values = prop.getValues();
InternalValue[] newVals = new InternalValue[values.length];
for (int i = 0; i < values.length; i++) {
InternalValue val = values[i];
String original = ((UUID) val.internalValue()).toString();
String adjusted = refTracker.getMappedUUID(original);
if (adjusted != null) {
newVals[i] = InternalValue.create(UUID.fromString(adjusted));
modified = true;
} else {
// reference doesn't need adjusting, just copy old value
newVals[i] = val;
}
}
if (modified) {
prop.setValues(newVals);
stateMgr.store(prop);
}
}
refTracker.clear();
// make sure import target is valid according to its definition
wsp.validate(importTarget);
// finally store the state of the import target
// (the parent of the imported subtree)
stateMgr.store(importTarget);
succeeded = true;
} finally {
if (!succeeded) {
// update operation failed, cancel all modifications
aborted = true;
stateMgr.cancel();
}
}
if (!aborted) {
try {
// finish update
stateMgr.update();
} catch (ItemStateException ise) {
aborted = true;
String msg = "internal error: failed to finish update operation";
log.debug(msg);
throw new RepositoryException(msg, ise);
}
}
}
}
| Workspace.clone(...,removeExisting=true) & Workspace.importXML(..., IMPORT_UUID_COLLISION_REMOVE_EXISTING) potentially leaves repository in inconsistent state
git-svn-id: e3d4743c6b03e3f6fd6d8117e7616b4c02d9b980@160782 13f79535-47bb-0310-9956-ffa450edef68
| src/java/org/apache/jackrabbit/core/xml/WorkspaceImporter.java | Workspace.clone(...,removeExisting=true) & Workspace.importXML(..., IMPORT_UUID_COLLISION_REMOVE_EXISTING) potentially leaves repository in inconsistent state | <ide><path>rc/java/org/apache/jackrabbit/core/xml/WorkspaceImporter.java
<ide> NodeId parentId = new NodeId(parentUUID);
<ide>
<ide> // unlink target node from this parent
<del> unlinkNodeState(target, parentUUID);
<add> unlinkNode(target, parentUUID);
<ide>
<ide> // remove child node entries
<ide> NodeState parent;
<ide> * @param parentUUID
<ide> * @throws RepositoryException if an error occurs
<ide> */
<del> private void unlinkNodeState(NodeState target, String parentUUID)
<add> private void unlinkNode(NodeState target, String parentUUID)
<ide> throws RepositoryException {
<ide>
<ide> // check if this node state would be orphaned after unlinking it from parent
<ide> NodeState.ChildNodeEntry entry = (NodeState.ChildNodeEntry) tmp.get(i);
<ide> NodeId nodeId = new NodeId(entry.getUUID());
<ide> try {
<del> NodeState nodeState = (NodeState) stateMgr.getItemState(nodeId);
<add> NodeState node = (NodeState) stateMgr.getItemState(nodeId);
<ide> // check if child node can be removed
<ide> // (access rights, locking & versioning status)
<del> wsp.checkRemoveNode(nodeState, (NodeId) target.getId(),
<add> wsp.checkRemoveNode(node, (NodeId) target.getId(),
<ide> WorkspaceImpl.CHECK_ACCESS | WorkspaceImpl.CHECK_LOCK
<ide> | WorkspaceImpl.CHECK_VERSIONING);
<ide> // unlink child node (recursive)
<del> unlinkNodeState(nodeState, target.getUUID());
<add> unlinkNode(node, target.getUUID());
<ide> } catch (ItemStateException ise) {
<ide> String msg = "internal error: failed to retrieve state of "
<ide> + nodeId;
<ide> PropertyId propId =
<ide> new PropertyId(target.getUUID(), entry.getName());
<ide> try {
<del> PropertyState propState = (PropertyState) stateMgr.getItemState(propId);
<add> PropertyState prop = (PropertyState) stateMgr.getItemState(propId);
<ide> // remove property entry
<ide> target.removePropertyEntry(propId.getName());
<ide> // destroy property state
<del> stateMgr.destroy(propState);
<add> stateMgr.destroy(prop);
<ide> } catch (ItemStateException ise) {
<ide> String msg = "internal error: failed to retrieve state of "
<ide> + propId;
<ide> target.removeParentUUID(parentUUID);
<ide>
<ide> if (orphaned) {
<del> // destroy target state
<add> // destroy target
<ide> stateMgr.destroy(target);
<ide> } else {
<del> // store target state
<add> // store target
<ide> stateMgr.store(target);
<ide> }
<ide> } |
|
Java | bsd-3-clause | 4e3c8eb277aa380633361d15f1f2290b0d8f5c69 | 0 | lockss/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon | /*
* $Id: ArchivalUnitStatus.java,v 1.80 2009-06-01 07:32:07 tlipkis Exp $
*/
/*
Copyright (c) 2000-2008 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.
*/
package org.lockss.state;
import java.io.*;
import java.util.*;
import java.text.*;
import java.net.MalformedURLException;
import org.lockss.config.Configuration;
import org.lockss.daemon.*;
import org.lockss.daemon.status.*;
import org.lockss.plugin.*;
import org.lockss.util.*;
import org.lockss.app.*;
import org.lockss.crawler.*;
import org.lockss.poller.*;
import org.lockss.poller.v3.*;
import org.lockss.protocol.*;
import org.lockss.repository.*;
import org.lockss.servlet.AdminServletManager;
/**
* Collect and report the status of the ArchivalUnits
*/
public class ArchivalUnitStatus
extends BaseLockssDaemonManager implements ConfigurableManager {
public static final String PREFIX = Configuration.PREFIX + "auStatus.";
/**
* The default maximum number of nodes to display in a single page of the ui.
*/
public static final String PARAM_MAX_NODES_TO_DISPLAY =
PREFIX + "nodesPerPage";
static final int DEFAULT_MAX_NODES_TO_DISPLAY = 100;
/**
* Node URLs are links to cached content page if true
*/
public static final String PARAM_CONTENT_IS_LINK =
PREFIX + "contentUrlIsLink";
static final boolean DEFAULT_CONTENT_IS_LINK = true;
/**
* Include number of AUs needing recrawl in overview if true
*/
public static final String PARAM_INCLUDE_NEEDS_RECRAWL =
PREFIX + "includeNeedsRecrawl";
static final boolean DEFAULT_INCLUDE_NEEDS_RECRAWL = true;
public static final String SERVICE_STATUS_TABLE_NAME =
"ArchivalUnitStatusTable";
public static final String AUIDS_TABLE_NAME = "AuIds";
public static final String AU_STATUS_TABLE_NAME = "ArchivalUnitTable";
public static final String NO_AU_PEERS_TABLE_NAME = "NoAuPeers";
public static final String PEERS_VOTE_TABLE_NAME = "PeerVoteSummary";
public static final String PEERS_REPAIR_TABLE_NAME = "PeerRepair";
static final OrderedObject DASH = new OrderedObject("-", new Long(-1));
private static Logger logger = Logger.getLogger("AuStatus");
private static int defaultNumRows = DEFAULT_MAX_NODES_TO_DISPLAY;
private static boolean isContentIsLink = DEFAULT_CONTENT_IS_LINK;
private static boolean includeNeedsRecrawl = DEFAULT_INCLUDE_NEEDS_RECRAWL;
private static final DecimalFormat agreementFormat =
new DecimalFormat("0.00");
/* DecimalFormat automatically applies half-even rounding to
* values being formatted under Java < 1.6. This is a workaround. */
private static String doubleToPercent(double d) {
int i = (int)(d * 10000);
double pc = i / 100.0;
return agreementFormat.format(pc);
}
public void startService() {
super.startService();
LockssDaemon theDaemon = getDaemon();
StatusService statusServ = theDaemon.getStatusService();
statusServ.registerStatusAccessor(SERVICE_STATUS_TABLE_NAME,
new AuSummary(theDaemon));
statusServ.registerOverviewAccessor(SERVICE_STATUS_TABLE_NAME,
new Overview(theDaemon));
statusServ.registerStatusAccessor(AUIDS_TABLE_NAME,
new AuIds(theDaemon));
statusServ.registerStatusAccessor(AU_STATUS_TABLE_NAME,
new AuStatus(theDaemon));
statusServ.registerStatusAccessor(NO_AU_PEERS_TABLE_NAME,
new NoAuPeers(theDaemon));
statusServ.registerStatusAccessor(PEERS_VOTE_TABLE_NAME,
new PeerVoteSummary(theDaemon));
statusServ.registerStatusAccessor(PEERS_REPAIR_TABLE_NAME,
new PeerRepair(theDaemon));
logger.debug2("Status accessors registered.");
}
public void stopService() {
// unregister our status accessors
LockssDaemon theDaemon = getDaemon();
StatusService statusServ = theDaemon.getStatusService();
statusServ.unregisterStatusAccessor(SERVICE_STATUS_TABLE_NAME);
statusServ.unregisterStatusAccessor(NO_AU_PEERS_TABLE_NAME);
statusServ.unregisterStatusAccessor(AU_STATUS_TABLE_NAME);
statusServ.unregisterStatusAccessor(PEERS_VOTE_TABLE_NAME);
statusServ.unregisterStatusAccessor(PEERS_REPAIR_TABLE_NAME);
logger.debug2("Status accessors unregistered.");
super.stopService();
}
public void setConfig(Configuration config, Configuration oldConfig,
Configuration.Differences changedKeys) {
defaultNumRows = config.getInt(PARAM_MAX_NODES_TO_DISPLAY,
DEFAULT_MAX_NODES_TO_DISPLAY);
isContentIsLink = config.getBoolean(PARAM_CONTENT_IS_LINK,
DEFAULT_CONTENT_IS_LINK);
includeNeedsRecrawl = config.getBoolean(PARAM_INCLUDE_NEEDS_RECRAWL,
DEFAULT_INCLUDE_NEEDS_RECRAWL);
}
static CrawlManagerStatus getCMStatus(LockssDaemon daemon) {
CrawlManager crawlMgr = daemon.getCrawlManager();
CrawlManager.StatusSource source = crawlMgr.getStatusSource();
return source.getStatus();
}
static class AuSummary implements StatusAccessor {
static final String TABLE_TITLE = "Archival Units";
static final String FOOT_STATUS = "Flags may follow status: C means the AU is complete, D means that the AU is no longer available from the publisher";
static final String FOOT_SIZE = "If blank, size has changed and is being recalculated. Check again later.";
private static final List columnDescriptors = ListUtil.list(
new ColumnDescriptor("AuName", "Volume", ColumnDescriptor.TYPE_STRING),
// new ColumnDescriptor("AuNodeCount", "Nodes", ColumnDescriptor.TYPE_INT),
new ColumnDescriptor("AuSize", "Content Size",
ColumnDescriptor.TYPE_INT, FOOT_SIZE),
new ColumnDescriptor("DiskUsage", "Disk Usage (MB)",
ColumnDescriptor.TYPE_FLOAT, FOOT_SIZE),
new ColumnDescriptor("Peers", "Peers", ColumnDescriptor.TYPE_INT),
new ColumnDescriptor("AuPolls", "Recent Polls",
ColumnDescriptor.TYPE_INT),
new ColumnDescriptor("Damaged", "Status",
ColumnDescriptor.TYPE_STRING,
FOOT_STATUS),
new ColumnDescriptor("AuLastPoll", "Last Poll",
ColumnDescriptor.TYPE_DATE),
new ColumnDescriptor("AuLastCrawlAttempt", "Last Crawl Start",
ColumnDescriptor.TYPE_DATE),
new ColumnDescriptor("AuLastCrawlResultMsg", "Last Crawl Result",
ColumnDescriptor.TYPE_STRING),
new ColumnDescriptor("AuLastCrawl", "Last Successful Crawl",
ColumnDescriptor.TYPE_DATE)
);
private static final List sortRules =
ListUtil.list(new
StatusTable.SortRule("AuName",
CatalogueOrderComparator.SINGLETON));
private LockssDaemon theDaemon;
private RepositoryManager repoMgr;
private CrawlManagerStatus cmStatus;
AuSummary(LockssDaemon theDaemon) {
this.theDaemon = theDaemon;
repoMgr = theDaemon.getRepositoryManager();
cmStatus = getCMStatus(theDaemon);
}
public String getDisplayName() {
return TABLE_TITLE;
}
public void populateTable(StatusTable table)
throws StatusService.NoSuchTableException {
List cols = columnDescriptors;
if (theDaemon.isDetectClockssSubscription()) {
cols = new ArrayList(cols);
cols.remove(cols.size() - 1);
cols.add(new ColumnDescriptor("Subscribed", "Subscribed",
ColumnDescriptor.TYPE_STRING));
}
table.setColumnDescriptors(cols);
table.setDefaultSortRules(sortRules);
Stats stats = new Stats();
table.setRows(getRows(table, stats));
table.setSummaryInfo(getSummaryInfo(stats));
}
public boolean requiresKey() {
return false;
}
class Stats {
int aus = 0;
}
private List getRows(StatusTable table, Stats stats) {
PluginManager pluginMgr = theDaemon.getPluginManager();
boolean includeInternalAus =
table.getOptions().get(StatusTable.OPTION_DEBUG_USER);
List rowL = new ArrayList();
for (Iterator iter = pluginMgr.getAllAus().iterator();
iter.hasNext(); ) {
ArchivalUnit au = (ArchivalUnit)iter.next();
if (!includeInternalAus && pluginMgr.isInternalAu(au)) {
continue;
}
try {
NodeManager nodeMan = theDaemon.getNodeManager(au);
rowL.add(makeRow(au, nodeMan));
stats.aus++;
} catch (Exception e) {
logger.warning("Unexpected expection building row", e);
}
}
return rowL;
}
private Map makeRow(ArchivalUnit au, NodeManager nodeMan) {
AuState auState = nodeMan.getAuState();
HashMap rowMap = new HashMap();
PollManager.V3PollStatusAccessor v3status =
theDaemon.getPollManager().getV3Status();
// If this is a v3 AU, we cannot access some of the poll
// status through the nodestate. Eventually, this will be totally
// refactored.
boolean isV3 = AuUtil.getProtocolVersion(au) == Poll.V3_PROTOCOL;
//"AuID"
rowMap.put("AuName", AuStatus.makeAuRef(au.getName(), au.getAuId()));
// rowMap.put("AuNodeCount", new Integer(-1));
long contentSize = AuUtil.getAuContentSize(au, false);
if (contentSize != -1) {
rowMap.put("AuSize", new Long(contentSize));
}
long du = AuUtil.getAuDiskUsage(au, false);
if (du != -1) {
rowMap.put("DiskUsage", new Double(((double)du) / (1024*1024)));
}
long lastCrawl = auState.getLastCrawlTime();
long lastAttempt = auState.getLastCrawlAttempt();
int lastResultCode = auState.getLastCrawlResult();
String lastResult = auState.getLastCrawlResultMsg();
rowMap.put("AuLastCrawl", new Long(lastCrawl));
// AuState files that show a successful crawl but no lastAttempt just
// have uninitialized lastXxx fields. Display time and status of
// last successful instead
if (lastCrawl > 0 && lastAttempt <= 0) {
lastAttempt = lastCrawl;
lastResultCode = Crawler.STATUS_SUCCESSFUL;
lastResult = "Successful";
}
rowMap.put("AuLastCrawlAttempt", new Long(lastAttempt));
String lastCrawlStatus =
lastCrawlStatus(au, lastCrawl, lastResultCode, lastResult);
if (lastCrawlStatus != null) {
rowMap.put("AuLastCrawlResultMsg", lastCrawlStatus);
}
rowMap.put("Peers", PeerRepair.makeAuRef("peers", au.getAuId()));
rowMap.put("AuLastPoll", new Long(auState.getLastTopLevelPollTime()));
Object stat;
if (isV3) {
int numPolls = v3status.getNumPolls(au.getAuId());
rowMap.put("AuPolls", pollsRef(new Integer(numPolls), au));
// Percent damaged. It's scary to see '0% Agreement' if there's no
// history, so we just show a friendlier message.
//
if (auState.getHighestV3Agreement() < 0 ||
auState.getLastTopLevelPollTime() <= 0) {
if (cmStatus.isRunningNCCrawl(au)) {
stat = new OrderedObject("Crawling", STATUS_ORDER_CRAWLING);
} else {
if (auState.lastCrawlTime > 0 || AuUtil.isPubDown(au)) {
stat = new OrderedObject("Waiting for Poll",
STATUS_ORDER_WAIT_POLL);
} else {
stat = new OrderedObject("Waiting for Crawl",
STATUS_ORDER_WAIT_CRAWL);
}
}
} else {
stat = agreeStatus(auState.getHighestV3Agreement());
}
} else {
rowMap.put("AuPolls",
theDaemon.getStatusService().
getReference(PollerStatus.MANAGER_STATUS_TABLE_NAME,
au));
CachedUrlSet auCus = au.getAuCachedUrlSet();
NodeState topNodeState = nodeMan.getNodeState(auCus);
stat = topNodeState.hasDamage()
? DAMAGE_STATE_DAMAGED : DAMAGE_STATE_OK;
}
boolean isPubDown = AuUtil.isPubDown(au);
boolean isClosed = AuUtil.isClosed(au);
if (isPubDown || isClosed) {
List val = ListUtil.list(stat, " (");
if (isClosed) {
val.add("C");
}
if (isPubDown) {
val.add("D");
}
val.add(")");
stat = val;
}
rowMap.put("Damaged", stat);
if (theDaemon.isDetectClockssSubscription()) {
rowMap.put("Subscribed",
AuUtil.getAuState(au).getClockssSubscriptionStatusString());
}
return rowMap;
}
String lastCrawlStatus(ArchivalUnit au, long lastCrawl,
int lastResultCode, String lastResult) {
if (AuUtil.isPubDown(au)) {
if (lastCrawl > 0) {
return "No longer crawled";
} else {
return "Never crawled";
}
} else {
if (lastResultCode > 0) {
return lastResult;
}
}
return null;
}
Object pollsRef(Object val, ArchivalUnit au) {
return new StatusTable.Reference(val,
V3PollStatus.POLLER_STATUS_TABLE_NAME,
au.getAuId());
}
private List getSummaryInfo(Stats stats) {
List res = new ArrayList();
String numaus = StringUtil.numberOfUnits(stats.aus, "Archival Unit",
"Archival Units");
res.add(new StatusTable.SummaryInfo(null,
ColumnDescriptor.TYPE_STRING,
numaus));
int n = repoMgr.sizeCalcQueueLen();
if (n != 0) {
res.add(new StatusTable.SummaryInfo(null,
ColumnDescriptor.TYPE_STRING,
n + " awaiting recalc"));
}
return res;
}
}
static class AuIds implements StatusAccessor {
static final String TABLE_TITLE = "AU Ids";
private static final List columnDescriptors = ListUtil.list(
new ColumnDescriptor("AuName", "Volume", ColumnDescriptor.TYPE_STRING),
new ColumnDescriptor("AuId", "AU Id", ColumnDescriptor.TYPE_STRING)
);
private static final List sortRules =
ListUtil.list(new
StatusTable.SortRule("AuName",
CatalogueOrderComparator.SINGLETON));
private LockssDaemon theDaemon;
AuIds(LockssDaemon theDaemon) {
this.theDaemon = theDaemon;
}
public String getDisplayName() {
return TABLE_TITLE;
}
public void populateTable(StatusTable table)
throws StatusService.NoSuchTableException {
table.setColumnDescriptors(columnDescriptors);
table.setDefaultSortRules(sortRules);
Stats stats = new Stats();
table.setRows(getRows(table, stats));
table.setSummaryInfo(getSummaryInfo(stats));
}
public boolean requiresKey() {
return false;
}
class Stats {
int aus = 0;
}
private List getRows(StatusTable table, Stats stats) {
PluginManager pluginMgr = theDaemon.getPluginManager();
boolean includeInternalAus =
table.getOptions().get(StatusTable.OPTION_DEBUG_USER);
List rowL = new ArrayList();
for (Iterator iter = pluginMgr.getAllAus().iterator();
iter.hasNext(); ) {
ArchivalUnit au = (ArchivalUnit)iter.next();
if (!includeInternalAus && pluginMgr.isInternalAu(au)) {
continue;
}
try {
rowL.add(makeRow(au));
stats.aus++;
} catch (Exception e) {
logger.warning("Unexpected expection building row", e);
}
}
return rowL;
}
private Map makeRow(ArchivalUnit au) {
HashMap rowMap = new HashMap();
rowMap.put("AuId", au.getAuId());
rowMap.put("AuName", AuStatus.makeAuRef(au.getName(), au.getAuId()));
return rowMap;
}
private List getSummaryInfo(Stats stats) {
String numaus = StringUtil.numberOfUnits(stats.aus, "Archival Unit",
"Archival Units");
return
ListUtil.list(new StatusTable.SummaryInfo(null,
ColumnDescriptor.TYPE_STRING,
numaus));
}
}
static final StatusTable.DisplayedValue DAMAGE_STATE_OK =
new StatusTable.DisplayedValue("Ok");
static final StatusTable.DisplayedValue DAMAGE_STATE_DAMAGED =
new StatusTable.DisplayedValue("Repairing");
// static {
// DAMAGE_STATE_OK.setColor("green");
// DAMAGE_STATE_DAMAGED.setColor("yellow");
// }
abstract static class PerAuTable implements StatusAccessor {
protected LockssDaemon theDaemon;
protected CrawlManagerStatus cmStatus;
PerAuTable(LockssDaemon theDaemon) {
this.theDaemon = theDaemon;
cmStatus = getCMStatus(theDaemon);
}
public boolean requiresKey() {
return true;
}
public String getDisplayName() {
throw new UnsupportedOperationException("Au table has no generic title");
}
public void populateTable(StatusTable table)
throws StatusService.NoSuchTableException {
String key = table.getKey();
try {
ArchivalUnit au = theDaemon.getPluginManager().getAuFromId(key);
if (au == null) {
throw new StatusService.NoSuchTableException("Unknown auid: " + key);
}
populateTable(table, au);
} catch (StatusService.NoSuchTableException e) {
throw e;
} catch (Exception e) {
logger.warning("Error building table", e);
throw new StatusService.
NoSuchTableException("Error building table for auid: " + key);
}
}
protected abstract void populateTable(StatusTable table, ArchivalUnit au)
throws StatusService.NoSuchTableException;
}
static class AuStatus extends PerAuTable {
private static final List columnDescriptors = ListUtil.list(
new ColumnDescriptor("NodeName", "Node Url",
ColumnDescriptor.TYPE_STRING),
// new ColumnDescriptor("NodeHasContent", "Content",
// ColumnDescriptor.TYPE_STRING),
new ColumnDescriptor("NodeVersion", "Version",
ColumnDescriptor.TYPE_INT),
new ColumnDescriptor("NodeContentSize", "Size",
ColumnDescriptor.TYPE_INT),
new ColumnDescriptor("NodeTreeSize", "Tree Size",
ColumnDescriptor.TYPE_INT),
new ColumnDescriptor("NodeChildCount", "Children",
ColumnDescriptor.TYPE_INT),
new ColumnDescriptor("NodeStatus", "Status",
ColumnDescriptor.TYPE_STRING)
);
private static final List sortRules =
ListUtil.list(new StatusTable.SortRule("sort", true));
AuStatus(LockssDaemon theDaemon) {
super(theDaemon);
}
protected void populateTable(StatusTable table, ArchivalUnit au)
throws StatusService.NoSuchTableException {
LockssRepository repo = theDaemon.getLockssRepository(au);
NodeManager nodeMan = theDaemon.getNodeManager(au);
table.setTitle(getTitle(au.getName()));
CachedUrlSet auCus = au.getAuCachedUrlSet();
NodeState topNode = nodeMan.getNodeState(auCus);
table.setSummaryInfo(getSummaryInfo(au, nodeMan.getAuState(), topNode));
if (!table.getOptions().get(StatusTable.OPTION_NO_ROWS)) {
table.setColumnDescriptors(columnDescriptors);
table.setDefaultSortRules(sortRules);
table.setRows(getRows(table, au, repo, nodeMan));
}
}
int getIntProp(StatusTable table, String name) {
Properties props = table.getProperties();
if (props == null) return -1;
String s = props.getProperty(name);
if (StringUtil.isNullString(s)) return -1;
try {
return Integer.parseInt(s);
} catch (Exception e) {
return -1;
}
}
private List getRows(StatusTable table, ArchivalUnit au,
LockssRepository repo, NodeManager nodeMan) {
int startRow = Math.max(0, getIntProp(table, "skiprows"));
int numRows = getIntProp(table, "numrows");
if (numRows <= 0) {
numRows = defaultNumRows;
}
CrawlSpec spec = au.getCrawlSpec();
List startUrls;
if (spec instanceof SpiderCrawlSpec) {
startUrls = ((SpiderCrawlSpec)spec).getStartingUrls();
} else {
startUrls = Collections.EMPTY_LIST;
}
List rowL = new ArrayList();
Iterator cusIter = au.getAuCachedUrlSet().contentHashIterator();
int endRow1 = startRow + numRows; // end row + 1
if (startRow > 0) {
// add 'previous'
int start = startRow - defaultNumRows;
if (start < 0) {
start = 0;
}
rowL.add(makeOtherRowsLink(false, start, au.getAuId()));
}
for (int curRow = 0; (curRow < endRow1) && cusIter.hasNext(); curRow++) {
CachedUrlSetNode cusn = (CachedUrlSetNode)cusIter.next();
if (curRow < startRow) {
continue;
}
CachedUrlSet cus;
if (cusn.getType() == CachedUrlSetNode.TYPE_CACHED_URL_SET) {
cus = (CachedUrlSet)cusn;
} else {
CachedUrlSetSpec cuss = new RangeCachedUrlSetSpec(cusn.getUrl());
cus = au.makeCachedUrlSet(cuss);
}
String url = cus.getUrl();
try {
Map row = makeRow(au, repo.getNode(url),
nodeMan.getNodeState(cus),
startUrls.contains(url));
row.put("sort", new Integer(curRow));
rowL.add(row);
} catch (MalformedURLException ignore) { }
}
if (cusIter.hasNext()) {
// add 'next'
rowL.add(makeOtherRowsLink(true, endRow1, au.getAuId()));
}
return rowL;
}
private Map makeRow(ArchivalUnit au, RepositoryNode node,
NodeState state, boolean isStartUrl) {
String url = node.getNodeUrl();
boolean hasContent = node.hasContent();
Object val = url;
if (isStartUrl) {
val = new StatusTable.DisplayedValue(val).setBold(true);
}
HashMap rowMap = new HashMap();
if (hasContent && isContentIsLink) {
Properties args = new Properties();
args.setProperty("auid", au.getAuId());
args.setProperty("url", url);
val =
new StatusTable.SrvLink(val,
AdminServletManager.SERVLET_DISPLAY_CONTENT,
args);
} else {
val = url;
}
rowMap.put("NodeName", val);
String status = null;
if (node.isDeleted()) {
status = "Deleted";
} else if (node.isContentInactive()) {
status = "Inactive";
} else if (state.hasDamage()) {
status = "Damaged";
} else {
// status = "Active";
}
if (status != null) {
rowMap.put("NodeStatus", status);
}
Object versionObj = DASH;
Object sizeObj = DASH;
if (hasContent) {
versionObj = new OrderedObject(new Long(node.getCurrentVersion()));
sizeObj = new OrderedObject(new Long(node.getContentSize()));
}
rowMap.put("NodeHasContent", (hasContent ? "yes" : "no"));
rowMap.put("NodeVersion", versionObj);
rowMap.put("NodeContentSize", sizeObj);
if (!node.isLeaf()) {
rowMap.put("NodeChildCount",
new OrderedObject(new Long(node.getChildCount())));
long treeSize = node.getTreeContentSize(null, false);
if (treeSize != -1) {
rowMap.put("NodeTreeSize", new OrderedObject(new Long(treeSize)));
}
} else {
rowMap.put("NodeChildCount", DASH);
rowMap.put("NodeTreeSize", DASH);
}
return rowMap;
}
private Map makeOtherRowsLink(boolean isNext, int startRow, String auKey) {
HashMap rowMap = new HashMap();
String label = (isNext ? "Next" : "Previous") + " (" +
(startRow + 1) + "-" + (startRow + defaultNumRows) + ")";
StatusTable.Reference link =
new StatusTable.Reference(label, AU_STATUS_TABLE_NAME, auKey);
link.setProperty("skiprows", Integer.toString(startRow));
link.setProperty("numrows", Integer.toString(defaultNumRows));
rowMap.put("NodeName", link);
rowMap.put("sort", new Integer(isNext ? Integer.MAX_VALUE : -1));
return rowMap;
}
private String getTitle(String key) {
return "Status of AU: " + key;
}
private List getSummaryInfo(ArchivalUnit au, AuState state,
NodeState topNode) {
int clockssPos = 1;
// Make the status string.
Object stat = null;
Object recentPollStat = null;
if (AuUtil.getProtocolVersion(au) == Poll.V3_PROTOCOL) {
if (state.getV3Agreement() < 0) {
if (state.lastCrawlTime < 0) {
stat = "Waiting for Crawl";
} else {
stat = "Waiting for Poll";
}
} else {
stat = agreeStatus(state.getHighestV3Agreement());
if (state.getHighestV3Agreement() != state.getV3Agreement()) {
recentPollStat = agreeStatus(state.getV3Agreement());
}
}
} else {
stat = topNode.hasDamage() ? DAMAGE_STATE_DAMAGED : DAMAGE_STATE_OK;
}
long contentSize = AuUtil.getAuContentSize(au, false);
long du = AuUtil.getAuDiskUsage(au, false);
StatusTable.SrvLink urlListLink =
new StatusTable.SrvLink("URL list",
AdminServletManager.SERVLET_LIST_OBJECTS,
PropUtil.fromArgs("type", "urls",
"auid", au.getAuId()));
StatusTable.SrvLink doiListLink =
new StatusTable.SrvLink("DOI list",
AdminServletManager.SERVLET_LIST_OBJECTS,
PropUtil.fromArgs("type", "dois",
"auid", au.getAuId()));
List res = new ArrayList();
res.add(new StatusTable.SummaryInfo("Volume",
ColumnDescriptor.TYPE_STRING,
au.getName()));
AuState.AccessType atype = state.getAccessType();
if (atype != null) {
res.add(new StatusTable.SummaryInfo("Access Type",
ColumnDescriptor.TYPE_STRING,
atype.toString()));
}
if (contentSize != -1) {
res.add(new StatusTable.SummaryInfo("Content Size",
ColumnDescriptor.TYPE_INT,
new Long(contentSize)));
} else {
res.add(new StatusTable.SummaryInfo("Content Size",
ColumnDescriptor.TYPE_STRING,
"Awaiting recalc"));
}
if (du != -1) {
res.add(new StatusTable.SummaryInfo("Disk Usage (MB)",
ColumnDescriptor.TYPE_FLOAT,
new Float(du / (float)(1024 * 1024))));
} else {
res.add(new StatusTable.SummaryInfo("Disk Usage",
ColumnDescriptor.TYPE_STRING,
"Awaiting recalc"));
}
AuNodeImpl auNode = AuUtil.getAuRepoNode(au);
String spec = LockssRepositoryImpl.getRepositorySpec(au);
String repo = LockssRepositoryImpl.mapAuToFileLocation(LockssRepositoryImpl.getLocalRepositoryPath(spec), au);
res.add(new StatusTable.SummaryInfo("Repository",
ColumnDescriptor.TYPE_STRING,
repo));
res.add(new StatusTable.SummaryInfo("Status",
ColumnDescriptor.TYPE_STRING,
stat));
if (recentPollStat != null) {
res.add(new StatusTable.SummaryInfo("Most recent poll",
ColumnDescriptor.TYPE_STRING,
recentPollStat));
}
String plat = au.getPlugin().getPublishingPlatform();
if (plat != null) {
res.add(new StatusTable.SummaryInfo("Publishing Platform",
ColumnDescriptor.TYPE_STRING,
plat));
}
res.add(new StatusTable.SummaryInfo("Available From Publisher",
ColumnDescriptor.TYPE_STRING,
(AuUtil.isPubDown(au)
? "No" : "Yes")));
// res.add(new StatusTable.SummaryInfo("Volume Complete",
// ColumnDescriptor.TYPE_STRING,
// (AuUtil.isClosed(au)
// ? "Yes" : "No")));
// res.add(new StatusTable.SummaryInfo("Polling Protocol Version",
// ColumnDescriptor.TYPE_INT,
// new Integer(AuUtil.getProtocolVersion(au))));
res.add(new StatusTable.SummaryInfo("Created",
ColumnDescriptor.TYPE_DATE,
new Long(state.getAuCreationTime())));
CrawlWindow window = au.getCrawlSpec().getCrawlWindow();
if (window != null) {
String wmsg = window.toString();
if (wmsg.length() > 140) {
wmsg = "(not displayable)";
}
if (!window.canCrawl()) {
wmsg = "Currently closed: " + wmsg;
}
res.add(new StatusTable.SummaryInfo("Crawl Window",
ColumnDescriptor.TYPE_STRING,
wmsg));
}
long lastCrawlAttempt = state.getLastCrawlAttempt();
res.add(new StatusTable.SummaryInfo("Last Completed Crawl",
ColumnDescriptor.TYPE_DATE,
new Long(state.getLastCrawlTime())));
if (lastCrawlAttempt > 0) {
res.add(new StatusTable.SummaryInfo("Last Crawl",
ColumnDescriptor.TYPE_DATE,
new Long(lastCrawlAttempt)));
res.add(new StatusTable.SummaryInfo("Last Crawl Result",
ColumnDescriptor.TYPE_STRING,
state.getLastCrawlResultMsg()));
}
long lastPollStart = state.getLastPollStart();
res.add(new StatusTable.SummaryInfo("Last Completed Poll",
ColumnDescriptor.TYPE_DATE,
new Long(state.getLastTopLevelPollTime())));
if (lastPollStart > 0) {
res.add(new StatusTable.SummaryInfo("Last Poll",
ColumnDescriptor.TYPE_DATE,
new Long(lastPollStart)));
String pollResult = state.getLastPollResultMsg();
if (!StringUtil.isNullString(pollResult)) {
res.add(new StatusTable.SummaryInfo("Last Poll Result",
ColumnDescriptor.TYPE_STRING,
pollResult));
}
}
PollManager pm = theDaemon.getPollManager();
boolean isCrawling = cmStatus.isRunningNCCrawl(au);
boolean isPolling = pm.isPollRunning(au);
List lst = new ArrayList();
if (isCrawling) {
lst.add(makeCrawlRef("Crawling", au));
}
if (isPolling) {
lst.add(makePollRef("Polling", au));
}
if (!lst.isEmpty()) {
res.add(new StatusTable.SummaryInfo("Current Activity",
ColumnDescriptor.TYPE_STRING,
lst));
}
if (theDaemon.isDetectClockssSubscription()) {
String subStatus =
AuUtil.getAuState(au).getClockssSubscriptionStatusString();
res.add(clockssPos,
new StatusTable.SummaryInfo("Subscribed",
ColumnDescriptor.TYPE_STRING,
subStatus));
}
Object peers = PeerRepair.makeAuRef("Repair candidates",
au.getAuId());
res.add(new StatusTable.SummaryInfo(null,
ColumnDescriptor.TYPE_STRING,
peers));
res.add(new StatusTable.SummaryInfo(null,
ColumnDescriptor.TYPE_STRING,
urlListLink));
res.add(new StatusTable.SummaryInfo(null,
ColumnDescriptor.TYPE_STRING,
doiListLink));
return res;
}
// utility method for making a Reference
public static StatusTable.Reference makeAuRef(Object value,
String key) {
StatusTable.Reference ref =
new StatusTable.Reference(value, AU_STATUS_TABLE_NAME, key);
// ref.setProperty("numrows", Integer.toString(defaultNumRows));
return ref;
}
}
/** list of peers that have said they don't have the AU. Primarily for
* stf */
static class NoAuPeers extends PerAuTable {
private static final List columnDescriptors = ListUtil.list(
new ColumnDescriptor("Peer", "Peer", ColumnDescriptor.TYPE_STRING)
);
NoAuPeers(LockssDaemon theDaemon) {
super(theDaemon);
}
protected void populateTable(StatusTable table, ArchivalUnit au)
throws StatusService.NoSuchTableException {
HistoryRepository historyRepo = theDaemon.getHistoryRepository(au);
table.setTitle("Peers not holding " + au.getName());
DatedPeerIdSet noAuSet = theDaemon.getPollManager().getNoAuPeerSet(au);
synchronized (noAuSet) {
try {
noAuSet.load();
table.setSummaryInfo(getSummaryInfo(au, noAuSet));
table.setColumnDescriptors(columnDescriptors);
table.setRows(getRows(table, au, noAuSet));
} catch (IOException e) {
String msg = "Couldn't load NoAuSet";
logger.warning(msg, e);
throw new StatusService.NoSuchTableException(msg, e);
} finally {
noAuSet.release();
}
}
}
private List getRows(StatusTable table, ArchivalUnit au,
DatedPeerIdSet noAuSet) {
List rows = new ArrayList();
try {
logger.info("noAuSet.size(): " + noAuSet.size());
} catch (IOException e) {
logger.error("noAuSet.size()", e);
}
for (PeerIdentity pid : noAuSet) {
logger.info("pid: " + pid);
Map row = new HashMap();
row.put("Peer", pid.getIdString());
rows.add(row);
}
return rows;
}
private List getSummaryInfo(ArchivalUnit au, DatedPeerIdSet noAuSet) {
List res = new ArrayList();
try {
res.add(new StatusTable.SummaryInfo("Last cleared",
ColumnDescriptor.TYPE_DATE,
noAuSet.getDate()));
} catch (IOException e) {
logger.warning("Couldn't get date", e);
}
return res;
}
}
abstract static class PeersAgreement extends PerAuTable {
protected static final List sortRules =
ListUtil.list(new StatusTable.SortRule("Box", true));
PeersAgreement(LockssDaemon theDaemon) {
super(theDaemon);
}
protected Map makeRow(CacheStats stats) {
Map rowMap = new HashMap();
PeerIdentity peer = stats.peer;
Object id = peer.getIdString();
if (peer.isLocalIdentity()) {
StatusTable.DisplayedValue val =
new StatusTable.DisplayedValue(id);
val.setBold(true);
id = val;
}
rowMap.put("Box", id);
return rowMap;
}
class CacheStats {
PeerIdentity peer;
int totalPolls = 0;
int agreePolls = 0;
Vote lastAgree;
long lastAgreeTime = 0;
Vote lastDisagree;
long lastDisagreeTime = 0;
float highestAgreement = 0.0f;
float lastAgreement = 0.0f;
float highestAgreementHint = -1.0f;
float lastAgreementHint = -1.0f;
CacheStats(PeerIdentity peer) {
this.peer = peer;
}
boolean isLastAgree() {
return (lastAgreeTime != 0 &&
(lastDisagreeTime == 0 || lastAgreeTime >= lastDisagreeTime));
}
boolean isV3Agree() {
PollManager pollmgr = theDaemon.getPollManager();
return highestAgreement >= pollmgr.getMinPercentForRepair();
}
}
}
static class PeerVoteSummary extends PeersAgreement {
private static final List columnDescriptors = ListUtil.list(
new ColumnDescriptor("Box", "Box",
ColumnDescriptor.TYPE_STRING),
new ColumnDescriptor("Last", "Last",
ColumnDescriptor.TYPE_STRING),
new ColumnDescriptor("Polls", "Polls",
ColumnDescriptor.TYPE_INT),
new ColumnDescriptor("Agree", "Agree",
ColumnDescriptor.TYPE_INT),
new ColumnDescriptor("LastAgree", "Last Agree",
ColumnDescriptor.TYPE_DATE),
new ColumnDescriptor("LastDisagree", "Last Disagree",
ColumnDescriptor.TYPE_DATE)
);
PeerVoteSummary(LockssDaemon theDaemon) {
super(theDaemon);
}
protected String getTitle(ArchivalUnit au) {
return "All caches voting on AU: " + au.getName();
}
protected void populateTable(StatusTable table, ArchivalUnit au)
throws StatusService.NoSuchTableException {
NodeManager nodeMan = theDaemon.getNodeManager(au);
table.setTitle(getTitle(au));
int totalPeers = 0;
int totalAgreement = 0;
if (!table.getOptions().get(StatusTable.OPTION_NO_ROWS)) {
table.setColumnDescriptors(columnDescriptors);
table.setDefaultSortRules(sortRules);
Map statsMap = buildCacheStats(au, nodeMan);
List rowL = new ArrayList();
for (Iterator iter = statsMap.entrySet().iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry)iter.next();
PeerIdentity peer = (PeerIdentity)entry.getKey();
CacheStats stats = (CacheStats)entry.getValue();
if (! peer.isLocalIdentity()) {
totalPeers++;
if (stats.isLastAgree()) {
totalAgreement++;
}
}
Map row = makeRow(stats);
rowL.add(row);
}
table.setRows(rowL);
}
table.setSummaryInfo(getSummaryInfo(au, totalPeers, totalAgreement));
}
public Map buildCacheStats(ArchivalUnit au, NodeManager nodeMan) {
Map statsMap = new HashMap();
NodeState node = nodeMan.getNodeState(au.getAuCachedUrlSet());
for (Iterator history_it = node.getPollHistories();
history_it.hasNext(); ) {
PollHistory history = (PollHistory)history_it.next();
long histTime = history.getStartTime();
for (Iterator votes_it = history.getVotes(); votes_it.hasNext(); ) {
Vote vote = (Vote)votes_it.next();
PeerIdentity peer = vote.getVoterIdentity();
CacheStats stats = (CacheStats)statsMap.get(peer);
if (stats == null) {
stats = new CacheStats(peer);
statsMap.put(peer, stats);
}
stats.totalPolls++;
if (vote.isAgreeVote()) {
stats.agreePolls++;
if (stats.lastAgree == null ||
histTime > stats.lastAgreeTime) {
stats.lastAgree = vote;
stats.lastAgreeTime = histTime;
}
} else {
if (stats.lastDisagree == null ||
histTime > stats.lastDisagreeTime) {
stats.lastDisagree = vote;
stats.lastDisagreeTime = histTime;
}
}
}
}
return statsMap;
}
protected Map makeRow(CacheStats stats) {
Map rowMap = super.makeRow(stats);
rowMap.put("Last",
stats.isLastAgree() ? "Agree" : "Disagree");
rowMap.put("Polls", new Long(stats.totalPolls));
rowMap.put("Agree", new Long(stats.agreePolls));
rowMap.put("LastAgree", new Long(stats.lastAgreeTime));
rowMap.put("LastDisagree", new Long(stats.lastDisagreeTime));
return rowMap;
}
protected List getSummaryInfo(ArchivalUnit au,
int totalPeers, int totalAgreement) {
List summaryList = ListUtil.list(
new StatusTable.SummaryInfo("Peers voting on AU",
ColumnDescriptor.TYPE_INT,
new Integer(totalPeers)),
new StatusTable.SummaryInfo("Agreeing peers",
ColumnDescriptor.TYPE_INT,
new Integer(totalAgreement))
);
return summaryList;
}
// utility method for making a Reference
public static StatusTable.Reference makeAuRef(Object value,
String key) {
return new StatusTable.Reference(value, PEERS_VOTE_TABLE_NAME,
key);
}
}
static class PeerRepair extends PeersAgreement {
private static final List columnDescriptors = ListUtil.list(
new ColumnDescriptor("Box", "Box",
ColumnDescriptor.TYPE_STRING),
new ColumnDescriptor("Last", "Consensus",
ColumnDescriptor.TYPE_STRING),
new ColumnDescriptor("HighestPercentAgreement", "Highest Agreement",
ColumnDescriptor.TYPE_PERCENT),
new ColumnDescriptor("LastPercentAgreement", "Last Agreement",
ColumnDescriptor.TYPE_PERCENT),
new ColumnDescriptor("HighestPercentAgreementHint",
"Highest Agreement Hint",
ColumnDescriptor.TYPE_PERCENT),
new ColumnDescriptor("LastPercentAgreementHint", "Last Agreement Hint",
ColumnDescriptor.TYPE_PERCENT),
new ColumnDescriptor("LastAgree",
"Last Consensus",
ColumnDescriptor.TYPE_DATE)
);
PeerRepair(LockssDaemon theDaemon) {
super(theDaemon);
}
protected String getTitle(ArchivalUnit au) {
return "Repair candidates for AU: " + au.getName();
}
private static final String FOOT_TITLE =
"Peers whose Highest Agreement is above a threshold have proven\n" +
"in the past that their content for this AU is the same, and will\n" +
"be served repairs on request. Peers whose Highest Agreement Hint\n" +
"is above the threshold have reported that this peer has proven to\n" +
"them that the content for the AU is the same, and are likely to\n" +
"supply repairs on request.";
protected void populateTable(StatusTable table, ArchivalUnit au)
throws StatusService.NoSuchTableException {
IdentityManager idMgr = theDaemon.getIdentityManager();
table.setTitle(getTitle(au));
table.setTitleFootnote(FOOT_TITLE);
int totalPeers = 0;
if (!table.getOptions().get(StatusTable.OPTION_NO_ROWS)) {
table.setColumnDescriptors(columnDescriptors);
table.setDefaultSortRules(sortRules);
Map statsMap = buildCacheStats(au, idMgr);
List rowL = new ArrayList();
for (Iterator iter = statsMap.entrySet().iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry)iter.next();
PeerIdentity peer = (PeerIdentity)entry.getKey();
CacheStats stats = (CacheStats)entry.getValue();
if (! peer.isLocalIdentity()) {
totalPeers++;
}
Map row = makeRow(stats);
rowL.add(row);
}
table.setRows(rowL);
}
table.setSummaryInfo(getSummaryInfo(au, totalPeers));
}
public Map buildCacheStats(ArchivalUnit au, IdentityManager idMgr) {
Map statsMap = new HashMap();
for (Iterator iter = idMgr.getIdentityAgreements(au).iterator();
iter.hasNext(); ) {
IdentityManager.IdentityAgreement ida =
(IdentityManager.IdentityAgreement)iter.next();
try {
PeerIdentity pid = idMgr.stringToPeerIdentity(ida.getId());
if (ida.getHighestPercentAgreement() >= 0.0 ||
ida.getHighestPercentAgreementHint() >= 0.0) {
CacheStats stats = new CacheStats(pid);
statsMap.put(pid, stats);
stats.lastAgreeTime = ida.getLastAgree();
stats.lastDisagreeTime = ida.getLastDisagree();
stats.highestAgreement = ida.getHighestPercentAgreement();
stats.lastAgreement = ida.getPercentAgreement();
stats.highestAgreementHint = ida.getHighestPercentAgreementHint();
stats.lastAgreementHint = ida.getPercentAgreementHint();
}
} catch (IdentityManager.MalformedIdentityKeyException e) {
logger.warning("Malformed id key in IdentityAgreement", e);
continue;
}
}
return statsMap;
}
protected Map makeRow(CacheStats stats) {
Map rowMap = super.makeRow(stats);
rowMap.put("Last", stats.isLastAgree() ? "Yes" : "No");
if (stats.highestAgreement >= 0.0f) {
rowMap.put("LastPercentAgreement",
new Float(stats.lastAgreement));
rowMap.put("HighestPercentAgreement",
new Float(stats.highestAgreement));
}
if (stats.highestAgreementHint >= 0.0f) {
rowMap.put("LastPercentAgreementHint",
new Float(stats.lastAgreementHint));
rowMap.put("HighestPercentAgreementHint",
new Float(stats.highestAgreementHint));
}
rowMap.put("LastAgree", new Long(stats.lastAgreeTime));
rowMap.put("LastDisagree", new Long(stats.lastDisagreeTime));
return rowMap;
}
protected List getSummaryInfo(ArchivalUnit au,
int totalPeers) {
List summaryList = ListUtil.list(
new StatusTable.SummaryInfo("Peers holding AU",
ColumnDescriptor.TYPE_INT,
new Integer(totalPeers)));
return summaryList;
}
// utility method for making a Reference
public static StatusTable.Reference makeAuRef(Object value,
String key) {
return new StatusTable.Reference(value, PEERS_REPAIR_TABLE_NAME,
key);
}
}
static class Overview implements OverviewAccessor {
private LockssDaemon daemon;
private PluginManager pluginMgr;
public Overview(LockssDaemon daemon) {
this.daemon = daemon;
this.pluginMgr = daemon.getPluginManager();
}
public Object getOverview(String tableName, BitSet options) {
boolean isDebug = options.get(StatusTable.OPTION_DEBUG_USER);
List res = new ArrayList();
int total = 0;
int internal = 0;
int neverCrawled = 0;
int needsRecrawl = 0;
for (ArchivalUnit au : pluginMgr.getAllAus()) {
if (pluginMgr.isInternalAu(au)) {
internal++;
if (!isDebug) {
continue;
}
}
total++;
AuState aus = AuUtil.getAuState(au);
if (AuUtil.isPubDown(au)) {
} else {
if (aus.getLastCrawlTime() <= 0) {
neverCrawled++;
} else if (au.shouldCrawlForNewContent(aus)) {
needsRecrawl++;
}
}
}
StringBuilder sb = new StringBuilder();
sb.append(StringUtil.numberOfUnits(total, "Archival Unit",
"Archival Units"));
if (internal != 0 && isDebug) {
sb.append(" (");
sb.append(internal);
sb.append(" internal)");
}
if (neverCrawled != 0) {
sb.append(", ");
sb.append(neverCrawled);
sb.append(" not collected");
}
if (includeNeedsRecrawl && needsRecrawl != 0) {
sb.append(", ");
sb.append(StringUtil.numberOfUnits(needsRecrawl,
" needs recrawl", " need recrawl"));
}
return new StatusTable.Reference(sb.toString(),
SERVICE_STATUS_TABLE_NAME);
}
}
static final double STATUS_ORDER_AGREE_BASE = 100.0;
static final double STATUS_ORDER_WAIT_POLL = 200.0;
static final double STATUS_ORDER_CRAWLING = 300.0;
static final double STATUS_ORDER_WAIT_CRAWL = 400.0;
static OrderedObject agreeStatus(double agreement) {
return new OrderedObject(doubleToPercent(agreement) + "% Agreement",
STATUS_ORDER_AGREE_BASE - agreement);
}
public static StatusTable.Reference makeCrawlRef(Object value,
ArchivalUnit au) {
return new StatusTable.Reference(value,
CrawlManagerImpl.CRAWL_STATUS_TABLE_NAME,
au.getAuId());
}
public static StatusTable.Reference makePollRef(Object value,
ArchivalUnit au) {
return new StatusTable.Reference(value,
V3PollStatus.POLLER_STATUS_TABLE_NAME,
au.getAuId());
}
}
| src/org/lockss/state/ArchivalUnitStatus.java | /*
* $Id: ArchivalUnitStatus.java,v 1.79 2009-05-22 19:14:55 dshr Exp $
*/
/*
Copyright (c) 2000-2008 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.
*/
package org.lockss.state;
import java.io.*;
import java.util.*;
import java.text.*;
import java.net.MalformedURLException;
import org.lockss.config.Configuration;
import org.lockss.daemon.*;
import org.lockss.daemon.status.*;
import org.lockss.plugin.*;
import org.lockss.util.*;
import org.lockss.app.*;
import org.lockss.crawler.*;
import org.lockss.poller.*;
import org.lockss.poller.v3.*;
import org.lockss.protocol.*;
import org.lockss.repository.*;
import org.lockss.servlet.AdminServletManager;
/**
* Collect and report the status of the ArchivalUnits
*/
public class ArchivalUnitStatus
extends BaseLockssDaemonManager implements ConfigurableManager {
public static final String PREFIX = Configuration.PREFIX + "auStatus.";
/**
* The default maximum number of nodes to display in a single page of the ui.
*/
public static final String PARAM_MAX_NODES_TO_DISPLAY =
PREFIX + "nodesPerPage";
static final int DEFAULT_MAX_NODES_TO_DISPLAY = 100;
/**
* Node URLs are links to cached content page if true
*/
public static final String PARAM_CONTENT_IS_LINK =
PREFIX + "contentUrlIsLink";
static final boolean DEFAULT_CONTENT_IS_LINK = true;
/**
* Include number of AUs needing recrawl in overview if true
*/
public static final String PARAM_INCLUDE_NEEDS_RECRAWL =
PREFIX + "includeNeedsRecrawl";
static final boolean DEFAULT_INCLUDE_NEEDS_RECRAWL = true;
public static final String SERVICE_STATUS_TABLE_NAME =
"ArchivalUnitStatusTable";
public static final String AUIDS_TABLE_NAME = "AuIds";
public static final String AU_STATUS_TABLE_NAME = "ArchivalUnitTable";
public static final String NO_AU_PEERS_TABLE_NAME = "NoAuPeers";
public static final String PEERS_VOTE_TABLE_NAME = "PeerVoteSummary";
public static final String PEERS_REPAIR_TABLE_NAME = "PeerRepair";
static final OrderedObject DASH = new OrderedObject("-", new Long(-1));
private static Logger logger = Logger.getLogger("AuStatus");
private static int defaultNumRows = DEFAULT_MAX_NODES_TO_DISPLAY;
private static boolean isContentIsLink = DEFAULT_CONTENT_IS_LINK;
private static boolean includeNeedsRecrawl = DEFAULT_INCLUDE_NEEDS_RECRAWL;
private static final DecimalFormat agreementFormat =
new DecimalFormat("0.00");
/* DecimalFormat automatically applies half-even rounding to
* values being formatted under Java < 1.6. This is a workaround. */
private static String doubleToPercent(double d) {
int i = (int)(d * 10000);
double pc = i / 100.0;
return agreementFormat.format(pc);
}
public void startService() {
super.startService();
LockssDaemon theDaemon = getDaemon();
StatusService statusServ = theDaemon.getStatusService();
statusServ.registerStatusAccessor(SERVICE_STATUS_TABLE_NAME,
new AuSummary(theDaemon));
statusServ.registerOverviewAccessor(SERVICE_STATUS_TABLE_NAME,
new Overview(theDaemon));
statusServ.registerStatusAccessor(AUIDS_TABLE_NAME,
new AuIds(theDaemon));
statusServ.registerStatusAccessor(AU_STATUS_TABLE_NAME,
new AuStatus(theDaemon));
statusServ.registerStatusAccessor(NO_AU_PEERS_TABLE_NAME,
new NoAuPeers(theDaemon));
statusServ.registerStatusAccessor(PEERS_VOTE_TABLE_NAME,
new PeerVoteSummary(theDaemon));
statusServ.registerStatusAccessor(PEERS_REPAIR_TABLE_NAME,
new PeerRepair(theDaemon));
logger.debug2("Status accessors registered.");
}
public void stopService() {
// unregister our status accessors
LockssDaemon theDaemon = getDaemon();
StatusService statusServ = theDaemon.getStatusService();
statusServ.unregisterStatusAccessor(SERVICE_STATUS_TABLE_NAME);
statusServ.unregisterStatusAccessor(NO_AU_PEERS_TABLE_NAME);
statusServ.unregisterStatusAccessor(AU_STATUS_TABLE_NAME);
statusServ.unregisterStatusAccessor(PEERS_VOTE_TABLE_NAME);
statusServ.unregisterStatusAccessor(PEERS_REPAIR_TABLE_NAME);
logger.debug2("Status accessors unregistered.");
super.stopService();
}
public void setConfig(Configuration config, Configuration oldConfig,
Configuration.Differences changedKeys) {
defaultNumRows = config.getInt(PARAM_MAX_NODES_TO_DISPLAY,
DEFAULT_MAX_NODES_TO_DISPLAY);
isContentIsLink = config.getBoolean(PARAM_CONTENT_IS_LINK,
DEFAULT_CONTENT_IS_LINK);
includeNeedsRecrawl = config.getBoolean(PARAM_INCLUDE_NEEDS_RECRAWL,
DEFAULT_INCLUDE_NEEDS_RECRAWL);
}
static CrawlManagerStatus getCMStatus(LockssDaemon daemon) {
CrawlManager crawlMgr = daemon.getCrawlManager();
CrawlManager.StatusSource source = crawlMgr.getStatusSource();
return source.getStatus();
}
static class AuSummary implements StatusAccessor {
static final String TABLE_TITLE = "Archival Units";
static final String FOOT_STATUS = "Flags may follow status: C means the AU is complete, D means that the AU is no longer available from the publisher";
static final String FOOT_SIZE = "If blank, size has changed and is being recalculated. Check again later.";
private static final List columnDescriptors = ListUtil.list(
new ColumnDescriptor("AuName", "Volume", ColumnDescriptor.TYPE_STRING),
// new ColumnDescriptor("AuNodeCount", "Nodes", ColumnDescriptor.TYPE_INT),
new ColumnDescriptor("AuSize", "Content Size",
ColumnDescriptor.TYPE_INT, FOOT_SIZE),
new ColumnDescriptor("DiskUsage", "Disk Usage (MB)",
ColumnDescriptor.TYPE_FLOAT, FOOT_SIZE),
new ColumnDescriptor("Peers", "Peers", ColumnDescriptor.TYPE_INT),
new ColumnDescriptor("AuPolls", "Recent Polls",
ColumnDescriptor.TYPE_INT),
new ColumnDescriptor("Damaged", "Status",
ColumnDescriptor.TYPE_STRING,
FOOT_STATUS),
new ColumnDescriptor("AuLastPoll", "Last Poll",
ColumnDescriptor.TYPE_DATE),
new ColumnDescriptor("AuLastCrawlAttempt", "Last Crawl Start",
ColumnDescriptor.TYPE_DATE),
new ColumnDescriptor("AuLastCrawlResultMsg", "Last Crawl Result",
ColumnDescriptor.TYPE_STRING),
new ColumnDescriptor("AuLastCrawl", "Last Successful Crawl",
ColumnDescriptor.TYPE_DATE)
);
private static final List sortRules =
ListUtil.list(new
StatusTable.SortRule("AuName",
CatalogueOrderComparator.SINGLETON));
private LockssDaemon theDaemon;
private RepositoryManager repoMgr;
private CrawlManagerStatus cmStatus;
AuSummary(LockssDaemon theDaemon) {
this.theDaemon = theDaemon;
repoMgr = theDaemon.getRepositoryManager();
cmStatus = getCMStatus(theDaemon);
}
public String getDisplayName() {
return TABLE_TITLE;
}
public void populateTable(StatusTable table)
throws StatusService.NoSuchTableException {
List cols = columnDescriptors;
if (theDaemon.isDetectClockssSubscription()) {
cols = new ArrayList(cols);
cols.remove(cols.size() - 1);
cols.add(new ColumnDescriptor("Subscribed", "Subscribed",
ColumnDescriptor.TYPE_STRING));
}
table.setColumnDescriptors(cols);
table.setDefaultSortRules(sortRules);
Stats stats = new Stats();
table.setRows(getRows(table, stats));
table.setSummaryInfo(getSummaryInfo(stats));
}
public boolean requiresKey() {
return false;
}
class Stats {
int aus = 0;
}
private List getRows(StatusTable table, Stats stats) {
PluginManager pluginMgr = theDaemon.getPluginManager();
boolean includeInternalAus =
table.getOptions().get(StatusTable.OPTION_DEBUG_USER);
List rowL = new ArrayList();
for (Iterator iter = pluginMgr.getAllAus().iterator();
iter.hasNext(); ) {
ArchivalUnit au = (ArchivalUnit)iter.next();
if (!includeInternalAus && pluginMgr.isInternalAu(au)) {
continue;
}
try {
NodeManager nodeMan = theDaemon.getNodeManager(au);
rowL.add(makeRow(au, nodeMan));
stats.aus++;
} catch (Exception e) {
logger.warning("Unexpected expection building row", e);
}
}
return rowL;
}
private Map makeRow(ArchivalUnit au, NodeManager nodeMan) {
AuState auState = nodeMan.getAuState();
HashMap rowMap = new HashMap();
PollManager.V3PollStatusAccessor v3status =
theDaemon.getPollManager().getV3Status();
// If this is a v3 AU, we cannot access some of the poll
// status through the nodestate. Eventually, this will be totally
// refactored.
boolean isV3 = AuUtil.getProtocolVersion(au) == Poll.V3_PROTOCOL;
//"AuID"
rowMap.put("AuName", AuStatus.makeAuRef(au.getName(), au.getAuId()));
// rowMap.put("AuNodeCount", new Integer(-1));
long contentSize = AuUtil.getAuContentSize(au, false);
if (contentSize != -1) {
rowMap.put("AuSize", new Long(contentSize));
}
long du = AuUtil.getAuDiskUsage(au, false);
if (du != -1) {
rowMap.put("DiskUsage", new Double(((double)du) / (1024*1024)));
}
long lastCrawl = auState.getLastCrawlTime();
long lastAttempt = auState.getLastCrawlAttempt();
int lastResultCode = auState.getLastCrawlResult();
String lastResult = auState.getLastCrawlResultMsg();
rowMap.put("AuLastCrawl", new Long(lastCrawl));
// AuState files that show a successful crawl but no lastAttempt just
// have uninitialized lastXxx fields. Display time and status of
// last successful instead
if (lastCrawl > 0 && lastAttempt <= 0) {
lastAttempt = lastCrawl;
lastResultCode = Crawler.STATUS_SUCCESSFUL;
lastResult = "Successful";
}
rowMap.put("AuLastCrawlAttempt", new Long(lastAttempt));
String lastCrawlStatus =
lastCrawlStatus(au, lastCrawl, lastResultCode, lastResult);
if (lastCrawlStatus != null) {
rowMap.put("AuLastCrawlResultMsg", lastCrawlStatus);
}
rowMap.put("Peers", PeerRepair.makeAuRef("peers", au.getAuId()));
rowMap.put("AuLastPoll", new Long(auState.getLastTopLevelPollTime()));
Object stat;
if (isV3) {
int numPolls = v3status.getNumPolls(au.getAuId());
rowMap.put("AuPolls", pollsRef(new Integer(numPolls), au));
// Percent damaged. It's scary to see '0% Agreement' if there's no
// history, so we just show a friendlier message.
//
if (auState.getHighestV3Agreement() < 0 ||
auState.getLastTopLevelPollTime() <= 0) {
if (cmStatus.isRunningNCCrawl(au)) {
stat = new OrderedObject("Crawling", STATUS_ORDER_CRAWLING);
} else {
if (auState.lastCrawlTime > 0 || AuUtil.isPubDown(au)) {
stat = new OrderedObject("Waiting for Poll",
STATUS_ORDER_WAIT_POLL);
} else {
stat = new OrderedObject("Waiting for Crawl",
STATUS_ORDER_WAIT_CRAWL);
}
}
} else {
stat = agreeStatus(auState.getHighestV3Agreement());
}
} else {
rowMap.put("AuPolls",
theDaemon.getStatusService().
getReference(PollerStatus.MANAGER_STATUS_TABLE_NAME,
au));
CachedUrlSet auCus = au.getAuCachedUrlSet();
NodeState topNodeState = nodeMan.getNodeState(auCus);
stat = topNodeState.hasDamage()
? DAMAGE_STATE_DAMAGED : DAMAGE_STATE_OK;
}
boolean isPubDown = AuUtil.isPubDown(au);
boolean isClosed = AuUtil.isClosed(au);
if (isPubDown || isClosed) {
List val = ListUtil.list(stat, " (");
if (isClosed) {
val.add("C");
}
if (isPubDown) {
val.add("D");
}
val.add(")");
stat = val;
}
rowMap.put("Damaged", stat);
if (theDaemon.isDetectClockssSubscription()) {
rowMap.put("Subscribed",
AuUtil.getAuState(au).getClockssSubscriptionStatusString());
}
return rowMap;
}
String lastCrawlStatus(ArchivalUnit au, long lastCrawl,
int lastResultCode, String lastResult) {
if (AuUtil.isPubDown(au)) {
if (lastCrawl > 0) {
return "No longer crawled";
} else {
return "Never crawled";
}
} else {
if (lastResultCode > 0) {
return lastResult;
}
}
return null;
}
Object pollsRef(Object val, ArchivalUnit au) {
return new StatusTable.Reference(val,
V3PollStatus.POLLER_STATUS_TABLE_NAME,
au.getAuId());
}
private List getSummaryInfo(Stats stats) {
List res = new ArrayList();
String numaus = StringUtil.numberOfUnits(stats.aus, "Archival Unit",
"Archival Units");
res.add(new StatusTable.SummaryInfo(null,
ColumnDescriptor.TYPE_STRING,
numaus));
int n = repoMgr.sizeCalcQueueLen();
if (n != 0) {
res.add(new StatusTable.SummaryInfo(null,
ColumnDescriptor.TYPE_STRING,
n + " awaiting recalc"));
}
return res;
}
}
static class AuIds implements StatusAccessor {
static final String TABLE_TITLE = "AU Ids";
private static final List columnDescriptors = ListUtil.list(
new ColumnDescriptor("AuName", "Volume", ColumnDescriptor.TYPE_STRING),
new ColumnDescriptor("AuId", "AU Id", ColumnDescriptor.TYPE_STRING)
);
private static final List sortRules =
ListUtil.list(new
StatusTable.SortRule("AuName",
CatalogueOrderComparator.SINGLETON));
private LockssDaemon theDaemon;
AuIds(LockssDaemon theDaemon) {
this.theDaemon = theDaemon;
}
public String getDisplayName() {
return TABLE_TITLE;
}
public void populateTable(StatusTable table)
throws StatusService.NoSuchTableException {
table.setColumnDescriptors(columnDescriptors);
table.setDefaultSortRules(sortRules);
Stats stats = new Stats();
table.setRows(getRows(table, stats));
table.setSummaryInfo(getSummaryInfo(stats));
}
public boolean requiresKey() {
return false;
}
class Stats {
int aus = 0;
}
private List getRows(StatusTable table, Stats stats) {
PluginManager pluginMgr = theDaemon.getPluginManager();
boolean includeInternalAus =
table.getOptions().get(StatusTable.OPTION_DEBUG_USER);
List rowL = new ArrayList();
for (Iterator iter = pluginMgr.getAllAus().iterator();
iter.hasNext(); ) {
ArchivalUnit au = (ArchivalUnit)iter.next();
if (!includeInternalAus && pluginMgr.isInternalAu(au)) {
continue;
}
try {
rowL.add(makeRow(au));
stats.aus++;
} catch (Exception e) {
logger.warning("Unexpected expection building row", e);
}
}
return rowL;
}
private Map makeRow(ArchivalUnit au) {
HashMap rowMap = new HashMap();
rowMap.put("AuId", au.getAuId());
rowMap.put("AuName", AuStatus.makeAuRef(au.getName(), au.getAuId()));
return rowMap;
}
private List getSummaryInfo(Stats stats) {
String numaus = StringUtil.numberOfUnits(stats.aus, "Archival Unit",
"Archival Units");
return
ListUtil.list(new StatusTable.SummaryInfo(null,
ColumnDescriptor.TYPE_STRING,
numaus));
}
}
static final StatusTable.DisplayedValue DAMAGE_STATE_OK =
new StatusTable.DisplayedValue("Ok");
static final StatusTable.DisplayedValue DAMAGE_STATE_DAMAGED =
new StatusTable.DisplayedValue("Repairing");
// static {
// DAMAGE_STATE_OK.setColor("green");
// DAMAGE_STATE_DAMAGED.setColor("yellow");
// }
abstract static class PerAuTable implements StatusAccessor {
protected LockssDaemon theDaemon;
protected CrawlManagerStatus cmStatus;
PerAuTable(LockssDaemon theDaemon) {
this.theDaemon = theDaemon;
cmStatus = getCMStatus(theDaemon);
}
public boolean requiresKey() {
return true;
}
public String getDisplayName() {
throw new UnsupportedOperationException("Au table has no generic title");
}
public void populateTable(StatusTable table)
throws StatusService.NoSuchTableException {
String key = table.getKey();
try {
ArchivalUnit au = theDaemon.getPluginManager().getAuFromId(key);
if (au == null) {
throw new StatusService.NoSuchTableException("Unknown auid: " + key);
}
populateTable(table, au);
} catch (StatusService.NoSuchTableException e) {
throw e;
} catch (Exception e) {
logger.warning("Error building table", e);
throw new StatusService.
NoSuchTableException("Error building table for auid: " + key);
}
}
protected abstract void populateTable(StatusTable table, ArchivalUnit au)
throws StatusService.NoSuchTableException;
}
static class AuStatus extends PerAuTable {
private static final List columnDescriptors = ListUtil.list(
new ColumnDescriptor("NodeName", "Node Url",
ColumnDescriptor.TYPE_STRING),
// new ColumnDescriptor("NodeHasContent", "Content",
// ColumnDescriptor.TYPE_STRING),
new ColumnDescriptor("NodeVersion", "Version",
ColumnDescriptor.TYPE_INT),
new ColumnDescriptor("NodeContentSize", "Size",
ColumnDescriptor.TYPE_INT),
new ColumnDescriptor("NodeTreeSize", "Tree Size",
ColumnDescriptor.TYPE_INT),
new ColumnDescriptor("NodeChildCount", "Children",
ColumnDescriptor.TYPE_INT),
new ColumnDescriptor("NodeStatus", "Status",
ColumnDescriptor.TYPE_STRING)
);
private static final List sortRules =
ListUtil.list(new StatusTable.SortRule("sort", true));
AuStatus(LockssDaemon theDaemon) {
super(theDaemon);
}
protected void populateTable(StatusTable table, ArchivalUnit au)
throws StatusService.NoSuchTableException {
LockssRepository repo = theDaemon.getLockssRepository(au);
NodeManager nodeMan = theDaemon.getNodeManager(au);
table.setTitle(getTitle(au.getName()));
CachedUrlSet auCus = au.getAuCachedUrlSet();
NodeState topNode = nodeMan.getNodeState(auCus);
table.setSummaryInfo(getSummaryInfo(au, nodeMan.getAuState(), topNode));
if (!table.getOptions().get(StatusTable.OPTION_NO_ROWS)) {
table.setColumnDescriptors(columnDescriptors);
table.setDefaultSortRules(sortRules);
table.setRows(getRows(table, au, repo, nodeMan));
}
}
int getIntProp(StatusTable table, String name) {
Properties props = table.getProperties();
if (props == null) return -1;
String s = props.getProperty(name);
if (StringUtil.isNullString(s)) return -1;
try {
return Integer.parseInt(s);
} catch (Exception e) {
return -1;
}
}
private List getRows(StatusTable table, ArchivalUnit au,
LockssRepository repo, NodeManager nodeMan) {
int startRow = Math.max(0, getIntProp(table, "skiprows"));
int numRows = getIntProp(table, "numrows");
if (numRows <= 0) {
numRows = defaultNumRows;
}
CrawlSpec spec = au.getCrawlSpec();
List startUrls;
if (spec instanceof SpiderCrawlSpec) {
startUrls = ((SpiderCrawlSpec)spec).getStartingUrls();
} else {
startUrls = Collections.EMPTY_LIST;
}
List rowL = new ArrayList();
Iterator cusIter = au.getAuCachedUrlSet().contentHashIterator();
int endRow1 = startRow + numRows; // end row + 1
if (startRow > 0) {
// add 'previous'
int start = startRow - defaultNumRows;
if (start < 0) {
start = 0;
}
rowL.add(makeOtherRowsLink(false, start, au.getAuId()));
}
for (int curRow = 0; (curRow < endRow1) && cusIter.hasNext(); curRow++) {
CachedUrlSetNode cusn = (CachedUrlSetNode)cusIter.next();
if (curRow < startRow) {
continue;
}
CachedUrlSet cus;
if (cusn.getType() == CachedUrlSetNode.TYPE_CACHED_URL_SET) {
cus = (CachedUrlSet)cusn;
} else {
CachedUrlSetSpec cuss = new RangeCachedUrlSetSpec(cusn.getUrl());
cus = au.makeCachedUrlSet(cuss);
}
String url = cus.getUrl();
try {
Map row = makeRow(au, repo.getNode(url),
nodeMan.getNodeState(cus),
startUrls.contains(url));
row.put("sort", new Integer(curRow));
rowL.add(row);
} catch (MalformedURLException ignore) { }
}
if (cusIter.hasNext()) {
// add 'next'
rowL.add(makeOtherRowsLink(true, endRow1, au.getAuId()));
}
return rowL;
}
private Map makeRow(ArchivalUnit au, RepositoryNode node,
NodeState state, boolean isStartUrl) {
String url = node.getNodeUrl();
boolean hasContent = node.hasContent();
Object val = url;
if (isStartUrl) {
val = new StatusTable.DisplayedValue(val).setBold(true);
}
HashMap rowMap = new HashMap();
if (hasContent && isContentIsLink) {
Properties args = new Properties();
args.setProperty("auid", au.getAuId());
args.setProperty("url", url);
val =
new StatusTable.SrvLink(val,
AdminServletManager.SERVLET_DISPLAY_CONTENT,
args);
} else {
val = url;
}
rowMap.put("NodeName", val);
String status = null;
if (node.isDeleted()) {
status = "Deleted";
} else if (node.isContentInactive()) {
status = "Inactive";
} else if (state.hasDamage()) {
status = "Damaged";
} else {
// status = "Active";
}
if (status != null) {
rowMap.put("NodeStatus", status);
}
Object versionObj = DASH;
Object sizeObj = DASH;
if (hasContent) {
versionObj = new OrderedObject(new Long(node.getCurrentVersion()));
sizeObj = new OrderedObject(new Long(node.getContentSize()));
}
rowMap.put("NodeHasContent", (hasContent ? "yes" : "no"));
rowMap.put("NodeVersion", versionObj);
rowMap.put("NodeContentSize", sizeObj);
if (!node.isLeaf()) {
rowMap.put("NodeChildCount",
new OrderedObject(new Long(node.getChildCount())));
long treeSize = node.getTreeContentSize(null, false);
if (treeSize != -1) {
rowMap.put("NodeTreeSize", new OrderedObject(new Long(treeSize)));
}
} else {
rowMap.put("NodeChildCount", DASH);
rowMap.put("NodeTreeSize", DASH);
}
return rowMap;
}
private Map makeOtherRowsLink(boolean isNext, int startRow, String auKey) {
HashMap rowMap = new HashMap();
String label = (isNext ? "Next" : "Previous") + " (" +
(startRow + 1) + "-" + (startRow + defaultNumRows) + ")";
StatusTable.Reference link =
new StatusTable.Reference(label, AU_STATUS_TABLE_NAME, auKey);
link.setProperty("skiprows", Integer.toString(startRow));
link.setProperty("numrows", Integer.toString(defaultNumRows));
rowMap.put("NodeName", link);
rowMap.put("sort", new Integer(isNext ? Integer.MAX_VALUE : -1));
return rowMap;
}
private String getTitle(String key) {
return "Status of AU: " + key;
}
private List getSummaryInfo(ArchivalUnit au, AuState state,
NodeState topNode) {
int clockssPos = 1;
// Make the status string.
Object stat = null;
Object recentPollStat = null;
if (AuUtil.getProtocolVersion(au) == Poll.V3_PROTOCOL) {
if (state.getV3Agreement() < 0) {
if (state.lastCrawlTime < 0) {
stat = "Waiting for Crawl";
} else {
stat = "Waiting for Poll";
}
} else {
stat = agreeStatus(state.getHighestV3Agreement());
if (state.getHighestV3Agreement() != state.getV3Agreement()) {
recentPollStat = agreeStatus(state.getV3Agreement());
}
}
} else {
stat = topNode.hasDamage() ? DAMAGE_STATE_DAMAGED : DAMAGE_STATE_OK;
}
long contentSize = AuUtil.getAuContentSize(au, false);
long du = AuUtil.getAuDiskUsage(au, false);
StatusTable.SrvLink urlListLink =
new StatusTable.SrvLink("URL list",
AdminServletManager.SERVLET_LIST_OBJECTS,
PropUtil.fromArgs("type", "urls",
"auid", au.getAuId()));
StatusTable.SrvLink doiListLink =
new StatusTable.SrvLink("DOI list",
AdminServletManager.SERVLET_LIST_OBJECTS,
PropUtil.fromArgs("type", "dois",
"auid", au.getAuId()));
List res = new ArrayList();
res.add(new StatusTable.SummaryInfo("Volume",
ColumnDescriptor.TYPE_STRING,
au.getName()));
AuState.AccessType atype = state.getAccessType();
if (atype != null) {
res.add(new StatusTable.SummaryInfo("Access Type",
ColumnDescriptor.TYPE_STRING,
atype.toString()));
}
if (contentSize != -1) {
res.add(new StatusTable.SummaryInfo("Content Size",
ColumnDescriptor.TYPE_INT,
new Long(contentSize)));
} else {
res.add(new StatusTable.SummaryInfo("Content Size",
ColumnDescriptor.TYPE_STRING,
"Awaiting recalc"));
}
if (du != -1) {
res.add(new StatusTable.SummaryInfo("Disk Usage (MB)",
ColumnDescriptor.TYPE_FLOAT,
new Float(du / (float)(1024 * 1024))));
} else {
res.add(new StatusTable.SummaryInfo("Disk Usage",
ColumnDescriptor.TYPE_STRING,
"Awaiting recalc"));
}
AuNodeImpl auNode = AuUtil.getAuRepoNode(au);
String spec = LockssRepositoryImpl.getRepositorySpec(au);
String repo = LockssRepositoryImpl.mapAuToFileLocation(LockssRepositoryImpl.getLocalRepositoryPath(spec), au);
res.add(new StatusTable.SummaryInfo("Repository",
ColumnDescriptor.TYPE_STRING,
repo));
res.add(new StatusTable.SummaryInfo("Status",
ColumnDescriptor.TYPE_STRING,
stat));
if (recentPollStat != null) {
res.add(new StatusTable.SummaryInfo("Most recent poll",
ColumnDescriptor.TYPE_STRING,
recentPollStat));
}
String plat = au.getPlugin().getPublishingPlatform();
if (plat != null) {
res.add(new StatusTable.SummaryInfo("Publishing Platform",
ColumnDescriptor.TYPE_STRING,
plat));
}
res.add(new StatusTable.SummaryInfo("Available From Publisher",
ColumnDescriptor.TYPE_STRING,
(AuUtil.isPubDown(au)
? "No" : "Yes")));
// res.add(new StatusTable.SummaryInfo("Volume Complete",
// ColumnDescriptor.TYPE_STRING,
// (AuUtil.isClosed(au)
// ? "Yes" : "No")));
// res.add(new StatusTable.SummaryInfo("Polling Protocol Version",
// ColumnDescriptor.TYPE_INT,
// new Integer(AuUtil.getProtocolVersion(au))));
res.add(new StatusTable.SummaryInfo("Created",
ColumnDescriptor.TYPE_DATE,
new Long(state.getAuCreationTime())));
long lastCrawlAttempt = state.getLastCrawlAttempt();
res.add(new StatusTable.SummaryInfo("Last Completed Crawl",
ColumnDescriptor.TYPE_DATE,
new Long(state.getLastCrawlTime())));
if (lastCrawlAttempt > 0) {
res.add(new StatusTable.SummaryInfo("Last Crawl",
ColumnDescriptor.TYPE_DATE,
new Long(lastCrawlAttempt)));
res.add(new StatusTable.SummaryInfo("Last Crawl Result",
ColumnDescriptor.TYPE_STRING,
state.getLastCrawlResultMsg()));
}
long lastPollStart = state.getLastPollStart();
res.add(new StatusTable.SummaryInfo("Last Completed Poll",
ColumnDescriptor.TYPE_DATE,
new Long(state.getLastTopLevelPollTime())));
if (lastPollStart > 0) {
res.add(new StatusTable.SummaryInfo("Last Poll",
ColumnDescriptor.TYPE_DATE,
new Long(lastPollStart)));
String pollResult = state.getLastPollResultMsg();
if (!StringUtil.isNullString(pollResult)) {
res.add(new StatusTable.SummaryInfo("Last Poll Result",
ColumnDescriptor.TYPE_STRING,
pollResult));
}
}
PollManager pm = theDaemon.getPollManager();
boolean isCrawling = cmStatus.isRunningNCCrawl(au);
boolean isPolling = pm.isPollRunning(au);
List lst = new ArrayList();
if (isCrawling) {
lst.add(makeCrawlRef("Crawling", au));
}
if (isPolling) {
lst.add(makePollRef("Polling", au));
}
if (!lst.isEmpty()) {
res.add(new StatusTable.SummaryInfo("Current Activity",
ColumnDescriptor.TYPE_STRING,
lst));
}
if (theDaemon.isDetectClockssSubscription()) {
String subStatus =
AuUtil.getAuState(au).getClockssSubscriptionStatusString();
res.add(clockssPos,
new StatusTable.SummaryInfo("Subscribed",
ColumnDescriptor.TYPE_STRING,
subStatus));
}
Object peers = PeerRepair.makeAuRef("Repair candidates",
au.getAuId());
res.add(new StatusTable.SummaryInfo(null,
ColumnDescriptor.TYPE_STRING,
peers));
res.add(new StatusTable.SummaryInfo(null,
ColumnDescriptor.TYPE_STRING,
urlListLink));
res.add(new StatusTable.SummaryInfo(null,
ColumnDescriptor.TYPE_STRING,
doiListLink));
return res;
}
// utility method for making a Reference
public static StatusTable.Reference makeAuRef(Object value,
String key) {
StatusTable.Reference ref =
new StatusTable.Reference(value, AU_STATUS_TABLE_NAME, key);
// ref.setProperty("numrows", Integer.toString(defaultNumRows));
return ref;
}
}
/** list of peers that have said they don't have the AU. Primarily for
* stf */
static class NoAuPeers extends PerAuTable {
private static final List columnDescriptors = ListUtil.list(
new ColumnDescriptor("Peer", "Peer", ColumnDescriptor.TYPE_STRING)
);
NoAuPeers(LockssDaemon theDaemon) {
super(theDaemon);
}
protected void populateTable(StatusTable table, ArchivalUnit au)
throws StatusService.NoSuchTableException {
HistoryRepository historyRepo = theDaemon.getHistoryRepository(au);
table.setTitle("Peers not holding " + au.getName());
DatedPeerIdSet noAuSet = theDaemon.getPollManager().getNoAuPeerSet(au);
synchronized (noAuSet) {
try {
noAuSet.load();
table.setSummaryInfo(getSummaryInfo(au, noAuSet));
table.setColumnDescriptors(columnDescriptors);
table.setRows(getRows(table, au, noAuSet));
} catch (IOException e) {
String msg = "Couldn't load NoAuSet";
logger.warning(msg, e);
throw new StatusService.NoSuchTableException(msg, e);
} finally {
noAuSet.release();
}
}
}
private List getRows(StatusTable table, ArchivalUnit au,
DatedPeerIdSet noAuSet) {
List rows = new ArrayList();
try {
logger.info("noAuSet.size(): " + noAuSet.size());
} catch (IOException e) {
logger.error("noAuSet.size()", e);
}
for (PeerIdentity pid : noAuSet) {
logger.info("pid: " + pid);
Map row = new HashMap();
row.put("Peer", pid.getIdString());
rows.add(row);
}
return rows;
}
private List getSummaryInfo(ArchivalUnit au, DatedPeerIdSet noAuSet) {
List res = new ArrayList();
try {
res.add(new StatusTable.SummaryInfo("Last cleared",
ColumnDescriptor.TYPE_DATE,
noAuSet.getDate()));
} catch (IOException e) {
logger.warning("Couldn't get date", e);
}
return res;
}
}
abstract static class PeersAgreement extends PerAuTable {
protected static final List sortRules =
ListUtil.list(new StatusTable.SortRule("Box", true));
PeersAgreement(LockssDaemon theDaemon) {
super(theDaemon);
}
protected Map makeRow(CacheStats stats) {
Map rowMap = new HashMap();
PeerIdentity peer = stats.peer;
Object id = peer.getIdString();
if (peer.isLocalIdentity()) {
StatusTable.DisplayedValue val =
new StatusTable.DisplayedValue(id);
val.setBold(true);
id = val;
}
rowMap.put("Box", id);
return rowMap;
}
class CacheStats {
PeerIdentity peer;
int totalPolls = 0;
int agreePolls = 0;
Vote lastAgree;
long lastAgreeTime = 0;
Vote lastDisagree;
long lastDisagreeTime = 0;
float highestAgreement = 0.0f;
float lastAgreement = 0.0f;
float highestAgreementHint = -1.0f;
float lastAgreementHint = -1.0f;
CacheStats(PeerIdentity peer) {
this.peer = peer;
}
boolean isLastAgree() {
return (lastAgreeTime != 0 &&
(lastDisagreeTime == 0 || lastAgreeTime >= lastDisagreeTime));
}
boolean isV3Agree() {
PollManager pollmgr = theDaemon.getPollManager();
return highestAgreement >= pollmgr.getMinPercentForRepair();
}
}
}
static class PeerVoteSummary extends PeersAgreement {
private static final List columnDescriptors = ListUtil.list(
new ColumnDescriptor("Box", "Box",
ColumnDescriptor.TYPE_STRING),
new ColumnDescriptor("Last", "Last",
ColumnDescriptor.TYPE_STRING),
new ColumnDescriptor("Polls", "Polls",
ColumnDescriptor.TYPE_INT),
new ColumnDescriptor("Agree", "Agree",
ColumnDescriptor.TYPE_INT),
new ColumnDescriptor("LastAgree", "Last Agree",
ColumnDescriptor.TYPE_DATE),
new ColumnDescriptor("LastDisagree", "Last Disagree",
ColumnDescriptor.TYPE_DATE)
);
PeerVoteSummary(LockssDaemon theDaemon) {
super(theDaemon);
}
protected String getTitle(ArchivalUnit au) {
return "All caches voting on AU: " + au.getName();
}
protected void populateTable(StatusTable table, ArchivalUnit au)
throws StatusService.NoSuchTableException {
NodeManager nodeMan = theDaemon.getNodeManager(au);
table.setTitle(getTitle(au));
int totalPeers = 0;
int totalAgreement = 0;
if (!table.getOptions().get(StatusTable.OPTION_NO_ROWS)) {
table.setColumnDescriptors(columnDescriptors);
table.setDefaultSortRules(sortRules);
Map statsMap = buildCacheStats(au, nodeMan);
List rowL = new ArrayList();
for (Iterator iter = statsMap.entrySet().iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry)iter.next();
PeerIdentity peer = (PeerIdentity)entry.getKey();
CacheStats stats = (CacheStats)entry.getValue();
if (! peer.isLocalIdentity()) {
totalPeers++;
if (stats.isLastAgree()) {
totalAgreement++;
}
}
Map row = makeRow(stats);
rowL.add(row);
}
table.setRows(rowL);
}
table.setSummaryInfo(getSummaryInfo(au, totalPeers, totalAgreement));
}
public Map buildCacheStats(ArchivalUnit au, NodeManager nodeMan) {
Map statsMap = new HashMap();
NodeState node = nodeMan.getNodeState(au.getAuCachedUrlSet());
for (Iterator history_it = node.getPollHistories();
history_it.hasNext(); ) {
PollHistory history = (PollHistory)history_it.next();
long histTime = history.getStartTime();
for (Iterator votes_it = history.getVotes(); votes_it.hasNext(); ) {
Vote vote = (Vote)votes_it.next();
PeerIdentity peer = vote.getVoterIdentity();
CacheStats stats = (CacheStats)statsMap.get(peer);
if (stats == null) {
stats = new CacheStats(peer);
statsMap.put(peer, stats);
}
stats.totalPolls++;
if (vote.isAgreeVote()) {
stats.agreePolls++;
if (stats.lastAgree == null ||
histTime > stats.lastAgreeTime) {
stats.lastAgree = vote;
stats.lastAgreeTime = histTime;
}
} else {
if (stats.lastDisagree == null ||
histTime > stats.lastDisagreeTime) {
stats.lastDisagree = vote;
stats.lastDisagreeTime = histTime;
}
}
}
}
return statsMap;
}
protected Map makeRow(CacheStats stats) {
Map rowMap = super.makeRow(stats);
rowMap.put("Last",
stats.isLastAgree() ? "Agree" : "Disagree");
rowMap.put("Polls", new Long(stats.totalPolls));
rowMap.put("Agree", new Long(stats.agreePolls));
rowMap.put("LastAgree", new Long(stats.lastAgreeTime));
rowMap.put("LastDisagree", new Long(stats.lastDisagreeTime));
return rowMap;
}
protected List getSummaryInfo(ArchivalUnit au,
int totalPeers, int totalAgreement) {
List summaryList = ListUtil.list(
new StatusTable.SummaryInfo("Peers voting on AU",
ColumnDescriptor.TYPE_INT,
new Integer(totalPeers)),
new StatusTable.SummaryInfo("Agreeing peers",
ColumnDescriptor.TYPE_INT,
new Integer(totalAgreement))
);
return summaryList;
}
// utility method for making a Reference
public static StatusTable.Reference makeAuRef(Object value,
String key) {
return new StatusTable.Reference(value, PEERS_VOTE_TABLE_NAME,
key);
}
}
static class PeerRepair extends PeersAgreement {
private static final List columnDescriptors = ListUtil.list(
new ColumnDescriptor("Box", "Box",
ColumnDescriptor.TYPE_STRING),
new ColumnDescriptor("Last", "Consensus",
ColumnDescriptor.TYPE_STRING),
new ColumnDescriptor("HighestPercentAgreement", "Highest Agreement",
ColumnDescriptor.TYPE_PERCENT),
new ColumnDescriptor("LastPercentAgreement", "Last Agreement",
ColumnDescriptor.TYPE_PERCENT),
new ColumnDescriptor("HighestPercentAgreementHint",
"Highest Agreement Hint",
ColumnDescriptor.TYPE_PERCENT),
new ColumnDescriptor("LastPercentAgreementHint", "Last Agreement Hint",
ColumnDescriptor.TYPE_PERCENT),
new ColumnDescriptor("LastAgree",
"Last Consensus",
ColumnDescriptor.TYPE_DATE)
);
PeerRepair(LockssDaemon theDaemon) {
super(theDaemon);
}
protected String getTitle(ArchivalUnit au) {
return "Repair candidates for AU: " + au.getName();
}
private static final String FOOT_TITLE =
"Peers whose Highest Agreement is above a threshold have proven\n" +
"in the past that their content for this AU is the same, and will\n" +
"be served repairs on request. Peers whose Highest Agreement Hint\n" +
"is above the threshold have reported that this peer has proven to\n" +
"them that the content for the AU is the same, and are likely to\n" +
"supply repairs on request.";
protected void populateTable(StatusTable table, ArchivalUnit au)
throws StatusService.NoSuchTableException {
IdentityManager idMgr = theDaemon.getIdentityManager();
table.setTitle(getTitle(au));
table.setTitleFootnote(FOOT_TITLE);
int totalPeers = 0;
if (!table.getOptions().get(StatusTable.OPTION_NO_ROWS)) {
table.setColumnDescriptors(columnDescriptors);
table.setDefaultSortRules(sortRules);
Map statsMap = buildCacheStats(au, idMgr);
List rowL = new ArrayList();
for (Iterator iter = statsMap.entrySet().iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry)iter.next();
PeerIdentity peer = (PeerIdentity)entry.getKey();
CacheStats stats = (CacheStats)entry.getValue();
if (! peer.isLocalIdentity()) {
totalPeers++;
}
Map row = makeRow(stats);
rowL.add(row);
}
table.setRows(rowL);
}
table.setSummaryInfo(getSummaryInfo(au, totalPeers));
}
public Map buildCacheStats(ArchivalUnit au, IdentityManager idMgr) {
Map statsMap = new HashMap();
for (Iterator iter = idMgr.getIdentityAgreements(au).iterator();
iter.hasNext(); ) {
IdentityManager.IdentityAgreement ida =
(IdentityManager.IdentityAgreement)iter.next();
try {
PeerIdentity pid = idMgr.stringToPeerIdentity(ida.getId());
if (ida.getHighestPercentAgreement() >= 0.0 ||
ida.getHighestPercentAgreementHint() >= 0.0) {
CacheStats stats = new CacheStats(pid);
statsMap.put(pid, stats);
stats.lastAgreeTime = ida.getLastAgree();
stats.lastDisagreeTime = ida.getLastDisagree();
stats.highestAgreement = ida.getHighestPercentAgreement();
stats.lastAgreement = ida.getPercentAgreement();
stats.highestAgreementHint = ida.getHighestPercentAgreementHint();
stats.lastAgreementHint = ida.getPercentAgreementHint();
}
} catch (IdentityManager.MalformedIdentityKeyException e) {
logger.warning("Malformed id key in IdentityAgreement", e);
continue;
}
}
return statsMap;
}
protected Map makeRow(CacheStats stats) {
Map rowMap = super.makeRow(stats);
rowMap.put("Last", stats.isLastAgree() ? "Yes" : "No");
if (stats.highestAgreement >= 0.0f) {
rowMap.put("LastPercentAgreement",
new Float(stats.lastAgreement));
rowMap.put("HighestPercentAgreement",
new Float(stats.highestAgreement));
}
if (stats.highestAgreementHint >= 0.0f) {
rowMap.put("LastPercentAgreementHint",
new Float(stats.lastAgreementHint));
rowMap.put("HighestPercentAgreementHint",
new Float(stats.highestAgreementHint));
}
rowMap.put("LastAgree", new Long(stats.lastAgreeTime));
rowMap.put("LastDisagree", new Long(stats.lastDisagreeTime));
return rowMap;
}
protected List getSummaryInfo(ArchivalUnit au,
int totalPeers) {
List summaryList = ListUtil.list(
new StatusTable.SummaryInfo("Peers holding AU",
ColumnDescriptor.TYPE_INT,
new Integer(totalPeers)));
return summaryList;
}
// utility method for making a Reference
public static StatusTable.Reference makeAuRef(Object value,
String key) {
return new StatusTable.Reference(value, PEERS_REPAIR_TABLE_NAME,
key);
}
}
static class Overview implements OverviewAccessor {
private LockssDaemon daemon;
private PluginManager pluginMgr;
public Overview(LockssDaemon daemon) {
this.daemon = daemon;
this.pluginMgr = daemon.getPluginManager();
}
public Object getOverview(String tableName, BitSet options) {
boolean isDebug = options.get(StatusTable.OPTION_DEBUG_USER);
List res = new ArrayList();
int total = 0;
int internal = 0;
int neverCrawled = 0;
int needsRecrawl = 0;
for (ArchivalUnit au : pluginMgr.getAllAus()) {
if (pluginMgr.isInternalAu(au)) {
internal++;
if (!isDebug) {
continue;
}
}
total++;
AuState aus = AuUtil.getAuState(au);
if (AuUtil.isPubDown(au)) {
} else {
if (aus.getLastCrawlTime() <= 0) {
neverCrawled++;
} else if (au.shouldCrawlForNewContent(aus)) {
needsRecrawl++;
}
}
}
StringBuilder sb = new StringBuilder();
sb.append(StringUtil.numberOfUnits(total, "Archival Unit",
"Archival Units"));
if (internal != 0 && isDebug) {
sb.append(" (");
sb.append(internal);
sb.append(" internal)");
}
if (neverCrawled != 0) {
sb.append(", ");
sb.append(neverCrawled);
sb.append(" not collected");
}
if (includeNeedsRecrawl && needsRecrawl != 0) {
sb.append(", ");
sb.append(StringUtil.numberOfUnits(needsRecrawl,
" needs recrawl", " need recrawl"));
}
return new StatusTable.Reference(sb.toString(),
SERVICE_STATUS_TABLE_NAME);
}
}
static final double STATUS_ORDER_AGREE_BASE = 100.0;
static final double STATUS_ORDER_WAIT_POLL = 200.0;
static final double STATUS_ORDER_CRAWLING = 300.0;
static final double STATUS_ORDER_WAIT_CRAWL = 400.0;
static OrderedObject agreeStatus(double agreement) {
return new OrderedObject(doubleToPercent(agreement) + "% Agreement",
STATUS_ORDER_AGREE_BASE - agreement);
}
public static StatusTable.Reference makeCrawlRef(Object value,
ArchivalUnit au) {
return new StatusTable.Reference(value,
CrawlManagerImpl.CRAWL_STATUS_TABLE_NAME,
au.getAuId());
}
public static StatusTable.Reference makePollRef(Object value,
ArchivalUnit au) {
return new StatusTable.Reference(value,
V3PollStatus.POLLER_STATUS_TABLE_NAME,
au.getAuId());
}
}
| Display existence of, current state, and possibly description of crawl
window.
git-svn-id: 293778eaa97c8c94097d610b1bd5133a8f478f36@8118 4f837ed2-42f5-46e7-a7a5-fa17313484d4
| src/org/lockss/state/ArchivalUnitStatus.java | Display existence of, current state, and possibly description of crawl window. | <ide><path>rc/org/lockss/state/ArchivalUnitStatus.java
<ide> /*
<del> * $Id: ArchivalUnitStatus.java,v 1.79 2009-05-22 19:14:55 dshr Exp $
<add> * $Id: ArchivalUnitStatus.java,v 1.80 2009-06-01 07:32:07 tlipkis Exp $
<ide> */
<ide>
<ide> /*
<ide> res.add(new StatusTable.SummaryInfo("Created",
<ide> ColumnDescriptor.TYPE_DATE,
<ide> new Long(state.getAuCreationTime())));
<add> CrawlWindow window = au.getCrawlSpec().getCrawlWindow();
<add> if (window != null) {
<add> String wmsg = window.toString();
<add> if (wmsg.length() > 140) {
<add> wmsg = "(not displayable)";
<add> }
<add> if (!window.canCrawl()) {
<add> wmsg = "Currently closed: " + wmsg;
<add> }
<add> res.add(new StatusTable.SummaryInfo("Crawl Window",
<add> ColumnDescriptor.TYPE_STRING,
<add> wmsg));
<add> }
<ide> long lastCrawlAttempt = state.getLastCrawlAttempt();
<ide> res.add(new StatusTable.SummaryInfo("Last Completed Crawl",
<ide> ColumnDescriptor.TYPE_DATE, |
|
Java | epl-1.0 | d8d184888b95deba16ff509b571b4a89bb96f104 | 0 | boothen/Json-Eclipse-Plugin,boothen/Json-Eclipse-Plugin,boothen/Json-Eclipse-Plugin,boothen/Json-Eclipse-Plugin | package com.boothen.jsonedit.folding;
import java.util.List;
import org.antlr.v4.runtime.ParserRuleContext;
import org.eclipse.jface.text.Position;
import com.boothen.jsonedit.antlr.JSONBaseVisitor;
import com.boothen.jsonedit.antlr.JSONParser.ArrayContext;
import com.boothen.jsonedit.antlr.JSONParser.ObjectContext;
/**
* Creates {@link Position} instances that wrap around inner nodes in the syntax tree.
* The root element is excluded explicitly.
*/
class FoldingVisitor extends JSONBaseVisitor<Void> {
private final List<Position> positions;
/**
* @param positions an (empty) list that will be filled during tree traversal
*/
public FoldingVisitor(List<Position> positions) {
this.positions = positions;
}
@Override
public Void visitObject(ObjectContext ctx) {
if (isFoldingPoint(ctx)) {
positions.add(createPosition(ctx));
}
return super.visitObject(ctx);
}
@Override
public Void visitArray(ArrayContext ctx) {
if (isFoldingPoint(ctx)) {
positions.add(createPosition(ctx));
}
return super.visitArray(ctx);
}
private Position createPosition(ParserRuleContext ctx) {
int startIndex = ctx.start.getStartIndex();
int stopIndex = ctx.stop.getStopIndex();
Position pos = new Position(startIndex, stopIndex - startIndex);
return pos;
}
private boolean isFoldingPoint(ParserRuleContext ctx) {
if (ctx.exception != null) {
return false;
}
// the root element is at depth 1 and not part of the traversal
// it contains one child with identical start/stop tokens
// we filter it out to avoid folding the entire file
if (ctx.depth() <= 2) {
return false;
}
// Skip elements that span less than two lines
return ctx.start.getLine() < ctx.stop.getLine() - 1;
}
}
| jsonedit-folding/src/main/java/com/boothen/jsonedit/folding/FoldingVisitor.java | package com.boothen.jsonedit.folding;
import java.util.List;
import org.antlr.v4.runtime.ParserRuleContext;
import org.eclipse.jface.text.Position;
import com.boothen.jsonedit.antlr.JSONBaseVisitor;
import com.boothen.jsonedit.antlr.JSONParser.ArrayContext;
import com.boothen.jsonedit.antlr.JSONParser.ObjectContext;
/**
* Creates {@link Position} instances that wrap around inner nodes in the syntax tree.
* The root element is excluded explicitly.
*/
class FoldingVisitor extends JSONBaseVisitor<Void> {
private final List<Position> positions;
/**
* @param positions an (empty) list that will be filled during tree traversal
*/
public FoldingVisitor(List<Position> positions) {
this.positions = positions;
}
@Override
public Void visitObject(ObjectContext ctx) {
if (isFoldingPoint(ctx)) {
positions.add(createPosition(ctx));
}
return super.visitObject(ctx);
}
@Override
public Void visitArray(ArrayContext ctx) {
if (isFoldingPoint(ctx)) {
positions.add(createPosition(ctx));
}
return super.visitArray(ctx);
}
private Position createPosition(ParserRuleContext ctx) {
int startIndex = ctx.start.getStartIndex();
int stopIndex = ctx.stop.getStopIndex();
Position pos = new Position(startIndex, stopIndex - startIndex);
return pos;
}
private boolean isFoldingPoint(ParserRuleContext ctx) {
// the root element is at depth 1 and not part of the traversal
// it contains one child with identical start/stop tokens
// we filter it out to avoid folding the entire file
if (ctx.depth() <= 2) {
return false;
}
// Skip elements that span less than two lines
return ctx.start.getLine() < ctx.stop.getLine() - 1;
}
}
| Create folding tags only for correct tree nodes
| jsonedit-folding/src/main/java/com/boothen/jsonedit/folding/FoldingVisitor.java | Create folding tags only for correct tree nodes | <ide><path>sonedit-folding/src/main/java/com/boothen/jsonedit/folding/FoldingVisitor.java
<ide> }
<ide>
<ide> private boolean isFoldingPoint(ParserRuleContext ctx) {
<add> if (ctx.exception != null) {
<add> return false;
<add> }
<add>
<ide> // the root element is at depth 1 and not part of the traversal
<ide> // it contains one child with identical start/stop tokens
<ide> // we filter it out to avoid folding the entire file |
|
Java | apache-2.0 | e497b487847607c3432c8ae672f4b37b44daf0f3 | 0 | williamchand/linebotsdk | package com.example.bot.spring;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.function.Consumer;
import java.net.URISyntaxException;
import java.net.URI;
import java.sql.*;
import javax.sql.DataSource;;
import java.util.Timer;
import java.util.TimerTask;
import com.heroku.sdk.jdbc.DatabaseUrl;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import com.google.common.io.ByteStreams;
import com.linecorp.bot.client.LineMessagingClient;
import com.linecorp.bot.client.MessageContentResponse;
import com.linecorp.bot.model.ReplyMessage;
import com.linecorp.bot.model.Multicast;
import com.linecorp.bot.model.PushMessage;
import com.linecorp.bot.model.action.MessageAction;
import com.linecorp.bot.model.action.PostbackAction;
import com.linecorp.bot.model.action.URIAction;
import com.linecorp.bot.model.event.BeaconEvent;
import com.linecorp.bot.model.event.Event;
import com.linecorp.bot.model.event.FollowEvent;
import com.linecorp.bot.model.event.JoinEvent;
import com.linecorp.bot.model.event.MessageEvent;
import com.linecorp.bot.model.event.PostbackEvent;
import com.linecorp.bot.model.event.UnfollowEvent;
import com.linecorp.bot.model.event.message.AudioMessageContent;
import com.linecorp.bot.model.event.message.ImageMessageContent;
import com.linecorp.bot.model.event.message.LocationMessageContent;
import com.linecorp.bot.model.event.message.StickerMessageContent;
import com.linecorp.bot.model.event.message.TextMessageContent;
import com.linecorp.bot.model.event.message.VideoMessageContent;
import com.linecorp.bot.model.event.source.GroupSource;
import com.linecorp.bot.model.event.source.RoomSource;
import com.linecorp.bot.model.event.source.Source;
import com.linecorp.bot.model.message.AudioMessage;
import com.linecorp.bot.model.message.ImageMessage;
import com.linecorp.bot.model.message.ImagemapMessage;
import com.linecorp.bot.model.message.LocationMessage;
import com.linecorp.bot.model.message.Message;
import com.linecorp.bot.model.message.StickerMessage;
import com.linecorp.bot.model.message.TemplateMessage;
import com.linecorp.bot.model.message.TextMessage;
import com.linecorp.bot.model.message.VideoMessage;
import com.linecorp.bot.model.message.imagemap.ImagemapArea;
import com.linecorp.bot.model.message.imagemap.ImagemapBaseSize;
import com.linecorp.bot.model.message.imagemap.MessageImagemapAction;
import com.linecorp.bot.model.message.imagemap.URIImagemapAction;
import com.linecorp.bot.model.message.template.ButtonsTemplate;
import com.linecorp.bot.model.message.template.CarouselColumn;
import com.linecorp.bot.model.message.template.CarouselTemplate;
import com.linecorp.bot.model.message.template.ConfirmTemplate;
import com.linecorp.bot.model.profile.UserProfileResponse;
import com.linecorp.bot.model.response.BotApiResponse;
import com.linecorp.bot.spring.boot.annotation.EventMapping;
import com.linecorp.bot.spring.boot.annotation.LineMessageHandler;
import lombok.NonNull;
import lombok.Value;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@LineMessageHandler
@RestController
public class KitchenSinkController {
@Autowired
private LineMessagingClient lineMessagingClient;
@EventMapping
public void handleTextMessageEvent(MessageEvent<TextMessageContent> event) throws Exception {
TextMessageContent message = event.getMessage();
handleTextContent(event.getReplyToken(), event, message);
}
@EventMapping
public void handleStickerMessageEvent(MessageEvent<StickerMessageContent> event) {
log.info("Received message(Ignored): {}", event);
}
@EventMapping
public void handleLocationMessageEvent(MessageEvent<LocationMessageContent> event) {
log.info("Received message(Ignored): {}", event);
}
@EventMapping
public void handleImageMessageEvent(MessageEvent<ImageMessageContent> event) throws IOException {
log.info("Received message(Ignored): {}", event);
}
@EventMapping
public void handleAudioMessageEvent(MessageEvent<AudioMessageContent> event) throws IOException {
log.info("Received message(Ignored): {}", event);
}
@EventMapping
public void handleVideoMessageEvent(MessageEvent<VideoMessageContent> event) throws IOException {
log.info("Received message(Ignored): {}", event);
}
@EventMapping
public void handleUnfollowEvent(UnfollowEvent event) {
log.info("unfollowed this bot: {}", event);
}
@EventMapping
public void handleFollowEvent(FollowEvent event) {
String replyToken = event.getReplyToken();
this.replyText(replyToken, "Got followed event");
}
@EventMapping
public void handleJoinEvent(JoinEvent event) {
String replyToken = event.getReplyToken();
this.replyText(replyToken, "Joined " + event.getSource());
}
@EventMapping
public void handlePostbackEvent(PostbackEvent event) {
log.info("Received message(Ignored): {}", event);
}
@EventMapping
public void handleBeaconEvent(BeaconEvent event) {
log.info("Received message(Ignored): {}", event);
}
@EventMapping
public void handleOtherEvent(Event event) {
log.info("Received message(Ignored): {}", event);
}
private void reply(@NonNull String replyToken, @NonNull Message message) {
reply(replyToken, Collections.singletonList(message));
}
private void reply(@NonNull String replyToken, @NonNull List<Message> messages) {
try {
BotApiResponse apiResponse = lineMessagingClient
.replyMessage(new ReplyMessage(replyToken, messages))
.get();
log.info("Sent messages: {}", apiResponse);
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
}
private void replyText(@NonNull String replyToken, @NonNull String message) {
if (replyToken.isEmpty()) {
throw new IllegalArgumentException("replyToken must not be empty");
}
if (message.length() > 1000) {
message = message.substring(0, 1000 - 2) + "……";
}
this.reply(replyToken, new TextMessage(message));
}
private Timer startTimer(final String value) {
Timer timer = new Timer("Timer" + value);
return timer;
}
private void handleTextContent(String replyToken, Event event, TextMessageContent content)
throws Exception {
String text = content.getText();
log.info("Got text message from {}: {}", replyToken, text);
if (text.indexOf("/profile")>=0){
String userId = event.getSource().getUserId();
if (userId != null) {
lineMessagingClient
.getProfile(userId)
.whenComplete((profile, throwable) -> {
if (throwable != null) {
this.replyText(replyToken, throwable.getMessage());
return;
}
this.reply(
replyToken,
Arrays.asList(new TextMessage(
"Id: " + userId),
new TextMessage(
"Display name: " + profile.getDisplayName()),
new TextMessage(
"Status message: " + profile.getStatusMessage()))
);
});
} else {
this.replyText(replyToken, "Bot can't use profile API without user ID");
}
}else if (text.indexOf("/leave")>=0){
Source source = event.getSource();
if (source instanceof GroupSource) {
this.replyText(replyToken, "Leaving group");
lineMessagingClient.leaveGroup(((GroupSource) source).getGroupId()).get();
} else if (source instanceof RoomSource) {
this.replyText(replyToken, "Leaving room");
lineMessagingClient.leaveRoom(((RoomSource) source).getRoomId()).get();
} else {
this.replyText(replyToken, "Bot can't leave from 1:1 chat");
}
}else if (text.indexOf("/question")>=0){
ConfirmTemplate confirmTemplate = new ConfirmTemplate(
"Do it?",
new MessageAction("Yes", "Yes!"),
new MessageAction("No", "No!")
);
TemplateMessage templateMessage = new TemplateMessage("Confirm alt text", confirmTemplate);
this.reply(replyToken, templateMessage);
}else if (text.indexOf("/buttons")>=0){
String imageUrl = createUri("/static/buttons/1040.jpg");
ButtonsTemplate buttonsTemplate = new ButtonsTemplate(
imageUrl,
"My button sample",
"Hello, my button",
Arrays.asList(
new URIAction("Go to line.me",
"https://line.me"),
new PostbackAction("Say hello1",
"hello �ん���"),
new PostbackAction("言 hello2",
"hello �ん���",
"hello �ん���"),
new MessageAction("Say message",
"Rice=ç±³")
));
TemplateMessage templateMessage = new TemplateMessage("Button alt text", buttonsTemplate);
this.reply(replyToken, templateMessage);
}else if (text.indexOf("/carousel")>=0){
String imageUrl = createUri("/static/buttons/1040.jpg");
CarouselTemplate carouselTemplate = new CarouselTemplate(
Arrays.asList(
new CarouselColumn(imageUrl, "hoge", "fuga", Arrays.asList(
new URIAction("Go to line.me",
"https://line.me"),
new PostbackAction("Say hello1",
"hello �ん���")
)),
new CarouselColumn(imageUrl, "hoge", "fuga", Arrays.asList(
new PostbackAction("言 hello2",
"hello �ん���",
"hello �ん���"),
new MessageAction("Say message",
"Rice=ç±³")
))
));
TemplateMessage templateMessage = new TemplateMessage("Carousel alt text", carouselTemplate);
this.reply(replyToken, templateMessage);
}else if (text.indexOf("/imagemap")>=0){
this.reply(replyToken, new ImagemapMessage(
createUri("/static/rich"),
"This is alt text",
new ImagemapBaseSize(1040, 1040),
Arrays.asList(
new URIImagemapAction(
"https://store.line.me/family/manga/en",
new ImagemapArea(
0, 0, 520, 520
)
),
new URIImagemapAction(
"https://store.line.me/family/music/en",
new ImagemapArea(
520, 0, 520, 520
)
),
new URIImagemapAction(
"https://store.line.me/family/play/en",
new ImagemapArea(
0, 520, 520, 520
)
),
new MessageImagemapAction(
"URANAI!",
new ImagemapArea(
520, 520, 520, 520
)
)
)
));
}else if (text.indexOf("/help")>=0){
this.replyText(replyToken,
"feature /help : bantuan\n"+"/imagemap:gambar yang dapat diklik\n"+"/buttons:tombol\n"+
"/question:pertanyaan\n"+"/carousel:carousel\n"+"/leave:keluar dari grup\n"+"/profile:user ID\n");
}else if(text.indexOf("/time")>=0){
try{
Connection connection = getConnection();
Statement stmt = connection.createStatement();
stmt.executeUpdate("DROP TABLE IF EXISTS ticks");
stmt.executeUpdate("CREATE TABLE ticks (tick timestamp)");
stmt.executeUpdate("INSERT INTO ticks VALUES (now() + INTERVAL '7 HOUR')");
ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks");
while (rs.next()) {
this.replyText(replyToken,"Read from DB: " + rs.getTimestamp("tick"));
}
}catch(SQLException e){
this.replyText(replyToken,e.getMessage());
}
}else if(text.indexOf("/delay")>=0){
Source source = event.getSource();
if (source instanceof GroupSource) {
String groupid = ((GroupSource) source).getGroupId();
}
Timer t0 = startTimer(groupid);
t0.schedule( new TimerTask() {
public void run() {
try{
Connection connection = getConnection();
Statement stmt = connection.createStatement();
stmt.executeUpdate("DROP TABLE IF EXISTS ticks");
stmt.executeUpdate("CREATE TABLE ticks (tick timestamp)");
stmt.executeUpdate("INSERT INTO ticks VALUES (now() + INTERVAL '7 HOUR')");
ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks");
while (rs.next()) {
this.replyText(replyToken,"Read from DB: " + rs.getTimestamp("tick"));
}
}catch(SQLException e){
this.replyText(replyToken,e.getMessage());
}
}
}, 30000, 1000); // Every second
}else if(text.indexOf("/cancel")>=0){
Source source = event.getSource();
if (source instanceof GroupSource) {
String groupid = ((GroupSource) source).getGroupId();
}
Timer t0 = startTimer(groupid);
t0.cancel();
}else{
log.info("Ignore message {}: {}", replyToken, text);
}
}
private static Connection getConnection() throws URISyntaxException, SQLException {
URI dbUri = new URI(System.getenv("DATABASE_URL"));
String username = dbUri.getUserInfo().split(":")[0];
String password = dbUri.getUserInfo().split(":")[1];
String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + dbUri.getPath();
return DriverManager.getConnection(dbUrl, username, password);
}
private static String createUri(String path) {
return ServletUriComponentsBuilder.fromCurrentContextPath()
.path(path).build()
.toUriString();
}
private void system(String... args) {
ProcessBuilder processBuilder = new ProcessBuilder(args);
try {
Process start = processBuilder.start();
int i = start.waitFor();
log.info("result: {} => {}", Arrays.toString(args), i);
} catch (IOException e) {
throw new UncheckedIOException(e);
} catch (InterruptedException e) {
log.info("Interrupted", e);
Thread.currentThread().interrupt();
}
}
private static DownloadedContent saveContent(String ext, MessageContentResponse responseBody) {
log.info("Got content-type: {}", responseBody);
DownloadedContent tempFile = createTempFile(ext);
try (OutputStream outputStream = Files.newOutputStream(tempFile.path)) {
ByteStreams.copy(responseBody.getStream(), outputStream);
log.info("Saved {}: {}", ext, tempFile);
return tempFile;
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private static DownloadedContent createTempFile(String ext) {
String fileName = LocalDateTime.now().toString() + '-' + UUID.randomUUID().toString() + '.' + ext;
Path tempFile = KitchenSinkApplication.downloadedContentDir.resolve(fileName);
tempFile.toFile().deleteOnExit();
return new DownloadedContent(
tempFile,
createUri("/downloaded/" + tempFile.getFileName()));
}
@Value
public static class DownloadedContent {
Path path;
String uri;
}
@RequestMapping("/greeting")
public Greeting greeting(@RequestParam(value="UserId", defaultValue="") String User,@RequestParam(value="message", defaultValue="") String message) {
this.pushText(User, message);
return new Greeting(User,message);
}
private void push(@NonNull String To, @NonNull Message message) {
push(To, Collections.singletonList(message));
}
private void push(@NonNull String To, @NonNull List<Message> messages) {
try {
BotApiResponse apiResponse = lineMessagingClient
.pushMessage(new PushMessage(To, messages))
.get();
log.info("Sent messages: {}", apiResponse);
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
}
private void pushText(@NonNull String To, @NonNull String message) {
if (To.isEmpty()) {
throw new IllegalArgumentException("replyToken must not be empty");
}
if (message.length() > 1000) {
message = message.substring(0, 1000 - 2) + "……";
}
this.push(To, new TextMessage(message));
}
} | sample-spring-boot-kitchensink/src/main/java/com/example/bot/spring/KitchenSinkController.java | package com.example.bot.spring;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.function.Consumer;
import java.net.URISyntaxException;
import java.net.URI;
import java.sql.*;
import javax.sql.DataSource;;
import java.util.Timer;
import java.util.TimerTask;
import com.heroku.sdk.jdbc.DatabaseUrl;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import com.google.common.io.ByteStreams;
import com.linecorp.bot.client.LineMessagingClient;
import com.linecorp.bot.client.MessageContentResponse;
import com.linecorp.bot.model.ReplyMessage;
import com.linecorp.bot.model.Multicast;
import com.linecorp.bot.model.PushMessage;
import com.linecorp.bot.model.action.MessageAction;
import com.linecorp.bot.model.action.PostbackAction;
import com.linecorp.bot.model.action.URIAction;
import com.linecorp.bot.model.event.BeaconEvent;
import com.linecorp.bot.model.event.Event;
import com.linecorp.bot.model.event.FollowEvent;
import com.linecorp.bot.model.event.JoinEvent;
import com.linecorp.bot.model.event.MessageEvent;
import com.linecorp.bot.model.event.PostbackEvent;
import com.linecorp.bot.model.event.UnfollowEvent;
import com.linecorp.bot.model.event.message.AudioMessageContent;
import com.linecorp.bot.model.event.message.ImageMessageContent;
import com.linecorp.bot.model.event.message.LocationMessageContent;
import com.linecorp.bot.model.event.message.StickerMessageContent;
import com.linecorp.bot.model.event.message.TextMessageContent;
import com.linecorp.bot.model.event.message.VideoMessageContent;
import com.linecorp.bot.model.event.source.GroupSource;
import com.linecorp.bot.model.event.source.RoomSource;
import com.linecorp.bot.model.event.source.Source;
import com.linecorp.bot.model.message.AudioMessage;
import com.linecorp.bot.model.message.ImageMessage;
import com.linecorp.bot.model.message.ImagemapMessage;
import com.linecorp.bot.model.message.LocationMessage;
import com.linecorp.bot.model.message.Message;
import com.linecorp.bot.model.message.StickerMessage;
import com.linecorp.bot.model.message.TemplateMessage;
import com.linecorp.bot.model.message.TextMessage;
import com.linecorp.bot.model.message.VideoMessage;
import com.linecorp.bot.model.message.imagemap.ImagemapArea;
import com.linecorp.bot.model.message.imagemap.ImagemapBaseSize;
import com.linecorp.bot.model.message.imagemap.MessageImagemapAction;
import com.linecorp.bot.model.message.imagemap.URIImagemapAction;
import com.linecorp.bot.model.message.template.ButtonsTemplate;
import com.linecorp.bot.model.message.template.CarouselColumn;
import com.linecorp.bot.model.message.template.CarouselTemplate;
import com.linecorp.bot.model.message.template.ConfirmTemplate;
import com.linecorp.bot.model.profile.UserProfileResponse;
import com.linecorp.bot.model.response.BotApiResponse;
import com.linecorp.bot.spring.boot.annotation.EventMapping;
import com.linecorp.bot.spring.boot.annotation.LineMessageHandler;
import lombok.NonNull;
import lombok.Value;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@LineMessageHandler
@RestController
public class KitchenSinkController {
@Autowired
private LineMessagingClient lineMessagingClient;
@EventMapping
public void handleTextMessageEvent(MessageEvent<TextMessageContent> event) throws Exception {
TextMessageContent message = event.getMessage();
handleTextContent(event.getReplyToken(), event, message);
}
@EventMapping
public void handleStickerMessageEvent(MessageEvent<StickerMessageContent> event) {
log.info("Received message(Ignored): {}", event);
}
@EventMapping
public void handleLocationMessageEvent(MessageEvent<LocationMessageContent> event) {
log.info("Received message(Ignored): {}", event);
}
@EventMapping
public void handleImageMessageEvent(MessageEvent<ImageMessageContent> event) throws IOException {
log.info("Received message(Ignored): {}", event);
}
@EventMapping
public void handleAudioMessageEvent(MessageEvent<AudioMessageContent> event) throws IOException {
log.info("Received message(Ignored): {}", event);
}
@EventMapping
public void handleVideoMessageEvent(MessageEvent<VideoMessageContent> event) throws IOException {
log.info("Received message(Ignored): {}", event);
}
@EventMapping
public void handleUnfollowEvent(UnfollowEvent event) {
log.info("unfollowed this bot: {}", event);
}
@EventMapping
public void handleFollowEvent(FollowEvent event) {
String replyToken = event.getReplyToken();
this.replyText(replyToken, "Got followed event");
}
@EventMapping
public void handleJoinEvent(JoinEvent event) {
String replyToken = event.getReplyToken();
this.replyText(replyToken, "Joined " + event.getSource());
}
@EventMapping
public void handlePostbackEvent(PostbackEvent event) {
log.info("Received message(Ignored): {}", event);
}
@EventMapping
public void handleBeaconEvent(BeaconEvent event) {
log.info("Received message(Ignored): {}", event);
}
@EventMapping
public void handleOtherEvent(Event event) {
log.info("Received message(Ignored): {}", event);
}
private void reply(@NonNull String replyToken, @NonNull Message message) {
reply(replyToken, Collections.singletonList(message));
}
private void reply(@NonNull String replyToken, @NonNull List<Message> messages) {
try {
BotApiResponse apiResponse = lineMessagingClient
.replyMessage(new ReplyMessage(replyToken, messages))
.get();
log.info("Sent messages: {}", apiResponse);
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
}
private void replyText(@NonNull String replyToken, @NonNull String message) {
if (replyToken.isEmpty()) {
throw new IllegalArgumentException("replyToken must not be empty");
}
if (message.length() > 1000) {
message = message.substring(0, 1000 - 2) + "……";
}
this.reply(replyToken, new TextMessage(message));
}
private Timer startTimer(final int value) {
Timer timer = new Timer("Timer" + value);
return timer;
}
private void handleTextContent(String replyToken, Event event, TextMessageContent content)
throws Exception {
String text = content.getText();
log.info("Got text message from {}: {}", replyToken, text);
if (text.indexOf("/profile")>=0){
String userId = event.getSource().getUserId();
if (userId != null) {
lineMessagingClient
.getProfile(userId)
.whenComplete((profile, throwable) -> {
if (throwable != null) {
this.replyText(replyToken, throwable.getMessage());
return;
}
this.reply(
replyToken,
Arrays.asList(new TextMessage(
"Id: " + userId),
new TextMessage(
"Display name: " + profile.getDisplayName()),
new TextMessage(
"Status message: " + profile.getStatusMessage()))
);
});
} else {
this.replyText(replyToken, "Bot can't use profile API without user ID");
}
}else if (text.indexOf("/leave")>=0){
Source source = event.getSource();
if (source instanceof GroupSource) {
this.replyText(replyToken, "Leaving group");
lineMessagingClient.leaveGroup(((GroupSource) source).getGroupId()).get();
} else if (source instanceof RoomSource) {
this.replyText(replyToken, "Leaving room");
lineMessagingClient.leaveRoom(((RoomSource) source).getRoomId()).get();
} else {
this.replyText(replyToken, "Bot can't leave from 1:1 chat");
}
}else if (text.indexOf("/question")>=0){
ConfirmTemplate confirmTemplate = new ConfirmTemplate(
"Do it?",
new MessageAction("Yes", "Yes!"),
new MessageAction("No", "No!")
);
TemplateMessage templateMessage = new TemplateMessage("Confirm alt text", confirmTemplate);
this.reply(replyToken, templateMessage);
}else if (text.indexOf("/buttons")>=0){
String imageUrl = createUri("/static/buttons/1040.jpg");
ButtonsTemplate buttonsTemplate = new ButtonsTemplate(
imageUrl,
"My button sample",
"Hello, my button",
Arrays.asList(
new URIAction("Go to line.me",
"https://line.me"),
new PostbackAction("Say hello1",
"hello �ん���"),
new PostbackAction("言 hello2",
"hello �ん���",
"hello �ん���"),
new MessageAction("Say message",
"Rice=ç±³")
));
TemplateMessage templateMessage = new TemplateMessage("Button alt text", buttonsTemplate);
this.reply(replyToken, templateMessage);
}else if (text.indexOf("/carousel")>=0){
String imageUrl = createUri("/static/buttons/1040.jpg");
CarouselTemplate carouselTemplate = new CarouselTemplate(
Arrays.asList(
new CarouselColumn(imageUrl, "hoge", "fuga", Arrays.asList(
new URIAction("Go to line.me",
"https://line.me"),
new PostbackAction("Say hello1",
"hello �ん���")
)),
new CarouselColumn(imageUrl, "hoge", "fuga", Arrays.asList(
new PostbackAction("言 hello2",
"hello �ん���",
"hello �ん���"),
new MessageAction("Say message",
"Rice=ç±³")
))
));
TemplateMessage templateMessage = new TemplateMessage("Carousel alt text", carouselTemplate);
this.reply(replyToken, templateMessage);
}else if (text.indexOf("/imagemap")>=0){
this.reply(replyToken, new ImagemapMessage(
createUri("/static/rich"),
"This is alt text",
new ImagemapBaseSize(1040, 1040),
Arrays.asList(
new URIImagemapAction(
"https://store.line.me/family/manga/en",
new ImagemapArea(
0, 0, 520, 520
)
),
new URIImagemapAction(
"https://store.line.me/family/music/en",
new ImagemapArea(
520, 0, 520, 520
)
),
new URIImagemapAction(
"https://store.line.me/family/play/en",
new ImagemapArea(
0, 520, 520, 520
)
),
new MessageImagemapAction(
"URANAI!",
new ImagemapArea(
520, 520, 520, 520
)
)
)
));
}else if (text.indexOf("/help")>=0){
this.replyText(replyToken,
"feature /help : bantuan\n"+"/imagemap:gambar yang dapat diklik\n"+"/buttons:tombol\n"+
"/question:pertanyaan\n"+"/carousel:carousel\n"+"/leave:keluar dari grup\n"+"/profile:user ID\n");
}else if(text.indexOf("/time")>=0){
try{
Connection connection = getConnection();
Statement stmt = connection.createStatement();
stmt.executeUpdate("DROP TABLE IF EXISTS ticks");
stmt.executeUpdate("CREATE TABLE ticks (tick timestamp)");
stmt.executeUpdate("INSERT INTO ticks VALUES (now() + INTERVAL '7 HOUR')");
ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks");
while (rs.next()) {
this.replyText(replyToken,"Read from DB: " + rs.getTimestamp("tick"));
}
}catch(SQLException e){
this.replyText(replyToken,e.getMessage());
}
}else if(text.indexOf("/delay")>=0){
Timer t0 = startTimer(0);
t0.schedule( new TimerTask() {
public void run() {
try{
Connection connection = getConnection();
Statement stmt = connection.createStatement();
stmt.executeUpdate("DROP TABLE IF EXISTS ticks");
stmt.executeUpdate("CREATE TABLE ticks (tick timestamp)");
stmt.executeUpdate("INSERT INTO ticks VALUES (now() + INTERVAL '7 HOUR')");
ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks");
while (rs.next()) {
this.replyText(replyToken,"Read from DB: " + rs.getTimestamp("tick"));
}
}catch(SQLException e){
this.replyText(replyToken,e.getMessage());
}
}
}, 30000, 1000); // Every second
}else if(text.indexOf("/cancel")>=0){
t0.cancel();
}else{
log.info("Ignore message {}: {}", replyToken, text);
}
}
private static Connection getConnection() throws URISyntaxException, SQLException {
URI dbUri = new URI(System.getenv("DATABASE_URL"));
String username = dbUri.getUserInfo().split(":")[0];
String password = dbUri.getUserInfo().split(":")[1];
String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + dbUri.getPath();
return DriverManager.getConnection(dbUrl, username, password);
}
private static String createUri(String path) {
return ServletUriComponentsBuilder.fromCurrentContextPath()
.path(path).build()
.toUriString();
}
private void system(String... args) {
ProcessBuilder processBuilder = new ProcessBuilder(args);
try {
Process start = processBuilder.start();
int i = start.waitFor();
log.info("result: {} => {}", Arrays.toString(args), i);
} catch (IOException e) {
throw new UncheckedIOException(e);
} catch (InterruptedException e) {
log.info("Interrupted", e);
Thread.currentThread().interrupt();
}
}
private static DownloadedContent saveContent(String ext, MessageContentResponse responseBody) {
log.info("Got content-type: {}", responseBody);
DownloadedContent tempFile = createTempFile(ext);
try (OutputStream outputStream = Files.newOutputStream(tempFile.path)) {
ByteStreams.copy(responseBody.getStream(), outputStream);
log.info("Saved {}: {}", ext, tempFile);
return tempFile;
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private static DownloadedContent createTempFile(String ext) {
String fileName = LocalDateTime.now().toString() + '-' + UUID.randomUUID().toString() + '.' + ext;
Path tempFile = KitchenSinkApplication.downloadedContentDir.resolve(fileName);
tempFile.toFile().deleteOnExit();
return new DownloadedContent(
tempFile,
createUri("/downloaded/" + tempFile.getFileName()));
}
@Value
public static class DownloadedContent {
Path path;
String uri;
}
@RequestMapping("/greeting")
public Greeting greeting(@RequestParam(value="UserId", defaultValue="") String User,@RequestParam(value="message", defaultValue="") String message) {
this.pushText(User, message);
return new Greeting(User,message);
}
private void push(@NonNull String To, @NonNull Message message) {
push(To, Collections.singletonList(message));
}
private void push(@NonNull String To, @NonNull List<Message> messages) {
try {
BotApiResponse apiResponse = lineMessagingClient
.pushMessage(new PushMessage(To, messages))
.get();
log.info("Sent messages: {}", apiResponse);
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
}
private void pushText(@NonNull String To, @NonNull String message) {
if (To.isEmpty()) {
throw new IllegalArgumentException("replyToken must not be empty");
}
if (message.length() > 1000) {
message = message.substring(0, 1000 - 2) + "……";
}
this.push(To, new TextMessage(message));
}
} | Add Existing Files
| sample-spring-boot-kitchensink/src/main/java/com/example/bot/spring/KitchenSinkController.java | Add Existing Files | <ide><path>ample-spring-boot-kitchensink/src/main/java/com/example/bot/spring/KitchenSinkController.java
<ide> }
<ide> this.reply(replyToken, new TextMessage(message));
<ide> }
<del> private Timer startTimer(final int value) {
<add> private Timer startTimer(final String value) {
<ide> Timer timer = new Timer("Timer" + value);
<ide> return timer;
<ide> }
<ide> this.replyText(replyToken,e.getMessage());
<ide> }
<ide> }else if(text.indexOf("/delay")>=0){
<del> Timer t0 = startTimer(0);
<add> Source source = event.getSource();
<add> if (source instanceof GroupSource) {
<add> String groupid = ((GroupSource) source).getGroupId();
<add> }
<add> Timer t0 = startTimer(groupid);
<ide> t0.schedule( new TimerTask() {
<ide> public void run() {
<ide> try{
<ide> }
<ide> }, 30000, 1000); // Every second
<ide> }else if(text.indexOf("/cancel")>=0){
<add> Source source = event.getSource();
<add> if (source instanceof GroupSource) {
<add> String groupid = ((GroupSource) source).getGroupId();
<add> }
<add> Timer t0 = startTimer(groupid);
<ide> t0.cancel();
<ide> }else{
<ide> log.info("Ignore message {}: {}", replyToken, text); |
|
Java | mit | 6750cc5cfd70ce29faec4a4618e5cb2b9dddcb41 | 0 | TeamCautionRobotics/2015-FRC-robot | package org.usfirst.frc.team1492.robot;
import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.Joystick.AxisType;
import edu.wpi.first.wpilibj.SampleRobot;
import edu.wpi.first.wpilibj.Talon;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
public class Robot extends SampleRobot {
Talon motorL;
Talon motorR;
Talon motorCenter; // Motor controller for the middle of the H
Talon motorElevator;
Joystick stickLeft;
Joystick stickRight;
Joystick stickAux;
DigitalInput limitSwitchElevatorTop;
DigitalInput limitSwitchElevatorBottom;
DigitalInput limitSwitchElevatorOne;
DigitalInput limitSwitchElevatorTwo;
DigitalInput limitSwitchElevatorThree;
double elevatorSpeed = 0;
double elevatorMaxSpeed = 1;
public Robot() {
motorL = new Talon(0);
motorR = new Talon(1);
motorCenter = new Talon(2);
motorElevator = new Talon(3);
stickLeft = new Joystick(0);
stickRight = new Joystick(1);
stickAux = new Joystick(2);
limitSwitchElevatorBottom = new DigitalInput(0);
limitSwitchElevatorTop = new DigitalInput(1);
limitSwitchElevatorOne = new DigitalInput(2);
limitSwitchElevatorTwo = new DigitalInput(3);
limitSwitchElevatorThree = new DigitalInput(4);
}
public void autonomous() {
}
public void operatorControl() {
// CameraThread c = new CameraThread();
while (isOperatorControl() && isEnabled()) {
driveControl();
manipulatorControl();
Timer.delay(0.005);
}
// c.finish();
}
public void test() {
}
public void driveControl() {
double leftSide = -stickLeft.getAxis(AxisType.kY);
double rightSide = stickRight.getAxis(AxisType.kY);
double horizontal = (stickLeft.getAxis(AxisType.kX) + stickRight
.getAxis(AxisType.kX)) / 2;
motorL.set(leftSide);
motorR.set(rightSide);
motorCenter.set(horizontal);
}
public void manipulatorControl() {
// elevator limit switches not edge ones
elevatorMaxSpeed = (stickAux.getAxis(AxisType.kZ) + 1) / 2;
SmartDashboard.putNumber("elevatorMaxSpeed", elevatorMaxSpeed);
SmartDashboard.putBoolean("!limitSwitchElevatorTop",
!limitSwitchElevatorTop.get());
SmartDashboard.putBoolean("!limitSwitchElevatorBottom",
!limitSwitchElevatorBottom.get());
SmartDashboard.putBoolean("!limitSwitchElevatorOne",
!limitSwitchElevatorOne.get());
if (!limitSwitchElevatorOne.get() /*
* || !limitSwitchElevatorTwo.get() ||
* !limitSwitchElevatorThree.get()
*/) {
elevatorSpeed = 0;
}
if (stickAux.getRawButton(3)) {
elevatorSpeed = -elevatorMaxSpeed;
}
if (stickAux.getRawButton(2)) {
elevatorSpeed = elevatorMaxSpeed;
}
if (!limitSwitchElevatorTop.get() || !limitSwitchElevatorBottom.get()) {
elevatorSpeed = 0;
}
motorElevator.set(elevatorSpeed);
}
}
| src/org/usfirst/frc/team1492/robot/Robot.java | package org.usfirst.frc.team1492.robot;
import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.Joystick.AxisType;
import edu.wpi.first.wpilibj.SampleRobot;
import edu.wpi.first.wpilibj.Servo;
import edu.wpi.first.wpilibj.Solenoid;
import edu.wpi.first.wpilibj.Talon;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
public class Robot extends SampleRobot {
Talon motorL;
Talon motorR;
Talon motorCenter; // Motor controller for the middle of the H
Talon motorElevator;
Joystick stickLeft;
Joystick stickRight;
Joystick stickAux;
Solenoid testSolenoid;
Servo cameraServo;
double cameraServoValue;
DigitalInput limitSwitchElevatorTop;
DigitalInput limitSwitchElevatorBottom;
DigitalInput limitSwitchElevatorOne;
DigitalInput limitSwitchElevatorTwo;
DigitalInput limitSwitchElevatorThree;
double elevatorSpeed = 0;
double elevatorMaxSpeed = 1;
public Robot() {
motorL = new Talon(0);
motorR = new Talon(1);
motorCenter = new Talon(2);
motorElevator = new Talon(3);
stickLeft = new Joystick(0);
stickRight = new Joystick(1);
stickAux = new Joystick(2);
testSolenoid = new Solenoid(0);
cameraServo = new Servo(7);
limitSwitchElevatorBottom = new DigitalInput(0);
limitSwitchElevatorTop = new DigitalInput(1);
limitSwitchElevatorOne = new DigitalInput(2);
limitSwitchElevatorTwo = new DigitalInput(3);
limitSwitchElevatorThree = new DigitalInput(4);
}
public void autonomous() {
}
public void operatorControl() {
// CameraThread c = new CameraThread();
while (isOperatorControl() && isEnabled()) {
driveControl();
manipulatorControl();
Timer.delay(0.005);
}
// c.finish();
}
public void test() {
}
public void driveControl() {
double leftSide = -stickLeft.getAxis(AxisType.kY);
double rightSide = stickRight.getAxis(AxisType.kY);
double horizontal = (stickLeft.getAxis(AxisType.kX) + stickRight
.getAxis(AxisType.kX)) / 2;
motorL.set(leftSide);
motorR.set(rightSide);
motorCenter.set(horizontal);
}
public void manipulatorControl() {
testSolenoid.set(stickRight.getRawButton(1));
if (stickRight.getRawButton(4)) {
cameraServoValue -= .05;
if (cameraServoValue < 0) {
cameraServoValue = 0;
}
}
if (stickRight.getRawButton(5)) {
cameraServoValue += .05;
if (cameraServoValue > 1) {
cameraServoValue = 1;
}
}
cameraServo.set(cameraServoValue);
// elevator limit switches not edge ones
elevatorMaxSpeed = (stickAux.getAxis(AxisType.kZ) + 1) / 2;
SmartDashboard.putNumber("elevatorMaxSpeed", elevatorMaxSpeed);
SmartDashboard.putBoolean("!limitSwitchElevatorTop",
!limitSwitchElevatorTop.get());
SmartDashboard.putBoolean("!limitSwitchElevatorBottom",
!limitSwitchElevatorBottom.get());
SmartDashboard.putBoolean("!limitSwitchElevatorOne",
!limitSwitchElevatorOne.get());
if (!limitSwitchElevatorOne.get() /*
* || !limitSwitchElevatorTwo.get() ||
* !limitSwitchElevatorThree.get()
*/) {
elevatorSpeed = 0;
}
if (stickAux.getRawButton(3)) {
elevatorSpeed = -elevatorMaxSpeed;
}
if (stickAux.getRawButton(2)) {
elevatorSpeed = elevatorMaxSpeed;
}
if (!limitSwitchElevatorTop.get() || !limitSwitchElevatorBottom.get()) {
elevatorSpeed = 0;
}
motorElevator.set(elevatorSpeed);
}
}
| Removed camera servo and test solenoid
| src/org/usfirst/frc/team1492/robot/Robot.java | Removed camera servo and test solenoid | <ide><path>rc/org/usfirst/frc/team1492/robot/Robot.java
<ide> import edu.wpi.first.wpilibj.Joystick;
<ide> import edu.wpi.first.wpilibj.Joystick.AxisType;
<ide> import edu.wpi.first.wpilibj.SampleRobot;
<del>import edu.wpi.first.wpilibj.Servo;
<del>import edu.wpi.first.wpilibj.Solenoid;
<ide> import edu.wpi.first.wpilibj.Talon;
<ide> import edu.wpi.first.wpilibj.Timer;
<ide> import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
<ide> Joystick stickLeft;
<ide> Joystick stickRight;
<ide> Joystick stickAux;
<del>
<del> Solenoid testSolenoid;
<del>
<del> Servo cameraServo;
<del> double cameraServoValue;
<ide>
<ide> DigitalInput limitSwitchElevatorTop;
<ide> DigitalInput limitSwitchElevatorBottom;
<ide> stickLeft = new Joystick(0);
<ide> stickRight = new Joystick(1);
<ide> stickAux = new Joystick(2);
<del>
<del> testSolenoid = new Solenoid(0);
<del>
<del> cameraServo = new Servo(7);
<ide>
<ide> limitSwitchElevatorBottom = new DigitalInput(0);
<ide> limitSwitchElevatorTop = new DigitalInput(1);
<ide>
<ide> public void manipulatorControl() {
<ide>
<del> testSolenoid.set(stickRight.getRawButton(1));
<del>
<del> if (stickRight.getRawButton(4)) {
<del> cameraServoValue -= .05;
<del> if (cameraServoValue < 0) {
<del> cameraServoValue = 0;
<del> }
<del> }
<del> if (stickRight.getRawButton(5)) {
<del> cameraServoValue += .05;
<del> if (cameraServoValue > 1) {
<del> cameraServoValue = 1;
<del> }
<del> }
<del>
<del> cameraServo.set(cameraServoValue);
<ide>
<ide> // elevator limit switches not edge ones
<ide> |
|
Java | mit | 559a1ce404edf6274e40a194146676fa1eb666ad | 0 | aistis-/numerical-methods | package tools;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Reader {
private ArrayList<String> fileData = new ArrayList<String>();
public Reader(String filePath) {
this.read(filePath); // read file data
}
public boolean read(String filePath) {
FileInputStream stream;
try {
stream = new FileInputStream(filePath);
} catch (FileNotFoundException e) {
return false;
}
Scanner scanner = new Scanner(stream);
System.out.println("Reading from file " + filePath);
while(scanner.hasNextLine()){
String line = scanner.nextLine();
if (0 < line.length()) {
this.fileData.add(line);
}
}
System.out.println("File read was successful");
scanner.close();
return true;
}
public String getLine(int line) {
return this.fileData.get(line - 1);
}
}
| src/tools/Reader.java | package tools;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Reader {
private ArrayList<String> fileData = new ArrayList<String>();
public Reader(String filePath) {
this.read(filePath); // read file data
}
public boolean read(String filePath) {
FileInputStream stream;
try {
stream = new FileInputStream(filePath);
} catch (FileNotFoundException e) {
return false;
}
Scanner scanner = new Scanner(stream);
System.out.println("Reading from file " + filePath + " started");
while(scanner.hasNextLine()){
String line = scanner.nextLine();
if (0 < line.length()) {
this.fileData.add(line);
}
}
scanner.close();
return true;
}
public String getLine(int line) {
return this.fileData.get(line - 1);
}
}
| Info message added
| src/tools/Reader.java | Info message added | <ide><path>rc/tools/Reader.java
<ide>
<ide> Scanner scanner = new Scanner(stream);
<ide>
<del> System.out.println("Reading from file " + filePath + " started");
<add> System.out.println("Reading from file " + filePath);
<ide>
<ide> while(scanner.hasNextLine()){
<ide> String line = scanner.nextLine();
<ide> this.fileData.add(line);
<ide> }
<ide> }
<add>
<add> System.out.println("File read was successful");
<ide>
<ide> scanner.close();
<ide> |
|
JavaScript | mit | 15304fe088e6dcf88dfdf8fd077722a92e4c9199 | 0 | machty/ember-concurrency,machty/ember-concurrency,machty/ember-concurrency,machty/ember-concurrency | import { scheduleOnce } from '@ember/runloop';
import { addObserver } from '@ember/object/observers';
import { addListener } from '@ember/object/events';
import EmberObject from '@ember/object';
import { getOwner } from '@ember/application';
import Ember from 'ember';
import {
default as TaskInstance,
getRunningInstance
} from './-task-instance';
import {
PERFORM_TYPE_DEFAULT,
PERFORM_TYPE_UNLINKED,
PERFORM_TYPE_LINKED
} from './-task-instance';
import TaskStateMixin from './-task-state-mixin';
import { TaskGroup } from './-task-group';
import {
propertyModifiers,
resolveScheduler
} from './-property-modifiers-mixin';
import {
objectAssign,
INVOKE,
_cleanupOnDestroy,
_ComputedProperty
} from './utils';
import EncapsulatedTask from './-encapsulated-task';
const PerformProxy = EmberObject.extend({
_task: null,
_performType: null,
_linkedObject: null,
perform(...args) {
return this._task._performShared(args, this._performType, this._linkedObject);
},
});
/**
The `Task` object lives on a host Ember object (e.g.
a Component, Route, or Controller). You call the
{@linkcode Task#perform .perform()} method on this object
to create run individual {@linkcode TaskInstance}s,
and at any point, you can call the {@linkcode Task#cancelAll .cancelAll()}
method on this object to cancel all running or enqueued
{@linkcode TaskInstance}s.
<style>
.ignore-this--this-is-here-to-hide-constructor,
#Task{ display: none }
</style>
@class Task
*/
export const Task = EmberObject.extend(TaskStateMixin, {
/**
* `true` if any current task instances are running.
*
* @memberof Task
* @member {boolean} isRunning
* @instance
* @readOnly
*/
/**
* `true` if any future task instances are queued.
*
* @memberof Task
* @member {boolean} isQueued
* @instance
* @readOnly
*/
/**
* `true` if the task is not in the running or queued state.
*
* @memberof Task
* @member {boolean} isIdle
* @instance
* @readOnly
*/
/**
* The current state of the task: `"running"`, `"queued"` or `"idle"`.
*
* @memberof Task
* @member {string} state
* @instance
* @readOnly
*/
/**
* The most recently started task instance.
*
* @memberof Task
* @member {TaskInstance} last
* @instance
* @readOnly
*/
/**
* The most recent task instance that is currently running.
*
* @memberof Task
* @member {TaskInstance} lastRunning
* @instance
* @readOnly
*/
/**
* The most recently performed task instance.
*
* @memberof Task
* @member {TaskInstance} lastPerformed
* @instance
* @readOnly
*/
/**
* The most recent task instance that succeeded.
*
* @memberof Task
* @member {TaskInstance} lastSuccessful
* @instance
* @readOnly
*/
/**
* The most recently completed task instance.
*
* @memberof Task
* @member {TaskInstance} lastComplete
* @instance
* @readOnly
*/
/**
* The most recent task instance that errored.
*
* @memberof Task
* @member {TaskInstance} lastErrored
* @instance
* @readOnly
*/
/**
* The most recently canceled task instance.
*
* @memberof Task
* @member {TaskInstance} lastCanceled
* @instance
* @readOnly
*/
/**
* The most recent task instance that is incomplete.
*
* @memberof Task
* @member {TaskInstance} lastIncomplete
* @instance
* @readOnly
*/
/**
* The number of times this task has been performed.
*
* @memberof Task
* @member {number} performCount
* @instance
* @readOnly
*/
fn: null,
context: null,
_observes: null,
_curryArgs: null,
_linkedObjects: null,
init() {
this._super(...arguments);
if (typeof this.fn === 'object') {
let owner = getOwner(this.context);
let ownerInjection = owner ? owner.ownerInjection() : {};
this._taskInstanceFactory = EncapsulatedTask.extend(ownerInjection, this.fn);
}
_cleanupOnDestroy(this.context, this, 'cancelAll', 'the object it lives on was destroyed or unrendered');
},
_curry(...args) {
let task = this._clone();
task._curryArgs = [...(this._curryArgs || []), ...args];
return task;
},
linked() {
let taskInstance = getRunningInstance();
if (!taskInstance) {
throw new Error(`You can only call .linked() from within a task.`);
}
return PerformProxy.create({
_task: this,
_performType: PERFORM_TYPE_LINKED,
_linkedObject: taskInstance,
});
},
unlinked() {
return PerformProxy.create({
_task: this,
_performType: PERFORM_TYPE_UNLINKED,
});
},
_clone() {
return Task.create({
fn: this.fn,
context: this.context,
_origin: this._origin,
_taskGroupPath: this._taskGroupPath,
_scheduler: this._scheduler,
_propertyName: this._propertyName,
});
},
/**
* This property is true if this task is NOT running, i.e. the number
* of currently running TaskInstances is zero.
*
* This property is useful for driving the state/style of buttons
* and loading UI, among other things.
*
* @memberof Task
* @instance
* @readOnly
*/
/**
* This property is true if this task is running, i.e. the number
* of currently running TaskInstances is greater than zero.
*
* This property is useful for driving the state/style of buttons
* and loading UI, among other things.
*
* @memberof Task
* @instance
* @readOnly
*/
/**
* EXPERIMENTAL
*
* This value describes what would happen to the TaskInstance returned
* from .perform() if .perform() were called right now. Returns one of
* the following values:
*
* - `succeed`: new TaskInstance will start running immediately
* - `drop`: new TaskInstance will be dropped
* - `enqueue`: new TaskInstance will be enqueued for later execution
*
* @memberof Task
* @instance
* @private
* @readOnly
*/
/**
* EXPERIMENTAL
*
* Returns true if calling .perform() right now would immediately start running
* the returned TaskInstance.
*
* @memberof Task
* @instance
* @private
* @readOnly
*/
/**
* EXPERIMENTAL
*
* Returns true if calling .perform() right now would immediately cancel (drop)
* the returned TaskInstance.
*
* @memberof Task
* @instance
* @private
* @readOnly
*/
/**
* EXPERIMENTAL
*
* Returns true if calling .perform() right now would enqueue the TaskInstance
* rather than execute immediately.
*
* @memberof Task
* @instance
* @private
* @readOnly
*/
/**
* EXPERIMENTAL
*
* Returns true if calling .perform() right now would cause a previous task to be canceled
*
* @memberof Task
* @instance
* @private
* @readOnly
*/
/**
* The current number of active running task instances. This
* number will never exceed maxConcurrency.
*
* @memberof Task
* @instance
* @readOnly
*/
/**
* Cancels all running or queued `TaskInstance`s for this Task.
* If you're trying to cancel a specific TaskInstance (rather
* than all of the instances running under this task) call
* `.cancel()` on the specific TaskInstance.
*
* @method cancelAll
* @memberof Task
* @instance
*/
toString() {
return `<Task:${this._propertyName}>`;
},
_taskInstanceFactory: TaskInstance,
/**
* Creates a new {@linkcode TaskInstance} and attempts to run it right away.
* If running this task instance would increase the task's concurrency
* to a number greater than the task's maxConcurrency, this task
* instance might be immediately canceled (dropped), or enqueued
* to run at later time, after the currently running task(s) have finished.
*
* @method perform
* @memberof Task
* @param {*} arg* - args to pass to the task function
* @instance
*
* @fires TaskInstance#TASK_NAME:started
* @fires TaskInstance#TASK_NAME:succeeded
* @fires TaskInstance#TASK_NAME:errored
* @fires TaskInstance#TASK_NAME:canceled
*
*/
perform(...args) {
return this._performShared(args, PERFORM_TYPE_DEFAULT, null);
},
_performShared(args, performType, linkedObject) {
let fullArgs = this._curryArgs ? [...this._curryArgs, ...args] : args;
let taskInstance = this._taskInstanceFactory.create({
fn: this.fn,
args: fullArgs,
context: this.context,
owner: this.context,
task: this,
_debug: this._debug,
_hasEnabledEvents: this._hasEnabledEvents,
_origin: this,
_performType: performType,
});
if (performType === PERFORM_TYPE_LINKED) {
linkedObject._expectsLinkedYield = true;
}
if (this.context.isDestroying) {
// TODO: express this in terms of lifetimes; a task linked to
// a dead lifetime should immediately cancel.
taskInstance.cancel();
}
this._scheduler.schedule(taskInstance);
return taskInstance;
},
[INVOKE](...args) {
return this.perform(...args);
},
});
/**
A {@link TaskProperty} is the Computed Property-like object returned
from the {@linkcode task} function. You can call Task Modifier methods
on this object to configure the behavior of the {@link Task}.
See [Managing Task Concurrency](/#/docs/task-concurrency) for an
overview of all the different task modifiers you can use and how
they impact automatic cancelation / enqueueing of task instances.
<style>
.ignore-this--this-is-here-to-hide-constructor,
#TaskProperty { display: none }
</style>
@class TaskProperty
*/
export function TaskProperty(taskFn) {
let tp = this;
_ComputedProperty.call(this, function(_propertyName) {
taskFn.displayName = `${_propertyName} (task)`;
return Task.create({
fn: tp.taskFn,
context: this,
_origin: this,
_taskGroupPath: tp._taskGroupPath,
_scheduler: resolveScheduler(tp, this, TaskGroup),
_propertyName,
_debug: tp._debug,
_hasEnabledEvents: tp._hasEnabledEvents
});
});
this.taskFn = taskFn;
this.eventNames = null;
this.cancelEventNames = null;
this._observes = null;
}
TaskProperty.prototype = Object.create(_ComputedProperty.prototype);
objectAssign(TaskProperty.prototype, propertyModifiers, {
constructor: TaskProperty,
setup(proto, taskName) {
if (this._maxConcurrency !== Infinity && !this._hasSetBufferPolicy) {
Ember.Logger.warn(`The use of maxConcurrency() without a specified task modifier is deprecated and won't be supported in future versions of ember-concurrency. Please specify a task modifier instead, e.g. \`${taskName}: task(...).enqueue().maxConcurrency(${this._maxConcurrency})\``);
}
registerOnPrototype(addListener, proto, this.eventNames, taskName, 'perform', false);
registerOnPrototype(addListener, proto, this.cancelEventNames, taskName, 'cancelAll', false);
registerOnPrototype(addObserver, proto, this._observes, taskName, 'perform', true);
},
/**
* Calling `task(...).on(eventName)` configures the task to be
* automatically performed when the specified events fire. In
* this way, it behaves like
* [Ember.on](http://emberjs.com/api/classes/Ember.html#method_on).
*
* You can use `task(...).on('init')` to perform the task
* when the host object is initialized.
*
* ```js
* export default Ember.Component.extend({
* pollForUpdates: task(function * () {
* // ... this runs when the Component is first created
* // because we specified .on('init')
* }).on('init'),
*
* handleFoo: task(function * (a, b, c) {
* // this gets performed automatically if the 'foo'
* // event fires on this Component,
* // e.g., if someone called component.trigger('foo')
* }).on('foo'),
* });
* ```
*
* [See the Writing Tasks Docs for more info](/#/docs/writing-tasks)
*
* @method on
* @memberof TaskProperty
* @param {String} eventNames*
* @instance
*/
on() {
this.eventNames = this.eventNames || [];
this.eventNames.push.apply(this.eventNames, arguments);
return this;
},
/**
* This behaves like the {@linkcode TaskProperty#on task(...).on() modifier},
* but instead will cause the task to be canceled if any of the
* specified events fire on the parent object.
*
* [See the Live Example](/#/docs/examples/route-tasks/1)
*
* @method cancelOn
* @memberof TaskProperty
* @param {String} eventNames*
* @instance
*/
cancelOn() {
this.cancelEventNames = this.cancelEventNames || [];
this.cancelEventNames.push.apply(this.cancelEventNames, arguments);
return this;
},
observes(...properties) {
this._observes = properties;
return this;
},
/**
* Configures the task to cancel old currently task instances
* to make room for a new one to perform. Sets default
* maxConcurrency to 1.
*
* [See the Live Example](/#/docs/examples/route-tasks/1)
*
* @method restartable
* @memberof TaskProperty
* @instance
*/
/**
* Configures the task to run task instances one-at-a-time in
* the order they were `.perform()`ed. Sets default
* maxConcurrency to 1.
*
* @method enqueue
* @memberof TaskProperty
* @instance
*/
/**
* Configures the task to immediately cancel (i.e. drop) any
* task instances performed when the task is already running
* at maxConcurrency. Sets default maxConcurrency to 1.
*
* @method drop
* @memberof TaskProperty
* @instance
*/
/**
* Configures the task to drop all but the most recently
* performed {@linkcode TaskInstance }.
*
* @method keepLatest
* @memberof TaskProperty
* @instance
*/
/**
* Sets the maximum number of task instances that are allowed
* to run at the same time. By default, with no task modifiers
* applied, this number is Infinity (there is no limit
* to the number of tasks that can run at the same time).
* {@linkcode TaskProperty#restartable .restartable()},
* {@linkcode TaskProperty#enqueue .enqueue()}, and
* {@linkcode TaskProperty#drop .drop()} set the default
* maxConcurrency to 1, but you can override this value
* to set the maximum number of concurrently running tasks
* to a number greater than 1.
*
* [See the AJAX Throttling example](/#/docs/examples/ajax-throttling)
*
* The example below uses a task with `maxConcurrency(3)` to limit
* the number of concurrent AJAX requests (for anyone using this task)
* to 3.
*
* ```js
* doSomeAjax: task(function * (url) {
* return Ember.$.getJSON(url).promise();
* }).maxConcurrency(3),
*
* elsewhere() {
* this.get('doSomeAjax').perform("http://www.example.com/json");
* },
* ```
*
* @method maxConcurrency
* @memberof TaskProperty
* @param {Number} n The maximum number of concurrently running tasks
* @instance
*/
/**
* Adds this task to a TaskGroup so that concurrency constraints
* can be shared between multiple tasks.
*
* [See the Task Group docs for more information](/#/docs/task-groups)
*
* @method group
* @memberof TaskProperty
* @param {String} groupPath A path to the TaskGroup property
* @instance
*/
/**
* Activates lifecycle events, allowing Evented host objects to react to task state
* changes.
*
* ```js
* export default Component.extend({
* uploadTask: task(function* (file) {
* // ... file upload stuff
* }).drop(),
*
* uploadedStarted: on('uploadTask:started', function(taskInstance) {
* this.get('analytics').track("User Photo: upload started");
* }),
* });
* ```
*
* @method evented
* @memberof TaskProperty
* @instance
*/
/**
* Logs lifecycle events to aid in debugging unexpected Task behavior.
* Presently only logs cancelation events and the reason for the cancelation,
* e.g. "TaskInstance 'doStuff' was canceled because the object it lives on was destroyed or unrendered"
*
* @method debug
* @memberof TaskProperty
* @instance
*/
perform() {
throw new Error("It looks like you tried to perform a task via `this.nameOfTask.perform()`, which isn't supported. Use `this.get('nameOfTask').perform()` instead.");
},
});
function registerOnPrototype(addListenerOrObserver, proto, names, taskName, taskMethod, once) {
if (names) {
for (let i = 0; i < names.length; ++i) {
let name = names[i];
addListenerOrObserver(proto, name, null, makeTaskCallback(taskName, taskMethod, once));
}
}
}
function makeTaskCallback(taskName, method, once) {
return function() {
let task = this.get(taskName);
if (once) {
scheduleOnce('actions', task, method, ...arguments);
} else {
task[method].apply(task, arguments);
}
};
}
| addon/-task-property.js | import { scheduleOnce } from '@ember/runloop';
import { addObserver } from '@ember/object/observers';
import { addListener } from '@ember/object/events';
import EmberObject from '@ember/object';
import { getOwner } from '@ember/application';
import Ember from 'ember';
import {
default as TaskInstance,
getRunningInstance
} from './-task-instance';
import {
PERFORM_TYPE_DEFAULT,
PERFORM_TYPE_UNLINKED,
PERFORM_TYPE_LINKED
} from './-task-instance';
import TaskStateMixin from './-task-state-mixin';
import { TaskGroup } from './-task-group';
import {
propertyModifiers,
resolveScheduler
} from './-property-modifiers-mixin';
import {
objectAssign,
INVOKE,
_cleanupOnDestroy,
_ComputedProperty
} from './utils';
import EncapsulatedTask from './-encapsulated-task';
const PerformProxy = EmberObject.extend({
_task: null,
_performType: null,
_linkedObject: null,
perform(...args) {
return this._task._performShared(args, this._performType, this._linkedObject);
},
});
/**
The `Task` object lives on a host Ember object (e.g.
a Component, Route, or Controller). You call the
{@linkcode Task#perform .perform()} method on this object
to create run individual {@linkcode TaskInstance}s,
and at any point, you can call the {@linkcode Task#cancelAll .cancelAll()}
method on this object to cancel all running or enqueued
{@linkcode TaskInstance}s.
<style>
.ignore-this--this-is-here-to-hide-constructor,
#Task{ display: none }
</style>
@class Task
*/
export const Task = EmberObject.extend(TaskStateMixin, {
/**
* `true` if any current task instances are running.
*
* @memberof Task
* @member {boolean} isRunning
* @instance
* @readOnly
*/
/**
* `true` if any future task instances are queued.
*
* @memberof Task
* @member {boolean} isQueued
* @instance
* @readOnly
*/
/**
* `true` if the task is not in the running or queued state.
*
* @memberof Task
* @member {boolean} isIdle
* @instance
* @readOnly
*/
/**
* The current state of the task: `"running"`, `"queued"` or `"idle"`.
*
* @memberof Task
* @member {string} state
* @instance
* @readOnly
*/
/**
* The most recently started task instance.
*
* @memberof Task
* @member {TaskInstance} last
* @instance
* @readOnly
*/
/**
* The most recent task instance that is currently running.
*
* @memberof Task
* @member {TaskInstance} lastRunning
* @instance
* @readOnly
*/
/**
* The most recently performed task instance.
*
* @memberof Task
* @member {TaskInstance} lastPerformed
* @instance
* @readOnly
*/
/**
* The most recent task instance that succeeded.
*
* @memberof Task
* @member {TaskInstance} lastSuccessful
* @instance
* @readOnly
*/
/**
* The most recently completed task instance.
*
* @memberof Task
* @member {TaskInstance} lastComplete
* @instance
* @readOnly
*/
/**
* The most recent task instance that errored.
*
* @memberof Task
* @member {TaskInstance} lastErrored
* @instance
* @readOnly
*/
/**
* The most recently canceled task instance.
*
* @memberof Task
* @member {TaskInstance} lastCanceled
* @instance
* @readOnly
*/
/**
* The most recent task instance that is incomplete.
*
* @memberof Task
* @member {TaskInstance} lastIncomplete
* @instance
* @readOnly
*/
/**
* The number of times this task has been performed.
*
* @memberof Task
* @member {number} performCount
* @instance
* @readOnly
*/
fn: null,
context: null,
_observes: null,
_curryArgs: null,
_linkedObjects: null,
init() {
this._super(...arguments);
if (typeof this.fn === 'object') {
let owner = getOwner(this.context);
let ownerInjection = owner ? owner.ownerInjection() : {};
this._taskInstanceFactory = EncapsulatedTask.extend(ownerInjection, this.fn);
}
_cleanupOnDestroy(this.context, this, 'cancelAll', 'the object it lives on was destroyed or unrendered');
},
_curry(...args) {
let task = this._clone();
task._curryArgs = [...(this._curryArgs || []), ...args];
return task;
},
linked() {
let taskInstance = getRunningInstance();
if (!taskInstance) {
throw new Error(`You can only call .linked() from within a task.`);
}
return PerformProxy.create({
_task: this,
_performType: PERFORM_TYPE_LINKED,
_linkedObject: taskInstance,
});
},
unlinked() {
return PerformProxy.create({
_task: this,
_performType: PERFORM_TYPE_UNLINKED,
});
},
_clone() {
return Task.create({
fn: this.fn,
context: this.context,
_origin: this._origin,
_taskGroupPath: this._taskGroupPath,
_scheduler: this._scheduler,
_propertyName: this._propertyName,
});
},
/**
* This property is true if this task is NOT running, i.e. the number
* of currently running TaskInstances is zero.
*
* This property is useful for driving the state/style of buttons
* and loading UI, among other things.
*
* @memberof Task
* @instance
* @readOnly
*/
/**
* This property is true if this task is running, i.e. the number
* of currently running TaskInstances is greater than zero.
*
* This property is useful for driving the state/style of buttons
* and loading UI, among other things.
*
* @memberof Task
* @instance
* @readOnly
*/
/**
* EXPERIMENTAL
*
* This value describes what would happen to the TaskInstance returned
* from .perform() if .perform() were called right now. Returns one of
* the following values:
*
* - `succeed`: new TaskInstance will start running immediately
* - `drop`: new TaskInstance will be dropped
* - `enqueue`: new TaskInstance will be enqueued for later execution
*
* @memberof Task
* @instance
* @private
* @readOnly
*/
/**
* EXPERIMENTAL
*
* Returns true if calling .perform() right now would immediately start running
* the returned TaskInstance.
*
* @memberof Task
* @instance
* @private
* @readOnly
*/
/**
* EXPERIMENTAL
*
* Returns true if calling .perform() right now would immediately cancel (drop)
* the returned TaskInstance.
*
* @memberof Task
* @instance
* @private
* @readOnly
*/
/**
* EXPERIMENTAL
*
* Returns true if calling .perform() right now would enqueue the TaskInstance
* rather than execute immediately.
*
* @memberof Task
* @instance
* @private
* @readOnly
*/
/**
* EXPERIMENTAL
*
* Returns true if calling .perform() right now would cause a previous task to be canceled
*
* @memberof Task
* @instance
* @private
* @readOnly
*/
/**
* The current number of active running task instances. This
* number will never exceed maxConcurrency.
*
* @memberof Task
* @instance
* @readOnly
*/
/**
* Cancels all running or queued `TaskInstance`s for this Task.
* If you're trying to cancel a specific TaskInstance (rather
* than all of the instances running under this task) call
* `.cancel()` on the specific TaskInstance.
*
* @method cancelAll
* @memberof Task
* @instance
*/
toString() {
return `<Task:${this._propertyName}>`;
},
_taskInstanceFactory: TaskInstance,
/**
* Creates a new {@linkcode TaskInstance} and attempts to run it right away.
* If running this task instance would increase the task's concurrency
* to a number greater than the task's maxConcurrency, this task
* instance might be immediately canceled (dropped), or enqueued
* to run at later time, after the currently running task(s) have finished.
*
* @method perform
* @memberof Task
* @param {*} arg* - args to pass to the task function
* @instance
*
* @fires TaskInstance#TASK_NAME:started
* @fires TaskInstance#TASK_NAME:succeeded
* @fires TaskInstance#TASK_NAME:errored
* @fires TaskInstance#TASK_NAME:canceled
*
*/
perform(...args) {
return this._performShared(args, PERFORM_TYPE_DEFAULT, null);
},
_performShared(args, performType, linkedObject) {
let fullArgs = this._curryArgs ? [...this._curryArgs, ...args] : args;
let taskInstance = this._taskInstanceFactory.create({
fn: this.fn,
args: fullArgs,
context: this.context,
owner: this.context,
task: this,
_debug: this._debug,
_hasEnabledEvents: this._hasEnabledEvents,
_origin: this,
_performType: performType,
});
if (performType === PERFORM_TYPE_LINKED) {
linkedObject._expectsLinkedYield = true;
}
if (this.context.isDestroying) {
// TODO: express this in terms of lifetimes; a task linked to
// a dead lifetime should immediately cancel.
taskInstance.cancel();
}
this._scheduler.schedule(taskInstance);
return taskInstance;
},
[INVOKE](...args) {
return this.perform(...args);
},
});
/**
A {@link TaskProperty} is the Computed Property-like object returned
from the {@linkcode task} function. You can call Task Modifier methods
on this object to configure the behavior of the {@link Task}.
See [Managing Task Concurrency](/#/docs/task-concurrency) for an
overview of all the different task modifiers you can use and how
they impact automatic cancelation / enqueueing of task instances.
<style>
.ignore-this--this-is-here-to-hide-constructor,
#TaskProperty { display: none }
</style>
@class TaskProperty
*/
export function TaskProperty(taskFn) {
let tp = this;
_ComputedProperty.call(this, function(_propertyName) {
taskFn.displayName = `${_propertyName} (task)`;
return Task.create({
fn: tp.taskFn,
context: this,
_origin: this,
_taskGroupPath: tp._taskGroupPath,
_scheduler: resolveScheduler(tp, this, TaskGroup),
_propertyName,
_debug: tp._debug,
_hasEnabledEvents: tp._hasEnabledEvents
});
});
this.taskFn = taskFn;
this.eventNames = null;
this.cancelEventNames = null;
this._observes = null;
}
TaskProperty.prototype = Object.create(_ComputedProperty.prototype);
objectAssign(TaskProperty.prototype, propertyModifiers, {
constructor: TaskProperty,
setup(proto, taskName) {
if (this._maxConcurrency !== Infinity && !this._hasSetBufferPolicy) {
Ember.Logger.warn(`The use of maxConcurrency() without a specified task modifier is deprecated and won't be supported in future versions of ember-concurrency. Please specify a task modifier instead, e.g. \`${taskName}: task(...).enqueue().maxConcurrency(${this._maxConcurrency})\``);
}
registerOnPrototype(addListener, proto, this.eventNames, taskName, 'perform', false);
registerOnPrototype(addListener, proto, this.cancelEventNames, taskName, 'cancelAll', false);
registerOnPrototype(addObserver, proto, this._observes, taskName, 'perform', true);
},
/**
* Calling `task(...).on(eventName)` configures the task to be
* automatically performed when the specified events fire. In
* this way, it behaves like
* [Ember.on](http://emberjs.com/api/classes/Ember.html#method_on).
*
* You can use `task(...).on('init')` to perform the task
* when the host object is initialized.
*
* ```js
* export default Ember.Component.extend({
* pollForUpdates: task(function * () {
* // ... this runs when the Component is first created
* // because we specified .on('init')
* }).on('init'),
*
* handleFoo: task(function * (a, b, c) {
* // this gets performed automatically if the 'foo'
* // event fires on this Component,
* // e.g., if someone called component.trigger('foo')
* }).on('foo'),
* });
* ```
*
* [See the Writing Tasks Docs for more info](/#/docs/writing-tasks)
*
* @method on
* @memberof TaskProperty
* @param {String} eventNames*
* @instance
*/
on() {
this.eventNames = this.eventNames || [];
this.eventNames.push.apply(this.eventNames, arguments);
return this;
},
/**
* This behaves like the {@linkcode TaskProperty#on task(...).on() modifier},
* but instead will cause the task to be canceled if any of the
* specified events fire on the parent object.
*
* [See the Live Example](/#/docs/examples/route-tasks/1)
*
* @method cancelOn
* @memberof TaskProperty
* @param {String} eventNames*
* @instance
*/
cancelOn() {
this.cancelEventNames = this.cancelEventNames || [];
this.cancelEventNames.push.apply(this.cancelEventNames, arguments);
return this;
},
observes(...properties) {
this._observes = properties;
return this;
},
/**
* Configures the task to cancel old currently task instances
* to make room for a new one to perform. Sets default
* maxConcurrency to 1.
*
* [See the Live Example](/#/docs/examples/route-tasks/1)
*
* @method restartable
* @memberof TaskProperty
* @instance
*/
/**
* Configures the task to run task instances one-at-a-time in
* the order they were `.perform()`ed. Sets default
* maxConcurrency to 1.
*
* @method enqueue
* @memberof TaskProperty
* @instance
*/
/**
* Configures the task to immediately cancel (i.e. drop) any
* task instances performed when the task is already running
* at maxConcurrency. Sets default maxConcurrency to 1.
*
* @method drop
* @memberof TaskProperty
* @instance
*/
/**
* Configures the task to drop all but the most recently
* performed {@linkcode TaskInstance }.
*
* @method keepLatest
* @memberof TaskProperty
* @instance
*/
/**
* Sets the maximum number of task instances that are allowed
* to run at the same time. By default, with no task modifiers
* applied, this number is Infinity (there is no limit
* to the number of tasks that can run at the same time).
* {@linkcode TaskProperty#restartable .restartable()},
* {@linkcode TaskProperty#enqueue .enqueue()}, and
* {@linkcode TaskProperty#drop .drop()} set the default
* maxConcurrency to 1, but you can override this value
* to set the maximum number of concurrently running tasks
* to a number greater than 1.
*
* [See the AJAX Throttling example](/#/docs/examples/ajax-throttling)
*
* The example below uses a task with `maxConcurrency(3)` to limit
* the number of concurrent AJAX requests (for anyone using this task)
* to 3.
*
* ```js
* doSomeAjax: task(function * (url) {
* return Ember.$.getJSON(url).promise();
* }).maxConcurrency(3),
*
* elsewhere() {
* this.get('doSomeAjax').perform("http://www.example.com/json");
* },
* ```
*
* @method maxConcurrency
* @memberof TaskProperty
* @param {Number} n The maximum number of concurrently running tasks
* @instance
*/
/**
* Adds this task to a TaskGroup so that concurrency constraints
* can be shared between multiple tasks.
*
* [See the Task Group docs for more information](/#/docs/task-groups)
*
* @method group
* @memberof TaskProperty
* @param {String} groupPath A path to the TaskGroup property
* @instance
*/
/**
* Logs lifecycle events to aid in debugging unexpected Task behavior.
* Presently only logs cancelation events and the reason for the cancelation,
* e.g. "TaskInstance 'doStuff' was canceled because the object it lives on was destroyed or unrendered"
*
* @method debug
* @memberof TaskProperty
* @instance
*/
perform() {
throw new Error("It looks like you tried to perform a task via `this.nameOfTask.perform()`, which isn't supported. Use `this.get('nameOfTask').perform()` instead.");
},
});
function registerOnPrototype(addListenerOrObserver, proto, names, taskName, taskMethod, once) {
if (names) {
for (let i = 0; i < names.length; ++i) {
let name = names[i];
addListenerOrObserver(proto, name, null, makeTaskCallback(taskName, taskMethod, once));
}
}
}
function makeTaskCallback(taskName, method, once) {
return function() {
let task = this.get(taskName);
if (once) {
scheduleOnce('actions', task, method, ...arguments);
} else {
task[method].apply(task, arguments);
}
};
}
| Add missing doc reference for `evented()` modifier (#228)
| addon/-task-property.js | Add missing doc reference for `evented()` modifier (#228) | <ide><path>ddon/-task-property.js
<ide> */
<ide>
<ide> /**
<add> * Activates lifecycle events, allowing Evented host objects to react to task state
<add> * changes.
<add> *
<add> * ```js
<add> * export default Component.extend({
<add> * uploadTask: task(function* (file) {
<add> * // ... file upload stuff
<add> * }).drop(),
<add> *
<add> * uploadedStarted: on('uploadTask:started', function(taskInstance) {
<add> * this.get('analytics').track("User Photo: upload started");
<add> * }),
<add> * });
<add> * ```
<add> *
<add> * @method evented
<add> * @memberof TaskProperty
<add> * @instance
<add> */
<add>
<add> /**
<ide> * Logs lifecycle events to aid in debugging unexpected Task behavior.
<ide> * Presently only logs cancelation events and the reason for the cancelation,
<ide> * e.g. "TaskInstance 'doStuff' was canceled because the object it lives on was destroyed or unrendered" |
|
Java | apache-2.0 | a55eb068616ef4b6801c2ac7970694f71f7fcf0b | 0 | ChiralBehaviors/Kramer,ChiralBehaviors/Kramer | /**
* Copyright (c) 2016 Chiral Behaviors, LLC, all rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.chiralbehaviors.layout.schema;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import com.chiralbehaviors.layout.Layout;
import com.chiralbehaviors.layout.RelationTableRow;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import javafx.collections.ObservableList;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.Control;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.util.Pair;
/**
* @author hhildebrand
*
*/
public class Relation extends SchemaNode {
private boolean autoFold = true;
private int averageCardinality = 1;
private final List<SchemaNode> children = new ArrayList<>();
private final List<ColumnSet> columnSets = new ArrayList<>();
private Relation fold;
private double outlineWidth = 0;
private double tableColumnWidth = 0;
private boolean useTable = false;
public Relation(String label) {
super(label);
}
public void addChild(SchemaNode child) {
children.add(child);
}
public void autoLayout(int cardinality, Layout layout, double width) {
double snapped = Layout.snap(width);
layout(cardinality, layout, snapped);
compress(layout, snapped);
}
public Control buildControl(int cardinality, Layout layout, double width) {
if (isFold()) {
return fold.buildControl(averageCardinality * cardinality, layout,
width);
}
return useTable ? buildNestedTable(n -> n, cardinality, layout, width)
: buildOutline(cellHeight(layout, width), n -> n,
cardinality, layout);
}
@Override
public JsonNode extractFrom(JsonNode jsonNode) {
if (isFold()) {
return fold.extractFrom(super.extractFrom(jsonNode));
}
return super.extractFrom(jsonNode);
}
public int getAverageCardinality() {
return averageCardinality;
}
public SchemaNode getChild(String field) {
for (SchemaNode child : children) {
if (child.getField()
.equals(field)) {
return child;
}
}
return null;
}
public List<SchemaNode> getChildren() {
return children;
}
@Override
public double getLabelWidth(Layout layout) {
if (isFold()) {
return fold.getLabelWidth(layout);
}
return layout.textWidth(label);
}
@JsonProperty
public boolean isFold() {
return fold != null;
}
@Override
public boolean isRelation() {
return true;
}
@Override
public boolean isUseTable() {
if (isFold()) {
return fold.isUseTable();
}
return useTable;
}
public void measure(JsonNode jsonNode, Layout layout) {
if (jsonNode.isArray()) {
ArrayNode array = (ArrayNode) jsonNode;
measure(array, layout, INDENT.NONE);
} else {
ArrayNode singleton = JsonNodeFactory.instance.arrayNode();
singleton.add(jsonNode);
measure(singleton, layout, INDENT.NONE);
}
}
public void setAverageCardinality(int averageCardinality) {
this.averageCardinality = averageCardinality;
}
public void setFold(boolean fold) {
this.fold = (fold && children.size() == 1 && children.get(0)
.isRelation()) ? (Relation) children.get(0)
: null;
}
@Override
public void setItems(Control control, JsonNode data, Layout layout) {
if (data == null) {
data = JsonNodeFactory.instance.arrayNode();
}
if (isFold()) {
fold.setItems(control, flatten(data), layout);
} else {
super.setItems(control, data, layout);
}
}
public void setUseTable(boolean useTable) {
this.useTable = useTable;
}
@Override
public String toString() {
return toString(0);
}
@Override
public String toString(int indent) {
StringBuffer buf = new StringBuffer();
buf.append(String.format("Relation [%s:%.2f x %s]", label,
tableColumnWidth, averageCardinality));
buf.append('\n');
children.forEach(c -> {
for (int i = 0; i < indent; i++) {
buf.append(" ");
}
buf.append(" - ");
buf.append(c.toString(indent + 1));
buf.append('\n');
});
return buf.toString();
}
@Override
Function<Double, Pair<Consumer<JsonNode>, Control>> buildColumn(int cardinality,
Function<JsonNode, JsonNode> extractor,
Map<SchemaNode, TableColumn<JsonNode, ?>> columnMap,
Layout layout,
double inset,
INDENT indent,
double justified) {
return buildColumn(cardinality, extractor, columnMap, layout, inset,
indent, false, justified);
}
@Override
TableColumn<JsonNode, JsonNode> buildColumn(Layout layout, double inset,
INDENT indent,
double justified) {
if (isFold()) {
return fold.buildColumn(layout, inset, indent, justified);
}
TableColumn<JsonNode, JsonNode> column = super.buildColumn(layout,
inset,
indent,
justified);
column.setPrefWidth(justified);
ObservableList<TableColumn<JsonNode, ?>> columns = column.getColumns();
children.forEach(child -> columns.add(child.buildColumn(layout,
inset(layout,
inset,
child,
indent),
indent(child),
justified)));
return column;
}
@Override
double cellHeight(Layout layout, double width) {
if (isFold()) {
return fold.cellHeight(layout, width);
}
if (!useTable) {
return (averageCardinality * (columnSets.stream()
.mapToDouble(cs -> cs.getCellHeight())
.sum()
+ layout.getListCellVerticalInset()))
+ layout.getListVerticalInset();
}
TableView<JsonNode> table = tableBase();
children.forEach(child -> {
INDENT indent = indent(child);
table.getColumns()
.add(child.buildColumn(layout, inset(layout, 0, child, indent),
indent, width));
});
return (averageCardinality * (rowHeight(layout, width)
+ layout.getTableRowVerticalInset()))
+ layout.measureHeader(table) + layout.getTableVerticalInset();
}
@Override
void compress(Layout layout, double justified) {
if (isFold()) {
fold.compress(layout, justified);
return;
}
if (useTable) {
return;
}
double available = justified - layout.getListCellHorizontalInset()
- layout.getListHorizontalInset();
double labelWidth = children.stream()
.mapToDouble(n -> n.getLabelWidth(layout))
.max()
.orElse(0);
columnSets.clear();
ColumnSet current = null;
double halfWidth = available / 2d;
for (SchemaNode child : children) {
double childWidth = labelWidth + child.layoutWidth(layout);
if (childWidth > halfWidth || current == null) {
current = new ColumnSet(labelWidth);
columnSets.add(current);
current.add(child);
if (childWidth > halfWidth) {
current = null;
}
} else {
current.add(child);
}
}
columnSets.forEach(cs -> cs.compress(layout, available));
}
// for testing
List<ColumnSet> getColumnSets() {
return columnSets;
}
@Override
double layout(int cardinality, Layout layout, double width) {
if (isFold()) {
return fold.layout(cardinality, layout, width);
}
useTable = false;
double labelWidth = children.stream()
.mapToDouble(child -> child.getLabelWidth(layout))
.max()
.getAsDouble();
double available = width - labelWidth
- layout.getListCellHorizontalInset();
outlineWidth = children.stream()
.mapToDouble(child -> {
return child.layout(cardinality, layout,
available);
})
.max()
.orElse(0d)
+ labelWidth;
double tableWidth = tableColumnWidth + layout.getTableHorizontalInset()
+ layout.getTableRowHorizontalInset();
double oWidth = outlineWidth + layout.getListCellHorizontalInset()
+ layout.getListHorizontalInset();
if (tableWidth <= oWidth) {
nestTable();
return tableWidth;
}
return oWidth;
}
/* (non-Javadoc)
* @see com.chiralbehaviors.layout.schema.SchemaNode#layoutWidth(com.chiralbehaviors.layout.Layout)
*/
@Override
double layoutWidth(Layout layout) {
return useTable ? tableColumnWidth + layout.getTableRowHorizontalInset()
+ layout.getTableHorizontalInset()
: outlineWidth + layout.getListCellHorizontalInset()
+ layout.getListHorizontalInset();
}
@Override
double measure(ArrayNode data, Layout layout, INDENT indent) {
if (isAutoFoldable()) {
fold = ((Relation) children.get(children.size() - 1));
}
if (data.isNull() || children.size() == 0) {
return 0;
}
double labelWidth = layout.textWidth(label);
labelWidth += layout.getTextHorizontalInset();
double sum = 0;
tableColumnWidth = 0;
for (SchemaNode child : children) {
ArrayNode aggregate = JsonNodeFactory.instance.arrayNode();
int cardSum = 0;
for (JsonNode node : data) {
JsonNode sub = node.get(child.field);
if (sub instanceof ArrayNode) {
aggregate.addAll((ArrayNode) sub);
cardSum += sub.size();
} else {
aggregate.add(sub);
cardSum += 1;
}
}
sum += data.size() == 0 ? 1 : Math.round(cardSum / data.size());
tableColumnWidth += child.measure(aggregate, layout, indent(child));
}
averageCardinality = (int) Math.ceil(sum / children.size());
tableColumnWidth = Layout.snap(Math.max(labelWidth, tableColumnWidth));
return isFold() ? fold.tableColumnWidth(layout)
: tableColumnWidth(layout);
}
@Override
Pair<Consumer<JsonNode>, Parent> outlineElement(double labelWidth,
Function<JsonNode, JsonNode> extractor,
double cellHeight,
int cardinality,
Layout layout,
double justified) {
if (isFold()) {
return fold.outlineElement(labelWidth, extract(extractor),
cellHeight,
averageCardinality * cardinality, layout,
justified);
}
double available = justified - labelWidth;
Control control = useTable ? buildNestedTable(n -> n, cardinality,
layout, available)
: buildOutline(cellHeight, n -> n,
cardinality, layout);
// control.setPrefWidth(available);
control.setPrefHeight(cellHeight);
TextArea labelText = new TextArea(label);
labelText.setWrapText(true);
labelText.setMinWidth(labelWidth);
labelText.setPrefWidth(labelWidth);
labelText.setMaxWidth(labelWidth);
labelText.setPrefRowCount(1);
labelText.setPrefHeight(cellHeight);
labelText.setMaxHeight(cellHeight);
labelText.setMaxHeight(cellHeight);
Pane box = new HBox();
box.setPrefWidth(justified);
box.setPrefHeight(cellHeight);
box.getChildren()
.add(labelText);
box.getChildren()
.add(control);
return new Pair<>(item -> {
if (item == null) {
return;
}
JsonNode extracted = extractor.apply(item);
JsonNode extractedField = extracted == null ? null
: extracted.get(field);
setItems(control, extractedField, layout);
}, box);
}
@Override
double rowHeight(Layout layout, double justified) {
if (isFold()) {
return fold.rowHeight(layout, justified);
}
return children.stream()
.mapToDouble(child -> Layout.snap(child.rowHeight(layout,
justified)))
.max()
.getAsDouble();
}
@Override
double tableColumnWidth(Layout layout) {
if (isFold()) {
return fold.tableColumnWidth(layout);
}
return tableColumnWidth + layout.getTableHorizontalInset()
+ layout.getTableRowHorizontalInset();
}
private Function<Double, Pair<Consumer<JsonNode>, Control>> buildColumn(int cardinality,
Function<JsonNode, JsonNode> extractor,
Map<SchemaNode, TableColumn<JsonNode, ?>> columnMap,
Layout layout,
double inset,
INDENT indent,
boolean root,
double justified) {
if (isFold()) {
return fold.buildColumn(averageCardinality * cardinality,
extract(extractor), columnMap, layout,
inset, indent, justified);
}
List<Function<Double, Pair<Consumer<JsonNode>, Control>>> fields = new ArrayList<>();
children.forEach(child -> fields.add(child.buildColumn(averageCardinality,
n -> n,
columnMap,
layout,
inset(layout,
inset,
child,
indent),
indent(child),
justified)));
double cellHeight = rowHeight(layout, justified)
+ layout.getListCellVerticalInset();
double calculatedHeight = (cellHeight * cardinality)
+ layout.getListVerticalInset();
Function<JsonNode, JsonNode> extract = root ? extractor
: extract(extractor);
return rendered -> {
double deficit = Math.max(0, rendered - calculatedHeight);
double childDeficit = Math.max(0, deficit / cardinality);
double extended = Layout.snap(cellHeight + childDeficit);
ListView<JsonNode> row = new ListView<JsonNode>();
layout.getModel()
.apply(row, this);
HBox.setHgrow(row, Priority.ALWAYS);
row.setMinWidth(0);
row.setPrefWidth(1);
row.setFixedCellSize(extended);
row.setPrefHeight(rendered);
row.setCellFactory(control -> {
ListCell<JsonNode> cell = rowCell(fields, extended
- layout.getListCellVerticalInset(),
layout);
cell.setPrefHeight(extended);
layout.getModel()
.apply(cell, Relation.this);
return cell;
});
return new Pair<>(node -> {
setItems(row, extract.apply(node), layout);
}, row);
};
}
private TableView<JsonNode> buildNestedTable(Function<JsonNode, JsonNode> extractor,
int cardinality, Layout layout,
double justified) {
if (isFold()) {
return fold.buildNestedTable(extract(extractor),
averageCardinality * cardinality,
layout, justified);
}
TableView<JsonNode> table = tableBase();
table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
children.forEach(child -> {
INDENT indent = indent(child);
table.getColumns()
.add(child.buildColumn(layout, inset(layout, 0, child, indent),
indent, justified));
});
Map<SchemaNode, TableColumn<JsonNode, ?>> columnMap = new HashMap<>();
List<TableColumn<JsonNode, ?>> columns = table.getColumns();
while (!columns.isEmpty()) {
List<TableColumn<JsonNode, ?>> leaves = new ArrayList<>();
columns.forEach(c -> {
columnMap.put((SchemaNode) c.getUserData(), c);
leaves.addAll(c.getColumns());
});
columns = leaves;
}
Function<Double, Pair<Consumer<JsonNode>, Control>> topLevel = buildColumn(averageCardinality,
n -> n,
columnMap,
layout,
0,
INDENT.NONE,
true,
justified);
double height = extendedHeight(layout, 1, rowHeight(layout, justified));
table.setRowFactory(tableView -> {
Pair<Consumer<JsonNode>, Control> relationRow = topLevel.apply(height);
RelationTableRow row = new RelationTableRow(relationRow.getKey(),
relationRow.getValue());
layout.getModel()
.apply(row, Relation.this);
return row;
});
layout.getModel()
.apply(table, this);
table.setFixedCellSize(height);
double rowHeight = rowHeight(layout, justified)
+ layout.getTableRowVerticalInset();
double contentHeight = (rowHeight * cardinality)
+ layout.measureHeader(table)
+ layout.getTableVerticalInset();
table.setPrefHeight(contentHeight);
if (cardinality > 1) {
table.setMinHeight(contentHeight);
}
return table;
}
private ListView<JsonNode> buildOutline(double cellHeight,
Function<JsonNode, JsonNode> extractor,
int cardinality, Layout layout) {
if (isFold()) {
return fold.buildOutline(cellHeight, extract(extractor),
averageCardinality * cardinality, layout);
}
double extended = cellHeight + layout.getListCellVerticalInset();
ListView<JsonNode> list = new ListView<>();
layout.getModel()
.apply(list, this);
list.setPrefHeight((extended * cardinality));
list.setFixedCellSize(cellHeight);
list.setPrefWidth(columnSets.get(0)
.getWidth()
+ layout.getListCellHorizontalInset()
+ layout.getListHorizontalInset());
list.setCellFactory(c -> {
ListCell<JsonNode> cell = listCell(extractor, cellHeight, layout);
layout.getModel()
.apply(cell, this);
return cell;
});
list.setPlaceholder(new Text());
return list;
}
private double extendedHeight(Layout layout, int cardinality,
double elementHeight) {
return Layout.snap(cardinality * (elementHeight
+ layout.getListCellVerticalInset()))
+ layout.getListVerticalInset();
}
private ArrayNode flatten(JsonNode data) {
ArrayNode flattened = JsonNodeFactory.instance.arrayNode();
if (data != null) {
if (data.isArray()) {
data.forEach(item -> {
flattened.addAll(SchemaNode.asArray(item.get(fold.getField())));
});
} else {
flattened.addAll(SchemaNode.asArray(data.get(fold.getField())));
}
}
return flattened;
}
private INDENT indent(SchemaNode child) {
INDENT indent = INDENT.NONE;
if (child.equals(children.get(0))) {
indent = INDENT.LEFT;
} else if (child.equals(children.get(children.size() - 1))) {
indent = INDENT.RIGHT;
}
return indent;
}
private double inset(Layout layout, double inset, SchemaNode child,
INDENT indent) {
switch (indent) {
case RIGHT:
if (child.equals(children.get(children.size() - 1))) {
return inset + layout.getNestedRightInset();
} else if (child.equals(children.get(0))) {
return layout.getNestedLeftInset();
}
break;
case LEFT:
if (child.equals(children.get(0))) {
return inset + layout.getNestedLeftInset();
} else if (child.equals(children.get(children.size() - 1))) {
return layout.getNestedRightInset();
}
break;
case NONE:
if (child.equals(children.get(children.size() - 1))) {
return layout.getNestedRightInset();
} else if (child.equals(children.get(0))) {
return layout.getNestedLeftInset();
}
break;
default:
}
return 0;
}
private boolean isAutoFoldable() {
return fold == null && autoFold && children.size() == 1
&& children.get(children.size() - 1) instanceof Relation;
}
private ListCell<JsonNode> listCell(Function<JsonNode, JsonNode> extractor,
double cellHeight, Layout layout) {
return new ListCell<JsonNode>() {
VBox cell;
List<Consumer<JsonNode>> controls = new ArrayList<>();
{
itemProperty().addListener((obs, oldItem, newItem) -> {
if (newItem != null) {
if (cell == null) {
initialize(extractor, layout);
}
setGraphic(cell);
}
});
emptyProperty().addListener((obs, wasEmpty, isEmpty) -> {
if (isEmpty) {
setGraphic(null);
} else {
setGraphic(cell);
}
});
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
setAlignment(Pos.CENTER);
setAlignment(Pos.CENTER);
}
@Override
protected void updateItem(JsonNode item, boolean empty) {
if (item == getItem()) {
return;
}
super.updateItem(item, empty);
super.setText(null);
if (empty) {
super.setGraphic(null);
return;
}
controls.forEach(child -> child.accept(item));
}
private void initialize(Function<JsonNode, JsonNode> extractor,
Layout layout) {
cell = new VBox();
cell.setMinSize(0, 0);
cell.setPrefSize(1, 1);
columnSets.forEach(cs -> {
Pair<Consumer<JsonNode>, Parent> master = cs.build(extractor,
layout);
controls.add(master.getKey());
cell.getChildren()
.add(master.getValue());
});
}
};
}
private void nestTable() {
useTable = true;
children.forEach(child -> {
if (child.isRelation()) {
((Relation) child).nestTable();
}
});
}
private ListCell<JsonNode> rowCell(List<Function<Double, Pair<Consumer<JsonNode>, Control>>> fields,
double resolvedHeight, Layout layout) {
return new ListCell<JsonNode>() {
private Consumer<JsonNode> master;
private HBox row;
{
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
setAlignment(Pos.CENTER);
}
@Override
protected void updateItem(JsonNode item, boolean empty) {
if (item == getItem()) {
return;
}
super.updateItem(item, empty);
if (empty) {
return;
}
if (item == null) {
setGraphic(null);
return;
}
if (row == null) {
buildRow();
}
setGraphic(row);
master.accept(item);
row.requestLayout();
}
private void buildRow() {
row = new HBox();
row.setMinWidth(0);
row.setPrefWidth(1);
row.setPrefHeight(resolvedHeight);
List<Consumer<JsonNode>> consumers = new ArrayList<>();
fields.forEach(p -> {
Pair<Consumer<JsonNode>, Control> pair = p.apply(resolvedHeight);
Control control = pair.getValue();
row.getChildren()
.add(control);
consumers.add(pair.getKey());
});
master = node -> consumers.forEach(c -> {
c.accept(node);
});
}
};
}
private TableView<JsonNode> tableBase() {
TableView<JsonNode> table = new TableView<>();
table.setPlaceholder(new Text());
table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
return table;
}
}
| kramer/src/main/java/com/chiralbehaviors/layout/schema/Relation.java | /**
* Copyright (c) 2016 Chiral Behaviors, LLC, all rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.chiralbehaviors.layout.schema;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import com.chiralbehaviors.layout.Layout;
import com.chiralbehaviors.layout.RelationTableRow;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import javafx.collections.ObservableList;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.Control;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.util.Pair;
/**
* @author hhildebrand
*
*/
public class Relation extends SchemaNode {
private boolean autoFold = true;
private int averageCardinality = 1;
private final List<SchemaNode> children = new ArrayList<>();
private final List<ColumnSet> columnSets = new ArrayList<>();
private Relation fold;
private double outlineWidth = 0;
private double tableColumnWidth = 0;
private boolean useTable = false;
public Relation(String label) {
super(label);
}
public void addChild(SchemaNode child) {
children.add(child);
}
public void autoLayout(int cardinality, Layout layout, double width) {
double snapped = Layout.snap(width);
layout(cardinality, layout, snapped);
compress(layout, snapped);
}
public Control buildControl(int cardinality, Layout layout, double width) {
if (isFold()) {
return fold.buildControl(averageCardinality * cardinality, layout,
width);
}
return useTable ? buildNestedTable(n -> n, cardinality, layout, width)
: buildOutline(cellHeight(layout, width), n -> n,
cardinality, layout);
}
@Override
public JsonNode extractFrom(JsonNode jsonNode) {
if (isFold()) {
return fold.extractFrom(super.extractFrom(jsonNode));
}
return super.extractFrom(jsonNode);
}
public int getAverageCardinality() {
return averageCardinality;
}
public SchemaNode getChild(String field) {
for (SchemaNode child : children) {
if (child.getField()
.equals(field)) {
return child;
}
}
return null;
}
public List<SchemaNode> getChildren() {
return children;
}
@Override
public double getLabelWidth(Layout layout) {
if (isFold()) {
return fold.getLabelWidth(layout);
}
return layout.textWidth(label);
}
@JsonProperty
public boolean isFold() {
return fold != null;
}
@Override
public boolean isRelation() {
return true;
}
@Override
public boolean isUseTable() {
if (isFold()) {
return fold.isUseTable();
}
return useTable;
}
public void measure(JsonNode jsonNode, Layout layout) {
if (jsonNode.isArray()) {
ArrayNode array = (ArrayNode) jsonNode;
measure(array, layout, INDENT.NONE);
} else {
ArrayNode singleton = JsonNodeFactory.instance.arrayNode();
singleton.add(jsonNode);
measure(singleton, layout, INDENT.NONE);
}
}
public void setAverageCardinality(int averageCardinality) {
this.averageCardinality = averageCardinality;
}
public void setFold(boolean fold) {
this.fold = (fold && children.size() == 1 && children.get(0)
.isRelation()) ? (Relation) children.get(0)
: null;
}
@Override
public void setItems(Control control, JsonNode data, Layout layout) {
if (data == null) {
data = JsonNodeFactory.instance.arrayNode();
}
if (isFold()) {
fold.setItems(control, flatten(data), layout);
} else {
super.setItems(control, data, layout);
}
}
public void setUseTable(boolean useTable) {
this.useTable = useTable;
}
@Override
public String toString() {
return toString(0);
}
@Override
public String toString(int indent) {
StringBuffer buf = new StringBuffer();
buf.append(String.format("Relation [%s:%.2f x %s]", label,
tableColumnWidth, averageCardinality));
buf.append('\n');
children.forEach(c -> {
for (int i = 0; i < indent; i++) {
buf.append(" ");
}
buf.append(" - ");
buf.append(c.toString(indent + 1));
buf.append('\n');
});
return buf.toString();
}
@Override
Function<Double, Pair<Consumer<JsonNode>, Control>> buildColumn(int cardinality,
Function<JsonNode, JsonNode> extractor,
Map<SchemaNode, TableColumn<JsonNode, ?>> columnMap,
Layout layout,
double inset,
INDENT indent,
double justified) {
return buildColumn(cardinality, extractor, columnMap, layout, inset,
indent, false, justified);
}
@Override
TableColumn<JsonNode, JsonNode> buildColumn(Layout layout, double inset,
INDENT indent,
double justified) {
if (isFold()) {
return fold.buildColumn(layout, inset, indent, justified);
}
TableColumn<JsonNode, JsonNode> column = super.buildColumn(layout,
inset,
indent,
justified);
column.setPrefWidth(justified);
ObservableList<TableColumn<JsonNode, ?>> columns = column.getColumns();
children.forEach(child -> columns.add(child.buildColumn(layout,
inset(layout,
inset,
child,
indent),
indent(child),
justified)));
return column;
}
@Override
double cellHeight(Layout layout, double width) {
if (isFold()) {
return fold.cellHeight(layout, width);
}
if (!useTable) {
return (averageCardinality * (columnSets.stream()
.mapToDouble(cs -> cs.getCellHeight())
.sum()
+ layout.getListCellVerticalInset()))
+ layout.getListVerticalInset();
}
TableView<JsonNode> table = tableBase();
children.forEach(child -> {
INDENT indent = indent(child);
table.getColumns()
.add(child.buildColumn(layout, inset(layout, 0, child, indent),
indent, width));
});
return (averageCardinality * (rowHeight(layout, width)
+ layout.getTableRowVerticalInset()))
+ layout.measureHeader(table) + layout.getTableVerticalInset();
}
@Override
void compress(Layout layout, double justified) {
if (isFold()) {
fold.compress(layout, justified);
return;
}
if (useTable) {
return;
}
double available = justified - layout.getListCellHorizontalInset()
- layout.getListHorizontalInset();
double labelWidth = children.stream()
.mapToDouble(n -> n.getLabelWidth(layout))
.max()
.orElse(0);
columnSets.clear();
ColumnSet current = null;
double halfWidth = available / 2d;
for (SchemaNode child : children) {
double childWidth = labelWidth + child.layoutWidth(layout);
if (childWidth > halfWidth || current == null) {
current = new ColumnSet(labelWidth);
columnSets.add(current);
current.add(child);
if (childWidth > halfWidth) {
current = null;
}
} else {
current.add(child);
}
}
columnSets.forEach(cs -> cs.compress(layout, available));
}
// for testing
List<ColumnSet> getColumnSets() {
return columnSets;
}
@Override
double layout(int cardinality, Layout layout, double width) {
if (isFold()) {
return fold.layout(cardinality, layout, width);
}
useTable = false;
double labelWidth = children.stream()
.mapToDouble(child -> child.getLabelWidth(layout))
.max()
.getAsDouble();
double available = width - labelWidth
- layout.getListCellHorizontalInset();
outlineWidth = children.stream()
.mapToDouble(child -> {
return child.layout(cardinality, layout,
available);
})
.max()
.orElse(0d)
+ labelWidth;
double tableWidth = tableColumnWidth + layout.getTableHorizontalInset()
+ layout.getTableRowHorizontalInset();
double oWidth = outlineWidth + layout.getListCellHorizontalInset()
+ layout.getListHorizontalInset();
if (tableWidth <= oWidth) {
nestTable();
return tableWidth;
}
return oWidth;
}
/* (non-Javadoc)
* @see com.chiralbehaviors.layout.schema.SchemaNode#layoutWidth(com.chiralbehaviors.layout.Layout)
*/
@Override
double layoutWidth(Layout layout) {
return useTable ? tableColumnWidth + layout.getTableRowHorizontalInset()
+ layout.getTableHorizontalInset()
: outlineWidth + layout.getListCellHorizontalInset()
+ layout.getListHorizontalInset();
}
@Override
double measure(ArrayNode data, Layout layout, INDENT indent) {
if (isAutoFoldable()) {
fold = ((Relation) children.get(children.size() - 1));
}
if (data.isNull() || children.size() == 0) {
return 0;
}
double labelWidth = layout.textWidth(label);
labelWidth += layout.getTextHorizontalInset();
double sum = 0;
tableColumnWidth = 0;
for (SchemaNode child : children) {
ArrayNode aggregate = JsonNodeFactory.instance.arrayNode();
int cardSum = 0;
for (JsonNode node : data) {
JsonNode sub = node.get(child.field);
if (sub instanceof ArrayNode) {
aggregate.addAll((ArrayNode) sub);
cardSum += sub.size();
} else {
aggregate.add(sub);
cardSum += 1;
}
}
sum += data.size() == 0 ? 1 : Math.round(cardSum / data.size());
tableColumnWidth += child.measure(aggregate, layout, indent(child));
}
averageCardinality = (int) Math.ceil(sum / children.size());
tableColumnWidth = Layout.snap(Math.max(labelWidth, tableColumnWidth));
return isFold() ? fold.tableColumnWidth(layout)
: tableColumnWidth(layout);
}
@Override
Pair<Consumer<JsonNode>, Parent> outlineElement(double labelWidth,
Function<JsonNode, JsonNode> extractor,
double cellHeight,
int cardinality,
Layout layout,
double justified) {
if (isFold()) {
return fold.outlineElement(labelWidth, extract(extractor),
cellHeight,
averageCardinality * cardinality, layout,
justified);
}
double available = justified - labelWidth;
Control control = useTable ? buildNestedTable(n -> n, cardinality,
layout, available)
: buildOutline(cellHeight, n -> n,
cardinality, layout);
// control.setPrefWidth(available);
control.setPrefHeight(cellHeight);
TextArea labelText = new TextArea(label);
labelText.setWrapText(true);
labelText.setMinWidth(labelWidth);
labelText.setPrefWidth(labelWidth);
labelText.setMaxWidth(labelWidth);
labelText.setPrefRowCount(1);
labelText.setPrefHeight(cellHeight);
labelText.setMaxHeight(cellHeight);
labelText.setMaxHeight(cellHeight);
Pane box = new HBox();
box.setPrefWidth(justified);
box.setPrefHeight(cellHeight);
box.getChildren()
.add(labelText);
box.getChildren()
.add(control);
return new Pair<>(item -> {
if (item == null) {
return;
}
JsonNode extracted = extractor.apply(item);
JsonNode extractedField = extracted == null ? null
: extracted.get(field);
setItems(control, extractedField, layout);
}, box);
}
@Override
double rowHeight(Layout layout, double justified) {
if (isFold()) {
return fold.rowHeight(layout, justified);
}
return children.stream()
.mapToDouble(child -> Layout.snap(child.rowHeight(layout,
justified)))
.max()
.getAsDouble();
}
@Override
double tableColumnWidth(Layout layout) {
if (isFold()) {
return fold.tableColumnWidth(layout);
}
return tableColumnWidth + layout.getTableHorizontalInset()
+ layout.getTableRowHorizontalInset();
}
private Function<Double, Pair<Consumer<JsonNode>, Control>> buildColumn(int cardinality,
Function<JsonNode, JsonNode> extractor,
Map<SchemaNode, TableColumn<JsonNode, ?>> columnMap,
Layout layout,
double inset,
INDENT indent,
boolean root,
double justified) {
if (isFold()) {
return fold.buildColumn(averageCardinality * cardinality,
extract(extractor), columnMap, layout,
inset, indent, justified);
}
List<Function<Double, Pair<Consumer<JsonNode>, Control>>> fields = new ArrayList<>();
children.forEach(child -> fields.add(child.buildColumn(averageCardinality,
n -> n,
columnMap,
layout,
inset(layout,
inset,
child,
indent),
indent(child),
justified)));
double cellHeight = rowHeight(layout, justified)
+ layout.getListCellVerticalInset();
double calculatedHeight = (cellHeight * cardinality)
+ layout.getListVerticalInset();
Function<JsonNode, JsonNode> extract = root ? extractor
: extract(extractor);
return rendered -> {
double deficit = Math.max(0, rendered - calculatedHeight);
double childDeficit = Math.max(0, deficit / cardinality);
double extended = Layout.snap(cellHeight + childDeficit);
ListView<JsonNode> row = new ListView<JsonNode>();
layout.getModel()
.apply(row, this);
HBox.setHgrow(row, Priority.ALWAYS);
row.setMinWidth(0);
row.setPrefWidth(1);
row.setFixedCellSize(extended);
row.setPrefHeight(rendered);
row.setCellFactory(control -> {
ListCell<JsonNode> cell = rowCell(fields, extended
- layout.getListCellVerticalInset(),
layout);
cell.setPrefHeight(extended);
layout.getModel()
.apply(cell, Relation.this);
return cell;
});
return new Pair<>(node -> {
setItems(row, extract.apply(node), layout);
}, row);
};
}
private TableView<JsonNode> buildNestedTable(Function<JsonNode, JsonNode> extractor,
int cardinality, Layout layout,
double justified) {
if (isFold()) {
return fold.buildNestedTable(extract(extractor),
averageCardinality * cardinality,
layout, justified);
}
TableView<JsonNode> table = tableBase();
table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
children.forEach(child -> {
INDENT indent = indent(child);
table.getColumns()
.add(child.buildColumn(layout, inset(layout, 0, child, indent),
indent, justified));
});
Map<SchemaNode, TableColumn<JsonNode, ?>> columnMap = new HashMap<>();
List<TableColumn<JsonNode, ?>> columns = table.getColumns();
while (!columns.isEmpty()) {
List<TableColumn<JsonNode, ?>> leaves = new ArrayList<>();
columns.forEach(c -> {
columnMap.put((SchemaNode) c.getUserData(), c);
leaves.addAll(c.getColumns());
});
columns = leaves;
}
Function<Double, Pair<Consumer<JsonNode>, Control>> topLevel = buildColumn(averageCardinality,
n -> n,
columnMap,
layout,
0,
INDENT.NONE,
true,
justified);
double height = extendedHeight(layout, 1, rowHeight(layout, justified));
table.setRowFactory(tableView -> {
Pair<Consumer<JsonNode>, Control> relationRow = topLevel.apply(height);
RelationTableRow row = new RelationTableRow(relationRow.getKey(),
relationRow.getValue());
layout.getModel()
.apply(row, Relation.this);
return row;
});
layout.getModel()
.apply(table, this);
table.setFixedCellSize(height);
double rowHeight = rowHeight(layout, justified)
+ layout.getTableRowVerticalInset();
double contentHeight = (rowHeight * cardinality)
+ layout.measureHeader(table)
+ layout.getTableVerticalInset();
table.setPrefHeight(contentHeight);
if (cardinality > 1) {
table.setMinHeight(contentHeight);
}
return table;
}
private ListView<JsonNode> buildOutline(double cellHeight,
Function<JsonNode, JsonNode> extractor,
int cardinality, Layout layout) {
if (isFold()) {
return fold.buildOutline(cellHeight, extract(extractor),
averageCardinality * cardinality, layout);
}
double extended = cellHeight + layout.getListCellVerticalInset();
ListView<JsonNode> list = new ListView<>();
layout.getModel()
.apply(list, this);
list.setPrefHeight((extended * cardinality));
list.setFixedCellSize(cellHeight);
list.setPrefWidth(columnSets.get(0)
.getWidth()
+ layout.getListCellHorizontalInset()
+ layout.getListHorizontalInset());
list.setCellFactory(c -> {
ListCell<JsonNode> cell = listCell(extractor, cellHeight, layout);
layout.getModel()
.apply(cell, this);
return cell;
});
list.setPlaceholder(new Text());
return list;
}
private double extendedHeight(Layout layout, int cardinality,
double elementHeight) {
return Layout.snap(cardinality * (elementHeight
+ layout.getListCellVerticalInset()))
+ layout.getListVerticalInset();
}
private ArrayNode flatten(JsonNode data) {
ArrayNode flattened = JsonNodeFactory.instance.arrayNode();
if (data != null) {
if (data.isArray()) {
data.forEach(item -> {
flattened.addAll(SchemaNode.asArray(item.get(fold.getField())));
});
} else {
flattened.addAll(SchemaNode.asArray(data.get(fold.getField())));
}
}
return flattened;
}
private INDENT indent(SchemaNode child) {
INDENT indent = INDENT.NONE;
if (child.equals(children.get(0))) {
indent = INDENT.LEFT;
} else if (child.equals(children.get(children.size() - 1))) {
indent = INDENT.RIGHT;
}
return indent;
}
private double inset(Layout layout, double inset, SchemaNode child,
INDENT indent) {
switch (indent) {
case RIGHT:
if (child.equals(children.get(children.size() - 1))) {
return inset + layout.getNestedRightInset();
} else if (child.equals(children.get(0))) {
return layout.getNestedLeftInset();
}
break;
case LEFT:
if (child.equals(children.get(0))) {
return inset + layout.getNestedLeftInset();
} else if (child.equals(children.get(children.size() - 1))) {
return layout.getNestedRightInset();
}
break;
case NONE:
if (child.equals(children.get(children.size() - 1))) {
return layout.getNestedRightInset();
} else if (child.equals(children.get(0))) {
return layout.getNestedLeftInset();
}
break;
default:
}
return 0;
}
private boolean isAutoFoldable() {
return fold == null && autoFold && children.size() == 1
&& children.get(children.size() - 1) instanceof Relation;
}
private ListCell<JsonNode> listCell(Function<JsonNode, JsonNode> extractor,
double cellHeight, Layout layout) {
return new ListCell<JsonNode>() {
VBox cell;
List<Consumer<JsonNode>> controls = new ArrayList<>();
{
itemProperty().addListener((obs, oldItem, newItem) -> {
if (newItem != null) {
if (cell == null) {
initialize(extractor, layout);
}
setGraphic(cell);
}
});
emptyProperty().addListener((obs, wasEmpty, isEmpty) -> {
if (isEmpty) {
setGraphic(null);
} else {
setGraphic(cell);
}
});
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
setAlignment(Pos.CENTER);
setAlignment(Pos.CENTER);
}
@Override
protected void updateItem(JsonNode item, boolean empty) {
if (item == getItem()) {
return;
}
super.updateItem(item, empty);
super.setText(null);
if (empty) {
super.setGraphic(null);
return;
}
controls.forEach(child -> child.accept(item));
}
private void initialize(Function<JsonNode, JsonNode> extractor,
Layout layout) {
cell = new VBox();
columnSets.forEach(cs -> {
Pair<Consumer<JsonNode>, Parent> master = cs.build(extractor,
layout);
controls.add(master.getKey());
cell.getChildren()
.add(master.getValue());
});
}
};
}
private void nestTable() {
useTable = true;
children.forEach(child -> {
if (child.isRelation()) {
((Relation) child).nestTable();
}
});
}
private ListCell<JsonNode> rowCell(List<Function<Double, Pair<Consumer<JsonNode>, Control>>> fields,
double resolvedHeight, Layout layout) {
return new ListCell<JsonNode>() {
private Consumer<JsonNode> master;
private HBox row;
{
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
setAlignment(Pos.CENTER);
}
@Override
protected void updateItem(JsonNode item, boolean empty) {
if (item == getItem()) {
return;
}
super.updateItem(item, empty);
if (empty) {
return;
}
if (item == null) {
setGraphic(null);
return;
}
if (row == null) {
buildRow();
}
setGraphic(row);
master.accept(item);
row.requestLayout();
}
private void buildRow() {
row = new HBox();
row.setMinWidth(0);
row.setPrefWidth(1);
row.setPrefHeight(resolvedHeight);
List<Consumer<JsonNode>> consumers = new ArrayList<>();
fields.forEach(p -> {
Pair<Consumer<JsonNode>, Control> pair = p.apply(resolvedHeight);
Control control = pair.getValue();
row.getChildren()
.add(control);
consumers.add(pair.getKey());
});
master = node -> consumers.forEach(c -> {
c.accept(node);
});
}
};
}
private TableView<JsonNode> tableBase() {
TableView<JsonNode> table = new TableView<>();
table.setPlaceholder(new Text());
table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
return table;
}
}
| holy fucking shit. Just needed to let the list cell be managed. | kramer/src/main/java/com/chiralbehaviors/layout/schema/Relation.java | holy fucking shit. Just needed to let the list cell be managed. | <ide><path>ramer/src/main/java/com/chiralbehaviors/layout/schema/Relation.java
<ide> private void initialize(Function<JsonNode, JsonNode> extractor,
<ide> Layout layout) {
<ide> cell = new VBox();
<add> cell.setMinSize(0, 0);
<add> cell.setPrefSize(1, 1);
<ide> columnSets.forEach(cs -> {
<ide> Pair<Consumer<JsonNode>, Parent> master = cs.build(extractor,
<ide> layout); |
|
JavaScript | apache-2.0 | 5c6cd653de379c0d145c424266871d2a29e469e0 | 0 | prembasumatary/aws-sdk-js,jeskew/aws-sdk-js,mohamed-kamal/aws-sdk-js,LiuJoyceC/aws-sdk-js,GlideMe/aws-sdk-js,GlideMe/aws-sdk-js,mapbox/aws-sdk-js,odeke-em/aws-sdk-js,jmswhll/aws-sdk-js,misfitdavidl/aws-sdk-js,GlideMe/aws-sdk-js,jeskew/aws-sdk-js,mohamed-kamal/aws-sdk-js,MitocGroup/aws-sdk-js,aws/aws-sdk-js,LiuJoyceC/aws-sdk-js,aws/aws-sdk-js,beni55/aws-sdk-js,mapbox/aws-sdk-js,AdityaManohar/aws-sdk-js,guymguym/aws-sdk-js,dconnolly/aws-sdk-js,aws/aws-sdk-js,jmswhll/aws-sdk-js,MitocGroup/aws-sdk-js,mapbox/aws-sdk-js,dconnolly/aws-sdk-js,chrisradek/aws-sdk-js,guymguym/aws-sdk-js,prestomation/aws-sdk-js,michael-donat/aws-sdk-js,michael-donat/aws-sdk-js,michael-donat/aws-sdk-js,ugie/aws-sdk-js,GlideMe/aws-sdk-js,Blufe/aws-sdk-js,jippeholwerda/aws-sdk-js,MitocGroup/aws-sdk-js,grimurjonsson/aws-sdk-js,Blufe/aws-sdk-js,chrisradek/aws-sdk-js,prestomation/aws-sdk-js,jippeholwerda/aws-sdk-js,misfitdavidl/aws-sdk-js,prembasumatary/aws-sdk-js,chrisradek/aws-sdk-js,guymguym/aws-sdk-js,j3tm0t0/aws-sdk-js,Blufe/aws-sdk-js,mohamed-kamal/aws-sdk-js,j3tm0t0/aws-sdk-js,AdityaManohar/aws-sdk-js,jippeholwerda/aws-sdk-js,prestomation/aws-sdk-js,grimurjonsson/aws-sdk-js,dconnolly/aws-sdk-js,jeskew/aws-sdk-js,beni55/aws-sdk-js,beni55/aws-sdk-js,ugie/aws-sdk-js,chrisradek/aws-sdk-js,guymguym/aws-sdk-js,AdityaManohar/aws-sdk-js,grimurjonsson/aws-sdk-js,LiuJoyceC/aws-sdk-js,jmswhll/aws-sdk-js,misfitdavidl/aws-sdk-js,ugie/aws-sdk-js,odeke-em/aws-sdk-js,odeke-em/aws-sdk-js,jeskew/aws-sdk-js,aws/aws-sdk-js,prembasumatary/aws-sdk-js,j3tm0t0/aws-sdk-js | /**
* Copyright 2011-2012 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.
*/
var AWS = require('./core');
var inherit = AWS.util.inherit;
/**
* The main configuration class used by all service objects to set
* the region, credentials, and other options for requests.
*
* By default, credentials and region settings are left unconfigured.
* This should be configured by the application before using any
* AWS service APIs.
*
* In order to set global configuration options, properties should
* be assigned to the global {AWS.config} object.
*
* @see AWS.config
*
* @!attribute credentials
* @return [AWS.Credentials] the AWS credentials to sign requests with.
*
* @!attribute region
* @example Set the global region setting to us-west-2
* AWS.config.update({region: 'us-west-2'});
* @return [AWS.Credentials] The region to send service requests to.
* @see http://docs.amazonwebservices.com/general/latest/gr/rande.html
* A list of available endpoints for each AWS service
*
* @!attribute maxRetries
* @return [Integer] the maximum amount of retries to perform for a
* service request. By default this value is calculated by the specific
* service object that the request is being made to.
*
* @!attribute sslEnabled
* @return [Boolean] whether SSL is enabled for requests
*
* @!attribute s3ForcePathStyle
* @return [Boolean] whether to force path style URLs for S3 objects
*/
AWS.Config = inherit({
/**
* Creates a new configuration object. This is the object that passes
* option data along to service requests, including credentials, security,
* region information, and some service specific settings.
*
* @example Creating a new configuration object with credentials and region
* var config = new AWS.Config({
* accessKeyId: 'AKID', secretAccessKey: 'SECRET', region: 'us-west-2'
* });
* @option options accessKeyId [String] your AWS access key ID.
* @option options secretAccessKey [String] your AWS secret access key.
* @option options sessionToken [AWS.Credentials] the optional AWS
* session token to sign requests with.
* @option options credentials [AWS.Credentials] the AWS credentials
* to sign requests with. You can either specify this object, or
* specify the accessKeyId and secretAccessKey options directly.
* @option options region [String] the region to send service requests to.
* See {region} for more information.
* @option options maxRetries [Integer] the maximum amount of retries to
* attempt with a request. See {maxRetries} for more information.
* @option options sslEnabled [Boolean] whether to enable SSL for
* requests.
* @option options s3ForcePathStyle [Booelan] whether to force path
* style URLs for S3 objects.
*/
constructor: function Config(options) {
if (options === undefined) options = {};
options = this.extractCredentials(options);
AWS.util.each.call(this, this.keys, function (key, value) {
this.set(key, options[key], value);
});
},
/**
* Updates the current configuration object with new options.
*
* @example Update maxRetries property of a configuration object
* config.update({maxRetries: 10});
* @param [Object] options a map of option keys and values.
* @see constructor
*/
update: function update(options) {
options = this.extractCredentials(options);
AWS.util.each.call(this, options, function (key, value) {
if (this.keys.hasOwnProperty(key)) this[key] = value;
});
},
/**
* Loads configuration data from a JSON file into this config object.
* @note Loading configuration will reset all existing configuration
* on the object.
* @param path [String] the path to load configuration from
* @return [AWS.Config] the same configuration object
*/
loadFromPath: function loadFromPath(path) {
this.clear();
var options = JSON.parse(AWS.util.readFileSync(path));
var fileSystemCreds = new AWS.FileSystemCredentials(path, this);
var chain = new AWS.CredentialProviderChain();
chain.providers.unshift(fileSystemCreds);
options.credentials = chain.resolve();
this.constructor(options);
return this;
},
/**
* Clears configuration data on this object
*
* @api private
*/
clear: function clear() {
/*jshint forin:false */
AWS.util.each.call(this, this.keys, function (key) {
delete this[key];
});
// reset credential provider
this.set('credentials', undefined);
},
/**
* Sets a property on the configuration object, allowing for a
* default value
* @api private
*/
set: function set(property, value, defaultValue) {
if (value === undefined) {
if (defaultValue === undefined) {
defaultValue = this.keys[property];
}
if (defaultValue instanceof Function) {
this[property] = defaultValue.call(this);
} else {
this[property] = defaultValue;
}
} else {
this[property] = value;
}
},
/**
* All of the keys with their default values.
*
* @constant
* @api private
*/
keys: {
credentials: function () {
return new AWS.CredentialProviderChain().resolve();
},
region: undefined,
maxRetries: undefined,
sslEnabled: true,
s3ForcePathStyle: false
},
/**
* Extracts accessKeyId, secretAccessKey and sessionToken
* from a configuration hash.
*
* @api private
*/
extractCredentials: function extractCredentials(options) {
if (options.accessKeyId && options.secretAccessKey) {
options = AWS.util.copy(options);
options.credentials = new AWS.Credentials(options);
}
return options;
}
});
/**
* Represents your AWS security credentials, specifically the
* {accessKeyId}, {secretAcessKey}, and optional {sessionToken}.
* Creating a +Credentials+ object allows you to pass around your
* security information to configuration and service objects.
*
* Note that this class typically does not need to be constructed manually,
* as the {AWS.Config} and {AWS.Client} classes both accept simple
* options hashes with the three keys. These structures will be converted
* into Credentials objects automatically.
*
* == Expiring and Refreshing Credentials
*
* Occasionally credentials can expire in the middle of a long-running
* application. In this case, the SDK will automatically attempt to
* refresh the credentials from the storage location if the Credentials
* class implements the {refresh} method.
*
* If you are implementing a credential storage location, you
* will want to create a subclass of the +Credentials+ class and
* override the {refresh} method. This method allows credentials to be
* retrieved from the backing store, be it a file system, database, or
* some network storage. The method should reset the credential attributes
* on the object.
*
* @!attribute accessKeyId
* @return [String] the AWS access key ID
* @!attribute secretAccessKey
* @return [String] the AWS secret access key
* @!attribute sessionToken
* @return [String] an optional AWS session token
*/
AWS.Credentials = inherit({
/**
* A credentials object can be created using positional arguments or an options
* hash.
*
* @overload AWS.Credentials(accessKeyId, secretAccessKey, sessionToken=null)
* Creates a Credentials object with a given set of credential information
* as positional arguments.
* @param accessKeyId [String] the AWS access key ID
* @param secretAccessKey [String] the AWS secret access key
* @param sessionToken [String] the optional AWS session token
* @example Create a credentials object with AWS credentials
* var creds = new AWS.Credentials('akid', 'secret', 'session');
* @overload AWS.Credentials(options)
* Creates a Credentials object with a given set of credential information
* as an options hash.
* @option options accessKeyId [String] the AWS access key ID
* @option options secretAccessKey [String] the AWS secret access key
* @option options sessionToken [String] the optional AWS session token
* @example Create a credentials object with AWS credentials
* var creds = new AWS.Credentials({
* accessKeyId: 'akid', secretAccessKey: 'secret', sessionToken: 'session'
* });
*/
constructor: function Credentials() {
if (arguments.length == 1 && typeof arguments[0] === 'object') {
var creds = arguments[0].credentials || arguments[0];
this.accessKeyId = creds.accessKeyId;
this.secretAccessKey = creds.secretAccessKey;
this.sessionToken = creds.sessionToken;
} else {
this.accessKeyId = arguments[0];
this.secretAccessKey = arguments[1];
this.sessionToken = arguments[2];
}
},
/**
* Refreshes the credentials.
*
* @note Subclasses should override this class to reset the
* {accessKeyId}, {secretAccessKey} and optional {sessionToken}
* on the credentials object.
*/
refresh: function refresh() { }
});
AWS.FileSystemCredentials = inherit(AWS.Credentials, {
constructor: function FileSystemCredentials(filename, initialCredentials) {
this.filename = filename;
AWS.Credentials.call(this, initialCredentials);
if (!this.accessKeyId) this.refresh();
},
refresh: function refresh() {
AWS.Credentials.call(this, JSON.parse(AWS.util.readFileSync(this.filename)));
}
});
AWS.EnvironmentCredentials = inherit(AWS.Credentials, {
constructor: function EnvironmentCredentials(envPrefix) {
this.envPrefix = envPrefix;
this.refresh();
},
refresh: function refresh() {
if (process === undefined) return;
var keys = ['ACCESS_KEY_ID', 'SECRET_ACCESS_KEY', 'SESSION_TOKEN'];
var values = [];
/*jshint forin:false*/
for (var i in keys) {
var prefix = '';
if (this.envPrefix) prefix = this.envPrefix + '_';
values[i] = process.env[prefix + keys[i]];
}
AWS.Credentials.apply(this, values);
}
});
AWS.CredentialProviderChain = inherit({
constructor: function CredentialProviderChain() {
this.providers = AWS.CredentialProviderChain.defaultProviders.slice(0);
},
resolve: function resolve() {
var finalCreds;
AWS.util.arrayEach(this.providers, function (provider) {
var creds;
if (provider instanceof Function) {
creds = provider.call();
} else {
creds = provider;
}
if (creds.accessKeyId) {
finalCreds = creds;
return AWS.util.abort;
}
});
return finalCreds ? finalCreds : new AWS.Credentials();
}
});
AWS.CredentialProviderChain.defaultProviders = [
function () { return new AWS.EnvironmentCredentials('AWS'); },
function () { return new AWS.EnvironmentCredentials('AMAZON'); }
];
/**
* @return [AWS.Config] The global configuration object singleton instance
* @readonly
*/
AWS.config = new AWS.Config();
| lib/config.js | /**
* Copyright 2011-2012 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.
*/
var AWS = require('./core');
var inherit = AWS.util.inherit;
/**
* The main configuration class used by all service objects to set
* the region, credentials, and other options for requests.
*
* By default, credentials and region settings are left unconfigured.
* This should be configured by the application before using any
* AWS service APIs.
*
* In order to set global configuration options, properties should
* be assigned to the global {AWS.config} object.
*
* @see AWS.config
*
* @!attribute credentials
* @return [AWS.Credentials] the AWS credentials to sign requests with.
*
* @!attribute region
* @example Set the global region setting to us-west-2
* AWS.config.update({region: 'us-west-2'});
* @return [AWS.Credentials] The region to send service requests to.
* @see http://docs.amazonwebservices.com/general/latest/gr/rande.html
* A list of available endpoints for each AWS service
*
* @!attribute maxRetries
* @return [Integer] the maximum amount of retries to perform for a
* service request. By default this value is calculated by the specific
* service object that the request is being made to.
*
* @!attribute sslEnabled
* @return [Boolean] whether SSL is enabled for requests
*
* @!attribute s3ForcePathStyle
* @return [Boolean] whether to force path style URLs for S3 objects
*/
AWS.Config = inherit({
/**
* Creates a new configuration object. This is the object that passes
* option data along to service requests, including credentials, security,
* region information, and some service specific settings.
*
* @example Creating a new configuration object with credentials and region
* var config = new AWS.Config({
* accessKeyId: 'AKID', secretAccessKey: 'SECRET', region: 'us-west-2'
* });
* @option options accessKeyId [String] your AWS access key ID.
* @option options secretAccessKey [String] your AWS secret access key.
* @option options sessionToken [AWS.Credentials] the optional AWS
* session token to sign requests with.
* @option options credentials [AWS.Credentials] the AWS credentials
* to sign requests with. You can either specify this object, or
* specify the accessKeyId and secretAccessKey options directly.
* @option options region [String] the region to send service requests to.
* See {region} for more information.
* @option options maxRetries [Integer] the maximum amount of retries to
* attempt with a request. See {maxRetries} for more information.
* @option options sslEnabled [Boolean] whether to enable SSL for
* requests.
* @option options s3ForcePathStyle [Booelan] whether to force path
* style URLs for S3 objects.
*/
constructor: function Config(options) {
if (options === undefined) options = {};
options = this.extractCredentials(options);
AWS.util.each.call(this, this.keys, function (key, value) {
this.set(key, options[key], value);
});
},
/**
* Updates the current configuration object with new options.
*
* @example Update maxRetries property of a configuration object
* config.update({maxRetries: 10});
* @param [Object] options a map of option keys and values.
* @see constructor
*/
update: function update(options) {
options = this.extractCredentials(options);
AWS.util.each.call(this, options, function (key, value) {
if (this.keys.hasOwnProperty(key)) this[key] = value;
});
},
/**
* Loads configuration data from a JSON file into this config object.
* @note Loading configuration will reset all existing configuration
* on the object.
* @param path [String] the path to load configuration from
* @return [AWS.Config] the same configuration object
*/
loadFromPath: function loadFromPath(path) {
this.clear();
var options = JSON.parse(AWS.util.readFileSync(path));
var fileSystemCreds = new AWS.FileSystemCredentials(path, this);
var chain = new AWS.CredentialProviderChain();
chain.providers.unshift(fileSystemCreds);
options.credentials = chain.resolve();
this.constructor(options);
return this;
},
/**
* Clears configuration data on this object
*
* @api private
*/
clear: function clear() {
/*jshint forin:false */
AWS.util.each.call(this, this.keys, function (key) {
delete this[key];
});
// reset credential provider
this.set('credentials', undefined);
},
/**
* Sets a property on the configuration object, allowing for a
* default value
* @api private
*/
set: function set(property, value, defaultValue) {
if (value === undefined) {
if (defaultValue === undefined) {
defaultValue = this.keys[property];
}
if (defaultValue instanceof Function) {
this[property] = defaultValue.call(this);
} else {
this[property] = defaultValue;
}
} else {
this[property] = value;
}
},
/**
* All of the keys with their default values.
*
* @constant
* @api private
*/
keys: {
credentials: function () {
return new AWS.CredentialProviderChain().resolve();
},
region: undefined,
maxRetries: undefined,
sslEnabled: true,
s3ForcePathStyle: false
},
/**
* Extracts accessKeyId, secretAccessKey and sessionToken
* from a configuration hash.
*
* @api private
*/
extractCredentials: function extractCredentials(options) {
if (options.accessKeyId && options.secretAccessKey) {
options = AWS.util.copy(options);
options.credentials = new AWS.Credentials(options);
}
return options;
}
});
AWS.Credentials = inherit({
/**
* A credentials object can be created using positional arguments or an options
* hash.
*
* @overload AWS.Credentials(accessKeyId, secretAccessKey, sessionToken=null)
* Creates a Credentials object with a given set of credential information
* as positional arguments.
* @param accessKeyId [String] the AWS access key ID
* @param secretAccessKey [String] the AWS secret access key
* @param sessionToken [String] the optional AWS session token
* @example Create a credentials object with AWS credentials
* var creds = new AWS.Credentials('akid', 'secret', 'session');
* @overload AWS.Credentials(options)
* Creates a Credentials object with a given set of credential information
* as an options hash.
* @option options accessKeyId [String] the AWS access key ID
* @option options secretAccessKey [String] the AWS secret access key
* @option options sessionToken [String] the optional AWS session token
* @example Create a credentials object with AWS credentials
* var creds = new AWS.Credentials({
* accessKeyId: 'akid', secretAccessKey: 'secret', sessionToken: 'session'
* });
*/
constructor: function Credentials() {
if (arguments.length == 1 && typeof arguments[0] === 'object') {
var creds = arguments[0].credentials || arguments[0];
this.accessKeyId = creds.accessKeyId;
this.secretAccessKey = creds.secretAccessKey;
this.sessionToken = creds.sessionToken;
} else {
this.accessKeyId = arguments[0];
this.secretAccessKey = arguments[1];
this.sessionToken = arguments[2];
}
},
/**
* Refreshes the credentials.
*
* @note Subclasses should override this class to provide credential
* refresh behavior.
*/
refresh: function refresh() { }
});
AWS.FileSystemCredentials = inherit(AWS.Credentials, {
constructor: function FileSystemCredentials(filename, initialCredentials) {
this.filename = filename;
AWS.Credentials.call(this, initialCredentials);
if (!this.accessKeyId) this.refresh();
},
refresh: function refresh() {
AWS.Credentials.call(this, JSON.parse(AWS.util.readFileSync(this.filename)));
}
});
AWS.EnvironmentCredentials = inherit(AWS.Credentials, {
constructor: function EnvironmentCredentials(envPrefix) {
this.envPrefix = envPrefix;
this.refresh();
},
refresh: function refresh() {
if (process === undefined) return;
var keys = ['ACCESS_KEY_ID', 'SECRET_ACCESS_KEY', 'SESSION_TOKEN'];
var values = [];
/*jshint forin:false*/
for (var i in keys) {
var prefix = '';
if (this.envPrefix) prefix = this.envPrefix + '_';
values[i] = process.env[prefix + keys[i]];
}
AWS.Credentials.apply(this, values);
}
});
AWS.CredentialProviderChain = inherit({
constructor: function CredentialProviderChain() {
this.providers = AWS.CredentialProviderChain.defaultProviders.slice(0);
},
resolve: function resolve() {
var finalCreds;
AWS.util.arrayEach(this.providers, function (provider) {
var creds;
if (provider instanceof Function) {
creds = provider.call();
} else {
creds = provider;
}
if (creds.accessKeyId) {
finalCreds = creds;
return AWS.util.abort;
}
});
return finalCreds ? finalCreds : new AWS.Credentials();
}
});
AWS.CredentialProviderChain.defaultProviders = [
function () { return new AWS.EnvironmentCredentials('AWS'); },
function () { return new AWS.EnvironmentCredentials('AMAZON'); }
];
/**
* @return [AWS.Config] The global configuration object singleton instance
* @readonly
*/
AWS.config = new AWS.Config();
| Document AWS.Credentials class
| lib/config.js | Document AWS.Credentials class | <ide><path>ib/config.js
<ide> }
<ide> });
<ide>
<add>/**
<add> * Represents your AWS security credentials, specifically the
<add> * {accessKeyId}, {secretAcessKey}, and optional {sessionToken}.
<add> * Creating a +Credentials+ object allows you to pass around your
<add> * security information to configuration and service objects.
<add> *
<add> * Note that this class typically does not need to be constructed manually,
<add> * as the {AWS.Config} and {AWS.Client} classes both accept simple
<add> * options hashes with the three keys. These structures will be converted
<add> * into Credentials objects automatically.
<add> *
<add> * == Expiring and Refreshing Credentials
<add> *
<add> * Occasionally credentials can expire in the middle of a long-running
<add> * application. In this case, the SDK will automatically attempt to
<add> * refresh the credentials from the storage location if the Credentials
<add> * class implements the {refresh} method.
<add> *
<add> * If you are implementing a credential storage location, you
<add> * will want to create a subclass of the +Credentials+ class and
<add> * override the {refresh} method. This method allows credentials to be
<add> * retrieved from the backing store, be it a file system, database, or
<add> * some network storage. The method should reset the credential attributes
<add> * on the object.
<add> *
<add> * @!attribute accessKeyId
<add> * @return [String] the AWS access key ID
<add> * @!attribute secretAccessKey
<add> * @return [String] the AWS secret access key
<add> * @!attribute sessionToken
<add> * @return [String] an optional AWS session token
<add> */
<ide> AWS.Credentials = inherit({
<ide>
<ide> /**
<ide> /**
<ide> * Refreshes the credentials.
<ide> *
<del> * @note Subclasses should override this class to provide credential
<del> * refresh behavior.
<add> * @note Subclasses should override this class to reset the
<add> * {accessKeyId}, {secretAccessKey} and optional {sessionToken}
<add> * on the credentials object.
<ide> */
<ide> refresh: function refresh() { }
<ide> |
|
Java | apache-2.0 | e31303c803953514ad3a9d19af17e7adfda43a55 | 0 | jooby-project/jooby,jooby-project/jooby,jooby-project/jooby,jooby-project/jooby,jooby-project/jooby | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* This copy of Woodstox XML processor is licensed under the
* Apache (Software) License, version 2.0 ("the License").
* See the License for details about distribution rights, and the
* specific rights regarding derivate works.
*
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/
*
* A copy is also included in the downloadable source code package
* containing Woodstox, in file "ASL2.0", under the same directory
* as this file.
*/
/**
o * 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.jooby;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static com.typesafe.config.ConfigValueFactory.fromAnyRef;
import static java.util.Objects.requireNonNull;
import java.io.File;
import java.lang.reflect.Type;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set;
import java.util.TimeZone;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import javax.inject.Singleton;
import javax.net.ssl.SSLContext;
import org.jooby.Route.Definition;
import org.jooby.Route.Mapper;
import org.jooby.Session.Store;
import org.jooby.handlers.AssetHandler;
import org.jooby.internal.AppPrinter;
import org.jooby.internal.BuiltinParser;
import org.jooby.internal.BuiltinRenderer;
import org.jooby.internal.CookieSessionManager;
import org.jooby.internal.DefaulErrRenderer;
import org.jooby.internal.HttpHandlerImpl;
import org.jooby.internal.JvmInfo;
import org.jooby.internal.LocaleUtils;
import org.jooby.internal.ParameterNameProvider;
import org.jooby.internal.RequestScope;
import org.jooby.internal.RouteMetadata;
import org.jooby.internal.ServerExecutorProvider;
import org.jooby.internal.ServerLookup;
import org.jooby.internal.ServerSessionManager;
import org.jooby.internal.SessionManager;
import org.jooby.internal.TypeConverters;
import org.jooby.internal.handlers.HeadHandler;
import org.jooby.internal.handlers.OptionsHandler;
import org.jooby.internal.handlers.TraceHandler;
import org.jooby.internal.js.JsJooby;
import org.jooby.internal.mvc.MvcRoutes;
import org.jooby.internal.parser.BeanParser;
import org.jooby.internal.parser.DateParser;
import org.jooby.internal.parser.LocalDateParser;
import org.jooby.internal.parser.LocaleParser;
import org.jooby.internal.parser.ParserExecutor;
import org.jooby.internal.parser.StaticMethodParser;
import org.jooby.internal.parser.StringConstructorParser;
import org.jooby.internal.ssl.SslContextProvider;
import org.jooby.scope.Providers;
import org.jooby.scope.RequestScoped;
import org.jooby.spi.HttpHandler;
import org.jooby.spi.Server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Joiner;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.escape.Escaper;
import com.google.common.html.HtmlEscapers;
import com.google.common.net.UrlEscapers;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.inject.Binder;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.Provider;
import com.google.inject.Stage;
import com.google.inject.TypeLiteral;
import com.google.inject.multibindings.Multibinder;
import com.google.inject.name.Named;
import com.google.inject.name.Names;
import com.google.inject.util.Types;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import com.typesafe.config.ConfigObject;
import com.typesafe.config.ConfigValue;
import com.typesafe.config.ConfigValueFactory;
import javaslang.Predicates;
import javaslang.control.Try;
import javaslang.control.Try.CheckedConsumer;
import javaslang.control.Try.CheckedRunnable;
/**
* <h1>jooby</h1>
* <h2>getting started</h2>
*
* <pre>
* public class MyApp extends Jooby {
*
* {
* use(new Jackson()); // 1. JSON serializer.
*
* // 2. Define a route
* get("/", req {@literal ->} {
* Map{@literal <}String, Object{@literal >} model = ...;
* return model;
* }
* }
*
* public static void main(String[] args) {
* run(MyApp::new, args); // 3. Done!
* }
* }
* </pre>
*
* <h2>application.conf</h2>
* <p>
* Jooby delegate configuration management to <a
* href="https://github.com/typesafehub/config">TypeSafe Config</a>.
* </p>
*
* <p>
* By default Jooby looks for an <code>application.conf</code>. If
* you want to specify a different file or location, you can do it with {@link #conf(String)}.
* </p>
*
* <p>
* <a href="https://github.com/typesafehub/config">TypeSafe Config</a> uses a hierarchical model to
* define and override properties.
* </p>
* <p>
* A {@link Jooby.Module} might provides his own set of properties through the
* {@link Jooby.Module#config()} method. By default, this method returns an empty config object.
* </p>
* For example:
*
* <pre>
* use(new M1());
* use(new M2());
* use(new M3());
* </pre>
*
* Previous example had the following order (first-listed are higher priority):
* <ul>
* <li>arguments properties</li>
* <li>System properties</li>
* <li>application.conf</li>
* <li>M3 properties</li>
* <li>M2 properties</li>
* <li>M1 properties</li>
* </ul>
* <p>
* Command line argmuents or system properties takes precedence over any application specific
* property.
* </p>
*
* <h2>env</h2>
* <p>
* Jooby defines one mode or environment: <strong>dev</strong>. In Jooby, <strong>dev</strong>
* is special and some modules could apply special settings while running in <strong>dev</strong>.
* Any other env is usually considered a <code>prod</code> like env. But that depends on module
* implementor.
* </p>
* <p>
* An <code>environment</code> can be defined in your <code>.conf</code> file using the
* <code>application.env</code> property. If missing, Jooby set the <code>env</code> for you to
* <strong>dev</strong>.
* </p>
* <p>
* There is more at {@link Env} please read the {@link Env} javadoc.
* </p>
*
* <h2>modules: the jump to full-stack framework</h2>
* <p>
* {@link Jooby.Module Modules} are quite similar to a Guice modules except that the configure
* callback has been complementing with {@link Env} and {@link Config}.
* </p>
*
* <pre>
* public class MyModule implements Jooby.Module {
* public void configure(Env env, Config config, Binder binder) {
* }
* }
* </pre>
*
* From the configure callback you can bind your services as you usually do in a Guice app.
* <p>
* There is more at {@link Jooby.Module} so please read the {@link Jooby.Module} javadoc.
* </p>
*
* <h2>path patterns</h2>
* <p>
* Jooby supports Ant-style path patterns:
* </p>
* <p>
* Some examples:
* </p>
* <ul>
* <li>{@code com/t?st.html} - matches {@code com/test.html} but also {@code com/tast.html} or
* {@code com/txst.html}</li>
* <li>{@code com/*.html} - matches all {@code .html} files in the {@code com} directory</li>
* <li><code>com/{@literal **}/test.html</code> - matches all {@code test.html} files underneath the
* {@code com} path</li>
* <li>{@code **}/{@code *} - matches any path at any level.</li>
* <li>{@code *} - matches any path at any level, shorthand for {@code **}/{@code *}.</li>
* </ul>
*
* <h3>variables</h3>
* <p>
* Jooby supports path parameters too:
* </p>
* <p>
* Some examples:
* </p>
* <ul>
* <li><code> /user/{id}</code> - /user/* and give you access to the <code>id</code> var.</li>
* <li><code> /user/:id</code> - /user/* and give you access to the <code>id</code> var.</li>
* <li><code> /user/{id:\\d+}</code> - /user/[digits] and give you access to the numeric
* <code>id</code> var.</li>
* </ul>
*
* <h2>routes</h2>
* <p>
* Routes perform actions in response to a server HTTP request.
* </p>
* <p>
* Routes are executed in the order they are defined, for example:
* </p>
*
* <pre>
* get("/", (req, rsp) {@literal ->} {
* log.info("first"); // start here and go to second
* });
*
* get("/", (req, rsp) {@literal ->} {
* log.info("second"); // execute after first and go to final
* });
*
* get("/", (req, rsp) {@literal ->} {
* rsp.send("final"); // done!
* });
* </pre>
*
* Previous example can be rewritten using {@link Route.Filter}:
*
* <pre>
* get("/", (req, rsp, chain) {@literal ->} {
* log.info("first"); // start here and go to second
* chain.next(req, rsp);
* });
*
* get("/", (req, rsp, chain) {@literal ->} {
* log.info("second"); // execute after first and go to final
* chain.next(req, rsp);
* });
*
* get("/", (req, rsp) {@literal ->} {
* rsp.send("final"); // done!
* });
* </pre>
*
* Due to the use of lambdas a route is a singleton and you should NOT use global variables. For
* example this is a bad practice:
*
* <pre>
* List{@literal <}String{@literal >} names = new ArrayList{@literal <}{@literal >}(); // names produces side effects
* get("/", (req, rsp) {@literal ->} {
* names.add(req.param("name").value();
* // response will be different between calls.
* rsp.send(names);
* });
* </pre>
*
* <h3>mvc routes</h3>
* <p>
* A Mvc route use annotations to define routes:
* </p>
*
* <pre>
* use(MyRoute.class);
* ...
*
* // MyRoute.java
* {@literal @}Path("/")
* public class MyRoute {
*
* {@literal @}GET
* public String hello() {
* return "Hello Jooby";
* }
* }
* </pre>
* <p>
* Programming model is quite similar to JAX-RS/Jersey with some minor differences and/or
* simplifications.
* </p>
*
* <p>
* To learn more about Mvc Routes, please check {@link org.jooby.mvc.Path},
* {@link org.jooby.mvc.Produces} {@link org.jooby.mvc.Consumes} javadoc.
* </p>
*
* <h2>static files</h2>
* <p>
* Static files, like: *.js, *.css, ..., etc... can be served with:
* </p>
*
* <pre>
* assets("assets/**");
* </pre>
* <p>
* Classpath resources under the <code>/assets</code> folder will be accessible from client/browser.
* </p>
*
* <h2>lifecyle</h2>
* <p>
* We do provide {@link #onStart(CheckedConsumer)} and {@link #onStop(CheckedConsumer)} callbacks.
* These callbacks are executed are application startup or shutdown time:
* </p>
*
* <pre>{@code
* {
* onStart(() -> {
* log.info("Welcome!");
* });
*
* onStop(() -> {
* log.info("Bye!");
* });
* }
* }</pre>
*
* <p>
* From life cycle callbacks you can access to application services:
* </p>
*
* <pre>{@code
* {
* onStart(registry -> {
* MyDatabase db = registry.require(MyDatabase.class);
* // do something with databse:
* });
* }
* }</pre>
*
*
* @author edgar
* @since 0.1.0
* @see Jooby.Module
*/
public class Jooby implements Router, LifeCycle, Registry {
/**
* <pre>{@code
* {
* on("dev", () -> {
* // run something on dev
* }).orElse(() -> {
* // run something on prod
* });
* }
* }</pre>
*
*/
public interface EnvPredicate {
/**
* <pre>{@code
* {
* on("dev", () -> {
* // run something on dev
* }).orElse(() -> {
* // run something on prod
* });
* }
* }</pre>
*
* @param callback Env callback.
*/
default void orElse(final Runnable callback) {
orElse(conf -> callback.run());
}
/**
* <pre>{@code
* {
* on("dev", () -> {
* // run something on dev
* }).orElse(conf -> {
* // run something on prod
* });
* }
* }</pre>
*
* @param callback Env callback.
*/
void orElse(Consumer<Config> callback);
}
/**
* A module can publish or produces: {@link Route.Definition routes}, {@link Parser},
* {@link Renderer}, and any other application specific service or contract of your choice.
* <p>
* It is similar to {@link com.google.inject.Module} except for the callback method receives a
* {@link Env}, {@link Config} and {@link Binder}.
* </p>
*
* <p>
* A module can provide his own set of properties through the {@link #config()} method. By
* default, this method returns an empty config object.
* </p>
* For example:
*
* <pre>
* use(new M1());
* use(new M2());
* use(new M3());
* </pre>
*
* Previous example had the following order (first-listed are higher priority):
* <ul>
* <li>System properties</li>
* <li>application.conf</li>
* <li>M3 properties</li>
* <li>M2 properties</li>
* <li>M1 properties</li>
* </ul>
*
* <p>
* A module can provide start/stop methods in order to start or close resources.
* </p>
*
* @author edgar
* @since 0.1.0
* @see Jooby#use(Jooby.Module)
*/
public interface Module {
/**
* @return Produces a module config object (when need it). By default a module doesn't produce
* any configuration object.
*/
default Config config() {
return ConfigFactory.empty();
}
/**
* Configure and produces bindings for the underlying application. A module can optimize or
* customize a service by checking current the {@link Env application env} and/or the current
* application properties available from {@link Config}.
*
* @param env The current application's env. Not null.
* @param conf The current config object. Not null.
* @param binder A guice binder. Not null.
*/
void configure(Env env, Config conf, Binder binder) throws Throwable;
}
private static class MvcClass implements Route.Props<MvcClass> {
Class<?> routeClass;
String path;
ImmutableMap.Builder<String, Object> attrs = ImmutableMap.builder();
private List<MediaType> consumes;
private String name;
private List<MediaType> produces;
private List<String> excludes;
private Mapper<?> mapper;
private String prefix;
public MvcClass(final Class<?> routeClass, final String path, final String prefix) {
this.routeClass = routeClass;
this.path = path;
this.prefix = prefix;
}
@Override
public MvcClass attr(final String name, final Object value) {
attrs.put(name, value);
return this;
}
@Override
public MvcClass name(final String name) {
this.name = name;
return this;
}
@Override
public MvcClass consumes(final List<MediaType> consumes) {
this.consumes = consumes;
return this;
}
@Override
public MvcClass produces(final List<MediaType> produces) {
this.produces = produces;
return this;
}
@Override
public MvcClass excludes(final List<String> excludes) {
this.excludes = excludes;
return this;
}
@Override
public MvcClass map(final Mapper<?> mapper) {
this.mapper = mapper;
return this;
}
public Route.Definition apply(final Route.Definition route) {
attrs.build().forEach(route::attr);
if (name != null) {
route.name(name);
}
if (prefix != null) {
route.name(prefix + "/" + route.name());
}
if (consumes != null) {
route.consumes(consumes);
}
if (produces != null) {
route.produces(produces);
}
if (excludes != null) {
route.excludes(excludes);
}
if (mapper != null) {
route.map(mapper);
}
return route;
}
}
private static class EnvDep {
Predicate<String> predicate;
Consumer<Config> callback;
public EnvDep(final Predicate<String> predicate, final Consumer<Config> callback) {
this.predicate = predicate;
this.callback = callback;
}
}
static {
// set pid as system property
String pid = System.getProperty("pid", JvmInfo.pid() + "");
System.setProperty("pid", pid);
}
/**
* Keep track of routes.
*/
private transient Set<Object> bag = new LinkedHashSet<>();
/**
* The override config. Optional.
*/
private transient Config srcconf;
private final transient AtomicBoolean started = new AtomicBoolean(false);
/** Keep the global injector instance. */
private transient Injector injector;
/** Session store. */
private transient Session.Definition session = new Session.Definition(Session.Mem.class);
/** Env builder. */
private transient Env.Builder env = Env.DEFAULT;
/** Route's prefix. */
private transient String prefix;
/** startup callback . */
private transient List<CheckedConsumer<Registry>> onStart = new ArrayList<>();
private transient List<CheckedConsumer<Registry>> onStarted = new ArrayList<>();
/** stop callback . */
private transient List<CheckedConsumer<Registry>> onStop = new ArrayList<>();
/** Mappers . */
@SuppressWarnings("rawtypes")
private transient Mapper mapper;
/** Don't add same mapper twice . */
private transient Set<String> mappers = new HashSet<>();
/** Bean parser . */
private transient Optional<Parser> beanParser = Optional.empty();
private transient ServerLookup server = new ServerLookup();
private transient String dateFormat;
private transient Charset charset;
private transient String[] languages;
private transient ZoneId zoneId;
private transient Integer port;
private transient Integer securePort;
private transient String numberFormat;
private transient boolean http2;
private transient List<Consumer<Binder>> executors = new ArrayList<>();
private transient boolean defaultExecSet;
private boolean throwBootstrapException;
/**
* creates the injector
*/
private transient BiFunction<Stage, com.google.inject.Module, Injector> injectorFactory = Guice::createInjector;
/**
* Creates a new {@link Jooby} application.
*/
public Jooby() {
this(null);
}
/**
* Creates a new application and prefix all the names of the routes with the given prefix. Useful,
* for dynamic/advanced routing. See {@link Route.Chain#next(String, Request, Response)}.
*
* @param prefix Route name prefix.
*/
public Jooby(final String prefix) {
this.prefix = prefix;
use(server);
}
@Override
public Jooby use(final Jooby app) {
return use(Optional.empty(), app);
}
@Override
public Jooby use(final String path, final Jooby app) {
return use(Optional.of(path), app);
}
/**
* Use the provided HTTP server.
*
* @param server Server.
* @return This jooby instance.
*/
public Jooby server(final Class<? extends Server> server) {
requireNonNull(server, "Server required.");
// remove server lookup
List<Object> tmp = bag.stream()
.skip(1)
.collect(Collectors.toList());
tmp.add(0,
(Module) (env, conf, binder) -> binder.bind(Server.class).to(server).asEagerSingleton());
bag.clear();
bag.addAll(tmp);
return this;
}
private Jooby use(final Optional<String> path, final Jooby app) {
requireNonNull(app, "App is required.");
Function<Route.Definition, Route.Definition> rewrite = r -> {
return path.map(p -> {
Route.Definition result = new Route.Definition(r.method(), p + r.pattern(), r.filter());
result.consumes(r.consumes());
result.produces(r.produces());
result.excludes(r.excludes());
return result;
}).orElse(r);
};
app.bag.forEach(it -> {
if (it instanceof Route.Definition) {
this.bag.add(rewrite.apply((Definition) it));
} else if (it instanceof Route.Group) {
((Route.Group) it).routes().forEach(r -> this.bag.add(rewrite.apply(r)));
} else if (it instanceof MvcClass) {
Object routes = path.<Object> map(p -> new MvcClass(((MvcClass) it).routeClass, p, prefix))
.orElse(it);
this.bag.add(routes);
} else {
// everything else
this.bag.add(it);
}
});
// start/stop callback
app.onStart.forEach(this.onStart::add);
app.onStarted.forEach(this.onStarted::add);
app.onStop.forEach(this.onStop::add);
// mapper
if (app.mapper != null) {
this.map(app.mapper);
}
return this;
}
@Override
public Route.Group use(final String pattern) {
Route.Group group = new Route.Group(pattern, prefix);
this.bag.add(group);
return group;
}
/**
* Set a custom {@link Env.Builder} to use.
*
* @param env A custom env builder.
* @return This jooby instance.
*/
public Jooby env(final Env.Builder env) {
this.env = requireNonNull(env, "Env builder is required.");
return this;
}
@Override
public Jooby onStart(final CheckedRunnable callback) {
LifeCycle.super.onStart(callback);
return this;
}
@Override
public Jooby onStart(final CheckedConsumer<Registry> callback) {
requireNonNull(callback, "Callback is required.");
onStart.add(callback);
return this;
}
@Override
public Jooby onStarted(final CheckedRunnable callback) {
LifeCycle.super.onStarted(callback);
return this;
}
@Override
public Jooby onStarted(final CheckedConsumer<Registry> callback) {
requireNonNull(callback, "Callback is required.");
onStarted.add(callback);
return this;
}
@Override
public Jooby onStop(final CheckedRunnable callback) {
LifeCycle.super.onStop(callback);
return this;
}
@Override
public Jooby onStop(final CheckedConsumer<Registry> callback) {
requireNonNull(callback, "Callback is required.");
onStop.add(callback);
return this;
}
/**
* Run the given callback if and only if, application runs in the given environment.
*
* <pre>
* {
* on("dev", () {@literal ->} {
* use(new DevModule());
* });
* }
* </pre>
*
* There is an else clause which is the opposite version of the env predicate:
*
* <pre>
* {
* on("dev", () {@literal ->} {
* use(new DevModule());
* }).orElse(() {@literal ->} {
* use(new RealModule());
* });
* }
* </pre>
*
* @param env Environment where we want to run the callback.
* @param callback An env callback.
* @return This jooby instance.
*/
public EnvPredicate on(final String env, final Runnable callback) {
requireNonNull(env, "Env is required.");
return on(envpredicate(env), callback);
}
/**
* Run the given callback if and only if, application runs in the given environment.
*
* <pre>
* {
* on("dev", () {@literal ->} {
* use(new DevModule());
* });
* }
* </pre>
*
* There is an else clause which is the opposite version of the env predicate:
*
* <pre>
* {
* on("dev", conf {@literal ->} {
* use(new DevModule());
* }).orElse(conf {@literal ->} {
* use(new RealModule());
* });
* }
* </pre>
*
* @param env Environment where we want to run the callback.
* @param callback An env callback.
* @return This jooby instance.
*/
public EnvPredicate on(final String env, final Consumer<Config> callback) {
requireNonNull(env, "Env is required.");
return on(envpredicate(env), callback);
}
/**
* Run the given callback if and only if, application runs in the given envirobment.
*
* <pre>
* {
* on("dev", "test", () {@literal ->} {
* use(new DevModule());
* });
* }
* </pre>
*
* There is an else clause which is the opposite version of the env predicate:
*
* <pre>
* {
* on(env {@literal ->} env.equals("dev"), () {@literal ->} {
* use(new DevModule());
* }).orElse(() {@literal ->} {
* use(new RealModule());
* });
* }
* </pre>
*
* @param predicate Predicate to check the environment.
* @param callback An env callback.
* @return This jooby instance.
*/
public EnvPredicate on(final Predicate<String> predicate, final Runnable callback) {
requireNonNull(predicate, "Predicate is required.");
requireNonNull(callback, "Callback is required.");
return on(predicate, conf -> callback.run());
}
/**
* Run the given callback if and only if, application runs in the given environment.
*
* <pre>
* {
* on(env {@literal ->} env.equals("dev"), conf {@literal ->} {
* use(new DevModule());
* });
* }
* </pre>
*
* @param predicate Predicate to check the environment.
* @param callback An env callback.
* @return This jooby instance.
*/
public EnvPredicate on(final Predicate<String> predicate, final Consumer<Config> callback) {
requireNonNull(predicate, "Predicate is required.");
requireNonNull(callback, "Callback is required.");
this.bag.add(new EnvDep(predicate, callback));
return otherwise -> this.bag.add(new EnvDep(predicate.negate(), otherwise));
}
/**
* Run the given callback if and only if, application runs in the given environment.
*
* <pre>
* {
* on("dev", "test", "mock", () {@literal ->} {
* use(new DevModule());
* });
* }
* </pre>
*
* @param env1 Environment where we want to run the callback.
* @param env2 Environment where we want to run the callback.
* @param env3 Environment where we want to run the callback.
* @param callback An env callback.
* @return This jooby instance.
*/
public Jooby on(final String env1, final String env2, final String env3,
final Runnable callback) {
on(envpredicate(env1).or(envpredicate(env2)).or(envpredicate(env3)), callback);
return this;
}
@Override
public <T> T require(final Key<T> type) {
checkState(injector != null, "App didn't start yet");
return injector.getInstance(type);
}
@Override
public Route.OneArgHandler promise(final Deferred.Initializer initializer) {
return req -> {
return new Deferred(initializer);
};
}
@Override
public Route.OneArgHandler promise(final String executor,
final Deferred.Initializer initializer) {
return req -> new Deferred(executor, initializer);
}
@Override
public Route.OneArgHandler promise(final Deferred.Initializer0 initializer) {
return req -> {
return new Deferred(initializer);
};
}
@Override
public Route.OneArgHandler promise(final String executor,
final Deferred.Initializer0 initializer) {
return req -> new Deferred(executor, initializer);
}
/**
* Setup a session store to use. Useful if you want/need to persist sessions between shutdowns,
* apply timeout policies, etc...
*
* Jooby comes with a dozen of {@link Session.Store}, checkout the
* <a href="http://jooby.org/doc/session">session modules</a>.
*
* This method returns a {@link Session.Definition} objects that let you customize the session
* cookie.
*
* @param store A session store.
* @return A session store definition.
*/
public Session.Definition session(final Class<? extends Session.Store> store) {
this.session = new Session.Definition(requireNonNull(store, "A session store is required."));
return this.session;
}
/**
* Setup a session store that saves data in a the session cookie. It makes the application
* stateless, which help to scale easily. Keep in mind that a cookie has a limited size (up to
* 4kb) so you must pay attention to what you put in the session object (don't use as cache).
*
* Cookie session signed data using the <code>application.secret</code> property, so you must
* provide an <code>application.secret</code> value. On dev environment you can set it in your
* <code>.conf</code> file. In prod is probably better to provide as command line argument and/or
* environment variable. Just make sure to keep it private.
*
* Please note {@link Session#id()}, {@link Session#accessedAt()}, etc.. make no sense for cookie
* sessions, just the {@link Session#attributes()}.
*
* This method returns a {@link Session.Definition} objects that let you customize the session
* cookie.
*
* @return A session definition/configuration object.
*/
public Session.Definition cookieSession() {
this.session = new Session.Definition();
return this.session;
}
/**
* Setup a session store to use. Useful if you want/need to persist sessions between shutdowns,
* apply timeout policies, etc...
*
* Jooby comes with a dozen of {@link Session.Store}, checkout the
* <a href="http://jooby.org/doc/session">session modules</a>.
*
* This method returns a {@link Session.Definition} objects that let you customize the session
* cookie.
*
* @param store A session store.
* @return A session store definition.
*/
public Session.Definition session(final Session.Store store) {
this.session = new Session.Definition(requireNonNull(store, "A session store is required."));
return this.session;
}
/**
* Register a new param/body converter. See {@link Parser} for more details.
*
* @param parser A parser.
* @return This jooby instance.
*/
public Jooby parser(final Parser parser) {
if (parser instanceof BeanParser) {
beanParser = Optional.of(parser);
} else {
bag.add(requireNonNull(parser, "A parser is required."));
}
return this;
}
/**
* Append a response {@link Renderer} for write HTTP messages.
*
* @param renderer A renderer renderer.
* @return This jooby instance.
*/
public Jooby renderer(final Renderer renderer) {
this.bag.add(requireNonNull(renderer, "A renderer is required."));
return this;
}
@Override
public Route.Collection before(final String method, final String pattern,
final Route.Before handler, final Route.Before... chain) {
Route.Definition[] routes = javaslang.collection.List.of(handler)
.appendAll(Arrays.asList(chain))
.map(before -> appendDefinition(new Route.Definition(method, pattern, before)))
.toJavaArray(Route.Definition.class);
return new Route.Collection(routes);
}
@Override
public Route.Collection after(final String method, final String pattern,
final Route.After handler, final Route.After... chain) {
Route.Definition[] routes = javaslang.collection.List.of(handler)
.appendAll(Arrays.asList(chain))
.map(after -> appendDefinition(new Route.Definition(method, pattern, after)))
.toJavaArray(Route.Definition.class);
return new Route.Collection(routes);
}
@Override
public Route.Collection complete(final String method, final String pattern,
final Route.Complete handler, final Route.Complete... chain) {
Route.Definition[] routes = javaslang.collection.List.of(handler)
.appendAll(Arrays.asList(chain))
.map(complete -> appendDefinition(new Route.Definition(method, pattern, complete)))
.toJavaArray(Route.Definition.class);
return new Route.Collection(routes);
}
@Override
public Route.Definition use(final String path, final Route.Filter filter) {
return appendDefinition(new Route.Definition("*", path, filter));
}
@Override
public Route.Definition use(final String verb, final String path, final Route.Filter filter) {
return appendDefinition(new Route.Definition(verb, path, filter));
}
@Override
public Route.Definition use(final String verb, final String path, final Route.Handler handler) {
return appendDefinition(new Route.Definition(verb, path, handler));
}
@Override
public Route.Definition use(final String path, final Route.Handler handler) {
return appendDefinition(new Route.Definition("*", path, handler));
}
@Override
public Route.Definition use(final String path, final Route.OneArgHandler handler) {
return appendDefinition(new Route.Definition("*", path, handler));
}
@Override
public Route.Definition get(final String path, final Route.Handler handler) {
return appendDefinition(new Route.Definition("GET", path, handler));
}
@Override
public Route.Collection get(final String path1, final String path2, final Route.Handler handler) {
return new Route.Collection(
new Route.Definition[]{get(path1, handler), get(path2, handler) });
}
@Override
public Route.Collection get(final String path1, final String path2, final String path3,
final Route.Handler handler) {
return new Route.Collection(
new Route.Definition[]{get(path1, handler), get(path2, handler), get(path3, handler) });
}
@Override
public Route.Definition get(final String path, final Route.OneArgHandler handler) {
return appendDefinition(new Route.Definition("GET", path, handler));
}
@Override
public Route.Collection get(final String path1, final String path2,
final Route.OneArgHandler handler) {
return new Route.Collection(
new Route.Definition[]{get(path1, handler), get(path2, handler) });
}
@Override
public Route.Collection get(final String path1, final String path2,
final String path3, final Route.OneArgHandler handler) {
return new Route.Collection(
new Route.Definition[]{get(path1, handler), get(path2, handler), get(path3, handler) });
}
@Override
public Route.Definition get(final String path, final Route.ZeroArgHandler handler) {
return appendDefinition(new Route.Definition("GET", path, handler));
}
@Override
public Route.Collection get(final String path1, final String path2,
final Route.ZeroArgHandler handler) {
return new Route.Collection(
new Route.Definition[]{get(path1, handler), get(path2, handler) });
}
@Override
public Route.Collection get(final String path1, final String path2,
final String path3, final Route.ZeroArgHandler handler) {
return new Route.Collection(
new Route.Definition[]{get(path1, handler), get(path2, handler), get(path3, handler) });
}
@Override
public Route.Definition get(final String path, final Route.Filter filter) {
return appendDefinition(new Route.Definition("GET", path, filter));
}
@Override
public Route.Collection get(final String path1, final String path2, final Route.Filter filter) {
return new Route.Collection(new Route.Definition[]{get(path1, filter), get(path2, filter) });
}
@Override
public Route.Collection get(final String path1, final String path2,
final String path3, final Route.Filter filter) {
return new Route.Collection(
new Route.Definition[]{get(path1, filter), get(path2, filter), get(path3, filter) });
}
@Override
public Route.Definition post(final String path, final Route.Handler handler) {
return appendDefinition(new Route.Definition("POST", path, handler));
}
@Override
public Route.Collection post(final String path1, final String path2,
final Route.Handler handler) {
return new Route.Collection(
new Route.Definition[]{post(path1, handler), post(path2, handler) });
}
@Override
public Route.Collection post(final String path1, final String path2,
final String path3, final Route.Handler handler) {
return new Route.Collection(
new Route.Definition[]{post(path1, handler), post(path2, handler), post(path3, handler) });
}
@Override
public Route.Definition post(final String path, final Route.OneArgHandler handler) {
return appendDefinition(new Route.Definition("POST", path, handler));
}
@Override
public Route.Collection post(final String path1, final String path2,
final Route.OneArgHandler handler) {
return new Route.Collection(
new Route.Definition[]{post(path1, handler), post(path2, handler) });
}
@Override
public Route.Collection post(final String path1, final String path2,
final String path3, final Route.OneArgHandler handler) {
return new Route.Collection(
new Route.Definition[]{post(path1, handler), post(path2, handler), post(path3, handler) });
}
@Override
public Route.Definition post(final String path, final Route.ZeroArgHandler handler) {
return appendDefinition(new Route.Definition("POST", path, handler));
}
@Override
public Route.Collection post(final String path1, final String path2,
final Route.ZeroArgHandler handler) {
return new Route.Collection(
new Route.Definition[]{post(path1, handler), post(path2, handler) });
}
@Override
public Route.Collection post(final String path1, final String path2,
final String path3, final Route.ZeroArgHandler handler) {
return new Route.Collection(
new Route.Definition[]{post(path1, handler), post(path2, handler), post(path3, handler) });
}
@Override
public Route.Definition post(final String path, final Route.Filter filter) {
return appendDefinition(new Route.Definition("POST", path, filter));
}
@Override
public Route.Collection post(final String path1, final String path2,
final Route.Filter filter) {
return new Route.Collection(
new Route.Definition[]{post(path1, filter), post(path2, filter) });
}
@Override
public Route.Collection post(final String path1, final String path2,
final String path3, final Route.Filter filter) {
return new Route.Collection(
new Route.Definition[]{post(path1, filter), post(path2, filter), post(path3, filter) });
}
@Override
public Route.Definition head(final String path, final Route.Handler handler) {
return appendDefinition(new Route.Definition("HEAD", path, handler));
}
@Override
public Route.Definition head(final String path,
final Route.OneArgHandler handler) {
return appendDefinition(new Route.Definition("HEAD", path, handler));
}
@Override
public Route.Definition head(final String path, final Route.ZeroArgHandler handler) {
return appendDefinition(new Route.Definition("HEAD", path, handler));
}
@Override
public Route.Definition head(final String path, final Route.Filter filter) {
return appendDefinition(new Route.Definition("HEAD", path, filter));
}
@Override
public Route.Definition head() {
return appendDefinition(new Route.Definition("HEAD", "*", filter(HeadHandler.class))
.name("*.head"));
}
@Override
public Route.Definition options(final String path, final Route.Handler handler) {
return appendDefinition(new Route.Definition("OPTIONS", path, handler));
}
@Override
public Route.Definition options(final String path,
final Route.OneArgHandler handler) {
return appendDefinition(new Route.Definition("OPTIONS", path, handler));
}
@Override
public Route.Definition options(final String path,
final Route.ZeroArgHandler handler) {
return appendDefinition(new Route.Definition("OPTIONS", path, handler));
}
@Override
public Route.Definition options(final String path,
final Route.Filter filter) {
return appendDefinition(new Route.Definition("OPTIONS", path, filter));
}
@Override
public Route.Definition options() {
return appendDefinition(new Route.Definition("OPTIONS", "*", handler(OptionsHandler.class))
.name("*.options"));
}
@Override
public Route.Definition put(final String path,
final Route.Handler handler) {
return appendDefinition(new Route.Definition("PUT", path, handler));
}
@Override
public Route.Collection put(final String path1, final String path2,
final Route.Handler handler) {
return new Route.Collection(
new Route.Definition[]{put(path1, handler), put(path2, handler) });
}
@Override
public Route.Collection put(final String path1, final String path2,
final String path3, final Route.Handler handler) {
return new Route.Collection(
new Route.Definition[]{put(path1, handler), put(path2, handler), put(path3, handler) });
}
@Override
public Route.Definition put(final String path,
final Route.OneArgHandler handler) {
return appendDefinition(new Route.Definition("PUT", path, handler));
}
@Override
public Route.Collection put(final String path1, final String path2,
final Route.OneArgHandler handler) {
return new Route.Collection(
new Route.Definition[]{put(path1, handler), put(path2, handler) });
}
@Override
public Route.Collection put(final String path1, final String path2,
final String path3, final Route.OneArgHandler handler) {
return new Route.Collection(
new Route.Definition[]{put(path1, handler), put(path2, handler), put(path3, handler) });
}
@Override
public Route.Definition put(final String path,
final Route.ZeroArgHandler handler) {
return appendDefinition(new Route.Definition("PUT", path, handler));
}
@Override
public Route.Collection put(final String path1, final String path2,
final Route.ZeroArgHandler handler) {
return new Route.Collection(
new Route.Definition[]{put(path1, handler), put(path2, handler) });
}
@Override
public Route.Collection put(final String path1, final String path2,
final String path3, final Route.ZeroArgHandler handler) {
return new Route.Collection(
new Route.Definition[]{put(path1, handler), put(path2, handler), put(path3, handler) });
}
@Override
public Route.Definition put(final String path,
final Route.Filter filter) {
return appendDefinition(new Route.Definition("PUT", path, filter));
}
@Override
public Route.Collection put(final String path1, final String path2,
final Route.Filter filter) {
return new Route.Collection(
new Route.Definition[]{put(path1, filter), put(path2, filter) });
}
@Override
public Route.Collection put(final String path1, final String path2,
final String path3, final Route.Filter filter) {
return new Route.Collection(
new Route.Definition[]{put(path1, filter), put(path2, filter), put(path3, filter) });
}
@Override
public Route.Definition patch(final String path, final Route.Handler handler) {
return appendDefinition(new Route.Definition("PATCH", path, handler));
}
@Override
public Route.Collection patch(final String path1, final String path2,
final Route.Handler handler) {
return new Route.Collection(
new Route.Definition[]{patch(path1, handler), patch(path2, handler) });
}
@Override
public Route.Collection patch(final String path1, final String path2,
final String path3, final Route.Handler handler) {
return new Route.Collection(
new Route.Definition[]{patch(path1, handler), patch(path2, handler),
patch(path3, handler) });
}
@Override
public Route.Definition patch(final String path, final Route.OneArgHandler handler) {
return appendDefinition(new Route.Definition("PATCH", path, handler));
}
@Override
public Route.Collection patch(final String path1, final String path2,
final Route.OneArgHandler handler) {
return new Route.Collection(
new Route.Definition[]{patch(path1, handler), patch(path2, handler) });
}
@Override
public Route.Collection patch(final String path1, final String path2,
final String path3, final Route.OneArgHandler handler) {
return new Route.Collection(
new Route.Definition[]{patch(path1, handler), patch(path2, handler),
patch(path3, handler) });
}
@Override
public Route.Definition patch(final String path, final Route.ZeroArgHandler handler) {
return appendDefinition(new Route.Definition("PATCH", path, handler));
}
@Override
public Route.Collection patch(final String path1, final String path2,
final Route.ZeroArgHandler handler) {
return new Route.Collection(
new Route.Definition[]{patch(path1, handler), patch(path2, handler) });
}
@Override
public Route.Collection patch(final String path1, final String path2,
final String path3, final Route.ZeroArgHandler handler) {
return new Route.Collection(
new Route.Definition[]{patch(path1, handler), patch(path2, handler),
patch(path3, handler) });
}
@Override
public Route.Definition patch(final String path,
final Route.Filter filter) {
return appendDefinition(new Route.Definition("PATCH", path, filter));
}
@Override
public Route.Collection patch(final String path1, final String path2,
final Route.Filter filter) {
return new Route.Collection(
new Route.Definition[]{patch(path1, filter), patch(path2, filter) });
}
@Override
public Route.Collection patch(final String path1, final String path2,
final String path3, final Route.Filter filter) {
return new Route.Collection(
new Route.Definition[]{patch(path1, filter), patch(path2, filter),
patch(path3, filter) });
}
@Override
public Route.Definition delete(final String path, final Route.Handler handler) {
return appendDefinition(new Route.Definition("DELETE", path, handler));
}
@Override
public Route.Collection delete(final String path1, final String path2,
final Route.Handler handler) {
return new Route.Collection(
new Route.Definition[]{delete(path1, handler), delete(path2, handler) });
}
@Override
public Route.Collection delete(final String path1, final String path2, final String path3,
final Route.Handler handler) {
return new Route.Collection(
new Route.Definition[]{delete(path1, handler), delete(path2, handler),
delete(path3, handler) });
}
@Override
public Route.Definition delete(final String path, final Route.OneArgHandler handler) {
return appendDefinition(new Route.Definition("DELETE", path, handler));
}
@Override
public Route.Collection delete(final String path1, final String path2,
final Route.OneArgHandler handler) {
return new Route.Collection(
new Route.Definition[]{delete(path1, handler), delete(path2, handler) });
}
@Override
public Route.Collection delete(final String path1, final String path2, final String path3,
final Route.OneArgHandler handler) {
return new Route.Collection(
new Route.Definition[]{delete(path1, handler), delete(path2, handler),
delete(path3, handler) });
}
@Override
public Route.Definition delete(final String path,
final Route.ZeroArgHandler handler) {
return appendDefinition(new Route.Definition("DELETE", path, handler));
}
@Override
public Route.Collection delete(final String path1,
final String path2, final Route.ZeroArgHandler handler) {
return new Route.Collection(
new Route.Definition[]{delete(path1, handler), delete(path2, handler) });
}
@Override
public Route.Collection delete(final String path1,
final String path2, final String path3,
final Route.ZeroArgHandler handler) {
return new Route.Collection(
new Route.Definition[]{delete(path1, handler), delete(path2, handler),
delete(path3, handler) });
}
@Override
public Route.Definition delete(final String path, final Route.Filter filter) {
return appendDefinition(new Route.Definition("DELETE", path, filter));
}
@Override
public Route.Collection delete(final String path1, final String path2,
final Route.Filter filter) {
return new Route.Collection(
new Route.Definition[]{delete(path1, filter), delete(path2, filter) });
}
@Override
public Route.Collection delete(final String path1, final String path2, final String path3,
final Route.Filter filter) {
return new Route.Collection(
new Route.Definition[]{delete(path1, filter), delete(path2, filter),
delete(path3, filter) });
}
@Override
public Route.Definition trace(final String path, final Route.Handler handler) {
return appendDefinition(new Route.Definition("TRACE", path, handler));
}
@Override
public Route.Definition trace(final String path, final Route.OneArgHandler handler) {
return appendDefinition(new Route.Definition("TRACE", path, handler));
}
@Override
public Route.Definition trace(final String path, final Route.ZeroArgHandler handler) {
return appendDefinition(new Route.Definition("TRACE", path, handler));
}
@Override
public Route.Definition trace(final String path, final Route.Filter filter) {
return appendDefinition(new Route.Definition("TRACE", path, filter));
}
@Override
public Route.Definition trace() {
return appendDefinition(new Route.Definition("TRACE", "*", handler(TraceHandler.class))
.name("*.trace"));
}
@Override
public Route.Definition connect(final String path, final Route.Handler handler) {
return appendDefinition(new Route.Definition("CONNECT", path, handler));
}
@Override
public Route.Definition connect(final String path, final Route.OneArgHandler handler) {
return appendDefinition(new Route.Definition("CONNECT", path, handler));
}
@Override
public Route.Definition connect(final String path, final Route.ZeroArgHandler handler) {
return appendDefinition(new Route.Definition("CONNECT", path, handler));
}
@Override
public Route.Definition connect(final String path, final Route.Filter filter) {
return appendDefinition(new Route.Definition("CONNECT", path, filter));
}
/**
* Creates a new {@link Route.Handler} that delegate the execution to the given handler. This is
* useful when the target handler requires some dependencies.
*
* <pre>
* public class MyHandler implements Route.Handler {
* @Inject
* public MyHandler(Dependency d) {
* }
*
* public void handle(Request req, Response rsp) throws Exception {
* // do something
* }
* }
* ...
* // external route
* get("/", handler(MyHandler.class));
*
* // inline version route
* get("/", (req, rsp) {@literal ->} {
* Dependency d = req.getInstance(Dependency.class);
* // do something
* });
* </pre>
*
* You can access to a dependency from a in-line route too, so the use of external route it is
* more or less a matter of taste.
*
* @param handler The external handler class.
* @return A new inline route handler.
*/
private Route.Handler handler(final Class<? extends Route.Handler> handler) {
requireNonNull(handler, "Route handler is required.");
return (req, rsp) -> req.require(handler).handle(req, rsp);
}
/**
* Creates a new {@link Route.Filter} that delegate the execution to the given filter. This is
* useful when the target handler requires some dependencies.
*
* <pre>
* public class MyFilter implements Filter {
* @Inject
* public MyFilter(Dependency d) {
* }
*
* public void handle(Request req, Response rsp, Route.Chain chain) throws Exception {
* // do something
* }
* }
* ...
* // external filter
* get("/", filter(MyFilter.class));
*
* // inline version route
* get("/", (req, rsp, chain) {@literal ->} {
* Dependency d = req.getInstance(Dependency.class);
* // do something
* });
* </pre>
*
* You can access to a dependency from a in-line route too, so the use of external filter it is
* more or less a matter of taste.
*
* @param filter The external filter class.
* @return A new inline route.
*/
private Route.Filter filter(final Class<? extends Route.Filter> filter) {
requireNonNull(filter, "Filter is required.");
return (req, rsp, chain) -> req.require(filter).handle(req, rsp, chain);
}
@Override
public Definition assets(final String path, final Path basedir) {
AssetHandler handler = new AssetHandler(basedir);
configureAssetHandler(handler);
return assets(path, handler);
}
@Override
public Route.Definition assets(final String path, final String location) {
AssetHandler handler = new AssetHandler(location);
configureAssetHandler(handler);
return assets(path, handler);
}
@Override
public Route.Definition assets(final String path, final AssetHandler handler) {
return appendDefinition(new Route.Definition("GET", path, handler));
}
@Override
public Route.Collection use(final Class<?> routeClass) {
requireNonNull(routeClass, "Route class is required.");
MvcClass mvc = new MvcClass(routeClass, "", prefix);
bag.add(mvc);
return new Route.Collection(mvc);
}
/**
* Keep track of routes in the order user define them.
*
* @param route A route definition to append.
* @return The same route definition.
*/
private Route.Definition appendDefinition(final Route.Definition route) {
route.prefix = prefix;
// reset name will update the name if prefix != null
route.name(route.name());
bag.add(route);
return route;
}
/**
* Import an application {@link Module}.
*
* @param module The module to import.
* @return This jooby instance.
* @see Jooby.Module
*/
public Jooby use(final Jooby.Module module) {
requireNonNull(module, "A module is required.");
bag.add(module);
return this;
}
/**
* Set/specify a custom .conf file, useful when you don't want a <code>application.conf</code>
* file.
*
* @param path Classpath location.
* @return This jooby instance.
*/
public Jooby conf(final String path) {
use(ConfigFactory.parseResources(path));
return this;
}
/**
* Set/specify a custom .conf file, useful when you don't want a <code>application.conf</code>
* file.
*
* @param path File system location.
* @return This jooby instance.
*/
public Jooby conf(final File path) {
use(ConfigFactory.parseFile(path));
return this;
}
/**
* Set the application configuration object. You must call this method when the default file
* name: <code>application.conf</code> doesn't work for you or when you need/want to register two
* or more files.
*
* @param config The application configuration object.
* @return This jooby instance.
* @see Config
*/
public Jooby use(final Config config) {
this.srcconf = requireNonNull(config, "Config required.");
return this;
}
@Override
public Jooby err(final Err.Handler err) {
this.bag.add(requireNonNull(err, "An err handler is required."));
return this;
}
@Override
public WebSocket.Definition ws(final String path, final WebSocket.FullHandler handler) {
WebSocket.Definition ws = new WebSocket.Definition(path, handler);
checkArgument(bag.add(ws), "Path is in use: '%s'", path);
return ws;
}
@Override
public Route.Definition sse(final String path, final Sse.Handler handler) {
return appendDefinition(new Route.Definition("GET", path, handler)).consumes(MediaType.sse);
}
@Override
public Route.Definition sse(final String path, final Sse.Handler1 handler) {
return appendDefinition(new Route.Definition("GET", path, handler)).consumes(MediaType.sse);
}
@SuppressWarnings("rawtypes")
@Override
public Route.Collection with(final Runnable callback) {
// hacky way of doing what we want... but we do simplify developer life
int size = this.bag.size();
callback.run();
// collect latest routes and apply route props
List<Route.Props> local = this.bag.stream()
.skip(size)
.filter(Predicates.instanceOf(Route.Props.class))
.map(r -> (Route.Props) r)
.collect(Collectors.toList());
return new Route.Collection(local.toArray(new Route.Props[local.size()]));
}
/**
* Prepare and startup a {@link Jooby} application.
*
* @param app Application supplier.
* @param args Application arguments.
*/
public static void run(final Supplier<? extends Jooby> app, final String... args) {
Config conf = ConfigFactory.systemProperties()
.withFallback(args(args));
System.setProperty("logback.configurationFile", logback(conf));
app.get().start(args);
}
/**
* Prepare and startup a {@link Jooby} application.
*
* @param app Application supplier.
* @param args Application arguments.
*/
public static void run(final Class<? extends Jooby> app, final String... args) {
run(() -> Try.of(() -> app.newInstance()).get(), args);
}
/**
* Export configuration from an application. Useful for tooling, testing, debugging, etc...
*
* @param app Application to extract/collect configuration.
* @return Application conf or <code>empty</code> conf on error.
*/
public static Config exportConf(final Jooby app) {
AtomicReference<Config> conf = new AtomicReference<>(ConfigFactory.empty());
app.on("*", c -> {
conf.set(c);
});
exportRoutes(app);
return conf.get();
}
/**
* Export routes from an application. Useful for route analysis, testing, debugging, etc...
*
* @param app Application to extract/collect routes.
* @return Application routes.
*/
public static List<Definition> exportRoutes(final Jooby app) {
@SuppressWarnings("serial")
class Success extends RuntimeException {
List<Definition> routes;
Success(final List<Route.Definition> routes) {
this.routes = routes;
}
}
List<Definition> routes = Collections.emptyList();
try {
app.start(new String[0], r -> {
throw new Success(r);
});
} catch (Success success) {
routes = success.routes;
} catch (Throwable x) {
logger(app).debug("Failed bootstrap: {}", app, x);
}
return routes;
}
/**
* Start an application.
*/
public void start() {
start(new String[0]);
}
/**
* Start an application.
*
* @param args Application arguments.
*/
public void start(final String... args) {
try {
start(args, null);
} catch (Throwable x) {
stop();
String msg = "An error occurred while starting the application:";
if (throwBootstrapException) {
throw new Err(Status.SERVICE_UNAVAILABLE, msg, x);
} else {
logger(this).error(msg, x);
}
}
}
private void start(final String[] args, final Consumer<List<Route.Definition>> routes)
throws Throwable {
long start = System.currentTimeMillis();
started.set(true);
this.injector = bootstrap(args(args), routes);
// shutdown hook
Runtime.getRuntime().addShutdownHook(new Thread(() -> stop()));
Config conf = injector.getInstance(Config.class);
Logger log = logger(this);
// inject class
injector.injectMembers(this);
// start services
for (CheckedConsumer<Registry> onStart : this.onStart) {
onStart.accept(this);
}
// route mapper
Set<Route.Definition> routeDefs = injector.getInstance(Route.KEY);
Set<WebSocket.Definition> sockets = injector.getInstance(WebSocket.KEY);
if (mapper != null) {
routeDefs.forEach(it -> it.map(mapper));
}
AppPrinter printer = new AppPrinter(routeDefs, sockets, conf);
printer.printConf(log, conf);
// Start server
Server server = injector.getInstance(Server.class);
String serverName = server.getClass().getSimpleName().replace("Server", "").toLowerCase();
server.start();
long end = System.currentTimeMillis();
log.info("[{}@{}]: Server started in {}ms\n\n{}\n",
conf.getString("application.env"),
serverName,
end - start,
printer);
// started services
for (CheckedConsumer<Registry> onStarted : this.onStarted) {
onStarted.accept(this);
}
boolean join = conf.hasPath("server.join") ? conf.getBoolean("server.join") : true;
if (join) {
server.join();
}
}
@Override
@SuppressWarnings("unchecked")
public Jooby map(final Mapper<?> mapper) {
requireNonNull(mapper, "Mapper is required.");
if (mappers.add(mapper.name())) {
this.mapper = Optional.ofNullable(this.mapper)
.map(next -> Route.Mapper.chain(mapper, next))
.orElse((Mapper<Object>) mapper);
}
return this;
}
/**
* Use the injection provider to create the Guice injector
*
* @param injectorFactory the injection provider
* @return this instance.
*/
public Jooby injector(
final BiFunction<Stage, com.google.inject.Module, Injector> injectorFactory) {
this.injectorFactory = injectorFactory;
return this;
}
/**
* Bind the provided abstract type to the given implementation:
*
* <pre>
* {
* bind(MyInterface.class, MyImplementation.class);
* }
* </pre>
*
* @param type Service interface.
* @param implementation Service implementation.
* @param <T> Service type.
* @return This instance.
*/
public <T> Jooby bind(final Class<T> type, final Class<? extends T> implementation) {
use((env, conf, binder) -> {
binder.bind(type).to(implementation);
});
return this;
}
/**
* Bind the provided abstract type to the given implementation:
*
* <pre>
* {
* bind(MyInterface.class, MyImplementation::new);
* }
* </pre>
*
* @param type Service interface.
* @param implementation Service implementation.
* @param <T> Service type.
* @return This instance.
*/
public <T> Jooby bind(final Class<T> type, final Supplier<T> implementation) {
use((env, conf, binder) -> {
binder.bind(type).toInstance(implementation.get());
});
return this;
}
/**
* Bind the provided type:
*
* <pre>
* {
* bind(MyInterface.class);
* }
* </pre>
*
* @param type Service interface.
* @param <T> Service type.
* @return This instance.
*/
public <T> Jooby bind(final Class<T> type) {
use((env, conf, binder) -> {
binder.bind(type);
});
return this;
}
/**
* Bind the provided type:
*
* <pre>
* {
* bind(new MyService());
* }
* </pre>
*
* @param service Service.
* @return This instance.
*/
@SuppressWarnings({"rawtypes", "unchecked" })
public Jooby bind(final Object service) {
use((env, conf, binder) -> {
Class type = service.getClass();
binder.bind(type).toInstance(service);
});
return this;
}
/**
* Bind the provided type and object that requires some type of configuration:
*
* <pre>{@code
* {
* bind(MyService.class, conf -> new MyService(conf.getString("service.url")));
* }
* }</pre>
*
* @param type Service type.
* @param provider Service provider.
* @param <T> Service type.
* @return This instance.
*/
public <T> Jooby bind(final Class<T> type, final Function<Config, ? extends T> provider) {
use((env, conf, binder) -> {
T service = provider.apply(conf);
binder.bind(type).toInstance(service);
});
return this;
}
/**
* Bind the provided type and object that requires some type of configuration:
*
* <pre>{@code
* {
* bind(conf -> new MyService(conf.getString("service.url")));
* }
* }</pre>
*
* @param provider Service provider.
* @param <T> Service type.
* @return This instance.
*/
@SuppressWarnings({"unchecked", "rawtypes" })
public <T> Jooby bind(final Function<Config, T> provider) {
use((env, conf, binder) -> {
Object service = provider.apply(conf);
Class type = service.getClass();
binder.bind(type).toInstance(service);
});
return this;
}
/**
* Set application date format.
*
* @param dateFormat A date format.
* @return This instance.
*/
public Jooby dateFormat(final String dateFormat) {
this.dateFormat = requireNonNull(dateFormat, "DateFormat required.");
return this;
}
/**
* Set application number format.
*
* @param numberFormat A number format.
* @return This instance.
*/
public Jooby numberFormat(final String numberFormat) {
this.numberFormat = requireNonNull(numberFormat, "NumberFormat required.");
return this;
}
/**
* Set application/default charset.
*
* @param charset A charset.
* @return This instance.
*/
public Jooby charset(final Charset charset) {
this.charset = requireNonNull(charset, "Charset required.");
return this;
}
/**
* Set application locale (first listed are higher priority).
*
* @param languages List of locale using the language tag format.
* @return This instance.
*/
public Jooby lang(final String... languages) {
this.languages = languages;
return this;
}
/**
* Set application time zone.
*
* @param zoneId ZoneId.
* @return This instance.
*/
public Jooby timezone(final ZoneId zoneId) {
this.zoneId = requireNonNull(zoneId, "ZoneId required.");
return this;
}
/**
* Set the HTTP port.
*
* <p>
* Keep in mind this work as a default port and can be reset via <code>application.port</code>
* property.
* </p>
*
* @param port HTTP port.
* @return This instance.
*/
public Jooby port(final int port) {
this.port = port;
return this;
}
/**
* <p>
* Set the HTTPS port to use.
* </p>
*
* <p>
* Keep in mind this work as a default port and can be reset via <code>application.port</code>
* property.
* </p>
*
* <h2>HTTPS</h2>
* <p>
* Jooby comes with a self-signed certificate, useful for development and test. But of course, you
* should NEVER use it in the real world.
* </p>
*
* <p>
* In order to setup HTTPS with a secure certificate, you need to set these properties:
* </p>
*
* <ul>
* <li>
* <code>ssl.keystore.cert</code>: An X.509 certificate chain file in PEM format. It can be an
* absolute path or a classpath resource.
* </li>
* <li>
* <code>ssl.keystore.key</code>: A PKCS#8 private key file in PEM format. It can be an absolute
* path or a classpath resource.
* </li>
* </ul>
*
* <p>
* Optionally, you can set these too:
* </p>
*
* <ul>
* <li>
* <code>ssl.keystore.password</code>: Password of the keystore.key (if any). Default is:
* null/empty.
* </li>
* <li>
* <code>ssl.trust.cert</code>: Trusted certificates for verifying the remote endpoint’s
* certificate. The file should contain an X.509 certificate chain in PEM format. Default uses the
* system default.
* </li>
* <li>
* <code>ssl.session.cacheSize</code>: Set the size of the cache used for storing SSL session
* objects. 0 to use the default value.
* </li>
* <li>
* <code>ssl.session.timeout</code>: Timeout for the cached SSL session objects, in seconds. 0 to
* use the default value.
* </li>
* </ul>
*
* <p>
* As you can see setup is very simple. All you need is your <code>.crt</code> and
* <code>.key</code> files.
* </p>
*
* @param port HTTPS port.
* @return This instance.
*/
public Jooby securePort(final int port) {
this.securePort = port;
return this;
}
/**
* <p>
* Enable <code>HTTP/2</code> protocol. Some servers require special configuration, others just
* works. It is a good idea to check the server documentation about
* <a href="http://jooby.org/doc/servers">HTTP/2</a>.
* </p>
*
* <p>
* In order to use HTTP/2 from a browser you must configure HTTPS, see {@link #securePort(int)}
* documentation.
* </p>
*
* <p>
* If HTTP/2 clear text is supported then you may skip the HTTPS setup, but of course you won't be
* able to use HTTP/2 with browsers.
* </p>
*
* @return This instance.
*/
public Jooby http2() {
this.http2 = true;
return this;
}
/**
* Set the default executor to use from {@link Deferred Deferred API}.
*
* Default executor runs each task in the thread that invokes {@link Executor#execute execute},
* that's a Jooby worker thread. A worker thread in Jooby can block.
*
* The {@link ExecutorService} will automatically shutdown.
*
* @param executor Executor to use.
* @return This jooby instance.
*/
public Jooby executor(final ExecutorService executor) {
executor((Executor) executor);
onStop(r -> executor.shutdown());
return this;
}
/**
* Set the default executor to use from {@link Deferred Deferred API}.
*
* Default executor runs each task in the thread that invokes {@link Executor#execute execute},
* that's a Jooby worker thread. A worker thread in Jooby can block.
*
* The {@link ExecutorService} will automatically shutdown.
*
* @param executor Executor to use.
* @return This jooby instance.
*/
public Jooby executor(final Executor executor) {
this.defaultExecSet = true;
this.executors.add(binder -> {
binder.bind(Key.get(String.class, Names.named("deferred"))).toInstance("deferred");
binder.bind(Key.get(Executor.class, Names.named("deferred"))).toInstance(executor);
});
return this;
}
/**
* Set a named executor to use from {@link Deferred Deferred API}. Useful for override the
* default/global executor.
*
* Default executor runs each task in the thread that invokes {@link Executor#execute execute},
* that's a Jooby worker thread. A worker thread in Jooby can block.
*
* The {@link ExecutorService} will automatically shutdown.
*
* @param name Name of the executor.
* @param executor Executor to use.
* @return This jooby instance.
*/
public Jooby executor(final String name, final ExecutorService executor) {
executor(name, (Executor) executor);
onStop(r -> executor.shutdown());
return this;
}
/**
* Set a named executor to use from {@link Deferred Deferred API}. Useful for override the
* default/global executor.
*
* Default executor runs each task in the thread that invokes {@link Executor#execute execute},
* that's a Jooby worker thread. A worker thread in Jooby can block.
*
* The {@link ExecutorService} will automatically shutdown.
*
* @param name Name of the executor.
* @param executor Executor to use.
* @return This jooby instance.
*/
public Jooby executor(final String name, final Executor executor) {
this.executors.add(binder -> {
binder.bind(Key.get(Executor.class, Names.named(name))).toInstance(executor);
});
return this;
}
/**
* Set the default executor to use from {@link Deferred Deferred API}. This works as reference to
* an executor, application directly or via module must provide an named executor.
*
* Default executor runs each task in the thread that invokes {@link Executor#execute execute},
* that's a Jooby worker thread. A worker thread in Jooby can block.
*
* @param name Executor to use.
* @return This jooby instance.
*/
public Jooby executor(final String name) {
defaultExecSet = true;
this.executors.add(binder -> {
binder.bind(Key.get(String.class, Names.named("deferred"))).toInstance(name);
});
return this;
}
/**
* Set a named executor to use from {@link Deferred Deferred API}. Useful for override the
* default/global executor.
*
* Default executor runs each task in the thread that invokes {@link Executor#execute execute},
* that's a Jooby worker thread. A worker thread in Jooby can block.
*
* @param name Name of the executor.
* @param provider Provider for the executor.
* @return This jooby instance.
*/
private Jooby executor(final String name, final Class<? extends Provider<Executor>> provider) {
this.executors.add(binder -> {
binder.bind(Key.get(Executor.class, Names.named(name))).toProvider(provider).in(Singleton.class);
});
return this;
}
/**
* If the application fails to start all the services are shutdown. Also, the exception is logged
* and usually the application is going to exit.
*
* This options turn off logging and rethrow the exception as {@link Err}. Here is an example:
*
* <pre>
* public class App extends Jooby {
* {
* throwBootstrapException();
* ...
* }
* }
*
* App app = new App();
*
* try {
* app.start();
* } catch (Err err) {
* Throwable cause = err.getCause();
* }
* </pre>
*
* @return
*/
public Jooby throwBootstrapException() {
this.throwBootstrapException = true;
return this;
}
/**
* Run app in javascript.
*
* @param jsargs Arguments, first arg must be the name of the javascript file.
* @throws Throwable If app fails to start.
*/
public static void main(final String[] jsargs) throws Throwable {
String[] args = new String[Math.max(0, jsargs.length - 1)];
if (args.length > 0) {
System.arraycopy(jsargs, 1, args, 0, args.length);
}
String filename = jsargs.length > 0 ? jsargs[0] : "app.js";
run(new JsJooby().run(new File(filename)), args);
}
private static List<Object> normalize(final List<Object> services, final Env env,
final RouteMetadata classInfo, final String prefix) {
List<Object> result = new ArrayList<>();
List<Object> snapshot = services;
/** modules, routes, parsers, renderers and websockets */
snapshot.forEach(candidate -> {
if (candidate instanceof Route.Definition) {
result.add(candidate);
} else if (candidate instanceof Route.Group) {
((Route.Group) candidate).routes()
.forEach(r -> result.add(r));
} else if (candidate instanceof MvcClass) {
MvcClass mvcRoute = ((MvcClass) candidate);
Class<?> mvcClass = mvcRoute.routeClass;
String path = ((MvcClass) candidate).path;
MvcRoutes.routes(env, classInfo, path, mvcClass)
.forEach(route -> result.add(mvcRoute.apply(route)));
} else {
result.add(candidate);
}
});
return result;
}
private static List<Object> processEnvDep(final Set<Object> src, final Env env) {
List<Object> result = new ArrayList<>();
List<Object> bag = new ArrayList<>(src);
bag.forEach(it -> {
if (it instanceof EnvDep) {
EnvDep envdep = (EnvDep) it;
if (envdep.predicate.test(env.name())) {
int from = src.size();
envdep.callback.accept(env.config());
int to = src.size();
result.addAll(new ArrayList<>(src).subList(from, to));
}
} else {
result.add(it);
}
});
return result;
}
private Injector bootstrap(final Config args,
final Consumer<List<Route.Definition>> rcallback) throws Throwable {
Config appconf = ConfigFactory.parseResources("application.conf");
Config initconf = srcconf == null ? appconf : srcconf.withFallback(appconf);
List<Config> modconf = modconf(this.bag);
Config conf = buildConfig(initconf, args, modconf);
final List<Locale> locales = LocaleUtils.parse(conf.getString("application.lang"));
Env env = this.env.build(conf, this, locales.get(0));
String envname = env.name();
final Charset charset = Charset.forName(conf.getString("application.charset"));
String dateFormat = conf.getString("application.dateFormat");
ZoneId zoneId = ZoneId.of(conf.getString("application.tz"));
DateTimeFormatter dateTimeFormatter = DateTimeFormatter
.ofPattern(dateFormat, locales.get(0))
.withZone(zoneId);
DecimalFormat numberFormat = new DecimalFormat(conf.getString("application.numberFormat"));
// Guice Stage
Stage stage = "dev".equals(envname) ? Stage.DEVELOPMENT : Stage.PRODUCTION;
// expand and normalize bag
RouteMetadata rm = new RouteMetadata(env);
List<Object> realbag = processEnvDep(this.bag, env);
List<Config> realmodconf = modconf(realbag);
List<Object> bag = normalize(realbag, env, rm, prefix);
// collect routes and fire route callback
if (rcallback != null) {
List<Route.Definition> routes = bag.stream()
.filter(it -> it instanceof Route.Definition)
.map(it -> (Route.Definition) it)
.collect(Collectors.<Route.Definition> toList());
rcallback.accept(routes);
}
// final config ? if we add a mod that depends on env
Config finalConfig;
Env finalEnv;
if (modconf.size() != realmodconf.size()) {
finalConfig = buildConfig(initconf, args, realmodconf);
finalEnv = this.env.build(finalConfig, this, locales.get(0));
} else {
finalConfig = conf;
finalEnv = env;
}
boolean cookieSession = session.store() == null;
if (cookieSession && !finalConfig.hasPath("application.secret")) {
throw new IllegalStateException("Required property 'application.secret' is missing");
}
/** executors: */
if (!defaultExecSet) {
// default executor
executor(MoreExecutors.directExecutor());
}
executor("direct", MoreExecutors.directExecutor());
executor("server", ServerExecutorProvider.class);
/** Some basic xss functions. */
xss(finalEnv);
/** dependency injection */
@SuppressWarnings("unchecked")
com.google.inject.Module joobyModule = binder -> {
/** type converters */
new TypeConverters().configure(binder);
/** bind config */
bindConfig(binder, finalConfig);
/** bind env */
binder.bind(Env.class).toInstance(finalEnv);
/** bind charset */
binder.bind(Charset.class).toInstance(charset);
/** bind locale */
binder.bind(Locale.class).toInstance(locales.get(0));
TypeLiteral<List<Locale>> localeType = (TypeLiteral<List<Locale>>) TypeLiteral
.get(Types.listOf(Locale.class));
binder.bind(localeType).toInstance(locales);
/** bind time zone */
binder.bind(ZoneId.class).toInstance(zoneId);
binder.bind(TimeZone.class).toInstance(TimeZone.getTimeZone(zoneId));
/** bind date format */
binder.bind(DateTimeFormatter.class).toInstance(dateTimeFormatter);
/** bind number format */
binder.bind(NumberFormat.class).toInstance(numberFormat);
binder.bind(DecimalFormat.class).toInstance(numberFormat);
/** bind ssl provider. */
binder.bind(SSLContext.class).toProvider(SslContextProvider.class);
/** routes */
Multibinder<Definition> definitions = Multibinder
.newSetBinder(binder, Definition.class);
/** web sockets */
Multibinder<WebSocket.Definition> sockets = Multibinder
.newSetBinder(binder, WebSocket.Definition.class);
/** tmp dir */
File tmpdir = new File(finalConfig.getString("application.tmpdir"));
tmpdir.mkdirs();
binder.bind(File.class).annotatedWith(Names.named("application.tmpdir"))
.toInstance(tmpdir);
binder.bind(ParameterNameProvider.class).toInstance(rm);
/** err handler */
Multibinder<Err.Handler> ehandlers = Multibinder
.newSetBinder(binder, Err.Handler.class);
/** parsers & renderers */
Multibinder<Parser> parsers = Multibinder
.newSetBinder(binder, Parser.class);
Multibinder<Renderer> renderers = Multibinder
.newSetBinder(binder, Renderer.class);
/** basic parser */
parsers.addBinding().toInstance(BuiltinParser.Basic);
parsers.addBinding().toInstance(BuiltinParser.Collection);
parsers.addBinding().toInstance(BuiltinParser.Optional);
parsers.addBinding().toInstance(BuiltinParser.Enum);
parsers.addBinding().toInstance(BuiltinParser.Upload);
parsers.addBinding().toInstance(BuiltinParser.Bytes);
/** basic render */
renderers.addBinding().toInstance(BuiltinRenderer.asset);
renderers.addBinding().toInstance(BuiltinRenderer.bytes);
renderers.addBinding().toInstance(BuiltinRenderer.byteBuffer);
renderers.addBinding().toInstance(BuiltinRenderer.file);
renderers.addBinding().toInstance(BuiltinRenderer.charBuffer);
renderers.addBinding().toInstance(BuiltinRenderer.stream);
renderers.addBinding().toInstance(BuiltinRenderer.reader);
renderers.addBinding().toInstance(BuiltinRenderer.fileChannel);
/** modules, routes, parsers, renderers and websockets */
Set<Object> routeClasses = new HashSet<>();
for (Object it : bag) {
Try.run(() -> bindService(
this.bag,
finalConfig,
finalEnv,
rm,
binder,
definitions,
sockets,
ehandlers,
parsers,
renderers,
routeClasses).accept(it))
.getOrElseThrow(Throwables::propagate);
}
parsers.addBinding().toInstance(new DateParser(dateFormat));
parsers.addBinding().toInstance(new LocalDateParser(dateTimeFormatter));
parsers.addBinding().toInstance(new LocaleParser());
parsers.addBinding().toInstance(new StaticMethodParser("valueOf"));
parsers.addBinding().toInstance(new StaticMethodParser("fromString"));
parsers.addBinding().toInstance(new StaticMethodParser("forName"));
parsers.addBinding().toInstance(new StringConstructorParser());
parsers.addBinding().toInstance(beanParser.orElseGet(() -> new BeanParser(false)));
binder.bind(ParserExecutor.class).in(Singleton.class);
/** override(able) renderer */
boolean stacktrace = finalConfig.hasPath("err.stacktrace")
? finalConfig.getBoolean("err.stacktrace")
: "dev".equals(envname);
renderers.addBinding().toInstance(new DefaulErrRenderer(stacktrace));
renderers.addBinding().toInstance(BuiltinRenderer.text);
binder.bind(HttpHandler.class).to(HttpHandlerImpl.class).in(Singleton.class);
RequestScope requestScope = new RequestScope();
binder.bind(RequestScope.class).toInstance(requestScope);
binder.bindScope(RequestScoped.class, requestScope);
/** session manager */
binder.bind(Session.Definition.class)
.toProvider(session(finalConfig.getConfig("session"), session))
.asEagerSingleton();
Object sstore = session.store();
if (cookieSession) {
binder.bind(SessionManager.class).to(CookieSessionManager.class)
.asEagerSingleton();
} else {
binder.bind(SessionManager.class).to(ServerSessionManager.class).asEagerSingleton();
if (sstore instanceof Class) {
binder.bind(Store.class).to((Class<? extends Store>) sstore)
.asEagerSingleton();
} else {
binder.bind(Store.class).toInstance((Store) sstore);
}
}
binder.bind(Request.class).toProvider(Providers.outOfScope(Request.class))
.in(RequestScoped.class);
binder.bind(Response.class).toProvider(Providers.outOfScope(Response.class))
.in(RequestScoped.class);
/** server sent event */
binder.bind(Sse.class).toProvider(Providers.outOfScope(Sse.class))
.in(RequestScoped.class);
binder.bind(Session.class).toProvider(Providers.outOfScope(Session.class))
.in(RequestScoped.class);
/** def err */
ehandlers.addBinding().toInstance(new Err.DefHandler());
/** executors. */
executors.forEach(it -> it.accept(binder));
};
Injector injector = injectorFactory.apply(stage, joobyModule);
onStart.addAll(0, finalEnv.startTasks());
onStarted.addAll(0, finalEnv.startedTasks());
onStop.addAll(finalEnv.stopTasks());
// clear bag and freeze it
this.bag.clear();
this.bag = ImmutableSet.of();
this.executors.clear();
this.executors = ImmutableList.of();
return injector;
}
private void xss(final Env env) {
Escaper ufe = UrlEscapers.urlFragmentEscaper();
Escaper fpe = UrlEscapers.urlFormParameterEscaper();
Escaper pse = UrlEscapers.urlPathSegmentEscaper();
Escaper html = HtmlEscapers.htmlEscaper();
env.xss("urlFragment", ufe::escape)
.xss("formParam", fpe::escape)
.xss("pathSegment", pse::escape)
.xss("html", html::escape);
}
private static Provider<Session.Definition> session(final Config $session,
final Session.Definition session) {
return () -> {
// save interval
session.saveInterval(session.saveInterval()
.orElse($session.getDuration("saveInterval", TimeUnit.MILLISECONDS)));
// build cookie
Cookie.Definition source = session.cookie();
source.name(source.name()
.orElse($session.getString("cookie.name")));
if (!source.comment().isPresent() && $session.hasPath("cookie.comment")) {
source.comment($session.getString("cookie.comment"));
}
if (!source.domain().isPresent() && $session.hasPath("cookie.domain")) {
source.domain($session.getString("cookie.domain"));
}
source.httpOnly(source.httpOnly()
.orElse($session.getBoolean("cookie.httpOnly")));
Object maxAge = $session.getAnyRef("cookie.maxAge");
if (maxAge instanceof String) {
maxAge = $session.getDuration("cookie.maxAge", TimeUnit.SECONDS);
}
source.maxAge(source.maxAge()
.orElse(((Number) maxAge).intValue()));
source.path(source.path()
.orElse($session.getString("cookie.path")));
source.secure(source.secure()
.orElse($session.getBoolean("cookie.secure")));
return session;
};
}
private static CheckedConsumer<? super Object> bindService(final Set<Object> src,
final Config conf,
final Env env,
final RouteMetadata rm,
final Binder binder,
final Multibinder<Route.Definition> definitions,
final Multibinder<WebSocket.Definition> sockets,
final Multibinder<Err.Handler> ehandlers,
final Multibinder<Parser> parsers,
final Multibinder<Renderer> renderers,
final Set<Object> routeClasses) {
return it -> {
if (it instanceof Jooby.Module) {
int from = src.size();
install((Jooby.Module) it, env, conf, binder);
int to = src.size();
// collect any route a module might add
if (to > from) {
List<Object> elements = normalize(new ArrayList<>(src).subList(from, to), env, rm, null);
for (Object e : elements) {
bindService(src,
conf,
env,
rm,
binder,
definitions,
sockets,
ehandlers,
parsers,
renderers,
routeClasses).accept(e);
}
}
} else if (it instanceof Route.Definition) {
Route.Definition rdef = (Definition) it;
Route.Filter h = rdef.filter();
if (h instanceof Route.MethodHandler) {
Class<?> routeClass = ((Route.MethodHandler) h).method().getDeclaringClass();
if (routeClasses.add(routeClass)) {
binder.bind(routeClass);
}
}
definitions.addBinding().toInstance(rdef);
} else if (it instanceof WebSocket.Definition) {
sockets.addBinding().toInstance((WebSocket.Definition) it);
} else if (it instanceof Parser) {
parsers.addBinding().toInstance((Parser) it);
} else if (it instanceof Renderer) {
renderers.addBinding().toInstance((Renderer) it);
} else {
ehandlers.addBinding().toInstance((Err.Handler) it);
}
};
}
private static List<Config> modconf(final Collection<Object> bag) {
return bag.stream()
.filter(it -> it instanceof Jooby.Module)
.map(it -> ((Jooby.Module) it).config())
.filter(c -> !c.isEmpty())
.collect(Collectors.toList());
}
/**
* Test if the application is up and running.
*
* @return True if the application is up and running.
*/
public boolean isStarted() {
return started.get();
}
/**
* Stop the application, close all the modules and stop the web server.
*/
public void stop() {
if (started.compareAndSet(true, false)) {
Logger log = logger(this);
fireStop(this, log, onStop);
if (injector != null) {
try {
injector.getInstance(Server.class).stop();
} catch (Throwable ex) {
log.debug("server.stop() resulted in exception", ex);
}
}
injector = null;
log.info("Stopped");
}
}
private static void fireStop(final Jooby app, final Logger log,
final List<CheckedConsumer<Registry>> onStop) {
// stop services
onStop.forEach(c -> Try.run(() -> c.accept(app))
.onFailure(x -> log.error("shutdown of {} resulted in error", c, x)));
}
/**
* Build configuration properties, it configure system, app and modules properties.
*
* @param source Source config to use.
* @param args Args conf.
* @param modules List of modules.
* @return A configuration properties ready to use.
*/
private Config buildConfig(final Config source, final Config args,
final List<Config> modules) {
// normalize tmpdir
Config system = ConfigFactory.systemProperties();
Config tmpdir = source.hasPath("java.io.tmpdir") ? source : system;
// system properties
system = system
// file encoding got corrupted sometimes, override it.
.withValue("file.encoding", fromAnyRef(System.getProperty("file.encoding")))
.withValue("java.io.tmpdir",
fromAnyRef(Paths.get(tmpdir.getString("java.io.tmpdir")).normalize().toString()));
// set module config
Config moduleStack = ConfigFactory.empty();
for (Config module : ImmutableList.copyOf(modules).reverse()) {
moduleStack = moduleStack.withFallback(module);
}
String env = Arrays.asList(system, args, source).stream()
.filter(it -> it.hasPath("application.env"))
.findFirst()
.map(c -> c.getString("application.env"))
.orElse("dev");
String cpath = Arrays.asList(system, args, source).stream()
.filter(it -> it.hasPath("application.path"))
.findFirst()
.map(c -> c.getString("application.path"))
.orElse("/");
Config envcof = envConf(source, env);
// application.[env].conf -> application.conf
Config conf = envcof.withFallback(source);
return system
.withFallback(args)
.withFallback(conf)
.withFallback(moduleStack)
.withFallback(MediaType.types)
.withFallback(defaultConfig(conf, Route.normalize(cpath)))
.resolve();
}
/**
* Build a conf from arguments.
*
* @param args Application arguments.
* @return A conf.
*/
static Config args(final String[] args) {
if (args == null || args.length == 0) {
return ConfigFactory.empty();
}
Map<String, String> conf = new HashMap<>();
for (String arg : args) {
String[] values = arg.split("=");
String name;
String value;
if (values.length == 2) {
name = values[0];
value = values[1];
} else {
name = "application.env";
value = values[0];
}
if (name.indexOf(".") == -1) {
conf.put("application." + name, value);
}
conf.put(name, value);
}
return ConfigFactory.parseMap(conf, "args");
}
/**
* Build a env config: <code>[application].[env].[conf]</code>.
* Stack looks like
*
* <pre>
* (file://[origin].[env].[conf])?
* (cp://[origin].[env].[conf])?
* file://application.[env].[conf]
* /application.[env].[conf]
* </pre>
*
* @param source App source to use.
* @param env Application env.
* @return A config env.
*/
private Config envConf(final Config source, final String env) {
String origin = source.origin().resource();
Config result = ConfigFactory.empty();
if (origin != null) {
// load [resource].[env].[ext]
int dot = origin.lastIndexOf('.');
String originConf = origin.substring(0, dot) + "." + env + origin.substring(dot);
result = fileConfig(originConf).withFallback(ConfigFactory.parseResources(originConf));
}
String appConfig = "application." + env + ".conf";
return result
.withFallback(fileConfig(appConfig))
.withFallback(fileConfig("application.conf"))
.withFallback(ConfigFactory.parseResources(appConfig));
}
/**
* Config from file system.
*
* @param fname A file name.
* @return A config for the file name.
*/
static Config fileConfig(final String fname) {
File dir = new File(System.getProperty("user.dir"));
File froot = new File(dir, fname);
if (froot.exists()) {
return ConfigFactory.parseFile(froot);
} else {
File fconfig = new File(new File(dir, "conf"), fname);
if (fconfig.exists()) {
return ConfigFactory.parseFile(fconfig);
}
}
return ConfigFactory.empty();
}
/**
* Build default application.* properties.
*
* @param conf A source config.
* @param cpath Application path.
* @return default properties.
*/
private Config defaultConfig(final Config conf, final String cpath) {
String ns = getClass().getPackage().getName();
String[] parts = ns.split("\\.");
String appname = parts[parts.length - 1];
// locale
final List<Locale> locales;
if (!conf.hasPath("application.lang")) {
locales = Optional.ofNullable(this.languages)
.map(langs -> LocaleUtils.parse(Joiner.on(",").join(langs)))
.orElse(ImmutableList.of(Locale.getDefault()));
} else {
locales = LocaleUtils.parse(conf.getString("application.lang"));
}
Locale locale = locales.iterator().next();
String lang = locale.toLanguageTag();
// time zone
final String tz;
if (!conf.hasPath("application.tz")) {
tz = Optional.ofNullable(zoneId).orElse(ZoneId.systemDefault()).getId();
} else {
tz = conf.getString("application.tz");
}
// number format
final String nf;
if (!conf.hasPath("application.numberFormat")) {
nf = Optional.ofNullable(numberFormat)
.orElseGet(() -> ((DecimalFormat) DecimalFormat.getInstance(locale)).toPattern());
} else {
nf = conf.getString("application.numberFormat");
}
int processors = Runtime.getRuntime().availableProcessors();
String version = Optional.ofNullable(getClass().getPackage().getImplementationVersion())
.orElse("0.0.0");
Config defs = ConfigFactory.parseResources(Jooby.class, "jooby.conf")
.withValue("contextPath", ConfigValueFactory.fromAnyRef(cpath.equals("/") ? "" : cpath))
.withValue("application.name", ConfigValueFactory.fromAnyRef(appname))
.withValue("application.version", ConfigValueFactory.fromAnyRef(version))
.withValue("application.class", ConfigValueFactory.fromAnyRef(getClass().getName()))
.withValue("application.ns", ConfigValueFactory.fromAnyRef(ns))
.withValue("application.lang", ConfigValueFactory.fromAnyRef(lang))
.withValue("application.tz", ConfigValueFactory.fromAnyRef(tz))
.withValue("application.numberFormat", ConfigValueFactory.fromAnyRef(nf))
.withValue("server.http2.enabled", ConfigValueFactory.fromAnyRef(http2))
.withValue("runtime.processors", ConfigValueFactory.fromAnyRef(processors))
.withValue("runtime.processors-plus1", ConfigValueFactory.fromAnyRef(processors + 1))
.withValue("runtime.processors-plus2", ConfigValueFactory.fromAnyRef(processors + 2))
.withValue("runtime.processors-x2", ConfigValueFactory.fromAnyRef(processors * 2))
.withValue("runtime.processors-x4", ConfigValueFactory.fromAnyRef(processors * 4))
.withValue("runtime.processors-x8", ConfigValueFactory.fromAnyRef(processors * 8))
.withValue("runtime.concurrencyLevel", ConfigValueFactory
.fromAnyRef(Math.max(4, processors)));
if (charset != null) {
defs = defs.withValue("application.charset", ConfigValueFactory.fromAnyRef(charset.name()));
}
if (port != null) {
defs = defs.withValue("application.port", ConfigValueFactory.fromAnyRef(port.intValue()));
}
if (securePort != null) {
defs = defs.withValue("application.securePort",
ConfigValueFactory.fromAnyRef(securePort.intValue()));
}
if (dateFormat != null) {
defs = defs.withValue("application.dateFormat", ConfigValueFactory.fromAnyRef(dateFormat));
}
return defs;
}
/**
* Install a {@link JoobyModule}.
*
* @param module The module to install.
* @param env Application env.
* @param config The configuration object.
* @param binder A Guice binder.
* @throws Throwable If module bootstrap fails.
*/
private static void install(final Jooby.Module module, final Env env, final Config config,
final Binder binder) throws Throwable {
module.configure(env, config, binder);
}
/**
* Bind a {@link Config} and make it available for injection. Each property of the config is also
* binded it and ready to be injected with {@link javax.inject.Named}.
*
* @param binder Guice binder.
* @param config App config.
*/
@SuppressWarnings("unchecked")
private void bindConfig(final Binder binder, final Config config) {
// root nodes
traverse(binder, "", config.root());
// terminal nodes
for (Entry<String, ConfigValue> entry : config.entrySet()) {
String name = entry.getKey();
Named named = Names.named(name);
Object value = entry.getValue().unwrapped();
if (value instanceof List) {
List<Object> values = (List<Object>) value;
Type listType = values.size() == 0
? String.class
: Types.listOf(values.iterator().next().getClass());
Key<Object> key = (Key<Object>) Key.get(listType, Names.named(name));
binder.bind(key).toInstance(values);
} else {
binder.bindConstant().annotatedWith(named).to(value.toString());
}
}
// bind config
binder.bind(Config.class).toInstance(config);
}
private static void traverse(final Binder binder, final String p, final ConfigObject root) {
root.forEach((n, v) -> {
if (v instanceof ConfigObject) {
ConfigObject child = (ConfigObject) v;
String path = p + n;
Named named = Names.named(path);
binder.bind(Config.class).annotatedWith(named).toInstance(child.toConfig());
traverse(binder, path + ".", child);
}
});
}
private static Predicate<String> envpredicate(final String candidate) {
return env -> env.equalsIgnoreCase(candidate) || candidate.equals("*");
}
static String logback(final Config conf) {
// Avoid warning message from logback when multiples files are present
String logback;
if (conf.hasPath("logback.configurationFile")) {
logback = conf.getString("logback.configurationFile");
} else {
String env = conf.hasPath("application.env") ? conf.getString("application.env") : null;
URL cpconf = Jooby.class.getResource("/logback." + env + ".xml");
ImmutableList.Builder<File> files = ImmutableList.builder();
File userdir = new File(System.getProperty("user.dir"));
File confdir = new File(userdir, "conf");
if (env != null) {
files.add(new File(userdir, "logback." + env + ".xml"));
files.add(new File(confdir, "logback." + env + ".xml"));
}
files.add(new File(userdir, "logback.xml"));
files.add(new File(confdir, "logback.xml"));
logback = files.build()
.stream()
.filter(f -> f.exists())
.map(f -> f.getAbsolutePath())
.findFirst()
.orElse((cpconf != null) ? cpconf.toString() : "logback.xml");
}
return logback;
}
private static Logger logger(final Jooby app) {
return LoggerFactory.getLogger(app.getClass());
}
public void configureAssetHandler(final AssetHandler handler) {
onStart(r -> {
Config conf = r.require(Config.class);
handler
.cdn(conf.getString("assets.cdn"))
.lastModified(conf.getBoolean("assets.lastModified"))
.etag(conf.getBoolean("assets.etag"))
.maxAge(conf.getString("assets.cache.maxAge"));
});
}
}
| jooby/src/main/java/org/jooby/Jooby.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* This copy of Woodstox XML processor is licensed under the
* Apache (Software) License, version 2.0 ("the License").
* See the License for details about distribution rights, and the
* specific rights regarding derivate works.
*
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/
*
* A copy is also included in the downloadable source code package
* containing Woodstox, in file "ASL2.0", under the same directory
* as this file.
*/
/**
o * 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.jooby;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static com.typesafe.config.ConfigValueFactory.fromAnyRef;
import static java.util.Objects.requireNonNull;
import java.io.File;
import java.lang.reflect.Type;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set;
import java.util.TimeZone;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import javax.inject.Singleton;
import javax.net.ssl.SSLContext;
import org.jooby.Route.Definition;
import org.jooby.Route.Mapper;
import org.jooby.Session.Store;
import org.jooby.handlers.AssetHandler;
import org.jooby.internal.AppPrinter;
import org.jooby.internal.BuiltinParser;
import org.jooby.internal.BuiltinRenderer;
import org.jooby.internal.CookieSessionManager;
import org.jooby.internal.DefaulErrRenderer;
import org.jooby.internal.HttpHandlerImpl;
import org.jooby.internal.JvmInfo;
import org.jooby.internal.LocaleUtils;
import org.jooby.internal.ParameterNameProvider;
import org.jooby.internal.RequestScope;
import org.jooby.internal.RouteMetadata;
import org.jooby.internal.ServerExecutorProvider;
import org.jooby.internal.ServerLookup;
import org.jooby.internal.ServerSessionManager;
import org.jooby.internal.SessionManager;
import org.jooby.internal.TypeConverters;
import org.jooby.internal.handlers.HeadHandler;
import org.jooby.internal.handlers.OptionsHandler;
import org.jooby.internal.handlers.TraceHandler;
import org.jooby.internal.js.JsJooby;
import org.jooby.internal.mvc.MvcRoutes;
import org.jooby.internal.parser.BeanParser;
import org.jooby.internal.parser.DateParser;
import org.jooby.internal.parser.LocalDateParser;
import org.jooby.internal.parser.LocaleParser;
import org.jooby.internal.parser.ParserExecutor;
import org.jooby.internal.parser.StaticMethodParser;
import org.jooby.internal.parser.StringConstructorParser;
import org.jooby.internal.ssl.SslContextProvider;
import org.jooby.scope.Providers;
import org.jooby.scope.RequestScoped;
import org.jooby.spi.HttpHandler;
import org.jooby.spi.Server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Joiner;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.escape.Escaper;
import com.google.common.html.HtmlEscapers;
import com.google.common.net.UrlEscapers;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.inject.Binder;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.Provider;
import com.google.inject.Stage;
import com.google.inject.TypeLiteral;
import com.google.inject.multibindings.Multibinder;
import com.google.inject.name.Named;
import com.google.inject.name.Names;
import com.google.inject.util.Types;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import com.typesafe.config.ConfigObject;
import com.typesafe.config.ConfigValue;
import com.typesafe.config.ConfigValueFactory;
import javaslang.Predicates;
import javaslang.control.Try;
import javaslang.control.Try.CheckedConsumer;
import javaslang.control.Try.CheckedRunnable;
/**
* <h1>jooby</h1>
* <h2>getting started</h2>
*
* <pre>
* public class MyApp extends Jooby {
*
* {
* use(new Jackson()); // 1. JSON serializer.
*
* // 2. Define a route
* get("/", req {@literal ->} {
* Map{@literal <}String, Object{@literal >} model = ...;
* return model;
* }
* }
*
* public static void main(String[] args) {
* run(MyApp::new, args); // 3. Done!
* }
* }
* </pre>
*
* <h2>application.conf</h2>
* <p>
* Jooby delegate configuration management to <a
* href="https://github.com/typesafehub/config">TypeSafe Config</a>.
* </p>
*
* <p>
* By default Jooby looks for an <code>application.conf</code>. If
* you want to specify a different file or location, you can do it with {@link #conf(String)}.
* </p>
*
* <p>
* <a href="https://github.com/typesafehub/config">TypeSafe Config</a> uses a hierarchical model to
* define and override properties.
* </p>
* <p>
* A {@link Jooby.Module} might provides his own set of properties through the
* {@link Jooby.Module#config()} method. By default, this method returns an empty config object.
* </p>
* For example:
*
* <pre>
* use(new M1());
* use(new M2());
* use(new M3());
* </pre>
*
* Previous example had the following order (first-listed are higher priority):
* <ul>
* <li>arguments properties</li>
* <li>System properties</li>
* <li>application.conf</li>
* <li>M3 properties</li>
* <li>M2 properties</li>
* <li>M1 properties</li>
* </ul>
* <p>
* Command line argmuents or system properties takes precedence over any application specific
* property.
* </p>
*
* <h2>env</h2>
* <p>
* Jooby defines one mode or environment: <strong>dev</strong>. In Jooby, <strong>dev</strong>
* is special and some modules could apply special settings while running in <strong>dev</strong>.
* Any other env is usually considered a <code>prod</code> like env. But that depends on module
* implementor.
* </p>
* <p>
* An <code>environment</code> can be defined in your <code>.conf</code> file using the
* <code>application.env</code> property. If missing, Jooby set the <code>env</code> for you to
* <strong>dev</strong>.
* </p>
* <p>
* There is more at {@link Env} please read the {@link Env} javadoc.
* </p>
*
* <h2>modules: the jump to full-stack framework</h2>
* <p>
* {@link Jooby.Module Modules} are quite similar to a Guice modules except that the configure
* callback has been complementing with {@link Env} and {@link Config}.
* </p>
*
* <pre>
* public class MyModule implements Jooby.Module {
* public void configure(Env env, Config config, Binder binder) {
* }
* }
* </pre>
*
* From the configure callback you can bind your services as you usually do in a Guice app.
* <p>
* There is more at {@link Jooby.Module} so please read the {@link Jooby.Module} javadoc.
* </p>
*
* <h2>path patterns</h2>
* <p>
* Jooby supports Ant-style path patterns:
* </p>
* <p>
* Some examples:
* </p>
* <ul>
* <li>{@code com/t?st.html} - matches {@code com/test.html} but also {@code com/tast.html} or
* {@code com/txst.html}</li>
* <li>{@code com/*.html} - matches all {@code .html} files in the {@code com} directory</li>
* <li><code>com/{@literal **}/test.html</code> - matches all {@code test.html} files underneath the
* {@code com} path</li>
* <li>{@code **}/{@code *} - matches any path at any level.</li>
* <li>{@code *} - matches any path at any level, shorthand for {@code **}/{@code *}.</li>
* </ul>
*
* <h3>variables</h3>
* <p>
* Jooby supports path parameters too:
* </p>
* <p>
* Some examples:
* </p>
* <ul>
* <li><code> /user/{id}</code> - /user/* and give you access to the <code>id</code> var.</li>
* <li><code> /user/:id</code> - /user/* and give you access to the <code>id</code> var.</li>
* <li><code> /user/{id:\\d+}</code> - /user/[digits] and give you access to the numeric
* <code>id</code> var.</li>
* </ul>
*
* <h2>routes</h2>
* <p>
* Routes perform actions in response to a server HTTP request.
* </p>
* <p>
* Routes are executed in the order they are defined, for example:
* </p>
*
* <pre>
* get("/", (req, rsp) {@literal ->} {
* log.info("first"); // start here and go to second
* });
*
* get("/", (req, rsp) {@literal ->} {
* log.info("second"); // execute after first and go to final
* });
*
* get("/", (req, rsp) {@literal ->} {
* rsp.send("final"); // done!
* });
* </pre>
*
* Previous example can be rewritten using {@link Route.Filter}:
*
* <pre>
* get("/", (req, rsp, chain) {@literal ->} {
* log.info("first"); // start here and go to second
* chain.next(req, rsp);
* });
*
* get("/", (req, rsp, chain) {@literal ->} {
* log.info("second"); // execute after first and go to final
* chain.next(req, rsp);
* });
*
* get("/", (req, rsp) {@literal ->} {
* rsp.send("final"); // done!
* });
* </pre>
*
* Due to the use of lambdas a route is a singleton and you should NOT use global variables. For
* example this is a bad practice:
*
* <pre>
* List{@literal <}String{@literal >} names = new ArrayList{@literal <}{@literal >}(); // names produces side effects
* get("/", (req, rsp) {@literal ->} {
* names.add(req.param("name").value();
* // response will be different between calls.
* rsp.send(names);
* });
* </pre>
*
* <h3>mvc routes</h3>
* <p>
* A Mvc route use annotations to define routes:
* </p>
*
* <pre>
* use(MyRoute.class);
* ...
*
* // MyRoute.java
* {@literal @}Path("/")
* public class MyRoute {
*
* {@literal @}GET
* public String hello() {
* return "Hello Jooby";
* }
* }
* </pre>
* <p>
* Programming model is quite similar to JAX-RS/Jersey with some minor differences and/or
* simplifications.
* </p>
*
* <p>
* To learn more about Mvc Routes, please check {@link org.jooby.mvc.Path},
* {@link org.jooby.mvc.Produces} {@link org.jooby.mvc.Consumes} javadoc.
* </p>
*
* <h2>static files</h2>
* <p>
* Static files, like: *.js, *.css, ..., etc... can be served with:
* </p>
*
* <pre>
* assets("assets/**");
* </pre>
* <p>
* Classpath resources under the <code>/assets</code> folder will be accessible from client/browser.
* </p>
*
* <h2>lifecyle</h2>
* <p>
* We do provide {@link #onStart(CheckedConsumer)} and {@link #onStop(CheckedConsumer)} callbacks.
* These callbacks are executed are application startup or shutdown time:
* </p>
*
* <pre>{@code
* {
* onStart(() -> {
* log.info("Welcome!");
* });
*
* onStop(() -> {
* log.info("Bye!");
* });
* }
* }</pre>
*
* <p>
* From life cycle callbacks you can access to application services:
* </p>
*
* <pre>{@code
* {
* onStart(registry -> {
* MyDatabase db = registry.require(MyDatabase.class);
* // do something with databse:
* });
* }
* }</pre>
*
*
* @author edgar
* @since 0.1.0
* @see Jooby.Module
*/
public class Jooby implements Router, LifeCycle, Registry {
/**
* <pre>{@code
* {
* on("dev", () -> {
* // run something on dev
* }).orElse(() -> {
* // run something on prod
* });
* }
* }</pre>
*
*/
public interface EnvPredicate {
/**
* <pre>{@code
* {
* on("dev", () -> {
* // run something on dev
* }).orElse(() -> {
* // run something on prod
* });
* }
* }</pre>
*
* @param callback Env callback.
*/
default void orElse(final Runnable callback) {
orElse(conf -> callback.run());
}
/**
* <pre>{@code
* {
* on("dev", () -> {
* // run something on dev
* }).orElse(conf -> {
* // run something on prod
* });
* }
* }</pre>
*
* @param callback Env callback.
*/
void orElse(Consumer<Config> callback);
}
/**
* A module can publish or produces: {@link Route.Definition routes}, {@link Parser},
* {@link Renderer}, and any other application specific service or contract of your choice.
* <p>
* It is similar to {@link com.google.inject.Module} except for the callback method receives a
* {@link Env}, {@link Config} and {@link Binder}.
* </p>
*
* <p>
* A module can provide his own set of properties through the {@link #config()} method. By
* default, this method returns an empty config object.
* </p>
* For example:
*
* <pre>
* use(new M1());
* use(new M2());
* use(new M3());
* </pre>
*
* Previous example had the following order (first-listed are higher priority):
* <ul>
* <li>System properties</li>
* <li>application.conf</li>
* <li>M3 properties</li>
* <li>M2 properties</li>
* <li>M1 properties</li>
* </ul>
*
* <p>
* A module can provide start/stop methods in order to start or close resources.
* </p>
*
* @author edgar
* @since 0.1.0
* @see Jooby#use(Jooby.Module)
*/
public interface Module {
/**
* @return Produces a module config object (when need it). By default a module doesn't produce
* any configuration object.
*/
default Config config() {
return ConfigFactory.empty();
}
/**
* Configure and produces bindings for the underlying application. A module can optimize or
* customize a service by checking current the {@link Env application env} and/or the current
* application properties available from {@link Config}.
*
* @param env The current application's env. Not null.
* @param conf The current config object. Not null.
* @param binder A guice binder. Not null.
*/
void configure(Env env, Config conf, Binder binder) throws Throwable;
}
private static class MvcClass implements Route.Props<MvcClass> {
Class<?> routeClass;
String path;
ImmutableMap.Builder<String, Object> attrs = ImmutableMap.builder();
private List<MediaType> consumes;
private String name;
private List<MediaType> produces;
private List<String> excludes;
private Mapper<?> mapper;
private String prefix;
public MvcClass(final Class<?> routeClass, final String path, final String prefix) {
this.routeClass = routeClass;
this.path = path;
this.prefix = prefix;
}
@Override
public MvcClass attr(final String name, final Object value) {
attrs.put(name, value);
return this;
}
@Override
public MvcClass name(final String name) {
this.name = name;
return this;
}
@Override
public MvcClass consumes(final List<MediaType> consumes) {
this.consumes = consumes;
return this;
}
@Override
public MvcClass produces(final List<MediaType> produces) {
this.produces = produces;
return this;
}
@Override
public MvcClass excludes(final List<String> excludes) {
this.excludes = excludes;
return this;
}
@Override
public MvcClass map(final Mapper<?> mapper) {
this.mapper = mapper;
return this;
}
public Route.Definition apply(final Route.Definition route) {
attrs.build().forEach(route::attr);
if (name != null) {
route.name(name);
}
if (prefix != null) {
route.name(prefix + "/" + route.name());
}
if (consumes != null) {
route.consumes(consumes);
}
if (produces != null) {
route.produces(produces);
}
if (excludes != null) {
route.excludes(excludes);
}
if (mapper != null) {
route.map(mapper);
}
return route;
}
}
private static class EnvDep {
Predicate<String> predicate;
Consumer<Config> callback;
public EnvDep(final Predicate<String> predicate, final Consumer<Config> callback) {
this.predicate = predicate;
this.callback = callback;
}
}
static {
// set pid as system property
String pid = System.getProperty("pid", JvmInfo.pid() + "");
System.setProperty("pid", pid);
}
/**
* Keep track of routes.
*/
private transient Set<Object> bag = new LinkedHashSet<>();
/**
* The override config. Optional.
*/
private transient Config srcconf;
private final transient AtomicBoolean started = new AtomicBoolean(false);
/** Keep the global injector instance. */
private transient Injector injector;
/** Session store. */
private transient Session.Definition session = new Session.Definition(Session.Mem.class);
/** Env builder. */
private transient Env.Builder env = Env.DEFAULT;
/** Route's prefix. */
private transient String prefix;
/** startup callback . */
private transient List<CheckedConsumer<Registry>> onStart = new ArrayList<>();
private transient List<CheckedConsumer<Registry>> onStarted = new ArrayList<>();
/** stop callback . */
private transient List<CheckedConsumer<Registry>> onStop = new ArrayList<>();
/** Mappers . */
@SuppressWarnings("rawtypes")
private transient Mapper mapper;
/** Don't add same mapper twice . */
private transient Set<String> mappers = new HashSet<>();
/** Bean parser . */
private transient Optional<Parser> beanParser = Optional.empty();
private transient ServerLookup server = new ServerLookup();
private transient String dateFormat;
private transient Charset charset;
private transient String[] languages;
private transient ZoneId zoneId;
private transient Integer port;
private transient Integer securePort;
private transient String numberFormat;
private transient boolean http2;
private transient List<Consumer<Binder>> executors = new ArrayList<>();
private transient boolean defaultExecSet;
private boolean throwBootstrapException;
/**
* creates the injector
*/
private transient BiFunction<Stage, com.google.inject.Module, Injector> injectorFactory = Guice::createInjector;
/**
* Creates a new {@link Jooby} application.
*/
public Jooby() {
this(null);
}
/**
* Creates a new application and prefix all the names of the routes with the given prefix. Useful,
* for dynamic/advanced routing. See {@link Route.Chain#next(String, Request, Response)}.
*
* @param prefix Route name prefix.
*/
public Jooby(final String prefix) {
this.prefix = prefix;
use(server);
}
@Override
public Jooby use(final Jooby app) {
return use(Optional.empty(), app);
}
@Override
public Jooby use(final String path, final Jooby app) {
return use(Optional.of(path), app);
}
/**
* Use the provided HTTP server.
*
* @param server Server.
* @return This jooby instance.
*/
public Jooby server(final Class<? extends Server> server) {
requireNonNull(server, "Server required.");
// remove server lookup
List<Object> tmp = bag.stream()
.skip(1)
.collect(Collectors.toList());
tmp.add(0,
(Module) (env, conf, binder) -> binder.bind(Server.class).to(server).asEagerSingleton());
bag.clear();
bag.addAll(tmp);
return this;
}
private Jooby use(final Optional<String> path, final Jooby app) {
requireNonNull(app, "App is required.");
Function<Route.Definition, Route.Definition> rewrite = r -> {
return path.map(p -> {
Route.Definition result = new Route.Definition(r.method(), p + r.pattern(), r.filter());
result.consumes(r.consumes());
result.produces(r.produces());
result.excludes(r.excludes());
return result;
}).orElse(r);
};
app.bag.forEach(it -> {
if (it instanceof Route.Definition) {
this.bag.add(rewrite.apply((Definition) it));
} else if (it instanceof Route.Group) {
((Route.Group) it).routes().forEach(r -> this.bag.add(rewrite.apply(r)));
} else if (it instanceof MvcClass) {
Object routes = path.<Object> map(p -> new MvcClass(((MvcClass) it).routeClass, p, prefix))
.orElse(it);
this.bag.add(routes);
} else {
// everything else
this.bag.add(it);
}
});
// start/stop callback
app.onStart.forEach(this.onStart::add);
app.onStarted.forEach(this.onStarted::add);
app.onStop.forEach(this.onStop::add);
// mapper
if (app.mapper != null) {
this.map(app.mapper);
}
return this;
}
@Override
public Route.Group use(final String pattern) {
Route.Group group = new Route.Group(pattern, prefix);
this.bag.add(group);
return group;
}
/**
* Set a custom {@link Env.Builder} to use.
*
* @param env A custom env builder.
* @return This jooby instance.
*/
public Jooby env(final Env.Builder env) {
this.env = requireNonNull(env, "Env builder is required.");
return this;
}
@Override
public Jooby onStart(final CheckedRunnable callback) {
LifeCycle.super.onStart(callback);
return this;
}
@Override
public Jooby onStart(final CheckedConsumer<Registry> callback) {
requireNonNull(callback, "Callback is required.");
onStart.add(callback);
return this;
}
@Override
public Jooby onStarted(final CheckedRunnable callback) {
LifeCycle.super.onStarted(callback);
return this;
}
@Override
public Jooby onStarted(final CheckedConsumer<Registry> callback) {
requireNonNull(callback, "Callback is required.");
onStarted.add(callback);
return this;
}
@Override
public Jooby onStop(final CheckedRunnable callback) {
LifeCycle.super.onStop(callback);
return this;
}
@Override
public Jooby onStop(final CheckedConsumer<Registry> callback) {
requireNonNull(callback, "Callback is required.");
onStop.add(callback);
return this;
}
/**
* Run the given callback if and only if, application runs in the given environment.
*
* <pre>
* {
* on("dev", () {@literal ->} {
* use(new DevModule());
* });
* }
* </pre>
*
* There is an else clause which is the opposite version of the env predicate:
*
* <pre>
* {
* on("dev", () {@literal ->} {
* use(new DevModule());
* }).orElse(() {@literal ->} {
* use(new RealModule());
* });
* }
* </pre>
*
* @param env Environment where we want to run the callback.
* @param callback An env callback.
* @return This jooby instance.
*/
public EnvPredicate on(final String env, final Runnable callback) {
requireNonNull(env, "Env is required.");
return on(envpredicate(env), callback);
}
/**
* Run the given callback if and only if, application runs in the given environment.
*
* <pre>
* {
* on("dev", () {@literal ->} {
* use(new DevModule());
* });
* }
* </pre>
*
* There is an else clause which is the opposite version of the env predicate:
*
* <pre>
* {
* on("dev", conf {@literal ->} {
* use(new DevModule());
* }).orElse(conf {@literal ->} {
* use(new RealModule());
* });
* }
* </pre>
*
* @param env Environment where we want to run the callback.
* @param callback An env callback.
* @return This jooby instance.
*/
public EnvPredicate on(final String env, final Consumer<Config> callback) {
requireNonNull(env, "Env is required.");
return on(envpredicate(env), callback);
}
/**
* Run the given callback if and only if, application runs in the given envirobment.
*
* <pre>
* {
* on("dev", "test", () {@literal ->} {
* use(new DevModule());
* });
* }
* </pre>
*
* There is an else clause which is the opposite version of the env predicate:
*
* <pre>
* {
* on(env {@literal ->} env.equals("dev"), () {@literal ->} {
* use(new DevModule());
* }).orElse(() {@literal ->} {
* use(new RealModule());
* });
* }
* </pre>
*
* @param predicate Predicate to check the environment.
* @param callback An env callback.
* @return This jooby instance.
*/
public EnvPredicate on(final Predicate<String> predicate, final Runnable callback) {
requireNonNull(predicate, "Predicate is required.");
requireNonNull(callback, "Callback is required.");
return on(predicate, conf -> callback.run());
}
/**
* Run the given callback if and only if, application runs in the given environment.
*
* <pre>
* {
* on(env {@literal ->} env.equals("dev"), conf {@literal ->} {
* use(new DevModule());
* });
* }
* </pre>
*
* @param predicate Predicate to check the environment.
* @param callback An env callback.
* @return This jooby instance.
*/
public EnvPredicate on(final Predicate<String> predicate, final Consumer<Config> callback) {
requireNonNull(predicate, "Predicate is required.");
requireNonNull(callback, "Callback is required.");
this.bag.add(new EnvDep(predicate, callback));
return otherwise -> this.bag.add(new EnvDep(predicate.negate(), otherwise));
}
/**
* Run the given callback if and only if, application runs in the given environment.
*
* <pre>
* {
* on("dev", "test", "mock", () {@literal ->} {
* use(new DevModule());
* });
* }
* </pre>
*
* @param env1 Environment where we want to run the callback.
* @param env2 Environment where we want to run the callback.
* @param env3 Environment where we want to run the callback.
* @param callback An env callback.
* @return This jooby instance.
*/
public Jooby on(final String env1, final String env2, final String env3,
final Runnable callback) {
on(envpredicate(env1).or(envpredicate(env2)).or(envpredicate(env3)), callback);
return this;
}
@Override
public <T> T require(final Key<T> type) {
checkState(injector != null, "App didn't start yet");
return injector.getInstance(type);
}
@Override
public Route.OneArgHandler promise(final Deferred.Initializer initializer) {
return req -> {
return new Deferred(initializer);
};
}
@Override
public Route.OneArgHandler promise(final String executor,
final Deferred.Initializer initializer) {
return req -> new Deferred(executor, initializer);
}
@Override
public Route.OneArgHandler promise(final Deferred.Initializer0 initializer) {
return req -> {
return new Deferred(initializer);
};
}
@Override
public Route.OneArgHandler promise(final String executor,
final Deferred.Initializer0 initializer) {
return req -> new Deferred(executor, initializer);
}
/**
* Setup a session store to use. Useful if you want/need to persist sessions between shutdowns,
* apply timeout policies, etc...
*
* Jooby comes with a dozen of {@link Session.Store}, checkout the
* <a href="http://jooby.org/doc/session">session modules</a>.
*
* This method returns a {@link Session.Definition} objects that let you customize the session
* cookie.
*
* @param store A session store.
* @return A session store definition.
*/
public Session.Definition session(final Class<? extends Session.Store> store) {
this.session = new Session.Definition(requireNonNull(store, "A session store is required."));
return this.session;
}
/**
* Setup a session store that saves data in a the session cookie. It makes the application
* stateless, which help to scale easily. Keep in mind that a cookie has a limited size (up to
* 4kb) so you must pay attention to what you put in the session object (don't use as cache).
*
* Cookie session signed data using the <code>application.secret</code> property, so you must
* provide an <code>application.secret</code> value. On dev environment you can set it in your
* <code>.conf</code> file. In prod is probably better to provide as command line argument and/or
* environment variable. Just make sure to keep it private.
*
* Please note {@link Session#id()}, {@link Session#accessedAt()}, etc.. make no sense for cookie
* sessions, just the {@link Session#attributes()}.
*
* This method returns a {@link Session.Definition} objects that let you customize the session
* cookie.
*
* @return A session definition/configuration object.
*/
public Session.Definition cookieSession() {
this.session = new Session.Definition();
return this.session;
}
/**
* Setup a session store to use. Useful if you want/need to persist sessions between shutdowns,
* apply timeout policies, etc...
*
* Jooby comes with a dozen of {@link Session.Store}, checkout the
* <a href="http://jooby.org/doc/session">session modules</a>.
*
* This method returns a {@link Session.Definition} objects that let you customize the session
* cookie.
*
* @param store A session store.
* @return A session store definition.
*/
public Session.Definition session(final Session.Store store) {
this.session = new Session.Definition(requireNonNull(store, "A session store is required."));
return this.session;
}
/**
* Register a new param/body converter. See {@link Parser} for more details.
*
* @param parser A parser.
* @return This jooby instance.
*/
public Jooby parser(final Parser parser) {
if (parser instanceof BeanParser) {
beanParser = Optional.of(parser);
} else {
bag.add(requireNonNull(parser, "A parser is required."));
}
return this;
}
/**
* Append a response {@link Renderer} for write HTTP messages.
*
* @param renderer A renderer renderer.
* @return This jooby instance.
*/
public Jooby renderer(final Renderer renderer) {
this.bag.add(requireNonNull(renderer, "A renderer is required."));
return this;
}
@Override
public Route.Collection before(final String method, final String pattern,
final Route.Before handler, final Route.Before... chain) {
Route.Definition[] routes = javaslang.collection.List.of(handler)
.appendAll(Arrays.asList(chain))
.map(before -> appendDefinition(new Route.Definition(method, pattern, before)))
.toJavaArray(Route.Definition.class);
return new Route.Collection(routes);
}
@Override
public Route.Collection after(final String method, final String pattern,
final Route.After handler, final Route.After... chain) {
Route.Definition[] routes = javaslang.collection.List.of(handler)
.appendAll(Arrays.asList(chain))
.map(after -> appendDefinition(new Route.Definition(method, pattern, after)))
.toJavaArray(Route.Definition.class);
return new Route.Collection(routes);
}
@Override
public Route.Collection complete(final String method, final String pattern,
final Route.Complete handler, final Route.Complete... chain) {
Route.Definition[] routes = javaslang.collection.List.of(handler)
.appendAll(Arrays.asList(chain))
.map(complete -> appendDefinition(new Route.Definition(method, pattern, complete)))
.toJavaArray(Route.Definition.class);
return new Route.Collection(routes);
}
@Override
public Route.Definition use(final String path, final Route.Filter filter) {
return appendDefinition(new Route.Definition("*", path, filter));
}
@Override
public Route.Definition use(final String verb, final String path, final Route.Filter filter) {
return appendDefinition(new Route.Definition(verb, path, filter));
}
@Override
public Route.Definition use(final String verb, final String path, final Route.Handler handler) {
return appendDefinition(new Route.Definition(verb, path, handler));
}
@Override
public Route.Definition use(final String path, final Route.Handler handler) {
return appendDefinition(new Route.Definition("*", path, handler));
}
@Override
public Route.Definition use(final String path, final Route.OneArgHandler handler) {
return appendDefinition(new Route.Definition("*", path, handler));
}
@Override
public Route.Definition get(final String path, final Route.Handler handler) {
return appendDefinition(new Route.Definition("GET", path, handler));
}
@Override
public Route.Collection get(final String path1, final String path2, final Route.Handler handler) {
return new Route.Collection(
new Route.Definition[]{get(path1, handler), get(path2, handler) });
}
@Override
public Route.Collection get(final String path1, final String path2, final String path3,
final Route.Handler handler) {
return new Route.Collection(
new Route.Definition[]{get(path1, handler), get(path2, handler), get(path3, handler) });
}
@Override
public Route.Definition get(final String path, final Route.OneArgHandler handler) {
return appendDefinition(new Route.Definition("GET", path, handler));
}
@Override
public Route.Collection get(final String path1, final String path2,
final Route.OneArgHandler handler) {
return new Route.Collection(
new Route.Definition[]{get(path1, handler), get(path2, handler) });
}
@Override
public Route.Collection get(final String path1, final String path2,
final String path3, final Route.OneArgHandler handler) {
return new Route.Collection(
new Route.Definition[]{get(path1, handler), get(path2, handler), get(path3, handler) });
}
@Override
public Route.Definition get(final String path, final Route.ZeroArgHandler handler) {
return appendDefinition(new Route.Definition("GET", path, handler));
}
@Override
public Route.Collection get(final String path1, final String path2,
final Route.ZeroArgHandler handler) {
return new Route.Collection(
new Route.Definition[]{get(path1, handler), get(path2, handler) });
}
@Override
public Route.Collection get(final String path1, final String path2,
final String path3, final Route.ZeroArgHandler handler) {
return new Route.Collection(
new Route.Definition[]{get(path1, handler), get(path2, handler), get(path3, handler) });
}
@Override
public Route.Definition get(final String path, final Route.Filter filter) {
return appendDefinition(new Route.Definition("GET", path, filter));
}
@Override
public Route.Collection get(final String path1, final String path2, final Route.Filter filter) {
return new Route.Collection(new Route.Definition[]{get(path1, filter), get(path2, filter) });
}
@Override
public Route.Collection get(final String path1, final String path2,
final String path3, final Route.Filter filter) {
return new Route.Collection(
new Route.Definition[]{get(path1, filter), get(path2, filter), get(path3, filter) });
}
@Override
public Route.Definition post(final String path, final Route.Handler handler) {
return appendDefinition(new Route.Definition("POST", path, handler));
}
@Override
public Route.Collection post(final String path1, final String path2,
final Route.Handler handler) {
return new Route.Collection(
new Route.Definition[]{post(path1, handler), post(path2, handler) });
}
@Override
public Route.Collection post(final String path1, final String path2,
final String path3, final Route.Handler handler) {
return new Route.Collection(
new Route.Definition[]{post(path1, handler), post(path2, handler), post(path3, handler) });
}
@Override
public Route.Definition post(final String path, final Route.OneArgHandler handler) {
return appendDefinition(new Route.Definition("POST", path, handler));
}
@Override
public Route.Collection post(final String path1, final String path2,
final Route.OneArgHandler handler) {
return new Route.Collection(
new Route.Definition[]{post(path1, handler), post(path2, handler) });
}
@Override
public Route.Collection post(final String path1, final String path2,
final String path3, final Route.OneArgHandler handler) {
return new Route.Collection(
new Route.Definition[]{post(path1, handler), post(path2, handler), post(path3, handler) });
}
@Override
public Route.Definition post(final String path, final Route.ZeroArgHandler handler) {
return appendDefinition(new Route.Definition("POST", path, handler));
}
@Override
public Route.Collection post(final String path1, final String path2,
final Route.ZeroArgHandler handler) {
return new Route.Collection(
new Route.Definition[]{post(path1, handler), post(path2, handler) });
}
@Override
public Route.Collection post(final String path1, final String path2,
final String path3, final Route.ZeroArgHandler handler) {
return new Route.Collection(
new Route.Definition[]{post(path1, handler), post(path2, handler), post(path3, handler) });
}
@Override
public Route.Definition post(final String path, final Route.Filter filter) {
return appendDefinition(new Route.Definition("POST", path, filter));
}
@Override
public Route.Collection post(final String path1, final String path2,
final Route.Filter filter) {
return new Route.Collection(
new Route.Definition[]{post(path1, filter), post(path2, filter) });
}
@Override
public Route.Collection post(final String path1, final String path2,
final String path3, final Route.Filter filter) {
return new Route.Collection(
new Route.Definition[]{post(path1, filter), post(path2, filter), post(path3, filter) });
}
@Override
public Route.Definition head(final String path, final Route.Handler handler) {
return appendDefinition(new Route.Definition("HEAD", path, handler));
}
@Override
public Route.Definition head(final String path,
final Route.OneArgHandler handler) {
return appendDefinition(new Route.Definition("HEAD", path, handler));
}
@Override
public Route.Definition head(final String path, final Route.ZeroArgHandler handler) {
return appendDefinition(new Route.Definition("HEAD", path, handler));
}
@Override
public Route.Definition head(final String path, final Route.Filter filter) {
return appendDefinition(new Route.Definition("HEAD", path, filter));
}
@Override
public Route.Definition head() {
return appendDefinition(new Route.Definition("HEAD", "*", filter(HeadHandler.class))
.name("*.head"));
}
@Override
public Route.Definition options(final String path, final Route.Handler handler) {
return appendDefinition(new Route.Definition("OPTIONS", path, handler));
}
@Override
public Route.Definition options(final String path,
final Route.OneArgHandler handler) {
return appendDefinition(new Route.Definition("OPTIONS", path, handler));
}
@Override
public Route.Definition options(final String path,
final Route.ZeroArgHandler handler) {
return appendDefinition(new Route.Definition("OPTIONS", path, handler));
}
@Override
public Route.Definition options(final String path,
final Route.Filter filter) {
return appendDefinition(new Route.Definition("OPTIONS", path, filter));
}
@Override
public Route.Definition options() {
return appendDefinition(new Route.Definition("OPTIONS", "*", handler(OptionsHandler.class))
.name("*.options"));
}
@Override
public Route.Definition put(final String path,
final Route.Handler handler) {
return appendDefinition(new Route.Definition("PUT", path, handler));
}
@Override
public Route.Collection put(final String path1, final String path2,
final Route.Handler handler) {
return new Route.Collection(
new Route.Definition[]{put(path1, handler), put(path2, handler) });
}
@Override
public Route.Collection put(final String path1, final String path2,
final String path3, final Route.Handler handler) {
return new Route.Collection(
new Route.Definition[]{put(path1, handler), put(path2, handler), put(path3, handler) });
}
@Override
public Route.Definition put(final String path,
final Route.OneArgHandler handler) {
return appendDefinition(new Route.Definition("PUT", path, handler));
}
@Override
public Route.Collection put(final String path1, final String path2,
final Route.OneArgHandler handler) {
return new Route.Collection(
new Route.Definition[]{put(path1, handler), put(path2, handler) });
}
@Override
public Route.Collection put(final String path1, final String path2,
final String path3, final Route.OneArgHandler handler) {
return new Route.Collection(
new Route.Definition[]{put(path1, handler), put(path2, handler), put(path3, handler) });
}
@Override
public Route.Definition put(final String path,
final Route.ZeroArgHandler handler) {
return appendDefinition(new Route.Definition("PUT", path, handler));
}
@Override
public Route.Collection put(final String path1, final String path2,
final Route.ZeroArgHandler handler) {
return new Route.Collection(
new Route.Definition[]{put(path1, handler), put(path2, handler) });
}
@Override
public Route.Collection put(final String path1, final String path2,
final String path3, final Route.ZeroArgHandler handler) {
return new Route.Collection(
new Route.Definition[]{put(path1, handler), put(path2, handler), put(path3, handler) });
}
@Override
public Route.Definition put(final String path,
final Route.Filter filter) {
return appendDefinition(new Route.Definition("PUT", path, filter));
}
@Override
public Route.Collection put(final String path1, final String path2,
final Route.Filter filter) {
return new Route.Collection(
new Route.Definition[]{put(path1, filter), put(path2, filter) });
}
@Override
public Route.Collection put(final String path1, final String path2,
final String path3, final Route.Filter filter) {
return new Route.Collection(
new Route.Definition[]{put(path1, filter), put(path2, filter), put(path3, filter) });
}
@Override
public Route.Definition patch(final String path, final Route.Handler handler) {
return appendDefinition(new Route.Definition("PATCH", path, handler));
}
@Override
public Route.Collection patch(final String path1, final String path2,
final Route.Handler handler) {
return new Route.Collection(
new Route.Definition[]{patch(path1, handler), patch(path2, handler) });
}
@Override
public Route.Collection patch(final String path1, final String path2,
final String path3, final Route.Handler handler) {
return new Route.Collection(
new Route.Definition[]{patch(path1, handler), patch(path2, handler),
patch(path3, handler) });
}
@Override
public Route.Definition patch(final String path, final Route.OneArgHandler handler) {
return appendDefinition(new Route.Definition("PATCH", path, handler));
}
@Override
public Route.Collection patch(final String path1, final String path2,
final Route.OneArgHandler handler) {
return new Route.Collection(
new Route.Definition[]{patch(path1, handler), patch(path2, handler) });
}
@Override
public Route.Collection patch(final String path1, final String path2,
final String path3, final Route.OneArgHandler handler) {
return new Route.Collection(
new Route.Definition[]{patch(path1, handler), patch(path2, handler),
patch(path3, handler) });
}
@Override
public Route.Definition patch(final String path, final Route.ZeroArgHandler handler) {
return appendDefinition(new Route.Definition("PATCH", path, handler));
}
@Override
public Route.Collection patch(final String path1, final String path2,
final Route.ZeroArgHandler handler) {
return new Route.Collection(
new Route.Definition[]{patch(path1, handler), patch(path2, handler) });
}
@Override
public Route.Collection patch(final String path1, final String path2,
final String path3, final Route.ZeroArgHandler handler) {
return new Route.Collection(
new Route.Definition[]{patch(path1, handler), patch(path2, handler),
patch(path3, handler) });
}
@Override
public Route.Definition patch(final String path,
final Route.Filter filter) {
return appendDefinition(new Route.Definition("PATCH", path, filter));
}
@Override
public Route.Collection patch(final String path1, final String path2,
final Route.Filter filter) {
return new Route.Collection(
new Route.Definition[]{patch(path1, filter), patch(path2, filter) });
}
@Override
public Route.Collection patch(final String path1, final String path2,
final String path3, final Route.Filter filter) {
return new Route.Collection(
new Route.Definition[]{patch(path1, filter), patch(path2, filter),
patch(path3, filter) });
}
@Override
public Route.Definition delete(final String path, final Route.Handler handler) {
return appendDefinition(new Route.Definition("DELETE", path, handler));
}
@Override
public Route.Collection delete(final String path1, final String path2,
final Route.Handler handler) {
return new Route.Collection(
new Route.Definition[]{delete(path1, handler), delete(path2, handler) });
}
@Override
public Route.Collection delete(final String path1, final String path2, final String path3,
final Route.Handler handler) {
return new Route.Collection(
new Route.Definition[]{delete(path1, handler), delete(path2, handler),
delete(path3, handler) });
}
@Override
public Route.Definition delete(final String path, final Route.OneArgHandler handler) {
return appendDefinition(new Route.Definition("DELETE", path, handler));
}
@Override
public Route.Collection delete(final String path1, final String path2,
final Route.OneArgHandler handler) {
return new Route.Collection(
new Route.Definition[]{delete(path1, handler), delete(path2, handler) });
}
@Override
public Route.Collection delete(final String path1, final String path2, final String path3,
final Route.OneArgHandler handler) {
return new Route.Collection(
new Route.Definition[]{delete(path1, handler), delete(path2, handler),
delete(path3, handler) });
}
@Override
public Route.Definition delete(final String path,
final Route.ZeroArgHandler handler) {
return appendDefinition(new Route.Definition("DELETE", path, handler));
}
@Override
public Route.Collection delete(final String path1,
final String path2, final Route.ZeroArgHandler handler) {
return new Route.Collection(
new Route.Definition[]{delete(path1, handler), delete(path2, handler) });
}
@Override
public Route.Collection delete(final String path1,
final String path2, final String path3,
final Route.ZeroArgHandler handler) {
return new Route.Collection(
new Route.Definition[]{delete(path1, handler), delete(path2, handler),
delete(path3, handler) });
}
@Override
public Route.Definition delete(final String path, final Route.Filter filter) {
return appendDefinition(new Route.Definition("DELETE", path, filter));
}
@Override
public Route.Collection delete(final String path1, final String path2,
final Route.Filter filter) {
return new Route.Collection(
new Route.Definition[]{delete(path1, filter), delete(path2, filter) });
}
@Override
public Route.Collection delete(final String path1, final String path2, final String path3,
final Route.Filter filter) {
return new Route.Collection(
new Route.Definition[]{delete(path1, filter), delete(path2, filter),
delete(path3, filter) });
}
@Override
public Route.Definition trace(final String path, final Route.Handler handler) {
return appendDefinition(new Route.Definition("TRACE", path, handler));
}
@Override
public Route.Definition trace(final String path, final Route.OneArgHandler handler) {
return appendDefinition(new Route.Definition("TRACE", path, handler));
}
@Override
public Route.Definition trace(final String path, final Route.ZeroArgHandler handler) {
return appendDefinition(new Route.Definition("TRACE", path, handler));
}
@Override
public Route.Definition trace(final String path, final Route.Filter filter) {
return appendDefinition(new Route.Definition("TRACE", path, filter));
}
@Override
public Route.Definition trace() {
return appendDefinition(new Route.Definition("TRACE", "*", handler(TraceHandler.class))
.name("*.trace"));
}
@Override
public Route.Definition connect(final String path, final Route.Handler handler) {
return appendDefinition(new Route.Definition("CONNECT", path, handler));
}
@Override
public Route.Definition connect(final String path, final Route.OneArgHandler handler) {
return appendDefinition(new Route.Definition("CONNECT", path, handler));
}
@Override
public Route.Definition connect(final String path, final Route.ZeroArgHandler handler) {
return appendDefinition(new Route.Definition("CONNECT", path, handler));
}
@Override
public Route.Definition connect(final String path, final Route.Filter filter) {
return appendDefinition(new Route.Definition("CONNECT", path, filter));
}
/**
* Creates a new {@link Route.Handler} that delegate the execution to the given handler. This is
* useful when the target handler requires some dependencies.
*
* <pre>
* public class MyHandler implements Route.Handler {
* @Inject
* public MyHandler(Dependency d) {
* }
*
* public void handle(Request req, Response rsp) throws Exception {
* // do something
* }
* }
* ...
* // external route
* get("/", handler(MyHandler.class));
*
* // inline version route
* get("/", (req, rsp) {@literal ->} {
* Dependency d = req.getInstance(Dependency.class);
* // do something
* });
* </pre>
*
* You can access to a dependency from a in-line route too, so the use of external route it is
* more or less a matter of taste.
*
* @param handler The external handler class.
* @return A new inline route handler.
*/
private Route.Handler handler(final Class<? extends Route.Handler> handler) {
requireNonNull(handler, "Route handler is required.");
return (req, rsp) -> req.require(handler).handle(req, rsp);
}
/**
* Creates a new {@link Route.Filter} that delegate the execution to the given filter. This is
* useful when the target handler requires some dependencies.
*
* <pre>
* public class MyFilter implements Filter {
* @Inject
* public MyFilter(Dependency d) {
* }
*
* public void handle(Request req, Response rsp, Route.Chain chain) throws Exception {
* // do something
* }
* }
* ...
* // external filter
* get("/", filter(MyFilter.class));
*
* // inline version route
* get("/", (req, rsp, chain) {@literal ->} {
* Dependency d = req.getInstance(Dependency.class);
* // do something
* });
* </pre>
*
* You can access to a dependency from a in-line route too, so the use of external filter it is
* more or less a matter of taste.
*
* @param filter The external filter class.
* @return A new inline route.
*/
private Route.Filter filter(final Class<? extends Route.Filter> filter) {
requireNonNull(filter, "Filter is required.");
return (req, rsp, chain) -> req.require(filter).handle(req, rsp, chain);
}
@Override
public Definition assets(final String path, final Path basedir) {
AssetHandler handler = new AssetHandler(basedir);
configureAssetHandler(handler);
return assets(path, handler);
}
@Override
public Route.Definition assets(final String path, final String location) {
AssetHandler handler = new AssetHandler(location);
configureAssetHandler(handler);
return assets(path, handler);
}
@Override
public Route.Definition assets(final String path, final AssetHandler handler) {
return appendDefinition(new Route.Definition("GET", path, handler));
}
@Override
public Route.Collection use(final Class<?> routeClass) {
requireNonNull(routeClass, "Route class is required.");
MvcClass mvc = new MvcClass(routeClass, "", prefix);
bag.add(mvc);
return new Route.Collection(mvc);
}
/**
* Keep track of routes in the order user define them.
*
* @param route A route definition to append.
* @return The same route definition.
*/
private Route.Definition appendDefinition(final Route.Definition route) {
route.prefix = prefix;
// reset name will update the name if prefix != null
route.name(route.name());
bag.add(route);
return route;
}
/**
* Import an application {@link Module}.
*
* @param module The module to import.
* @return This jooby instance.
* @see Jooby.Module
*/
public Jooby use(final Jooby.Module module) {
requireNonNull(module, "A module is required.");
bag.add(module);
return this;
}
/**
* Set/specify a custom .conf file, useful when you don't want a <code>application.conf</code>
* file.
*
* @param path Classpath location.
* @return This jooby instance.
*/
public Jooby conf(final String path) {
use(ConfigFactory.parseResources(path));
return this;
}
/**
* Set/specify a custom .conf file, useful when you don't want a <code>application.conf</code>
* file.
*
* @param path File system location.
* @return This jooby instance.
*/
public Jooby conf(final File path) {
use(ConfigFactory.parseFile(path));
return this;
}
/**
* Set the application configuration object. You must call this method when the default file
* name: <code>application.conf</code> doesn't work for you or when you need/want to register two
* or more files.
*
* @param config The application configuration object.
* @return This jooby instance.
* @see Config
*/
public Jooby use(final Config config) {
this.srcconf = requireNonNull(config, "Config required.");
return this;
}
@Override
public Jooby err(final Err.Handler err) {
this.bag.add(requireNonNull(err, "An err handler is required."));
return this;
}
@Override
public WebSocket.Definition ws(final String path, final WebSocket.FullHandler handler) {
WebSocket.Definition ws = new WebSocket.Definition(path, handler);
checkArgument(bag.add(ws), "Path is in use: '%s'", path);
return ws;
}
@Override
public Route.Definition sse(final String path, final Sse.Handler handler) {
return appendDefinition(new Route.Definition("GET", path, handler)).consumes(MediaType.sse);
}
@Override
public Route.Definition sse(final String path, final Sse.Handler1 handler) {
return appendDefinition(new Route.Definition("GET", path, handler)).consumes(MediaType.sse);
}
@SuppressWarnings("rawtypes")
@Override
public Route.Collection with(final Runnable callback) {
// hacky way of doing what we want... but we do simplify developer life
int size = this.bag.size();
callback.run();
// collect latest routes and apply route props
List<Route.Props> local = this.bag.stream()
.skip(size)
.filter(Predicates.instanceOf(Route.Props.class))
.map(r -> (Route.Props) r)
.collect(Collectors.toList());
return new Route.Collection(local.toArray(new Route.Props[local.size()]));
}
/**
* Prepare and startup a {@link Jooby} application.
*
* @param app Application supplier.
* @param args Application arguments.
*/
public static void run(final Supplier<? extends Jooby> app, final String... args) {
Config conf = ConfigFactory.systemProperties()
.withFallback(args(args));
System.setProperty("logback.configurationFile", logback(conf));
app.get().start(args);
}
/**
* Prepare and startup a {@link Jooby} application.
*
* @param app Application supplier.
* @param args Application arguments.
*/
public static void run(final Class<? extends Jooby> app, final String... args) {
run(() -> Try.of(() -> app.newInstance()).get(), args);
}
/**
* Export configuration from an application. Useful for tooling, testing, debugging, etc...
*
* @param app Application to extract/collect configuration.
* @return Application conf or <code>empty</code> conf on error.
*/
public static Config exportConf(final Jooby app) {
AtomicReference<Config> conf = new AtomicReference<>(ConfigFactory.empty());
app.on("*", c -> {
conf.set(c);
});
exportRoutes(app);
return conf.get();
}
/**
* Export routes from an application. Useful for route analysis, testing, debugging, etc...
*
* @param app Application to extract/collect routes.
* @return Application routes.
*/
public static List<Definition> exportRoutes(final Jooby app) {
@SuppressWarnings("serial")
class Success extends RuntimeException {
List<Definition> routes;
Success(final List<Route.Definition> routes) {
this.routes = routes;
}
}
List<Definition> routes = Collections.emptyList();
try {
app.start(new String[0], r -> {
throw new Success(r);
});
} catch (Success success) {
routes = success.routes;
} catch (Throwable x) {
logger(app).debug("Failed bootstrap: {}", app, x);
}
return routes;
}
/**
* Start an application.
*/
public void start() {
start(new String[0]);
}
/**
* Start an application.
*
* @param args Application arguments.
*/
public void start(final String... args) {
try {
start(args, null);
} catch (Throwable x) {
stop();
String msg = "An error occurred while starting the application:";
if (throwBootstrapException) {
throw new Err(Status.SERVICE_UNAVAILABLE, msg, x);
} else {
logger(this).error(msg, x);
}
}
}
private void start(final String[] args, final Consumer<List<Route.Definition>> routes)
throws Throwable {
long start = System.currentTimeMillis();
started.set(true);
this.injector = bootstrap(args(args), routes);
// shutdown hook
Runtime.getRuntime().addShutdownHook(new Thread(() -> stop()));
Config conf = injector.getInstance(Config.class);
Logger log = logger(this);
// inject class
injector.injectMembers(this);
// start services
for (CheckedConsumer<Registry> onStart : this.onStart) {
onStart.accept(this);
}
// route mapper
Set<Route.Definition> routeDefs = injector.getInstance(Route.KEY);
Set<WebSocket.Definition> sockets = injector.getInstance(WebSocket.KEY);
if (mapper != null) {
routeDefs.forEach(it -> it.map(mapper));
}
AppPrinter printer = new AppPrinter(routeDefs, sockets, conf);
printer.printConf(log, conf);
// Start server
Server server = injector.getInstance(Server.class);
String serverName = server.getClass().getSimpleName().replace("Server", "").toLowerCase();
server.start();
long end = System.currentTimeMillis();
log.info("[{}@{}]: Server started in {}ms\n\n{}\n",
conf.getString("application.env"),
serverName,
end - start,
printer);
// started services
for (CheckedConsumer<Registry> onStarted : this.onStarted) {
onStarted.accept(this);
}
boolean join = conf.hasPath("server.join") ? conf.getBoolean("server.join") : true;
if (join) {
server.join();
}
}
@Override
@SuppressWarnings("unchecked")
public Jooby map(final Mapper<?> mapper) {
requireNonNull(mapper, "Mapper is required.");
if (mappers.add(mapper.name())) {
this.mapper = Optional.ofNullable(this.mapper)
.map(next -> Route.Mapper.chain(mapper, next))
.orElse((Mapper<Object>) mapper);
}
return this;
}
/**
* Use the injection provider to create the Guice injector
*
* @param injectorFactory the injection provider
* @return this instance.
*/
public Jooby injector(
final BiFunction<Stage, com.google.inject.Module, Injector> injectorFactory) {
this.injectorFactory = injectorFactory;
return this;
}
/**
* Bind the provided abstract type to the given implementation:
*
* <pre>
* {
* bind(MyInterface.class, MyImplementation.class);
* }
* </pre>
*
* @param type Service interface.
* @param implementation Service implementation.
* @param <T> Service type.
* @return This instance.
*/
public <T> Jooby bind(final Class<T> type, final Class<? extends T> implementation) {
use((env, conf, binder) -> {
binder.bind(type).to(implementation);
});
return this;
}
/**
* Bind the provided abstract type to the given implementation:
*
* <pre>
* {
* bind(MyInterface.class, MyImplementation::new);
* }
* </pre>
*
* @param type Service interface.
* @param implementation Service implementation.
* @param <T> Service type.
* @return This instance.
*/
public <T> Jooby bind(final Class<T> type, final Supplier<T> implementation) {
use((env, conf, binder) -> {
binder.bind(type).toInstance(implementation.get());
});
return this;
}
/**
* Bind the provided type:
*
* <pre>
* {
* bind(MyInterface.class);
* }
* </pre>
*
* @param type Service interface.
* @param <T> Service type.
* @return This instance.
*/
public <T> Jooby bind(final Class<T> type) {
use((env, conf, binder) -> {
binder.bind(type);
});
return this;
}
/**
* Bind the provided type:
*
* <pre>
* {
* bind(new MyService());
* }
* </pre>
*
* @param service Service.
* @return This instance.
*/
@SuppressWarnings({"rawtypes", "unchecked" })
public Jooby bind(final Object service) {
use((env, conf, binder) -> {
Class type = service.getClass();
binder.bind(type).toInstance(service);
});
return this;
}
/**
* Bind the provided type and object that requires some type of configuration:
*
* <pre>{@code
* {
* bind(MyService.class, conf -> new MyService(conf.getString("service.url")));
* }
* }</pre>
*
* @param type Service type.
* @param provider Service provider.
* @param <T> Service type.
* @return This instance.
*/
public <T> Jooby bind(final Class<T> type, final Function<Config, ? extends T> provider) {
use((env, conf, binder) -> {
T service = provider.apply(conf);
binder.bind(type).toInstance(service);
});
return this;
}
/**
* Bind the provided type and object that requires some type of configuration:
*
* <pre>{@code
* {
* bind(conf -> new MyService(conf.getString("service.url")));
* }
* }</pre>
*
* @param provider Service provider.
* @param <T> Service type.
* @return This instance.
*/
@SuppressWarnings({"unchecked", "rawtypes" })
public <T> Jooby bind(final Function<Config, T> provider) {
use((env, conf, binder) -> {
Object service = provider.apply(conf);
Class type = service.getClass();
binder.bind(type).toInstance(service);
});
return this;
}
/**
* Set application date format.
*
* @param dateFormat A date format.
* @return This instance.
*/
public Jooby dateFormat(final String dateFormat) {
this.dateFormat = requireNonNull(dateFormat, "DateFormat required.");
return this;
}
/**
* Set application number format.
*
* @param numberFormat A number format.
* @return This instance.
*/
public Jooby numberFormat(final String numberFormat) {
this.numberFormat = requireNonNull(numberFormat, "NumberFormat required.");
return this;
}
/**
* Set application/default charset.
*
* @param charset A charset.
* @return This instance.
*/
public Jooby charset(final Charset charset) {
this.charset = requireNonNull(charset, "Charset required.");
return this;
}
/**
* Set application locale (first listed are higher priority).
*
* @param languages List of locale using the language tag format.
* @return This instance.
*/
public Jooby lang(final String... languages) {
this.languages = languages;
return this;
}
/**
* Set application time zone.
*
* @param zoneId ZoneId.
* @return This instance.
*/
public Jooby timezone(final ZoneId zoneId) {
this.zoneId = requireNonNull(zoneId, "ZoneId required.");
return this;
}
/**
* Set the HTTP port.
*
* <p>
* Keep in mind this work as a default port and can be reset via <code>application.port</code>
* property.
* </p>
*
* @param port HTTP port.
* @return This instance.
*/
public Jooby port(final int port) {
this.port = port;
return this;
}
/**
* <p>
* Set the HTTPS port to use.
* </p>
*
* <p>
* Keep in mind this work as a default port and can be reset via <code>application.port</code>
* property.
* </p>
*
* <h2>HTTPS</h2>
* <p>
* Jooby comes with a self-signed certificate, useful for development and test. But of course, you
* should NEVER use it in the real world.
* </p>
*
* <p>
* In order to setup HTTPS with a secure certificate, you need to set these properties:
* </p>
*
* <ul>
* <li>
* <code>ssl.keystore.cert</code>: An X.509 certificate chain file in PEM format. It can be an
* absolute path or a classpath resource.
* </li>
* <li>
* <code>ssl.keystore.key</code>: A PKCS#8 private key file in PEM format. It can be an absolute
* path or a classpath resource.
* </li>
* </ul>
*
* <p>
* Optionally, you can set these too:
* </p>
*
* <ul>
* <li>
* <code>ssl.keystore.password</code>: Password of the keystore.key (if any). Default is:
* null/empty.
* </li>
* <li>
* <code>ssl.trust.cert</code>: Trusted certificates for verifying the remote endpoint’s
* certificate. The file should contain an X.509 certificate chain in PEM format. Default uses the
* system default.
* </li>
* <li>
* <code>ssl.session.cacheSize</code>: Set the size of the cache used for storing SSL session
* objects. 0 to use the default value.
* </li>
* <li>
* <code>ssl.session.timeout</code>: Timeout for the cached SSL session objects, in seconds. 0 to
* use the default value.
* </li>
* </ul>
*
* <p>
* As you can see setup is very simple. All you need is your <code>.crt</code> and
* <code>.key</code> files.
* </p>
*
* @param port HTTPS port.
* @return This instance.
*/
public Jooby securePort(final int port) {
this.securePort = port;
return this;
}
/**
* <p>
* Enable <code>HTTP/2</code> protocol. Some servers require special configuration, others just
* works. It is a good idea to check the server documentation about
* <a href="http://jooby.org/doc/servers">HTTP/2</a>.
* </p>
*
* <p>
* In order to use HTTP/2 from a browser you must configure HTTPS, see {@link #securePort(int)}
* documentation.
* </p>
*
* <p>
* If HTTP/2 clear text is supported then you may skip the HTTPS setup, but of course you won't be
* able to use HTTP/2 with browsers.
* </p>
*
* @return This instance.
*/
public Jooby http2() {
this.http2 = true;
return this;
}
/**
* Set the default executor to use from {@link Deferred Deferred API}.
*
* Default executor runs each task in the thread that invokes {@link Executor#execute execute},
* that's a Jooby worker thread. A worker thread in Jooby can block.
*
* The {@link ExecutorService} will automatically shutdown.
*
* @param executor Executor to use.
* @return This jooby instance.
*/
public Jooby executor(final ExecutorService executor) {
executor((Executor) executor);
onStop(r -> executor.shutdown());
return this;
}
/**
* Set the default executor to use from {@link Deferred Deferred API}.
*
* Default executor runs each task in the thread that invokes {@link Executor#execute execute},
* that's a Jooby worker thread. A worker thread in Jooby can block.
*
* The {@link ExecutorService} will automatically shutdown.
*
* @param executor Executor to use.
* @return This jooby instance.
*/
public Jooby executor(final Executor executor) {
this.defaultExecSet = true;
this.executors.add(binder -> {
binder.bind(Key.get(String.class, Names.named("deferred"))).toInstance("deferred");
binder.bind(Key.get(Executor.class, Names.named("deferred"))).toInstance(executor);
});
return this;
}
/**
* Set a named executor to use from {@link Deferred Deferred API}. Useful for override the
* default/global executor.
*
* Default executor runs each task in the thread that invokes {@link Executor#execute execute},
* that's a Jooby worker thread. A worker thread in Jooby can block.
*
* The {@link ExecutorService} will automatically shutdown.
*
* @param name Name of the executor.
* @param executor Executor to use.
* @return This jooby instance.
*/
public Jooby executor(final String name, final ExecutorService executor) {
executor(name, (Executor) executor);
onStop(r -> executor.shutdown());
return this;
}
/**
* Set a named executor to use from {@link Deferred Deferred API}. Useful for override the
* default/global executor.
*
* Default executor runs each task in the thread that invokes {@link Executor#execute execute},
* that's a Jooby worker thread. A worker thread in Jooby can block.
*
* The {@link ExecutorService} will automatically shutdown.
*
* @param name Name of the executor.
* @param executor Executor to use.
* @return This jooby instance.
*/
public Jooby executor(final String name, final Executor executor) {
this.executors.add(binder -> {
binder.bind(Key.get(Executor.class, Names.named(name))).toInstance(executor);
});
return this;
}
/**
* Set the default executor to use from {@link Deferred Deferred API}. This works as reference to
* an executor, application directly or via module must provide an named executor.
*
* Default executor runs each task in the thread that invokes {@link Executor#execute execute},
* that's a Jooby worker thread. A worker thread in Jooby can block.
*
* @param name Executor to use.
* @return This jooby instance.
*/
public Jooby executor(final String name) {
defaultExecSet = true;
this.executors.add(binder -> {
binder.bind(Key.get(String.class, Names.named("deferred"))).toInstance(name);
});
return this;
}
/**
* Set a named executor to use from {@link Deferred Deferred API}. Useful for override the
* default/global executor.
*
* Default executor runs each task in the thread that invokes {@link Executor#execute execute},
* that's a Jooby worker thread. A worker thread in Jooby can block.
*
* @param name Name of the executor.
* @param provider Provider for the executor.
* @return This jooby instance.
*/
private Jooby executor(final String name, final Class<? extends Provider<Executor>> provider) {
this.executors.add(binder -> {
binder.bind(Key.get(Executor.class, Names.named(name))).toProvider(provider).in(Singleton.class);
});
return this;
}
/**
* If the application fails to start all the services are shutdown. Also, the exception is logged
* and usually the application is going to exit.
*
* This options turn off logging and rethrow the exception as {@link Err}. Here is an example:
*
* <pre>
* public class App extends Jooby {
* {
* throwBootstrapException();
* ...
* }
* }
*
* App app = new App();
*
* try {
* app.start();
* } catch (Err err) {
* Throwable cause = err.getCause();
* }
* </pre>
*
* @return
*/
public Jooby throwBootstrapException() {
this.throwBootstrapException = true;
return this;
}
/**
* Run app in javascript.
*
* @param jsargs Arguments, first arg must be the name of the javascript file.
* @throws Throwable If app fails to start.
*/
public static void main(final String[] jsargs) throws Throwable {
String[] args = new String[Math.max(0, jsargs.length - 1)];
if (args.length > 0) {
System.arraycopy(jsargs, 1, args, 0, args.length);
}
String filename = jsargs.length > 0 ? jsargs[0] : "app.js";
run(new JsJooby().run(new File(filename)), args);
}
private static List<Object> normalize(final List<Object> services, final Env env,
final RouteMetadata classInfo, final String prefix) {
List<Object> result = new ArrayList<>();
List<Object> snapshot = services;
/** modules, routes, parsers, renderers and websockets */
snapshot.forEach(candidate -> {
if (candidate instanceof Route.Definition) {
result.add(candidate);
} else if (candidate instanceof Route.Group) {
((Route.Group) candidate).routes()
.forEach(r -> result.add(r));
} else if (candidate instanceof MvcClass) {
MvcClass mvcRoute = ((MvcClass) candidate);
Class<?> mvcClass = mvcRoute.routeClass;
String path = ((MvcClass) candidate).path;
MvcRoutes.routes(env, classInfo, path, mvcClass)
.forEach(route -> result.add(mvcRoute.apply(route)));
} else {
result.add(candidate);
}
});
return result;
}
private static List<Object> processEnvDep(final Set<Object> src, final Env env) {
List<Object> result = new ArrayList<>();
List<Object> bag = new ArrayList<>(src);
bag.forEach(it -> {
if (it instanceof EnvDep) {
EnvDep envdep = (EnvDep) it;
if (envdep.predicate.test(env.name())) {
int from = src.size();
envdep.callback.accept(env.config());
int to = src.size();
result.addAll(new ArrayList<>(src).subList(from, to));
}
} else {
result.add(it);
}
});
return result;
}
private Injector bootstrap(final Config args,
final Consumer<List<Route.Definition>> rcallback) throws Throwable {
Config appconf = ConfigFactory.parseResources("application.conf");
Config initconf = srcconf == null ? appconf : srcconf.withFallback(appconf);
List<Config> modconf = modconf(this.bag);
Config conf = buildConfig(initconf, args, modconf);
final List<Locale> locales = LocaleUtils.parse(conf.getString("application.lang"));
Env env = this.env.build(conf, this, locales.get(0));
String envname = env.name();
final Charset charset = Charset.forName(conf.getString("application.charset"));
String dateFormat = conf.getString("application.dateFormat");
ZoneId zoneId = ZoneId.of(conf.getString("application.tz"));
DateTimeFormatter dateTimeFormatter = DateTimeFormatter
.ofPattern(dateFormat, locales.get(0))
.withZone(zoneId);
DecimalFormat numberFormat = new DecimalFormat(conf.getString("application.numberFormat"));
// Guice Stage
Stage stage = "dev".equals(envname) ? Stage.DEVELOPMENT : Stage.PRODUCTION;
// expand and normalize bag
RouteMetadata rm = new RouteMetadata(env);
List<Object> realbag = processEnvDep(this.bag, env);
List<Config> realmodconf = modconf(realbag);
List<Object> bag = normalize(realbag, env, rm, prefix);
// collect routes and fire route callback
if (rcallback != null) {
List<Route.Definition> routes = bag.stream()
.filter(it -> it instanceof Route.Definition)
.map(it -> (Route.Definition) it)
.collect(Collectors.<Route.Definition> toList());
rcallback.accept(routes);
}
// final config ? if we add a mod that depends on env
Config finalConfig;
Env finalEnv;
if (modconf.size() != realmodconf.size()) {
finalConfig = buildConfig(initconf, args, realmodconf);
finalEnv = this.env.build(finalConfig, this, locales.get(0));
} else {
finalConfig = conf;
finalEnv = env;
}
boolean cookieSession = session.store() == null;
if (cookieSession && !finalConfig.hasPath("application.secret")) {
throw new IllegalStateException("Required property 'application.secret' is missing");
}
/** executors: */
if (!defaultExecSet) {
// default executor
executor(MoreExecutors.directExecutor());
}
executor("direct", MoreExecutors.directExecutor());
executor("server", ServerExecutorProvider.class);
/** Some basic xss functions. */
xss(finalEnv);
/** dependency injection */
@SuppressWarnings("unchecked")
com.google.inject.Module joobyModule = binder -> {
/** type converters */
new TypeConverters().configure(binder);
/** bind config */
bindConfig(binder, finalConfig);
/** bind env */
binder.bind(Env.class).toInstance(finalEnv);
/** bind charset */
binder.bind(Charset.class).toInstance(charset);
/** bind locale */
binder.bind(Locale.class).toInstance(locales.get(0));
TypeLiteral<List<Locale>> localeType = (TypeLiteral<List<Locale>>) TypeLiteral
.get(Types.listOf(Locale.class));
binder.bind(localeType).toInstance(locales);
/** bind time zone */
binder.bind(ZoneId.class).toInstance(zoneId);
binder.bind(TimeZone.class).toInstance(TimeZone.getTimeZone(zoneId));
/** bind date format */
binder.bind(DateTimeFormatter.class).toInstance(dateTimeFormatter);
/** bind number format */
binder.bind(NumberFormat.class).toInstance(numberFormat);
binder.bind(DecimalFormat.class).toInstance(numberFormat);
/** bind ssl provider. */
binder.bind(SSLContext.class).toProvider(SslContextProvider.class);
/** routes */
Multibinder<Definition> definitions = Multibinder
.newSetBinder(binder, Definition.class);
/** web sockets */
Multibinder<WebSocket.Definition> sockets = Multibinder
.newSetBinder(binder, WebSocket.Definition.class);
/** tmp dir */
File tmpdir = new File(finalConfig.getString("application.tmpdir"));
tmpdir.mkdirs();
binder.bind(File.class).annotatedWith(Names.named("application.tmpdir"))
.toInstance(tmpdir);
binder.bind(ParameterNameProvider.class).toInstance(rm);
/** err handler */
Multibinder<Err.Handler> ehandlers = Multibinder
.newSetBinder(binder, Err.Handler.class);
/** parsers & renderers */
Multibinder<Parser> parsers = Multibinder
.newSetBinder(binder, Parser.class);
Multibinder<Renderer> renderers = Multibinder
.newSetBinder(binder, Renderer.class);
/** basic parser */
parsers.addBinding().toInstance(BuiltinParser.Basic);
parsers.addBinding().toInstance(BuiltinParser.Collection);
parsers.addBinding().toInstance(BuiltinParser.Optional);
parsers.addBinding().toInstance(BuiltinParser.Enum);
parsers.addBinding().toInstance(BuiltinParser.Upload);
parsers.addBinding().toInstance(BuiltinParser.Bytes);
/** basic render */
renderers.addBinding().toInstance(BuiltinRenderer.asset);
renderers.addBinding().toInstance(BuiltinRenderer.bytes);
renderers.addBinding().toInstance(BuiltinRenderer.byteBuffer);
renderers.addBinding().toInstance(BuiltinRenderer.file);
renderers.addBinding().toInstance(BuiltinRenderer.charBuffer);
renderers.addBinding().toInstance(BuiltinRenderer.stream);
renderers.addBinding().toInstance(BuiltinRenderer.reader);
renderers.addBinding().toInstance(BuiltinRenderer.fileChannel);
/** modules, routes, parsers, renderers and websockets */
Set<Object> routeClasses = new HashSet<>();
for (Object it : bag) {
Try.run(() -> bindService(
this.bag,
finalConfig,
finalEnv,
rm,
binder,
definitions,
sockets,
ehandlers,
parsers,
renderers,
routeClasses).accept(it))
.getOrElseThrow(Throwables::propagate);
}
parsers.addBinding().toInstance(new DateParser(dateFormat));
parsers.addBinding().toInstance(new LocalDateParser(dateTimeFormatter));
parsers.addBinding().toInstance(new LocaleParser());
parsers.addBinding().toInstance(new StaticMethodParser("valueOf"));
parsers.addBinding().toInstance(new StaticMethodParser("fromString"));
parsers.addBinding().toInstance(new StaticMethodParser("forName"));
parsers.addBinding().toInstance(new StringConstructorParser());
parsers.addBinding().toInstance(beanParser.orElseGet(() -> new BeanParser(false)));
binder.bind(ParserExecutor.class).in(Singleton.class);
/** override(able) renderer */
boolean stacktrace = finalConfig.hasPath("err.stacktrace")
? finalConfig.getBoolean("err.stacktrace")
: "dev".equals(envname);
renderers.addBinding().toInstance(new DefaulErrRenderer(stacktrace));
renderers.addBinding().toInstance(BuiltinRenderer.text);
binder.bind(HttpHandler.class).to(HttpHandlerImpl.class).in(Singleton.class);
RequestScope requestScope = new RequestScope();
binder.bind(RequestScope.class).toInstance(requestScope);
binder.bindScope(RequestScoped.class, requestScope);
/** session manager */
binder.bind(Session.Definition.class)
.toProvider(session(finalConfig.getConfig("session"), session))
.asEagerSingleton();
Object sstore = session.store();
if (cookieSession) {
binder.bind(SessionManager.class).to(CookieSessionManager.class)
.asEagerSingleton();
} else {
binder.bind(SessionManager.class).to(ServerSessionManager.class).asEagerSingleton();
if (sstore instanceof Class) {
binder.bind(Store.class).to((Class<? extends Store>) sstore)
.asEagerSingleton();
} else {
binder.bind(Store.class).toInstance((Store) sstore);
}
}
binder.bind(Request.class).toProvider(Providers.outOfScope(Request.class))
.in(RequestScoped.class);
binder.bind(Response.class).toProvider(Providers.outOfScope(Response.class))
.in(RequestScoped.class);
/** server sent event */
binder.bind(Sse.class).toProvider(Providers.outOfScope(Sse.class))
.in(RequestScoped.class);
binder.bind(Session.class).toProvider(Providers.outOfScope(Session.class))
.in(RequestScoped.class);
/** def err */
ehandlers.addBinding().toInstance(new Err.DefHandler());
/** executors. */
executors.forEach(it -> it.accept(binder));
};
Injector injector = injectorFactory.apply(stage, joobyModule);
onStart.addAll(0, finalEnv.startTasks());
onStarted.addAll(0, finalEnv.startedTasks());
onStop.addAll(finalEnv.stopTasks());
// clear bag and freeze it
this.bag.clear();
this.bag = ImmutableSet.of();
this.executors.clear();
this.executors = ImmutableList.of();
return injector;
}
private void xss(final Env env) {
Escaper ufe = UrlEscapers.urlFragmentEscaper();
Escaper fpe = UrlEscapers.urlFormParameterEscaper();
Escaper pse = UrlEscapers.urlPathSegmentEscaper();
Escaper html = HtmlEscapers.htmlEscaper();
env.xss("urlFragment", ufe::escape)
.xss("formParam", fpe::escape)
.xss("pathSegment", pse::escape)
.xss("html", html::escape);
}
private static Provider<Session.Definition> session(final Config $session,
final Session.Definition session) {
return () -> {
// save interval
session.saveInterval(session.saveInterval()
.orElse($session.getDuration("saveInterval", TimeUnit.MILLISECONDS)));
// build cookie
Cookie.Definition source = session.cookie();
source.name(source.name()
.orElse($session.getString("cookie.name")));
if (!source.comment().isPresent() && $session.hasPath("cookie.comment")) {
source.comment($session.getString("cookie.comment"));
}
if (!source.domain().isPresent() && $session.hasPath("cookie.domain")) {
source.domain($session.getString("cookie.domain"));
}
source.httpOnly(source.httpOnly()
.orElse($session.getBoolean("cookie.httpOnly")));
Object maxAge = $session.getAnyRef("cookie.maxAge");
if (maxAge instanceof String) {
maxAge = $session.getDuration("cookie.maxAge", TimeUnit.SECONDS);
}
source.maxAge(source.maxAge()
.orElse(((Number) maxAge).intValue()));
source.path(source.path()
.orElse($session.getString("cookie.path")));
source.secure(source.secure()
.orElse($session.getBoolean("cookie.secure")));
return session;
};
}
private static CheckedConsumer<? super Object> bindService(final Set<Object> src,
final Config conf,
final Env env,
final RouteMetadata rm,
final Binder binder,
final Multibinder<Route.Definition> definitions,
final Multibinder<WebSocket.Definition> sockets,
final Multibinder<Err.Handler> ehandlers,
final Multibinder<Parser> parsers,
final Multibinder<Renderer> renderers,
final Set<Object> routeClasses) {
return it -> {
if (it instanceof Jooby.Module) {
int from = src.size();
install((Jooby.Module) it, env, conf, binder);
int to = src.size();
// collect any route a module might add
if (to > from) {
List<Object> elements = normalize(new ArrayList<>(src).subList(from, to), env, rm, null);
for (Object e : elements) {
bindService(src,
conf,
env,
rm,
binder,
definitions,
sockets,
ehandlers,
parsers,
renderers,
routeClasses).accept(e);
}
}
} else if (it instanceof Route.Definition) {
Route.Definition rdef = (Definition) it;
Route.Filter h = rdef.filter();
if (h instanceof Route.MethodHandler) {
Class<?> routeClass = ((Route.MethodHandler) h).method().getDeclaringClass();
if (routeClasses.add(routeClass)) {
binder.bind(routeClass);
}
}
definitions.addBinding().toInstance(rdef);
} else if (it instanceof WebSocket.Definition) {
sockets.addBinding().toInstance((WebSocket.Definition) it);
} else if (it instanceof Parser) {
parsers.addBinding().toInstance((Parser) it);
} else if (it instanceof Renderer) {
renderers.addBinding().toInstance((Renderer) it);
} else {
ehandlers.addBinding().toInstance((Err.Handler) it);
}
};
}
private static List<Config> modconf(final Collection<Object> bag) {
return bag.stream()
.filter(it -> it instanceof Jooby.Module)
.map(it -> ((Jooby.Module) it).config())
.filter(c -> !c.isEmpty())
.collect(Collectors.toList());
}
/**
* Test if the application is up and running.
*
* @return True if the application is up and running.
*/
public boolean isStarted() {
return started.get();
}
/**
* Stop the application, close all the modules and stop the web server.
*/
public void stop() {
if (started.compareAndSet(true, false)) {
Logger log = logger(this);
fireStop(this, log, onStop);
if (injector != null) {
try {
injector.getInstance(Server.class).stop();
} catch (Throwable ex) {
log.debug("server.stop() resulted in exception", ex);
}
}
injector = null;
log.info("Stopped");
}
}
private static void fireStop(final Jooby app, final Logger log,
final List<CheckedConsumer<Registry>> onStop) {
// stop services
onStop.forEach(c -> Try.run(() -> c.accept(app))
.onFailure(x -> log.error("shutdown of {} resulted in error", c, x)));
}
/**
* Build configuration properties, it configure system, app and modules properties.
*
* @param source Source config to use.
* @param args Args conf.
* @param modules List of modules.
* @return A configuration properties ready to use.
*/
private Config buildConfig(final Config source, final Config args,
final List<Config> modules) {
// normalize tmpdir
Config system = ConfigFactory.systemProperties();
Config tmpdir = source.hasPath("java.io.tmpdir") ? source : system;
// system properties
system = system
// file encoding got corrupted sometimes, override it.
.withValue("file.encoding", fromAnyRef(System.getProperty("file.encoding")))
.withValue("java.io.tmpdir",
fromAnyRef(Paths.get(tmpdir.getString("java.io.tmpdir")).normalize().toString()));
// set module config
Config moduleStack = ConfigFactory.empty();
for (Config module : ImmutableList.copyOf(modules).reverse()) {
moduleStack = moduleStack.withFallback(module);
}
String env = Arrays.asList(system, args, source).stream()
.filter(it -> it.hasPath("application.env"))
.findFirst()
.map(c -> c.getString("application.env"))
.orElse("dev");
String cpath = Arrays.asList(system, args, source).stream()
.filter(it -> it.hasPath("application.path"))
.findFirst()
.map(c -> c.getString("application.path"))
.orElse("/");
Config envcof = envConf(source, env);
// application.[env].conf -> application.conf
Config conf = envcof.withFallback(source);
return system
.withFallback(args)
.withFallback(conf)
.withFallback(moduleStack)
.withFallback(MediaType.types)
.withFallback(defaultConfig(conf, Route.normalize(cpath)))
.resolve();
}
/**
* Build a conf from arguments.
*
* @param args Application arguments.
* @return A conf.
*/
static Config args(final String[] args) {
if (args == null || args.length == 0) {
return ConfigFactory.empty();
}
Map<String, String> conf = new HashMap<>();
for (String arg : args) {
String[] values = arg.split("=");
String name;
String value;
if (values.length == 2) {
name = values[0];
value = values[1];
} else {
name = "application.env";
value = values[0];
}
if (name.indexOf(".") == -1) {
conf.put("application." + name, value);
}
conf.put(name, value);
}
return ConfigFactory.parseMap(conf, "args");
}
/**
* Build a env config: <code>[application].[env].[conf]</code>.
* Stack looks like
*
* <pre>
* (file://[origin].[env].[conf])?
* (cp://[origin].[env].[conf])?
* file://application.[env].[conf]
* /application.[env].[conf]
* </pre>
*
* @param source App source to use.
* @param env Application env.
* @return A config env.
*/
private Config envConf(final Config source, final String env) {
String origin = source.origin().resource();
Config result = ConfigFactory.empty();
if (origin != null) {
// load [resource].[env].[ext]
int dot = origin.lastIndexOf('.');
String originConf = origin.substring(0, dot) + "." + env + origin.substring(dot);
result = fileConfig(originConf).withFallback(ConfigFactory.parseResources(originConf));
}
String appConfig = "application." + env + ".conf";
return result
.withFallback(fileConfig(appConfig))
.withFallback(fileConfig("application.conf"))
.withFallback(ConfigFactory.parseResources(appConfig));
}
/**
* Config from file system.
*
* @param fname A file name.
* @return A config for the file name.
*/
static Config fileConfig(final String fname) {
File dir = new File(System.getProperty("user.dir"));
File froot = new File(dir, fname);
if (froot.exists()) {
return ConfigFactory.parseFile(froot);
} else {
File fconfig = new File(new File(dir, "conf"), fname);
if (fconfig.exists()) {
return ConfigFactory.parseFile(fconfig);
}
}
return ConfigFactory.empty();
}
/**
* Build default application.* properties.
*
* @param conf A source config.
* @param cpath Application path.
* @return default properties.
*/
private Config defaultConfig(final Config conf, final String cpath) {
String ns = getClass().getPackage().getName();
String[] parts = ns.split("\\.");
String appname = parts[parts.length - 1];
// locale
final List<Locale> locales;
if (!conf.hasPath("application.lang")) {
locales = Optional.ofNullable(this.languages)
.map(langs -> LocaleUtils.parse(Joiner.on(",").join(langs)))
.orElse(ImmutableList.of(Locale.getDefault()));
} else {
locales = LocaleUtils.parse(conf.getString("application.lang"));
}
Locale locale = locales.iterator().next();
String lang = locale.toLanguageTag();
// time zone
final String tz;
if (!conf.hasPath("application.tz")) {
tz = Optional.ofNullable(zoneId).orElse(ZoneId.systemDefault()).getId();
} else {
tz = conf.getString("application.tz");
}
// number format
final String nf;
if (!conf.hasPath("application.numberFormat")) {
nf = Optional.ofNullable(numberFormat)
.orElseGet(() -> ((DecimalFormat) DecimalFormat.getInstance(locale)).toPattern());
} else {
nf = conf.getString("application.numberFormat");
}
int processors = Runtime.getRuntime().availableProcessors();
String version = Optional.ofNullable(getClass().getPackage().getImplementationVersion())
.orElse("0.0.0");
Config defs = ConfigFactory.parseResources(Jooby.class, "jooby.conf")
.withValue("contextPath", ConfigValueFactory.fromAnyRef(cpath.equals("/") ? "" : cpath))
.withValue("application.name", ConfigValueFactory.fromAnyRef(appname))
.withValue("application.version", ConfigValueFactory.fromAnyRef(version))
.withValue("application.class", ConfigValueFactory.fromAnyRef(getClass().getName()))
.withValue("application.ns", ConfigValueFactory.fromAnyRef(ns))
.withValue("application.lang", ConfigValueFactory.fromAnyRef(lang))
.withValue("application.tz", ConfigValueFactory.fromAnyRef(tz))
.withValue("application.numberFormat", ConfigValueFactory.fromAnyRef(nf))
.withValue("server.http2.enabled", ConfigValueFactory.fromAnyRef(http2))
.withValue("runtime.processors", ConfigValueFactory.fromAnyRef(processors))
.withValue("runtime.processors-plus1", ConfigValueFactory.fromAnyRef(processors + 1))
.withValue("runtime.processors-plus2", ConfigValueFactory.fromAnyRef(processors + 2))
.withValue("runtime.processors-x2", ConfigValueFactory.fromAnyRef(processors * 2))
.withValue("runtime.processors-x4", ConfigValueFactory.fromAnyRef(processors * 4))
.withValue("runtime.processors-x8", ConfigValueFactory.fromAnyRef(processors * 8))
.withValue("runtime.concurrencyLevel", ConfigValueFactory
.fromAnyRef(Math.max(4, processors)));
if (charset != null) {
defs = defs.withValue("application.charset", ConfigValueFactory.fromAnyRef(charset.name()));
}
if (port != null) {
defs = defs.withValue("application.port", ConfigValueFactory.fromAnyRef(port.intValue()));
}
if (securePort != null) {
defs = defs.withValue("application.securePort",
ConfigValueFactory.fromAnyRef(securePort.intValue()));
}
if (dateFormat != null) {
defs = defs.withValue("application.dateFormat", ConfigValueFactory.fromAnyRef(dateFormat));
}
return defs;
}
/**
* Install a {@link JoobyModule}.
*
* @param module The module to install.
* @param env Application env.
* @param config The configuration object.
* @param binder A Guice binder.
* @throws Throwable If module bootstrap fails.
*/
private static void install(final Jooby.Module module, final Env env, final Config config,
final Binder binder) throws Throwable {
module.configure(env, config, binder);
}
/**
* Bind a {@link Config} and make it available for injection. Each property of the config is also
* binded it and ready to be injected with {@link javax.inject.Named}.
*
* @param binder Guice binder.
* @param config App config.
*/
@SuppressWarnings("unchecked")
private void bindConfig(final Binder binder, final Config config) {
// root nodes
traverse(binder, "", config.root());
// terminal nodes
for (Entry<String, ConfigValue> entry : config.entrySet()) {
String name = entry.getKey();
Named named = Names.named(name);
Object value = entry.getValue().unwrapped();
if (value instanceof List) {
List<Object> values = (List<Object>) value;
Type listType = values.size() == 0
? String.class
: Types.listOf(values.iterator().next().getClass());
Key<Object> key = (Key<Object>) Key.get(listType, Names.named(name));
binder.bind(key).toInstance(values);
} else {
binder.bindConstant().annotatedWith(named).to(value.toString());
}
}
// bind config
binder.bind(Config.class).toInstance(config);
}
private static void traverse(final Binder binder, final String p, final ConfigObject root) {
root.forEach((n, v) -> {
if (v instanceof ConfigObject) {
ConfigObject child = (ConfigObject) v;
String path = p + n;
Named named = Names.named(path);
binder.bind(Config.class).annotatedWith(named).toInstance(child.toConfig());
traverse(binder, path + ".", child);
}
});
}
private static Predicate<String> envpredicate(final String candidate) {
return env -> env.equalsIgnoreCase(candidate) || candidate.equals("*");
}
static String logback(final Config conf) {
// Avoid warning message from logback when multiples files are present
String logback;
if (conf.hasPath("logback.configurationFile")) {
logback = conf.getString("logback.configurationFile");
} else {
String env = conf.hasPath("application.env") ? conf.getString("application.env") : null;
URL cpconf = Jooby.class.getResource("logback." + env + ".xml");
ImmutableList.Builder<File> files = ImmutableList.builder();
File userdir = new File(System.getProperty("user.dir"));
File confdir = new File(userdir, "conf");
if (env != null) {
files.add(new File(userdir, "logback." + env + ".xml"));
files.add(new File(confdir, "logback." + env + ".xml"));
}
files.add(new File(userdir, "logback.xml"));
files.add(new File(confdir, "logback.xml"));
logback = files.build()
.stream()
.filter(f -> f.exists())
.map(f -> f.getAbsolutePath())
.findFirst()
.orElse((cpconf != null) ? cpconf.toString() : "logback.xml");
}
return logback;
}
private static Logger logger(final Jooby app) {
return LoggerFactory.getLogger(app.getClass());
}
public void configureAssetHandler(final AssetHandler handler) {
onStart(r -> {
Config conf = r.require(Config.class);
handler
.cdn(conf.getString("assets.cdn"))
.lastModified(conf.getBoolean("assets.lastModified"))
.etag(conf.getBoolean("assets.etag"))
.maxAge(conf.getString("assets.cache.maxAge"));
});
}
}
| Fix path when loading Logback configuration on classpath.
| jooby/src/main/java/org/jooby/Jooby.java | Fix path when loading Logback configuration on classpath. | <ide><path>ooby/src/main/java/org/jooby/Jooby.java
<ide> logback = conf.getString("logback.configurationFile");
<ide> } else {
<ide> String env = conf.hasPath("application.env") ? conf.getString("application.env") : null;
<del> URL cpconf = Jooby.class.getResource("logback." + env + ".xml");
<add> URL cpconf = Jooby.class.getResource("/logback." + env + ".xml");
<ide> ImmutableList.Builder<File> files = ImmutableList.builder();
<ide> File userdir = new File(System.getProperty("user.dir"));
<ide> File confdir = new File(userdir, "conf"); |
|
Java | apache-2.0 | 98b83dad479d872e7da457e6fa66393f2e1a54fc | 0 | taer/lettuce,lettuce-io/lettuce-core,pulse00/lettuce,pulse00/lettuce,Hocdoc/lettuce,Hocdoc/lettuce,lettuce-io/lettuce-core,lettuce-io/lettuce-core,lettuce-io/lettuce-core,mp911de/lettuce,mp911de/lettuce,taer/lettuce | // Copyright (C) 2011 - Will Glozer. All rights reserved.
package com.lambdaworks.redis.protocol;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.ReentrantLock;
import com.lambdaworks.redis.RedisChannelHandler;
import com.lambdaworks.redis.RedisChannelWriter;
import com.lambdaworks.redis.RedisCommandInterruptedException;
import com.lambdaworks.redis.RedisException;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
/**
* A netty {@link ChannelHandler} responsible for writing redis commands and reading responses from the server.
*
* @param <K> Key type.
* @param <V> Value type.
* @author Will Glozer
*/
@ChannelHandler.Sharable
public class CommandHandler<K, V> extends ChannelDuplexHandler implements RedisChannelWriter<K, V> {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(CommandHandler.class);
protected BlockingQueue<RedisCommand<K, V, ?>> queue;
protected BlockingQueue<RedisCommand<K, V, ?>> commandBuffer = new LinkedBlockingQueue<RedisCommand<K, V, ?>>();
protected ByteBuf buffer;
protected RedisStateMachine<K, V> rsm;
private AtomicReference<Channel> channel = new AtomicReference<Channel>();
private boolean closed;
private RedisChannelHandler<K, V> redisChannelHandler;
private final ReentrantLock writeLock = new ReentrantLock();
private final ReentrantLock readLock = new ReentrantLock();
/**
* Initialize a new instance that handles commands from the supplied queue.
*
* @param queue The command queue.
*/
public CommandHandler(BlockingQueue<RedisCommand<K, V, ?>> queue) {
this.queue = queue;
}
/**
*
* @see io.netty.channel.ChannelInboundHandlerAdapter#channelRegistered(io.netty.channel.ChannelHandlerContext)
*/
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
buffer = ctx.alloc().heapBuffer();
rsm = new RedisStateMachine<K, V>();
}
/**
*
* @see io.netty.channel.ChannelInboundHandlerAdapter#channelRead(io.netty.channel.ChannelHandlerContext, java.lang.Object)
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf input = (ByteBuf) msg;
try {
if (!input.isReadable() || input.refCnt() == 0) {
return;
}
if (buffer == null) {
logger.warn("CommandHandler is closed, incoming response will be discarded.");
return;
}
try {
readLock.lock();
buffer.writeBytes(input);
if (logger.isTraceEnabled()) {
logger.trace("[" + ctx.channel().remoteAddress() + "] Received: "
+ buffer.toString(Charset.defaultCharset()).trim());
}
decode(ctx, buffer);
} finally {
readLock.unlock();
}
} finally {
input.release();
}
}
protected void decode(ChannelHandlerContext ctx, ByteBuf buffer) throws InterruptedException {
while (!queue.isEmpty() && rsm.decode(buffer, queue.peek(), queue.peek().getOutput())) {
RedisCommand<K, V, ?> cmd = queue.take();
cmd.complete();
if (buffer != null && buffer.refCnt() != 0) {
buffer.discardReadBytes();
}
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
if (!queue.isEmpty()) {
RedisCommand<K, V, ?> command = queue.take();
command.setException(cause);
command.complete();
}
super.exceptionCaught(ctx, cause);
}
@Override
public <T> RedisCommand<K, V, T> write(RedisCommand<K, V, T> command) {
try {
if (closed) {
throw new RedisException("Connection is closed");
}
try {
writeLock.lock();
Channel channel = this.channel.get();
if (channel != null) {
if (logger.isDebugEnabled()) {
logger.debug("[" + this + "] write() writeAndFlush Command " + command);
}
channel.writeAndFlush(command);
} else {
if (logger.isDebugEnabled()) {
logger.debug("[" + this + "] write() buffering Command " + command);
}
commandBuffer.put(command);
}
} finally {
writeLock.unlock();
}
} catch (InterruptedException e) {
throw new RedisCommandInterruptedException(e);
}
return command;
}
/**
*
* @see io.netty.channel.ChannelDuplexHandler#write(io.netty.channel.ChannelHandlerContext, java.lang.Object,
* io.netty.channel.ChannelPromise)
*/
@Override
@SuppressWarnings("unchecked")
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
final RedisCommand<K, V, ?> cmd = (RedisCommand<K, V, ?>) msg;
ByteBuf buf = ctx.alloc().heapBuffer();
cmd.encode(buf);
if (logger.isTraceEnabled()) {
logger.trace("[" + ctx.channel().remoteAddress() + "] Sent: " + buf.toString(Charset.defaultCharset()).trim());
}
if (cmd.getOutput() == null) {
ctx.write(buf, promise);
cmd.complete();
} else {
queue.put(cmd);
ctx.write(buf, promise);
}
}
/**
* @see io.netty.channel.ChannelInboundHandlerAdapter#channelActive(io.netty.channel.ChannelHandlerContext)
*/
@Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
logger.debug("[" + this + "] channelActive()");
List<RedisCommand<K, V, ?>> tmp = new ArrayList<RedisCommand<K, V, ?>>(queue.size() + commandBuffer.size());
try {
writeLock.lock();
tmp.addAll(commandBuffer);
tmp.addAll(queue);
queue.clear();
commandBuffer.clear();
this.channel.set(ctx.channel());
if (redisChannelHandler != null) {
redisChannelHandler.activated();
}
} finally {
writeLock.unlock();
}
for (RedisCommand<K, V, ?> cmd : tmp) {
if (!cmd.isCancelled()) {
if (logger.isDebugEnabled()) {
logger.debug("[" + this + "] channelActive() triggering command " + cmd);
}
ctx.channel().writeAndFlush(cmd);
}
}
tmp.clear();
logger.debug("[" + this + "] channelActive() done");
}
/**
*
* @see io.netty.channel.ChannelInboundHandlerAdapter#channelInactive(io.netty.channel.ChannelHandlerContext)
*/
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
logger.debug("[" + this + "] channelInactive()");
this.channel.set(null);
if (closed) {
int size = 0;
if (queue != null) {
size += queue.size();
}
if (commandBuffer != null) {
size += commandBuffer.size();
}
List<RedisCommand<K, V, ?>> toCancel = new ArrayList<RedisCommand<K, V, ?>>(size);
if (queue != null) {
toCancel.addAll(queue);
queue.clear();
queue = null;
}
if (commandBuffer != null) {
toCancel.addAll(commandBuffer);
commandBuffer.clear();
commandBuffer = null;
}
for (RedisCommand<K, V, ?> cmd : toCancel) {
if (cmd.getOutput() != null) {
cmd.getOutput().setError("Connection closed");
}
cmd.complete();
}
}
if (redisChannelHandler != null) {
redisChannelHandler.deactivated();
}
logger.debug("[" + this + "] channelInactive() done");
}
/**
* Close the connection.
*/
@Override
public void close() {
logger.debug("[" + this + "] close()");
if (closed) {
return;
}
if (buffer != null) {
try {
readLock.lock();
buffer.release();
} finally {
readLock.unlock();
}
buffer = null;
}
closed = true;
if (channel.get() != null) {
ConnectionWatchdog watchdog = channel.get().pipeline().get(ConnectionWatchdog.class);
if (watchdog != null) {
watchdog.setReconnect(false);
}
try {
channel.get().close().sync();
} catch (InterruptedException e) {
throw new RedisException(e);
}
channel.set(null);
}
}
public boolean isClosed() {
return closed;
}
@Override
public void setRedisChannelHandler(RedisChannelHandler<K, V> redisChannelHandler) {
this.redisChannelHandler = redisChannelHandler;
}
}
| src/main/java/com/lambdaworks/redis/protocol/CommandHandler.java | // Copyright (C) 2011 - Will Glozer. All rights reserved.
package com.lambdaworks.redis.protocol;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.ReentrantLock;
import com.lambdaworks.redis.RedisChannelHandler;
import com.lambdaworks.redis.RedisChannelWriter;
import com.lambdaworks.redis.RedisCommandInterruptedException;
import com.lambdaworks.redis.RedisException;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
/**
* A netty {@link ChannelHandler} responsible for writing redis commands and reading responses from the server.
*
* @param <K> Key type.
* @param <V> Value type.
* @author Will Glozer
*/
@ChannelHandler.Sharable
public class CommandHandler<K, V> extends ChannelDuplexHandler implements RedisChannelWriter<K, V> {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(CommandHandler.class);
protected BlockingQueue<RedisCommand<K, V, ?>> queue;
protected BlockingQueue<RedisCommand<K, V, ?>> commandBuffer = new LinkedBlockingQueue<RedisCommand<K, V, ?>>();
protected ByteBuf buffer;
protected RedisStateMachine<K, V> rsm;
private AtomicReference<Channel> channel = new AtomicReference<Channel>();
private boolean closed;
private RedisChannelHandler<K, V> redisChannelHandler;
private final ReentrantLock writeLock = new ReentrantLock();
private final ReentrantLock readLock = new ReentrantLock();
/**
* Initialize a new instance that handles commands from the supplied queue.
*
* @param queue The command queue.
*/
public CommandHandler(BlockingQueue<RedisCommand<K, V, ?>> queue) {
this.queue = queue;
}
/**
*
* @see io.netty.channel.ChannelInboundHandlerAdapter#channelRegistered(io.netty.channel.ChannelHandlerContext)
*/
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
buffer = ctx.alloc().heapBuffer();
rsm = new RedisStateMachine<K, V>();
}
/**
*
* @see io.netty.channel.ChannelInboundHandlerAdapter#channelRead(io.netty.channel.ChannelHandlerContext, java.lang.Object)
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf input = (ByteBuf) msg;
try {
if (!input.isReadable() || input.refCnt() == 0) {
return;
}
if (buffer == null) {
logger.warn("CommandHandler is closed, incoming response will be discarded.");
return;
}
try {
readLock.lock();
buffer.writeBytes(input);
if (logger.isTraceEnabled()) {
logger.trace("[" + ctx.channel().remoteAddress() + "] Received: "
+ buffer.toString(Charset.defaultCharset()).trim());
}
decode(ctx, buffer);
} finally {
readLock.unlock();
}
} finally {
input.release();
}
}
protected void decode(ChannelHandlerContext ctx, ByteBuf buffer) throws InterruptedException {
while (!queue.isEmpty() && rsm.decode(buffer, queue.peek(), queue.peek().getOutput())) {
RedisCommand<K, V, ?> cmd = queue.take();
cmd.complete();
if (buffer != null && buffer.refCnt() != 0) {
buffer.discardReadBytes();
}
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
if (!queue.isEmpty()) {
RedisCommand<K, V, ?> command = queue.take();
command.setException(cause);
command.complete();
}
super.exceptionCaught(ctx, cause);
}
@Override
public <T> RedisCommand<K, V, T> write(RedisCommand<K, V, T> command) {
try {
if (closed) {
throw new RedisException("Connection is closed");
}
try {
writeLock.lock();
Channel channel = this.channel.get();
if (channel != null) {
if (logger.isDebugEnabled()) {
logger.debug("[" + this + "] write() writeAndFlush Command " + command);
}
channel.writeAndFlush(command);
} else {
if (logger.isDebugEnabled()) {
logger.debug("[" + this + "] write() buffering Command " + command);
}
commandBuffer.put(command);
}
} finally {
writeLock.unlock();
}
} catch (InterruptedException e) {
throw new RedisCommandInterruptedException(e);
}
return command;
}
/**
*
* @see io.netty.channel.ChannelDuplexHandler#write(io.netty.channel.ChannelHandlerContext, java.lang.Object,
* io.netty.channel.ChannelPromise)
*/
@Override
@SuppressWarnings("unchecked")
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
final RedisCommand<K, V, ?> cmd = (RedisCommand<K, V, ?>) msg;
ByteBuf buf = ctx.alloc().heapBuffer();
cmd.encode(buf);
if (logger.isTraceEnabled()) {
logger.trace("[" + ctx.channel().remoteAddress() + "] Sent: " + buf.toString(Charset.defaultCharset()).trim());
}
if (cmd.getOutput() == null) {
ctx.write(buf, promise);
cmd.complete();
} else {
queue.put(cmd);
ctx.write(buf, promise);
}
}
/**
* @see io.netty.channel.ChannelInboundHandlerAdapter#channelActive(io.netty.channel.ChannelHandlerContext)
*/
@Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
logger.debug("[" + this + "] channelActive()");
List<RedisCommand<K, V, ?>> tmp = new ArrayList<RedisCommand<K, V, ?>>(queue.size() + commandBuffer.size());
try {
writeLock.lock();
tmp.addAll(commandBuffer);
tmp.addAll(queue);
queue.clear();
commandBuffer.clear();
this.channel.set(ctx.channel());
if (redisChannelHandler != null) {
redisChannelHandler.activated();
}
} finally {
writeLock.unlock();
}
for (RedisCommand<K, V, ?> cmd : tmp) {
if (!cmd.isCancelled()) {
if (logger.isDebugEnabled()) {
logger.debug("[" + this + "] channelActive() triggering command " + cmd);
}
ctx.channel().writeAndFlush(cmd);
}
}
tmp.clear();
logger.debug("[" + this + "] channelActive() done");
}
/**
*
* @see io.netty.channel.ChannelInboundHandlerAdapter#channelInactive(io.netty.channel.ChannelHandlerContext)
*/
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
logger.debug("[" + this + "] channelInactive()");
this.channel.set(null);
if (closed) {
List<RedisCommand<K, V, ?>> toCancel = new ArrayList<RedisCommand<K, V, ?>>(queue.size() + commandBuffer.size());
toCancel.addAll(queue);
toCancel.addAll(commandBuffer);
queue.clear();
queue = null;
commandBuffer.clear();
commandBuffer = null;
for (RedisCommand<K, V, ?> cmd : toCancel) {
if (cmd.getOutput() != null) {
cmd.getOutput().setError("Connection closed");
}
cmd.complete();
}
}
if (redisChannelHandler != null) {
redisChannelHandler.deactivated();
}
logger.debug("[" + this + "] channelInactive() done");
}
/**
* Close the connection.
*/
@Override
public void close() {
logger.debug("[" + this + "] close()");
if (closed) {
return;
}
if (buffer != null) {
try {
readLock.lock();
buffer.release();
} finally {
readLock.unlock();
}
buffer = null;
}
closed = true;
if (channel.get() != null) {
ConnectionWatchdog watchdog = channel.get().pipeline().get(ConnectionWatchdog.class);
if (watchdog != null) {
watchdog.setReconnect(false);
}
try {
channel.get().close().sync();
} catch (InterruptedException e) {
throw new RedisException(e);
}
channel.set(null);
}
}
public boolean isClosed() {
return closed;
}
@Override
public void setRedisChannelHandler(RedisChannelHandler<K, V> redisChannelHandler) {
this.redisChannelHandler = redisChannelHandler;
}
}
| Handle premature channelInactive while ongoing close (avoid NPE)
| src/main/java/com/lambdaworks/redis/protocol/CommandHandler.java | Handle premature channelInactive while ongoing close (avoid NPE) | <ide><path>rc/main/java/com/lambdaworks/redis/protocol/CommandHandler.java
<ide>
<ide> if (closed) {
<ide>
<del> List<RedisCommand<K, V, ?>> toCancel = new ArrayList<RedisCommand<K, V, ?>>(queue.size() + commandBuffer.size());
<del>
<del> toCancel.addAll(queue);
<del> toCancel.addAll(commandBuffer);
<del>
<del> queue.clear();
<del> queue = null;
<del>
<del> commandBuffer.clear();
<del> commandBuffer = null;
<add> int size = 0;
<add> if (queue != null) {
<add> size += queue.size();
<add> }
<add>
<add> if (commandBuffer != null) {
<add> size += commandBuffer.size();
<add> }
<add>
<add> List<RedisCommand<K, V, ?>> toCancel = new ArrayList<RedisCommand<K, V, ?>>(size);
<add>
<add> if (queue != null) {
<add> toCancel.addAll(queue);
<add> queue.clear();
<add> queue = null;
<add> }
<add>
<add> if (commandBuffer != null) {
<add> toCancel.addAll(commandBuffer);
<add> commandBuffer.clear();
<add> commandBuffer = null;
<add> }
<ide>
<ide> for (RedisCommand<K, V, ?> cmd : toCancel) {
<ide> if (cmd.getOutput() != null) { |
|
JavaScript | agpl-3.0 | 7aa45cfbbcd690fcc68b200a0630c5447860b141 | 0 | inverse/emoncms,inverse/emoncms,emoncms/emoncms,chaveiro/emoncms,emoncms/emoncms,chaveiro/emoncms,chaveiro/emoncms,emoncms/emoncms,emoncms/emoncms,chaveiro/emoncms,emoncms/emoncms,inverse/emoncms,inverse/emoncms | /*global view */
/*eslint no-undef: "error"*/
var plotdata = [];
var timeWindowChanged = 0;
var ajaxAsyncXdr = [];
var event_visFeedData;
var event_refresh;
var showlegend = true;
var datetimepicker1;
var datetimepicker2;
var datatype;
var graphtype;
function convertToPlotlist(multigraphFeedlist) {
if (!multigraphFeedlist[0]) return;
var plotlist = [];
var showtag = (typeof multigraphFeedlist[0]["showtag"] !== "undefined" ? multigraphFeedlist[0]["showtag"] : true);
showlegend = (typeof multigraphFeedlist[0]["showlegend"] === "undefined" || multigraphFeedlist[0]["showlegend"]);
var barwidth = 1;
view.ymin = (typeof multigraphFeedlist[0]["ymin"] !== "undefined" ? multigraphFeedlist[0]["ymin"] : null);
view.ymax = (typeof multigraphFeedlist[0]["ymax"] !== "undefined" ? multigraphFeedlist[0]["ymax"] : null);
view.y2min = (typeof multigraphFeedlist[0]["y2min"] !== "undefined" ? multigraphFeedlist[0]["y2min"] : null);
view.y2max = (typeof multigraphFeedlist[0]["y2max"] !== "undefined" ? multigraphFeedlist[0]["y2max"] : null);
datatype=1;
for (var z in multigraphFeedlist) {
z = parseInt(z,10);
var tag = (showtag && typeof multigraphFeedlist[parseInt(z,10)]["tag"] !== "undefined" && multigraphFeedlist[parseInt(z,10)]["tag"] !== "" ? multigraphFeedlist[parseInt(z,10)]["tag"]+": " : "");
var stacked = (typeof multigraphFeedlist[z]["stacked"] !== "undefined" && multigraphFeedlist[z]["stacked"]);
barwidth = typeof multigraphFeedlist[z]["barwidth"] === "undefined" ? 1 : multigraphFeedlist[z]["barwidth"];
if ( typeof multigraphFeedlist[z]["graphtype"] === "undefined" ) {
//console.log(multigraphFeedlist[z]);
multigraphFeedlist[z]["datatype"] === "1" ? graphtype="lines" : graphtype="bars";
} else {
graphtype=multigraphFeedlist[z]["graphtype"];
}
if (multigraphFeedlist[z]["datatype"] === "2")
datatype=2;
if (graphtype.substring(0, 5) === "lines") {
plotlist[z] = {
id: multigraphFeedlist[z]["id"],
selected: 1,
plot: {
data: null,
label: tag + multigraphFeedlist[z]["name"],
stack: stacked,
points: {
show: true,
radius: 0,
lineWidth: 1, // in pixels
fill: false
},
lines: {
show: true,
fill: multigraphFeedlist[z]["fill"] ? (stacked ? 1.0 : 0.5) : 0.0,
steps: graphtype === "lineswithsteps" ? true : false
}
}
};
}
else if (graphtype === "bars") {
plotlist[z] = {
id: multigraphFeedlist[z]["id"],
selected: 1,
plot: {
data: null,
label: tag + multigraphFeedlist[z]["name"],
stack: stacked,
bars: {
show: true,
align: "center", barWidth: 3600*24*1000*barwidth, fill: multigraphFeedlist[z]["fill"] ? (stacked ? 1.0 : 0.5) : 0.0
}
}
};
} else {
console.log("ERROR: Unknown plot graphtype! Graphtype: ", multigraphFeedlist[z]["graphtype"]);
}
if (multigraphFeedlist[z]["left"] === true) {
plotlist[z].plot.yaxis = 1;
} else if (multigraphFeedlist[z]["right"] === true) {
plotlist[z].plot.yaxis = 2;
} else {
console.log("ERROR: Unknown plot alignment! Alignment setting: ", multigraphFeedlist[z]["right"]);
}
// Only set the plotcolour variable if we have a value to set it with
if (multigraphFeedlist[z]["lineColour"]) {
// Some browsers really want the leading "#". It works without in chrome, not in IE and opera.
// What the hell, people?
if (multigraphFeedlist[z]["lineColour"].indexOf("#") === -1) {
plotlist[z].plot.color = "#" + multigraphFeedlist[z]["lineColour"];
} else {
plotlist[z].plot.color = multigraphFeedlist[z]["lineColour"];
}
}
if (multigraphFeedlist[z]["left"] === false && multigraphFeedlist[z]["right"] === false) {
plotlist[z].selected = 0;
}
}
return plotlist;
}
/*
Handle Feeds
*/
function visFeedData() {
if (typeof multigraphFeedlist !== "undefined" && typeof multigraphFeedlist[0] !== "undefined" && typeof multigraphFeedlist[0]["autorefresh"] !== "undefined") {
var now = new Date().getTime();
var timeWindow = view.end - view.start;
if (now - view.end < 2000 * multigraphFeedlist[0]["autorefresh"]) {
view.end = now;
view.start = view.end - timeWindow;
visFeedDataOri();
clearTimeout(event_refresh); // Cancel any pending event
event_refresh = setTimeout(visFeedData, 1000 * multigraphFeedlist[0]["autorefresh"]);
} else {
visFeedDataOri();
}
} else {
visFeedDataOri();
}
}
// Ignore load request spurts
function visFeedDataOri() {
datetimepicker1.setLocalDate(new Date(view.start));
datetimepicker2.setLocalDate(new Date(view.end));
datetimepicker1.setEndDate(new Date(view.end));
datetimepicker2.setStartDate(new Date(view.start));
clearTimeout(event_visFeedData); // Cancel any pending events
event_visFeedData = setTimeout(function() { visFeedDataDelayed(); }, 500);
if (typeof multigraphFeedlist !== "undefined" && multigraphFeedlist.length !== plotdata.length) {plotdata = [];}
plot();
}
// Load relevant feed data asynchronously
function visFeedDataDelayed() {
var plotlist = convertToPlotlist(multigraphFeedlist);
var npoints = 800;
interval = Math.round(((view.end - view.start)/npoints)/1000);
for(var i in plotlist) {
if (plotlist[i].selected) {
if (!plotlist[i].plot.data) {
var skipmissing = 0; if (multigraphFeedlist[i]["skipmissing"]) {skipmissing = 1;}
if (typeof plotdata[i] === "undefined") plotdata[i] = [];
if (typeof ajaxAsyncXdr[i] !== "undefined") {
ajaxAsyncXdr[i].abort(); // Abort pending loads
ajaxAsyncXdr[i]=undefined;
}
var context = {index:i, plotlist:plotlist[i]};
ajaxAsyncXdr[i] = get_feed_data_async(visFeedDataCallback,context,plotlist[i].id,view.start,view.end,interval,skipmissing,1);
}
}
}
}
//load feed data to multigraph plot
function visFeedDataCallback(context,data) {
var i = context["index"];
context["plotlist"].plot.data = data;
if (context["plotlist"].plot.data) {
plotdata[i] = context["plotlist"].plot;
}
plot();
}
function plot() {
$.plot($("#graph"), plotdata, {
canvas: true,
grid: { show: true, hoverable: true, clickable: true },
xaxis: { mode: "time", timezone: "browser", min: view.start, max: view.end },
selection: { mode: "x" },
legend: { show: showlegend, position: "nw", toggle: true },
toggle: { scale: "visible" },
touch: { pan: "x", scale: "x" },
yaxis: { min: view.ymin , max: view.ymax},
y2axis: { min: view.y2min , max: view.y2max}
});
}
function multigraphInit(element) {
// Get start and end time of multigraph view
// end time and timewindow is stored in the first multigraphFeedlist item.
// start time is calculated from end - timewindow
plotdata = [];
var timeWindow = (3600000*24.0*7);
var now = new Date().getTime();
view.start = now - timeWindow;
view.end = now;
if (typeof multigraphFeedlist !== "undefined" && typeof multigraphFeedlist[0] !== "undefined") {
view.end = multigraphFeedlist[0].end;
if (view.end==0) view.end = now;
if (multigraphFeedlist[0].timeWindow) {
view.start = view.end - multigraphFeedlist[0].timeWindow;
}
}
var out =
"<div id='graph_bound' style='height:400px; width:100%; position:relative; '>"+
"<div id='graph'></div>"+
"<div id='graph-buttons-timemanual' style='position:absolute; top:15px; right:35px; opacity:0.5; display: none;'>"+
"<div class='input-prepend input-append'>"+
"<span class='add-on'>Select time window</span>"+
"<span class='add-on'>Start:</span>"+
"<span id='datetimepicker1'>"+
"<input id='timewindow-start' data-format='dd/MM/yyyy hh:mm:ss' type='text' style='width:140px'/>"+
"<span class='add-on'><i data-time-icon='icon-time' data-date-icon='icon-calendar'></i></span>"+
"</span> "+
"<span class='add-on'>End:</span>"+
"<span id='datetimepicker2'>"+
"<input id='timewindow-end' data-format='dd/MM/yyyy hh:mm:ss' type='text' style='width:140px'/>"+
"<span class='add-on'><i data-time-icon='icon-time' data-date-icon='icon-calendar'></i></span>"+
"</span> "+
"<button class='btn graph-timewindow-set' type='button'><i class='icon-ok'></i></button>"+
"</div> "+
"</div>"+
"<div id='graph-buttons' style='position:absolute; top:15px; right:35px; opacity:0.5; display: none;'>"+
"<div id='graph-buttons-normal'>"+
"<div class='input-prepend input-append' id='graph-tooltip' style='margin:0'>"+
"<span class='add-on'>Tooltip:</span>"+
"<span class='add-on'><input id='enableTooltip' type='checkbox' checked ></span>"+
"</div> "+
"<div class='btn-group'>"+
"<button class='btn graph-time' type='button' time='1'>D</button>"+
"<button class='btn graph-time' type='button' time='7'>W</button>"+
"<button class='btn graph-time' type='button' time='30'>M</button>"+
"<button class='btn graph-time' type='button' time='365'>Y</button>"+
"<button class='btn graph-timewindow' type='button'><i class='icon-resize-horizontal'></i></button></div>"+
"<div class='btn-group' id='graph-navbar' style='display: none;'>"+
"<button class='btn graph-nav' id='zoomin'>+</button>"+
"<button class='btn graph-nav' id='zoomout'>-</button>"+
"<button class='btn graph-nav' id='left'><</button>"+
"<button class='btn graph-nav' id='right'>></button></div>"+
"</div>"+
"</div>"+
"</div>";
$(element).html(out);
// Tool tip
var previousPoint = null;
var previousSeries = null;
$(element).bind("plothover", function (event, pos, item) {
//$("#x").text(pos.x.toFixed(2));
//$("#y").text(pos.y.toFixed(2));
if ($("#enableTooltip:checked").length > 0) {
if (item) {
if (previousPoint != item.dataIndex || previousSeries != item.seriesIndex) {
previousPoint = item.dataIndex;
previousSeries = item.seriesIndex;
$("#tooltip").remove();
var x = item.datapoint[0].toFixed(2);
if (typeof(item.datapoint[2])==="undefined") {
y=Number(item.datapoint[1].toFixed(2));
} else {
y=Number((item.datapoint[1]-item.datapoint[2]).toFixed(2));
}
if (datatype === 1)
options = { month:"short", day:"2-digit", hour:"2-digit", minute:"2-digit", second:"2-digit"};
else
options = { month:"short", day:"2-digit"};
var formattedTime=new Date(parseInt(x));
// I'd like to eventually add colour hinting to the background of the tooltop.
// This is why showTooltip has the bgColour parameter.
tooltip(item.pageX, item.pageY, item.series.label + " at " + formattedTime.toLocaleDateString("en-GB",options) + " = " + y, "#DDDDDD");
}
} else {
$("#tooltip").remove();
previousPoint = null;
}
}
});
vis_resize();
$(document).on('window.resized hidden.sidebar.collapse shown.sidebar.collapse',vis_resize);
function vis_resize() {
var width = $("#graph_bound").width();
$("#graph").width(width);
var height = width * 0.5;
if (embed) $("#graph").height($(window).height()); else $("#graph").height(height);
plot();
}
// Graph selections
$("#graph").bind("plotselected", function (event, ranges) {
view.start = ranges.xaxis.from;
view.end = ranges.xaxis.to;
visFeedData();
});
// Navigation actions
$("#zoomout").click(function () {view.zoomout(); visFeedData();});
$("#zoomin").click(function () {view.zoomin(); visFeedData();});
$("#right").click(function () {view.panright(); visFeedData();});
$("#left").click(function () {view.panleft(); visFeedData();});
$(".graph-time").click(function () {view.timewindow($(this).attr("time")); visFeedData();});
$(".graph-timewindow").click(function () {
$("#graph-buttons-timemanual").show();
$("#graph-buttons-normal").hide();
});
$(".graph-timewindow-set").click(function () {
var timewindow_start = parse_timepicker_time($("#timewindow-start").val());
var timewindow_end = parse_timepicker_time($("#timewindow-end").val());
if (!timewindow_start) {alert("Please enter a valid start date."); return false; }
if (!timewindow_end) {alert("Please enter a valid end date."); return false; }
if (timewindow_start>=timewindow_end) {alert("Start date must be further back in time than end date."); return false; }
$("#graph-buttons-timemanual").hide();
$("#graph-buttons-normal").show();
view.start = timewindow_start * 1000;
view.end = timewindow_end *1000;
visFeedData();
});
$("#datetimepicker1").datetimepicker({
language: 'en-EN'
});
$("#datetimepicker2").datetimepicker({
language: 'en-EN',
useCurrent: false //Important! See issue #1075
});
$("#datetimepicker1").on("changeDate", function (e) {
if (view.datetimepicker_previous == null) view.datetimepicker_previous = view.start;
if (Math.abs(view.datetimepicker_previous - e.date.getTime()) > 1000*60*60*24)
{
var d = new Date(e.date.getFullYear(), e.date.getMonth(), e.date.getDate());
d.setTime( d.getTime() - e.date.getTimezoneOffset()*60*1000 );
var out = d;
$("#datetimepicker1").data("datetimepicker").setDate(out);
} else {
var out = e.date;
}
view.datetimepicker_previous = e.date.getTime();
$("#datetimepicker2").data("datetimepicker").setStartDate(out);
});
$("#datetimepicker2").on("changeDate", function (e) {
if (view.datetimepicker_previous === null) {view.datetimepicker_previous = view.end;}
if (Math.abs(view.datetimepicker_previous - e.date.getTime()) > 1000*60*60*24)
{
var d = new Date(e.date.getFullYear(), e.date.getMonth(), e.date.getDate());
d.setTime( d.getTime() - e.date.getTimezoneOffset()*60*1000 );
var out = d;
$("#datetimepicker2").data("datetimepicker").setDate(out);
} else {
var out = e.date;
}
view.datetimepicker_previous = e.date.getTime();
$("#datetimepicker1").data("datetimepicker").setEndDate(out);
});
datetimepicker1 = $("#datetimepicker1").data("datetimepicker");
datetimepicker2 = $("#datetimepicker2").data("datetimepicker");
// Navigation and zooming buttons for mouse and touch
$("#graph").mouseenter(function() {
$("#graph-navbar").show();
$("#graph-tooltip").show();
$("#graph-buttons").stop().fadeIn();
$("#stats").stop().fadeIn();
});
$("#graph_bound").mouseleave(function() {
$("#graph-buttons").stop().fadeOut();
$("#stats").stop().fadeOut();
});
$("#graph").bind("touchstarted", function (event, pos) {
$("#graph-navbar").hide();
$("#graph-tooltip").hide();
$("#graph-buttons").stop().fadeOut();
$("#stats").stop().fadeOut();
});
$("#graph").bind("touchended", function (event, ranges) {
$("#graph-buttons").stop().fadeIn();
$("#stats").stop().fadeIn();
view.start = ranges.xaxis.from;
view.end = ranges.xaxis.to;
visFeedData();
});
}
| Modules/vis/visualisations/multigraph/multigraph.js | /*global view */
/*eslint no-undef: "error"*/
var plotdata = [];
var timeWindowChanged = 0;
var ajaxAsyncXdr = [];
var event_visFeedData;
var event_refresh;
var showlegend = true;
var datetimepicker1;
var datetimepicker2;
var datatype;
var graphtype;
function convertToPlotlist(multigraphFeedlist) {
if (!multigraphFeedlist[0]) return;
var plotlist = [];
var showtag = (typeof multigraphFeedlist[0]["showtag"] !== "undefined" ? multigraphFeedlist[0]["showtag"] : true);
showlegend = (typeof multigraphFeedlist[0]["showlegend"] === "undefined" || multigraphFeedlist[0]["showlegend"]);
var barwidth = 1;
view.ymin = (typeof multigraphFeedlist[0]["ymin"] !== "undefined" ? multigraphFeedlist[0]["ymin"] : null);
view.ymax = (typeof multigraphFeedlist[0]["ymax"] !== "undefined" ? multigraphFeedlist[0]["ymax"] : null);
view.y2min = (typeof multigraphFeedlist[0]["y2min"] !== "undefined" ? multigraphFeedlist[0]["y2min"] : null);
view.y2max = (typeof multigraphFeedlist[0]["y2max"] !== "undefined" ? multigraphFeedlist[0]["y2max"] : null);
datatype=1;
for (var z in multigraphFeedlist) {
z = parseInt(z);
var tag = (showtag && typeof multigraphFeedlist[z]["tag"] !== "undefined" && multigraphFeedlist[z]["tag"] !== "" ? multigraphFeedlist[z]["tag"]+": " : "");
var stacked = (typeof multigraphFeedlist[z]["stacked"] !== "undefined" && multigraphFeedlist[z]["stacked"]);
barwidth = typeof multigraphFeedlist[z]["barwidth"] === "undefined" ? 1 : multigraphFeedlist[z]["barwidth"];
if ( typeof multigraphFeedlist[z]["graphtype"] === "undefined" ) {
//console.log(multigraphFeedlist[z]);
multigraphFeedlist[z]["datatype"] === "1" ? graphtype="lines" : graphtype="bars";
} else {
graphtype=multigraphFeedlist[z]["graphtype"];
}
if (multigraphFeedlist[z]["datatype"] === "2")
datatype=2;
if (graphtype.substring(0, 5) === "lines") {
plotlist[z] = {
id: multigraphFeedlist[z]["id"],
selected: 1,
plot: {
data: null,
label: tag + multigraphFeedlist[z]["name"],
stack: stacked,
points: {
show: true,
radius: 0,
lineWidth: 1, // in pixels
fill: false
},
lines: {
show: true,
fill: multigraphFeedlist[z]["fill"] ? (stacked ? 1.0 : 0.5) : 0.0,
steps: graphtype === "lineswithsteps" ? true : false
}
}
};
}
else if (graphtype === "bars") {
plotlist[z] = {
id: multigraphFeedlist[z]["id"],
selected: 1,
plot: {
data: null,
label: tag + multigraphFeedlist[z]["name"],
stack: stacked,
bars: {
show: true,
align: "center", barWidth: 3600*24*1000*barwidth, fill: multigraphFeedlist[z]["fill"] ? (stacked ? 1.0 : 0.5) : 0.0
}
}
};
} else {
console.log("ERROR: Unknown plot graphtype! Graphtype: ", multigraphFeedlist[z]["graphtype"]);
}
if (multigraphFeedlist[z]["left"] === true) {
plotlist[z].plot.yaxis = 1;
} else if (multigraphFeedlist[z]["right"] === true) {
plotlist[z].plot.yaxis = 2;
} else {
console.log("ERROR: Unknown plot alignment! Alignment setting: ", multigraphFeedlist[z]["right"]);
}
// Only set the plotcolour variable if we have a value to set it with
if (multigraphFeedlist[z]["lineColour"]) {
// Some browsers really want the leading "#". It works without in chrome, not in IE and opera.
// What the hell, people?
if (multigraphFeedlist[z]["lineColour"].indexOf("#") === -1) {
plotlist[z].plot.color = "#" + multigraphFeedlist[z]["lineColour"];
} else {
plotlist[z].plot.color = multigraphFeedlist[z]["lineColour"];
}
}
if (multigraphFeedlist[z]["left"] === false && multigraphFeedlist[z]["right"] === false) {
plotlist[z].selected = 0;
}
}
return plotlist;
}
/*
Handle Feeds
*/
function visFeedData() {
if (typeof multigraphFeedlist !== "undefined" && typeof multigraphFeedlist[0] !== "undefined" && typeof multigraphFeedlist[0]["autorefresh"] !== "undefined") {
var now = new Date().getTime();
var timeWindow = view.end - view.start;
if (now - view.end < 2000 * multigraphFeedlist[0]["autorefresh"]) {
view.end = now;
view.start = view.end - timeWindow;
visFeedDataOri();
clearTimeout(event_refresh); // Cancel any pending event
event_refresh = setTimeout(visFeedData, 1000 * multigraphFeedlist[0]["autorefresh"]);
} else {
visFeedDataOri();
}
} else {
visFeedDataOri();
}
}
// Ignore load request spurts
function visFeedDataOri() {
datetimepicker1.setLocalDate(new Date(view.start));
datetimepicker2.setLocalDate(new Date(view.end));
datetimepicker1.setEndDate(new Date(view.end));
datetimepicker2.setStartDate(new Date(view.start));
clearTimeout(event_visFeedData); // Cancel any pending events
event_visFeedData = setTimeout(function() { visFeedDataDelayed(); }, 500);
if (typeof multigraphFeedlist !== "undefined" && multigraphFeedlist.length !== plotdata.length) {plotdata = [];}
plot();
}
// Load relevant feed data asynchronously
function visFeedDataDelayed() {
var plotlist = convertToPlotlist(multigraphFeedlist);
var npoints = 800;
interval = Math.round(((view.end - view.start)/npoints)/1000);
for(var i in plotlist) {
if (plotlist[i].selected) {
if (!plotlist[i].plot.data) {
var skipmissing = 0; if (multigraphFeedlist[i]["skipmissing"]) {skipmissing = 1;}
if (typeof plotdata[i] === "undefined") plotdata[i] = [];
if (typeof ajaxAsyncXdr[i] !== "undefined") {
ajaxAsyncXdr[i].abort(); // Abort pending loads
ajaxAsyncXdr[i]=undefined;
}
var context = {index:i, plotlist:plotlist[i]};
ajaxAsyncXdr[i] = get_feed_data_async(visFeedDataCallback,context,plotlist[i].id,view.start,view.end,interval,skipmissing,1);
}
}
}
}
//load feed data to multigraph plot
function visFeedDataCallback(context,data) {
var i = context["index"];
context["plotlist"].plot.data = data;
if (context["plotlist"].plot.data) {
plotdata[i] = context["plotlist"].plot;
}
plot();
}
function plot() {
$.plot($("#graph"), plotdata, {
canvas: true,
grid: { show: true, hoverable: true, clickable: true },
xaxis: { mode: "time", timezone: "browser", min: view.start, max: view.end },
selection: { mode: "x" },
legend: { show: showlegend, position: "nw", toggle: true },
toggle: { scale: "visible" },
touch: { pan: "x", scale: "x" },
yaxis: { min: view.ymin , max: view.ymax},
y2axis: { min: view.y2min , max: view.y2max}
});
}
function multigraphInit(element) {
// Get start and end time of multigraph view
// end time and timewindow is stored in the first multigraphFeedlist item.
// start time is calculated from end - timewindow
plotdata = [];
var timeWindow = (3600000*24.0*7);
var now = new Date().getTime();
view.start = now - timeWindow;
view.end = now;
if (typeof multigraphFeedlist !== "undefined" && typeof multigraphFeedlist[0] !== "undefined") {
view.end = multigraphFeedlist[0].end;
if (view.end==0) view.end = now;
if (multigraphFeedlist[0].timeWindow) {
view.start = view.end - multigraphFeedlist[0].timeWindow;
}
}
var out =
"<div id='graph_bound' style='height:400px; width:100%; position:relative; '>"+
"<div id='graph'></div>"+
"<div id='graph-buttons-timemanual' style='position:absolute; top:15px; right:35px; opacity:0.5; display: none;'>"+
"<div class='input-prepend input-append'>"+
"<span class='add-on'>Select time window</span>"+
"<span class='add-on'>Start:</span>"+
"<span id='datetimepicker1'>"+
"<input id='timewindow-start' data-format='dd/MM/yyyy hh:mm:ss' type='text' style='width:140px'/>"+
"<span class='add-on'><i data-time-icon='icon-time' data-date-icon='icon-calendar'></i></span>"+
"</span> "+
"<span class='add-on'>End:</span>"+
"<span id='datetimepicker2'>"+
"<input id='timewindow-end' data-format='dd/MM/yyyy hh:mm:ss' type='text' style='width:140px'/>"+
"<span class='add-on'><i data-time-icon='icon-time' data-date-icon='icon-calendar'></i></span>"+
"</span> "+
"<button class='btn graph-timewindow-set' type='button'><i class='icon-ok'></i></button>"+
"</div> "+
"</div>"+
"<div id='graph-buttons' style='position:absolute; top:15px; right:35px; opacity:0.5; display: none;'>"+
"<div id='graph-buttons-normal'>"+
"<div class='input-prepend input-append' id='graph-tooltip' style='margin:0'>"+
"<span class='add-on'>Tooltip:</span>"+
"<span class='add-on'><input id='enableTooltip' type='checkbox' checked ></span>"+
"</div> "+
"<div class='btn-group'>"+
"<button class='btn graph-time' type='button' time='1'>D</button>"+
"<button class='btn graph-time' type='button' time='7'>W</button>"+
"<button class='btn graph-time' type='button' time='30'>M</button>"+
"<button class='btn graph-time' type='button' time='365'>Y</button>"+
"<button class='btn graph-timewindow' type='button'><i class='icon-resize-horizontal'></i></button></div>"+
"<div class='btn-group' id='graph-navbar' style='display: none;'>"+
"<button class='btn graph-nav' id='zoomin'>+</button>"+
"<button class='btn graph-nav' id='zoomout'>-</button>"+
"<button class='btn graph-nav' id='left'><</button>"+
"<button class='btn graph-nav' id='right'>></button></div>"+
"</div>"+
"</div>"+
"</div>";
$(element).html(out);
// Tool tip
var previousPoint = null;
var previousSeries = null;
$(element).bind("plothover", function (event, pos, item) {
//$("#x").text(pos.x.toFixed(2));
//$("#y").text(pos.y.toFixed(2));
if ($("#enableTooltip:checked").length > 0) {
if (item) {
if (previousPoint != item.dataIndex || previousSeries != item.seriesIndex) {
previousPoint = item.dataIndex;
previousSeries = item.seriesIndex;
$("#tooltip").remove();
var x = item.datapoint[0].toFixed(2);
if (typeof(item.datapoint[2])==="undefined") {
y=Number(item.datapoint[1].toFixed(2));
} else {
y=Number((item.datapoint[1]-item.datapoint[2]).toFixed(2));
}
if (datatype === 1)
options = { month:"short", day:"2-digit", hour:"2-digit", minute:"2-digit", second:"2-digit"};
else
options = { month:"short", day:"2-digit"};
var formattedTime=new Date(parseInt(x));
// I'd like to eventually add colour hinting to the background of the tooltop.
// This is why showTooltip has the bgColour parameter.
tooltip(item.pageX, item.pageY, item.series.label + " at " + formattedTime.toLocaleDateString("en-GB",options) + " = " + y, "#DDDDDD");
}
} else {
$("#tooltip").remove();
previousPoint = null;
}
}
});
vis_resize();
$(document).on('window.resized hidden.sidebar.collapse shown.sidebar.collapse',vis_resize);
function vis_resize() {
var width = $("#graph_bound").width();
$("#graph").width(width);
var height = width * 0.5;
if (embed) $("#graph").height($(window).height()); else $("#graph").height(height);
plot();
}
// Graph selections
$("#graph").bind("plotselected", function (event, ranges) {
view.start = ranges.xaxis.from;
view.end = ranges.xaxis.to;
visFeedData();
});
// Navigation actions
$("#zoomout").click(function () {view.zoomout(); visFeedData();});
$("#zoomin").click(function () {view.zoomin(); visFeedData();});
$("#right").click(function () {view.panright(); visFeedData();});
$("#left").click(function () {view.panleft(); visFeedData();});
$(".graph-time").click(function () {view.timewindow($(this).attr("time")); visFeedData();});
$(".graph-timewindow").click(function () {
$("#graph-buttons-timemanual").show();
$("#graph-buttons-normal").hide();
});
$(".graph-timewindow-set").click(function () {
var timewindow_start = parse_timepicker_time($("#timewindow-start").val());
var timewindow_end = parse_timepicker_time($("#timewindow-end").val());
if (!timewindow_start) {alert("Please enter a valid start date."); return false; }
if (!timewindow_end) {alert("Please enter a valid end date."); return false; }
if (timewindow_start>=timewindow_end) {alert("Start date must be further back in time than end date."); return false; }
$("#graph-buttons-timemanual").hide();
$("#graph-buttons-normal").show();
view.start = timewindow_start * 1000;
view.end = timewindow_end *1000;
visFeedData();
});
$("#datetimepicker1").datetimepicker({
language: 'en-EN'
});
$("#datetimepicker2").datetimepicker({
language: 'en-EN',
useCurrent: false //Important! See issue #1075
});
$("#datetimepicker1").on("changeDate", function (e) {
if (view.datetimepicker_previous == null) view.datetimepicker_previous = view.start;
if (Math.abs(view.datetimepicker_previous - e.date.getTime()) > 1000*60*60*24)
{
var d = new Date(e.date.getFullYear(), e.date.getMonth(), e.date.getDate());
d.setTime( d.getTime() - e.date.getTimezoneOffset()*60*1000 );
var out = d;
$("#datetimepicker1").data("datetimepicker").setDate(out);
} else {
var out = e.date;
}
view.datetimepicker_previous = e.date.getTime();
$("#datetimepicker2").data("datetimepicker").setStartDate(out);
});
$("#datetimepicker2").on("changeDate", function (e) {
if (view.datetimepicker_previous === null) {view.datetimepicker_previous = view.end;}
if (Math.abs(view.datetimepicker_previous - e.date.getTime()) > 1000*60*60*24)
{
var d = new Date(e.date.getFullYear(), e.date.getMonth(), e.date.getDate());
d.setTime( d.getTime() - e.date.getTimezoneOffset()*60*1000 );
var out = d;
$("#datetimepicker2").data("datetimepicker").setDate(out);
} else {
var out = e.date;
}
view.datetimepicker_previous = e.date.getTime();
$("#datetimepicker1").data("datetimepicker").setEndDate(out);
});
datetimepicker1 = $("#datetimepicker1").data("datetimepicker");
datetimepicker2 = $("#datetimepicker2").data("datetimepicker");
// Navigation and zooming buttons for mouse and touch
$("#graph").mouseenter(function() {
$("#graph-navbar").show();
$("#graph-tooltip").show();
$("#graph-buttons").stop().fadeIn();
$("#stats").stop().fadeIn();
});
$("#graph_bound").mouseleave(function() {
$("#graph-buttons").stop().fadeOut();
$("#stats").stop().fadeOut();
});
$("#graph").bind("touchstarted", function (event, pos) {
$("#graph-navbar").hide();
$("#graph-tooltip").hide();
$("#graph-buttons").stop().fadeOut();
$("#stats").stop().fadeOut();
});
$("#graph").bind("touchended", function (event, ranges) {
$("#graph-buttons").stop().fadeIn();
$("#stats").stop().fadeIn();
view.start = ranges.xaxis.from;
view.end = ranges.xaxis.to;
visFeedData();
});
}
| Update multigraph.js | Modules/vis/visualisations/multigraph/multigraph.js | Update multigraph.js | <ide><path>odules/vis/visualisations/multigraph/multigraph.js
<ide> datatype=1;
<ide>
<ide> for (var z in multigraphFeedlist) {
<del> z = parseInt(z);
<del> var tag = (showtag && typeof multigraphFeedlist[z]["tag"] !== "undefined" && multigraphFeedlist[z]["tag"] !== "" ? multigraphFeedlist[z]["tag"]+": " : "");
<add> z = parseInt(z,10);
<add> var tag = (showtag && typeof multigraphFeedlist[parseInt(z,10)]["tag"] !== "undefined" && multigraphFeedlist[parseInt(z,10)]["tag"] !== "" ? multigraphFeedlist[parseInt(z,10)]["tag"]+": " : "");
<ide> var stacked = (typeof multigraphFeedlist[z]["stacked"] !== "undefined" && multigraphFeedlist[z]["stacked"]);
<ide> barwidth = typeof multigraphFeedlist[z]["barwidth"] === "undefined" ? 1 : multigraphFeedlist[z]["barwidth"];
<ide> |
|
Java | agpl-3.0 | 2d13f8989509d52a0b9292336aa090be8b979336 | 0 | Periapsis/aphelion,Periapsis/aphelion | /*
* Aphelion
* Copyright (c) 2013 Joris van der Wel
*
* This file is part of Aphelion
*
* Aphelion is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3 of the License.
*
* Aphelion is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Aphelion. If not, see <http://www.gnu.org/licenses/>.
*
* In addition, the following supplemental terms apply, based on section 7 of
* the GNU Affero General Public License (version 3):
* a) Preservation of all legal notices and author attributions
* b) Prohibition of misrepresentation of the origin of this material, and
* modified versions are required to be marked in reasonable ways as
* different from the original version (for example by appending a copyright notice).
*
* Linking this library statically or dynamically with other modules is making a
* combined work based on this library. Thus, the terms and conditions of the
* GNU Affero General Public License cover the whole combination.
*
* As a special exception, the copyright holders of this library give you
* permission to link this library with independent modules to produce an
* executable, regardless of the license terms of these independent modules,
* and to copy and distribute the resulting executable under terms of your
* choice, provided that you also meet, for each linked independent module,
* the terms and conditions of the license of that module. An independent
* module is a module which is not derived from or based on this library.
*/
package aphelion.shared.net;
import aphelion.client.net.SingleGameConnection;
import aphelion.server.AphelionServer;
import aphelion.server.http.HttpServer;
import aphelion.shared.event.TickedEventLoop;
import aphelion.shared.net.game.GameProtocolConnection;
import aphelion.shared.net.game.GameProtoListener;
import aphelion.shared.net.protobuf.GameC2S;
import aphelion.shared.net.protobuf.GameC2S.C2S;
import aphelion.shared.net.protobuf.GameOperation.ActorMove;
import aphelion.shared.net.protobuf.GameS2C;
import aphelion.shared.net.protobuf.GameS2C.ArenaSync;
import aphelion.shared.net.protobuf.GameS2C.S2C;
import aphelion.shared.physics.EnvironmentConf;
import aphelion.shared.physics.valueobjects.PhysicsMovement;
import com.google.protobuf.ByteString;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.channels.ServerSocketChannel;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.junit.*;
import static org.junit.Assert.*;
/**
*
* @author Joris
*/
public class WebSocketTest
{
private static final Logger log = Logger.getLogger(WebSocketTest.class.getName());
TickedEventLoop loop;
SessionToken sessionToken;
private long sentC2SMove;
private long receivedC2SMove;
int serverNewClient; int clientNewClient;
boolean clientRemoved; boolean serverRemoved;
int serverMessages; int clientMessages;
int clientConnections; int serverConnections;
int serverPidSum;
int clientPidSum;
@Before
public void setUp()
{
serverNewClient = 0;
clientNewClient = 0;
clientRemoved = false;
serverRemoved = false;
serverMessages = 0;
clientMessages = 0;
clientConnections = 0;
serverConnections = 0;
clientPidSum = 0;
serverPidSum = 0;
}
@After
public void breakDown()
{
loop = null;
sessionToken = null;
}
@Test(timeout=20000)
public void testSingleGameWebSocket() throws IOException, URISyntaxException
{
// use the same loop for client and server
loop = new TickedEventLoop(EnvironmentConf.TICK_LENGTH, 1, null);
// Set up the server
// use an ephemeral port. aka a temporary port number
try (ServerSocketChannel ssChannel = HttpServer.openServerChannel(new InetSocketAddress("127.0.0.1", 0)))
{
AphelionServer server = new AphelionServer(ssChannel, new File("./www"), loop);
loop.addLoopEvent(server);
server.setGameClientListener(new testSingleGameWebSocket_ServerGameListener());
// set up the client
SingleGameConnection client = new SingleGameConnection(
new URI("ws://127.0.0.1:"+server.getHTTPListeningPort()+"/aphelion"),
loop,
1); // 1 connection;
client.addListener(new testSingleGameWebSocket_ClientGameListener());
loop.addLoopEvent(client);
server.setup();
client.connect();
log.log(Level.INFO, "Starting loop");
loop.run();
assertEquals(1, clientNewClient);
assertEquals(1, serverNewClient);
assertTrue(clientRemoved);
assertTrue(serverRemoved);
assertEquals(1, clientMessages);
assertEquals(1, serverMessages);
double latency = (receivedC2SMove - sentC2SMove) / 1000000d;
log.log(Level.INFO, "Latency: {0}ms", latency);
client.close(WS_CLOSE_STATUS.NORMAL);
server.closeAll(WS_CLOSE_STATUS.NORMAL);
server.stop();
client.stop();
}
}
private class testSingleGameWebSocket_ServerGameListener implements GameProtoListener
{
@Override
public void gameNewClient(GameProtocolConnection game)
{
log.log(Level.INFO, "Server: new client");
++serverNewClient;
assertEquals(0, serverConnections);
assertEquals(0, clientNewClient);
assertEquals(1, serverNewClient);
assertTrue(game.server);
sessionToken = game.session;
}
@Override
public void gameRemovedClient(GameProtocolConnection game)
{
log.log(Level.INFO, "Server: removed client");
assertEquals(0, serverConnections);
serverRemoved = true;
if (clientRemoved)
{
loop.interrupt();
}
}
@Override
public void gameC2SMessage(GameProtocolConnection game, GameC2S.C2S c2s, long receivedAt)
{
++serverMessages;
log.log(Level.INFO, "Server: C2S message: {0}", serverMessages);
assertEquals(1, c2s.getActorMoveCount());
assertEquals(1, c2s.getAllFields().size());
ActorMove move = c2s.getActorMove(0);
receivedC2SMove = System.nanoTime();
assertEquals(123, move.getTick());
assertEquals(456, move.getPid());
List<PhysicsMovement> moves = PhysicsMovement.unserializeListLE(move.getMove().asReadOnlyByteBuffer());
assertEquals(4, moves.size());
assertEquals(0x1, moves.get(0).bits);
assertEquals(0x1 | 0x4, moves.get(1).bits);
assertEquals(0x0, moves.get(2).bits);
assertEquals(0x8, moves.get(3).bits);
S2C.Builder s2c = S2C.newBuilder();
ArenaSync.Builder arenaSync = s2c.addArenaSyncBuilder();
arenaSync.setName("jowie");
arenaSync.setShip("warbird");
arenaSync.setCurrentTicks(5021034);
arenaSync.setCurrentNanoTime(164029301000000000L);
arenaSync.setYourPid(102);
arenaSync.setYourSeed(1234567890);
game.send(s2c.build());
}
@Override
public void gameS2CMessage(GameProtocolConnection game, GameS2C.S2C s2c, long receivedAt)
{
assertTrue(false);
}
@Override
public void gameNewConnection(GameProtocolConnection game)
{
++serverConnections;
log.log(Level.INFO, "Server: gameNewConnection: {0}", serverConnections);
assertEquals(1, serverNewClient);
}
@Override
public void gameDropConnection(GameProtocolConnection game, WS_CLOSE_STATUS code, String reason)
{
--serverConnections;
log.log(Level.INFO, "Server: gameDropConnection: {0}", serverConnections);
assertEquals(1, serverNewClient);
}
@Override
public void gameEstablishFailure(WS_CLOSE_STATUS code, String reason)
{
assert false;
}
}
private class testSingleGameWebSocket_ClientGameListener implements GameProtoListener
{
@Override
public void gameNewClient(GameProtocolConnection game)
{
log.log(Level.INFO, "Client: new client");
++clientNewClient;
assertEquals(0, clientConnections);
assertEquals(1, serverNewClient);
assertEquals(1, clientNewClient);
assertFalse(game.server);
assertEquals(sessionToken, game.session);
C2S.Builder c2s = C2S.newBuilder();
ActorMove.Builder actorMove = c2s.addActorMoveBuilder();
actorMove.setTick(123);
actorMove.setPid(456);
actorMove.setMove(ByteString.copyFrom(PhysicsMovement.serializeListLE(Arrays.asList(
PhysicsMovement.get(0x1),
PhysicsMovement.get(0x1 | 0x4),
PhysicsMovement.get(0x0),
PhysicsMovement.get(0x8)))));
sentC2SMove = System.nanoTime();
game.send(c2s.build());
}
@Override
public void gameRemovedClient(GameProtocolConnection game)
{
assertEquals(0, clientConnections);
log.log(Level.INFO, "Client: removed client");
clientRemoved = true;
if (serverRemoved)
{
loop.interrupt();
}
}
@Override
public void gameC2SMessage(GameProtocolConnection game, GameC2S.C2S c2s, long receivedAt)
{
assertTrue(false);
}
@Override
public void gameS2CMessage(GameProtocolConnection game, GameS2C.S2C s2c, long receivedAt)
{
++clientMessages;
log.log(Level.INFO, "Client: S2C message: {0}", clientMessages);
assertEquals(1, s2c.getArenaSyncCount());
assertEquals(1, s2c.getAllFields().size());
ArenaSync arenaSync = s2c.getArenaSync(0);
assertEquals("jowie", arenaSync.getName());
assertEquals("warbird", arenaSync.getShip());
assertEquals(5021034, arenaSync.getCurrentTicks());
assertEquals(164029301000000000L, arenaSync.getCurrentNanoTime());
assertEquals(102, arenaSync.getYourPid());
// done with the test
game.requestClose(WS_CLOSE_STATUS.NORMAL);
}
@Override
public void gameNewConnection(GameProtocolConnection game)
{
assertEquals(1, clientNewClient);
++clientConnections;
log.log(Level.INFO, "Client: gameNewConnection: {0}", clientConnections);
}
@Override
public void gameDropConnection(GameProtocolConnection game, WS_CLOSE_STATUS code, String reason)
{
assertEquals(1, clientNewClient);
--clientConnections;
log.log(Level.INFO, "Client: gameDropConnection: {0}", clientNewClient);
}
@Override
public void gameEstablishFailure(WS_CLOSE_STATUS code, String reason)
{
assert false;
}
}
@Test(timeout=20000)
public void testMultiGameWebSocket() throws IOException, URISyntaxException
{
// use the same loop for client and server
loop = new TickedEventLoop(EnvironmentConf.TICK_LENGTH, 1, null);
// Set up the server
// use an ephemeral port. aka a temporary port number
try (ServerSocketChannel ssChannel = HttpServer.openServerChannel(new InetSocketAddress("127.0.0.1", 0)))
{
AphelionServer server = new AphelionServer(ssChannel, new File("./www"), loop);
loop.addLoopEvent(server);
server.setGameClientListener(new testMultiGameWebSocket_ServerGameListener());
server.setup();
// set up the client
SingleGameConnection client = new SingleGameConnection(
new URI("ws://127.0.0.1:"+server.getHTTPListeningPort()+"/aphelion"),
loop,
5); // 5 connections;
client.addListener(new testMultiGameWebSocket_ClientGameListener());
loop.addLoopEvent(client);
client.connect();
log.log(Level.INFO, "Start loop");
loop.run();
assertEquals(1, clientNewClient);
assertEquals(1, serverNewClient);
assertTrue(clientRemoved);
assertTrue(serverRemoved);
assertEquals(18, clientMessages);
assertEquals(28, serverMessages);
assertEquals(210, clientPidSum);
assertEquals(465, serverPidSum);
client.close(WS_CLOSE_STATUS.NORMAL);
server.closeAll(WS_CLOSE_STATUS.NORMAL);
server.stop();
client.stop();
}
}
private class testMultiGameWebSocket_ServerGameListener implements GameProtoListener
{
@Override
public void gameNewClient(GameProtocolConnection game)
{
++serverNewClient;
log.log(Level.INFO, "Server: new client {0}", serverNewClient);
assertEquals(0, serverConnections);
assertEquals(0, clientNewClient);
assertEquals(1, serverNewClient);
assertTrue(game.server);
sessionToken = game.session;
}
@Override
public void gameRemovedClient(GameProtocolConnection game)
{
log.log(Level.INFO, "Server: removed client");
assertEquals(0, serverConnections);
serverRemoved = true;
if (clientRemoved)
{
loop.interrupt();
}
}
@Override
public void gameC2SMessage(GameProtocolConnection game, GameC2S.C2S c2s, long receivedAt)
{
log.log(Level.INFO, "Server: Received message {0}", serverMessages);
++serverMessages;
assertTrue(c2s.getActorMoveCount() > 0);
assertEquals(1, c2s.getAllFields().size());
for (int a = 0; a < c2s.getActorMoveCount(); ++a)
{
ActorMove move = c2s.getActorMove(a);
assertEquals(123, move.getTick());
serverPidSum += move.getPid();
List<PhysicsMovement> moves = PhysicsMovement.unserializeListLE(move.getMove().asReadOnlyByteBuffer());
assertEquals(4, moves.size());
assertEquals(0x1, moves.get(0).bits);
assertEquals(0x1 | 0x4, moves.get(1).bits);
assertEquals(0x0, moves.get(2).bits);
assertEquals(0x8, moves.get(3).bits);
}
if (clientMessages == 18 && serverMessages == 28)
{
game.requestClose(WS_CLOSE_STATUS.NORMAL);
}
}
@Override
public void gameS2CMessage(GameProtocolConnection game, GameS2C.S2C s2c, long receivedAt)
{
assertTrue(false);
}
@Override
public void gameNewConnection(GameProtocolConnection game)
{
++serverConnections;
log.log(Level.INFO, "Server: gameNewConnection {0}", serverConnections);
if (serverConnections == 5)
{
S2C.Builder s2c = S2C.newBuilder();
for (int a = 0; a < 20; ++a)
{
if (a <= 17)
{
// send the last 3 in a batch
s2c = S2C.newBuilder();
}
ActorMove.Builder actorMove = s2c.addActorMoveBuilder();
actorMove.setTick(123);
actorMove.setPid(a + 1);
actorMove.setMove(ByteString.copyFrom(PhysicsMovement.serializeListLE(Arrays.asList(
PhysicsMovement.get(0x1),
PhysicsMovement.get(0x1 | 0x4),
PhysicsMovement.get(0x0),
PhysicsMovement.get(0x8)))));
if (a < 17)
{
log.log(Level.INFO, "Server: gameNewConnection: send(s2c) {0}", s2c.getActorMoveCount());
game.send(s2c);
}
}
log.log(Level.INFO, "Server: gameNewConnection: send(s2c) {0} (after loop)", s2c.getActorMoveCount());
game.send(s2c);
}
}
@Override
public void gameDropConnection(GameProtocolConnection game, WS_CLOSE_STATUS code, String reason)
{
--serverConnections;
log.log(Level.INFO, "Server: gameDropConnection {0}", serverConnections);
}
@Override
public void gameEstablishFailure(WS_CLOSE_STATUS code, String reason)
{
assert false;
}
}
private class testMultiGameWebSocket_ClientGameListener implements GameProtoListener
{
@Override
public void gameNewClient(GameProtocolConnection game)
{
++clientNewClient;
log.log(Level.INFO, "Client: new client {0} clientNewClient");
assertEquals(0, clientConnections);
assertEquals(1, serverNewClient);
assertEquals(1, clientNewClient);
assertFalse(game.server);
assertEquals(sessionToken, game.session);
}
@Override
public void gameRemovedClient(GameProtocolConnection game)
{
log.log(Level.INFO, "Client: removed client");
assertEquals(0, clientConnections);
clientRemoved = true;
if (serverRemoved)
{
loop.interrupt();
}
}
@Override
public void gameC2SMessage(GameProtocolConnection game, GameC2S.C2S c2s, long receivedAt)
{
assertTrue(false);
}
@Override
public void gameS2CMessage(GameProtocolConnection game, GameS2C.S2C s2c, long receivedAt)
{
++clientMessages;
log.log(Level.INFO, "Client: received message {0}", clientMessages);
assertTrue(s2c.getActorMoveCount() > 0);
assertEquals(1, s2c.getAllFields().size());
for (int a = 0; a < s2c.getActorMoveCount(); ++a)
{
ActorMove move = s2c.getActorMove(a);
assertEquals(123, move.getTick());
clientPidSum += move.getPid();
List<PhysicsMovement> moves = PhysicsMovement.unserializeListLE(move.getMove().asReadOnlyByteBuffer());
assertEquals(4, moves.size());
assertEquals(0x1, moves.get(0).bits);
assertEquals(0x1 | 0x4, moves.get(1).bits);
assertEquals(0x0, moves.get(2).bits);
assertEquals(0x8, moves.get(3).bits);
}
if (clientMessages == 18 && serverMessages == 28)
{
game.requestClose(WS_CLOSE_STATUS.NORMAL);
}
}
@Override
public void gameNewConnection(GameProtocolConnection game)
{
++clientConnections;
log.log(Level.INFO, "Client: gameNewConnection {0}", clientConnections);
if (clientConnections == 5)
{
C2S.Builder c2s = C2S.newBuilder();
for (int a = 0; a < 30; ++a)
{
if (a <= 27)
{
// send the last 3 in a batch
c2s = C2S.newBuilder();
}
ActorMove.Builder actorMove = c2s.addActorMoveBuilder();
actorMove.setTick(123);
actorMove.setPid(a + 1);
actorMove.setMove(ByteString.copyFrom(PhysicsMovement.serializeListLE(Arrays.asList(
PhysicsMovement.get(0x1),
PhysicsMovement.get(0x1 | 0x4),
PhysicsMovement.get(0x0),
PhysicsMovement.get(0x8)))));
if (a < 27)
{
log.log(Level.INFO, "Client: gameNewConnection: send(c2s) {0}", c2s.getActorMoveCount());
game.send(c2s);
}
}
log.log(Level.INFO, "Client: gameNewConnection: send(c2s) {0} (after loop)", c2s.getActorMoveCount());
game.send(c2s);
}
}
@Override
public void gameDropConnection(GameProtocolConnection game, WS_CLOSE_STATUS code, String reason)
{
--clientConnections;
log.log(Level.INFO, "Client: gameDropConnection {0}", clientConnections);
}
@Override
public void gameEstablishFailure(WS_CLOSE_STATUS code, String reason)
{
assert false;
}
}
}
| src/test/java/aphelion/shared/net/WebSocketTest.java | /*
* Aphelion
* Copyright (c) 2013 Joris van der Wel
*
* This file is part of Aphelion
*
* Aphelion is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3 of the License.
*
* Aphelion is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Aphelion. If not, see <http://www.gnu.org/licenses/>.
*
* In addition, the following supplemental terms apply, based on section 7 of
* the GNU Affero General Public License (version 3):
* a) Preservation of all legal notices and author attributions
* b) Prohibition of misrepresentation of the origin of this material, and
* modified versions are required to be marked in reasonable ways as
* different from the original version (for example by appending a copyright notice).
*
* Linking this library statically or dynamically with other modules is making a
* combined work based on this library. Thus, the terms and conditions of the
* GNU Affero General Public License cover the whole combination.
*
* As a special exception, the copyright holders of this library give you
* permission to link this library with independent modules to produce an
* executable, regardless of the license terms of these independent modules,
* and to copy and distribute the resulting executable under terms of your
* choice, provided that you also meet, for each linked independent module,
* the terms and conditions of the license of that module. An independent
* module is a module which is not derived from or based on this library.
*/
package aphelion.shared.net;
import aphelion.client.net.SingleGameConnection;
import aphelion.server.AphelionServer;
import aphelion.server.http.HttpServer;
import aphelion.shared.event.TickedEventLoop;
import aphelion.shared.net.game.GameProtocolConnection;
import aphelion.shared.net.game.GameProtoListener;
import aphelion.shared.net.protobuf.GameC2S;
import aphelion.shared.net.protobuf.GameC2S.C2S;
import aphelion.shared.net.protobuf.GameOperation.ActorMove;
import aphelion.shared.net.protobuf.GameS2C;
import aphelion.shared.net.protobuf.GameS2C.ArenaSync;
import aphelion.shared.net.protobuf.GameS2C.S2C;
import aphelion.shared.physics.EnvironmentConf;
import aphelion.shared.physics.valueobjects.PhysicsMovement;
import com.google.protobuf.ByteString;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.channels.ServerSocketChannel;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.junit.*;
import static org.junit.Assert.*;
/**
*
* @author Joris
*/
public class WebSocketTest
{
private static final Logger log = Logger.getLogger(WebSocketTest.class.getName());
TickedEventLoop loop;
SessionToken sessionToken;
private long sentC2SMove;
private long receivedC2SMove;
int serverNewClient; int clientNewClient;
boolean clientRemoved; boolean serverRemoved;
int serverMessages; int clientMessages;
int clientConnections; int serverConnections;
int serverPidSum;
int clientPidSum;
@Before
public void setUp()
{
serverNewClient = 0;
clientNewClient = 0;
clientRemoved = false;
serverRemoved = false;
serverMessages = 0;
clientMessages = 0;
clientConnections = 0;
serverConnections = 0;
clientPidSum = 0;
serverPidSum = 0;
}
@After
public void breakDown()
{
loop = null;
sessionToken = null;
}
@Test(timeout=2000)
public void testSingleGameWebSocket() throws IOException, URISyntaxException
{
// use the same loop for client and server
loop = new TickedEventLoop(EnvironmentConf.TICK_LENGTH, 1, null);
// Set up the server
// use an ephemeral port. aka a temporary port number
try (ServerSocketChannel ssChannel = HttpServer.openServerChannel(new InetSocketAddress("127.0.0.1", 0)))
{
AphelionServer server = new AphelionServer(ssChannel, new File("./www"), loop);
loop.addLoopEvent(server);
server.setGameClientListener(new testSingleGameWebSocket_ServerGameListener());
// set up the client
SingleGameConnection client = new SingleGameConnection(
new URI("ws://127.0.0.1:"+server.getHTTPListeningPort()+"/aphelion"),
loop,
1); // 1 connection;
client.addListener(new testSingleGameWebSocket_ClientGameListener());
loop.addLoopEvent(client);
server.setup();
client.connect();
log.log(Level.INFO, "Starting loop");
loop.run();
assertEquals(1, clientNewClient);
assertEquals(1, serverNewClient);
assertTrue(clientRemoved);
assertTrue(serverRemoved);
assertEquals(1, clientMessages);
assertEquals(1, serverMessages);
double latency = (receivedC2SMove - sentC2SMove) / 1000000d;
log.log(Level.INFO, "Latency: {0}ms", latency);
client.close(WS_CLOSE_STATUS.NORMAL);
server.closeAll(WS_CLOSE_STATUS.NORMAL);
server.stop();
client.stop();
}
}
private class testSingleGameWebSocket_ServerGameListener implements GameProtoListener
{
@Override
public void gameNewClient(GameProtocolConnection game)
{
log.log(Level.INFO, "Server: new client");
++serverNewClient;
assertEquals(0, serverConnections);
assertEquals(0, clientNewClient);
assertEquals(1, serverNewClient);
assertTrue(game.server);
sessionToken = game.session;
}
@Override
public void gameRemovedClient(GameProtocolConnection game)
{
log.log(Level.INFO, "Server: removed client");
assertEquals(0, serverConnections);
serverRemoved = true;
if (clientRemoved)
{
loop.interrupt();
}
}
@Override
public void gameC2SMessage(GameProtocolConnection game, GameC2S.C2S c2s, long receivedAt)
{
++serverMessages;
log.log(Level.INFO, "Server: C2S message: {0}", serverMessages);
assertEquals(1, c2s.getActorMoveCount());
assertEquals(1, c2s.getAllFields().size());
ActorMove move = c2s.getActorMove(0);
receivedC2SMove = System.nanoTime();
assertEquals(123, move.getTick());
assertEquals(456, move.getPid());
List<PhysicsMovement> moves = PhysicsMovement.unserializeListLE(move.getMove().asReadOnlyByteBuffer());
assertEquals(4, moves.size());
assertEquals(0x1, moves.get(0).bits);
assertEquals(0x1 | 0x4, moves.get(1).bits);
assertEquals(0x0, moves.get(2).bits);
assertEquals(0x8, moves.get(3).bits);
S2C.Builder s2c = S2C.newBuilder();
ArenaSync.Builder arenaSync = s2c.addArenaSyncBuilder();
arenaSync.setName("jowie");
arenaSync.setShip("warbird");
arenaSync.setCurrentTicks(5021034);
arenaSync.setCurrentNanoTime(164029301000000000L);
arenaSync.setYourPid(102);
arenaSync.setYourSeed(1234567890);
game.send(s2c.build());
}
@Override
public void gameS2CMessage(GameProtocolConnection game, GameS2C.S2C s2c, long receivedAt)
{
assertTrue(false);
}
@Override
public void gameNewConnection(GameProtocolConnection game)
{
++serverConnections;
log.log(Level.INFO, "Server: gameNewConnection: {0}", serverConnections);
assertEquals(1, serverNewClient);
}
@Override
public void gameDropConnection(GameProtocolConnection game, WS_CLOSE_STATUS code, String reason)
{
--serverConnections;
log.log(Level.INFO, "Server: gameDropConnection: {0}", serverConnections);
assertEquals(1, serverNewClient);
}
@Override
public void gameEstablishFailure(WS_CLOSE_STATUS code, String reason)
{
assert false;
}
}
private class testSingleGameWebSocket_ClientGameListener implements GameProtoListener
{
@Override
public void gameNewClient(GameProtocolConnection game)
{
log.log(Level.INFO, "Client: new client");
++clientNewClient;
assertEquals(0, clientConnections);
assertEquals(1, serverNewClient);
assertEquals(1, clientNewClient);
assertFalse(game.server);
assertEquals(sessionToken, game.session);
C2S.Builder c2s = C2S.newBuilder();
ActorMove.Builder actorMove = c2s.addActorMoveBuilder();
actorMove.setTick(123);
actorMove.setPid(456);
actorMove.setMove(ByteString.copyFrom(PhysicsMovement.serializeListLE(Arrays.asList(
PhysicsMovement.get(0x1),
PhysicsMovement.get(0x1 | 0x4),
PhysicsMovement.get(0x0),
PhysicsMovement.get(0x8)))));
sentC2SMove = System.nanoTime();
game.send(c2s.build());
}
@Override
public void gameRemovedClient(GameProtocolConnection game)
{
assertEquals(0, clientConnections);
log.log(Level.INFO, "Client: removed client");
clientRemoved = true;
if (serverRemoved)
{
loop.interrupt();
}
}
@Override
public void gameC2SMessage(GameProtocolConnection game, GameC2S.C2S c2s, long receivedAt)
{
assertTrue(false);
}
@Override
public void gameS2CMessage(GameProtocolConnection game, GameS2C.S2C s2c, long receivedAt)
{
++clientMessages;
log.log(Level.INFO, "Client: S2C message: {0}", clientMessages);
assertEquals(1, s2c.getArenaSyncCount());
assertEquals(1, s2c.getAllFields().size());
ArenaSync arenaSync = s2c.getArenaSync(0);
assertEquals("jowie", arenaSync.getName());
assertEquals("warbird", arenaSync.getShip());
assertEquals(5021034, arenaSync.getCurrentTicks());
assertEquals(164029301000000000L, arenaSync.getCurrentNanoTime());
assertEquals(102, arenaSync.getYourPid());
// done with the test
game.requestClose(WS_CLOSE_STATUS.NORMAL);
}
@Override
public void gameNewConnection(GameProtocolConnection game)
{
assertEquals(1, clientNewClient);
++clientConnections;
log.log(Level.INFO, "Client: gameNewConnection: {0}", clientConnections);
}
@Override
public void gameDropConnection(GameProtocolConnection game, WS_CLOSE_STATUS code, String reason)
{
assertEquals(1, clientNewClient);
--clientConnections;
log.log(Level.INFO, "Client: gameDropConnection: {0}", clientNewClient);
}
@Override
public void gameEstablishFailure(WS_CLOSE_STATUS code, String reason)
{
assert false;
}
}
@Test(timeout=2000)
public void testMultiGameWebSocket() throws IOException, URISyntaxException
{
// use the same loop for client and server
loop = new TickedEventLoop(EnvironmentConf.TICK_LENGTH, 1, null);
// Set up the server
// use an ephemeral port. aka a temporary port number
try (ServerSocketChannel ssChannel = HttpServer.openServerChannel(new InetSocketAddress("127.0.0.1", 0)))
{
AphelionServer server = new AphelionServer(ssChannel, new File("./www"), loop);
loop.addLoopEvent(server);
server.setGameClientListener(new testMultiGameWebSocket_ServerGameListener());
server.setup();
// set up the client
SingleGameConnection client = new SingleGameConnection(
new URI("ws://127.0.0.1:"+server.getHTTPListeningPort()+"/aphelion"),
loop,
5); // 5 connections;
client.addListener(new testMultiGameWebSocket_ClientGameListener());
loop.addLoopEvent(client);
client.connect();
log.log(Level.INFO, "Start loop");
loop.run();
assertEquals(1, clientNewClient);
assertEquals(1, serverNewClient);
assertTrue(clientRemoved);
assertTrue(serverRemoved);
assertEquals(18, clientMessages);
assertEquals(28, serverMessages);
assertEquals(210, clientPidSum);
assertEquals(465, serverPidSum);
client.close(WS_CLOSE_STATUS.NORMAL);
server.closeAll(WS_CLOSE_STATUS.NORMAL);
server.stop();
client.stop();
}
}
private class testMultiGameWebSocket_ServerGameListener implements GameProtoListener
{
@Override
public void gameNewClient(GameProtocolConnection game)
{
++serverNewClient;
log.log(Level.INFO, "Server: new client {0}", serverNewClient);
assertEquals(0, serverConnections);
assertEquals(0, clientNewClient);
assertEquals(1, serverNewClient);
assertTrue(game.server);
sessionToken = game.session;
}
@Override
public void gameRemovedClient(GameProtocolConnection game)
{
log.log(Level.INFO, "Server: removed client");
assertEquals(0, serverConnections);
serverRemoved = true;
if (clientRemoved)
{
loop.interrupt();
}
}
@Override
public void gameC2SMessage(GameProtocolConnection game, GameC2S.C2S c2s, long receivedAt)
{
log.log(Level.INFO, "Server: Received message {0}", serverMessages);
++serverMessages;
assertTrue(c2s.getActorMoveCount() > 0);
assertEquals(1, c2s.getAllFields().size());
for (int a = 0; a < c2s.getActorMoveCount(); ++a)
{
ActorMove move = c2s.getActorMove(a);
assertEquals(123, move.getTick());
serverPidSum += move.getPid();
List<PhysicsMovement> moves = PhysicsMovement.unserializeListLE(move.getMove().asReadOnlyByteBuffer());
assertEquals(4, moves.size());
assertEquals(0x1, moves.get(0).bits);
assertEquals(0x1 | 0x4, moves.get(1).bits);
assertEquals(0x0, moves.get(2).bits);
assertEquals(0x8, moves.get(3).bits);
}
if (clientMessages == 18 && serverMessages == 28)
{
game.requestClose(WS_CLOSE_STATUS.NORMAL);
}
}
@Override
public void gameS2CMessage(GameProtocolConnection game, GameS2C.S2C s2c, long receivedAt)
{
assertTrue(false);
}
@Override
public void gameNewConnection(GameProtocolConnection game)
{
++serverConnections;
log.log(Level.INFO, "Server: gameNewConnection {0}", serverConnections);
if (serverConnections == 5)
{
S2C.Builder s2c = S2C.newBuilder();
for (int a = 0; a < 20; ++a)
{
if (a <= 17)
{
// send the last 3 in a batch
s2c = S2C.newBuilder();
}
ActorMove.Builder actorMove = s2c.addActorMoveBuilder();
actorMove.setTick(123);
actorMove.setPid(a + 1);
actorMove.setMove(ByteString.copyFrom(PhysicsMovement.serializeListLE(Arrays.asList(
PhysicsMovement.get(0x1),
PhysicsMovement.get(0x1 | 0x4),
PhysicsMovement.get(0x0),
PhysicsMovement.get(0x8)))));
if (a < 17)
{
log.log(Level.INFO, "Server: gameNewConnection: send(s2c) {0}", s2c.getActorMoveCount());
game.send(s2c);
}
}
log.log(Level.INFO, "Server: gameNewConnection: send(s2c) {0} (after loop)", s2c.getActorMoveCount());
game.send(s2c);
}
}
@Override
public void gameDropConnection(GameProtocolConnection game, WS_CLOSE_STATUS code, String reason)
{
--serverConnections;
log.log(Level.INFO, "Server: gameDropConnection {0}", serverConnections);
}
@Override
public void gameEstablishFailure(WS_CLOSE_STATUS code, String reason)
{
assert false;
}
}
private class testMultiGameWebSocket_ClientGameListener implements GameProtoListener
{
@Override
public void gameNewClient(GameProtocolConnection game)
{
++clientNewClient;
log.log(Level.INFO, "Client: new client {0} clientNewClient");
assertEquals(0, clientConnections);
assertEquals(1, serverNewClient);
assertEquals(1, clientNewClient);
assertFalse(game.server);
assertEquals(sessionToken, game.session);
}
@Override
public void gameRemovedClient(GameProtocolConnection game)
{
log.log(Level.INFO, "Client: removed client");
assertEquals(0, clientConnections);
clientRemoved = true;
if (serverRemoved)
{
loop.interrupt();
}
}
@Override
public void gameC2SMessage(GameProtocolConnection game, GameC2S.C2S c2s, long receivedAt)
{
assertTrue(false);
}
@Override
public void gameS2CMessage(GameProtocolConnection game, GameS2C.S2C s2c, long receivedAt)
{
++clientMessages;
log.log(Level.INFO, "Client: received message {0}", clientMessages);
assertTrue(s2c.getActorMoveCount() > 0);
assertEquals(1, s2c.getAllFields().size());
for (int a = 0; a < s2c.getActorMoveCount(); ++a)
{
ActorMove move = s2c.getActorMove(a);
assertEquals(123, move.getTick());
clientPidSum += move.getPid();
List<PhysicsMovement> moves = PhysicsMovement.unserializeListLE(move.getMove().asReadOnlyByteBuffer());
assertEquals(4, moves.size());
assertEquals(0x1, moves.get(0).bits);
assertEquals(0x1 | 0x4, moves.get(1).bits);
assertEquals(0x0, moves.get(2).bits);
assertEquals(0x8, moves.get(3).bits);
}
if (clientMessages == 18 && serverMessages == 28)
{
game.requestClose(WS_CLOSE_STATUS.NORMAL);
}
}
@Override
public void gameNewConnection(GameProtocolConnection game)
{
++clientConnections;
log.log(Level.INFO, "Client: gameNewConnection {0}", clientConnections);
if (clientConnections == 5)
{
C2S.Builder c2s = C2S.newBuilder();
for (int a = 0; a < 30; ++a)
{
if (a <= 27)
{
// send the last 3 in a batch
c2s = C2S.newBuilder();
}
ActorMove.Builder actorMove = c2s.addActorMoveBuilder();
actorMove.setTick(123);
actorMove.setPid(a + 1);
actorMove.setMove(ByteString.copyFrom(PhysicsMovement.serializeListLE(Arrays.asList(
PhysicsMovement.get(0x1),
PhysicsMovement.get(0x1 | 0x4),
PhysicsMovement.get(0x0),
PhysicsMovement.get(0x8)))));
if (a < 27)
{
log.log(Level.INFO, "Client: gameNewConnection: send(c2s) {0}", c2s.getActorMoveCount());
game.send(c2s);
}
}
log.log(Level.INFO, "Client: gameNewConnection: send(c2s) {0} (after loop)", c2s.getActorMoveCount());
game.send(c2s);
}
}
@Override
public void gameDropConnection(GameProtocolConnection game, WS_CLOSE_STATUS code, String reason)
{
--clientConnections;
log.log(Level.INFO, "Client: gameDropConnection {0}", clientConnections);
}
@Override
public void gameEstablishFailure(WS_CLOSE_STATUS code, String reason)
{
assert false;
}
}
}
| Increase timeout in the websocket test case
The protocol .class files are lazy loaded which might not be able to complete within 2 seconds (especially when running with coverage)
| src/test/java/aphelion/shared/net/WebSocketTest.java | Increase timeout in the websocket test case | <ide><path>rc/test/java/aphelion/shared/net/WebSocketTest.java
<ide> sessionToken = null;
<ide> }
<ide>
<del> @Test(timeout=2000)
<add> @Test(timeout=20000)
<ide> public void testSingleGameWebSocket() throws IOException, URISyntaxException
<ide> {
<ide> // use the same loop for client and server
<ide> }
<ide>
<ide>
<del> @Test(timeout=2000)
<add> @Test(timeout=20000)
<ide> public void testMultiGameWebSocket() throws IOException, URISyntaxException
<ide> {
<ide> // use the same loop for client and server |
|
Java | apache-2.0 | 143a62b6bfe4239849095eb766ab2a136d80c73c | 0 | gorcz/spring-boot,hehuabing/spring-boot,bsodzik/spring-boot,balajinsr/spring-boot,joshthornhill/spring-boot,axibase/spring-boot,frost2014/spring-boot,VitDevelop/spring-boot,jforge/spring-boot,master-slave/spring-boot,satheeshmb/spring-boot,kayelau/spring-boot,VitDevelop/spring-boot,fulvio-m/spring-boot,mbrukman/spring-boot,roberthafner/spring-boot,jbovet/spring-boot,soul2zimate/spring-boot,nghiavo/spring-boot,cbtpro/spring-boot,afroje-reshma/spring-boot-sample,isopov/spring-boot,vpavic/spring-boot,jbovet/spring-boot,playleud/spring-boot,philwebb/spring-boot-concourse,nandakishorm/spring-boot,zhanhb/spring-boot,sungha/spring-boot,5zzang/spring-boot,vakninr/spring-boot,jorgepgjr/spring-boot,kamilszymanski/spring-boot,ojacquemart/spring-boot,RobertNickens/spring-boot,eddumelendez/spring-boot,frost2014/spring-boot,orangesdk/spring-boot,jmnarloch/spring-boot,yangdd1205/spring-boot,zorosteven/spring-boot,mlc0202/spring-boot,artembilan/spring-boot,sbcoba/spring-boot,AstaTus/spring-boot,lingounet/spring-boot,nebhale/spring-boot,simonnordberg/spring-boot,olivergierke/spring-boot,shakuzen/spring-boot,trecloux/spring-boot,na-na/spring-boot,mbnshankar/spring-boot,isopov/spring-boot,yhj630520/spring-boot,npcode/spring-boot,mbrukman/spring-boot,panbiping/spring-boot,liupd/spring-boot,designreuse/spring-boot,axelfontaine/spring-boot,paweldolecinski/spring-boot,ralenmandao/spring-boot,hqrt/jenkins2-course-spring-boot,rickeysu/spring-boot,izestrea/spring-boot,dfa1/spring-boot,ydsakyclguozi/spring-boot,felipeg48/spring-boot,rweisleder/spring-boot,liupd/spring-boot,qq83387856/spring-boot,smilence1986/spring-boot,xialeizhou/spring-boot,5zzang/spring-boot,xialeizhou/spring-boot,zhangshuangquan/spring-root,xdweleven/spring-boot,okba1/spring-boot,tan9/spring-boot,NetoDevel/spring-boot,meloncocoo/spring-boot,joshthornhill/spring-boot,mbnshankar/spring-boot,mevasaroj/jenkins2-course-spring-boot,ptahchiev/spring-boot,tbadie/spring-boot,roymanish/spring-boot,RichardCSantana/spring-boot,rmoorman/spring-boot,johnktims/spring-boot,coolcao/spring-boot,zhanhb/spring-boot,raiamber1/spring-boot,huangyugui/spring-boot,JiweiWong/spring-boot,lenicliu/spring-boot,vaseemahmed01/spring-boot,donthadineshkumar/spring-boot,mbrukman/spring-boot,liupd/spring-boot,5zzang/spring-boot,sebastiankirsch/spring-boot,satheeshmb/spring-boot,VitDevelop/spring-boot,srikalyan/spring-boot,scottfrederick/spring-boot,rstirling/spring-boot,roberthafner/spring-boot,mike-kukla/spring-boot,vaseemahmed01/spring-boot,brettwooldridge/spring-boot,jayarampradhan/spring-boot,paweldolecinski/spring-boot,bijukunjummen/spring-boot,rajendra-chola/jenkins2-course-spring-boot,eliudiaz/spring-boot,forestqqqq/spring-boot,kdvolder/spring-boot,jayeshmuralidharan/spring-boot,dnsw83/spring-boot,linead/spring-boot,ameraljovic/spring-boot,yuxiaole/spring-boot,jeremiahmarks/spring-boot,Buzzardo/spring-boot,krmcbride/spring-boot,damoyang/spring-boot,trecloux/spring-boot,neo4j-contrib/spring-boot,nebhale/spring-boot,shangyi0102/spring-boot,mike-kukla/spring-boot,mbnshankar/spring-boot,qerub/spring-boot,bbrouwer/spring-boot,paweldolecinski/spring-boot,lexandro/spring-boot,roymanish/spring-boot,lburgazzoli/spring-boot,ractive/spring-boot,end-user/spring-boot,tsachev/spring-boot,lcardito/spring-boot,tan9/spring-boot,qerub/spring-boot,orangesdk/spring-boot,ollie314/spring-boot,felipeg48/spring-boot,bbrouwer/spring-boot,existmaster/spring-boot,johnktims/spring-boot,candrews/spring-boot,coolcao/spring-boot,coolcao/spring-boot,bbrouwer/spring-boot,Chomeh/spring-boot,philwebb/spring-boot-concourse,gorcz/spring-boot,DeezCashews/spring-boot,bijukunjummen/spring-boot,brettwooldridge/spring-boot,jvz/spring-boot,nareshmiriyala/spring-boot,ameraljovic/spring-boot,meftaul/spring-boot,nisuhw/spring-boot,spring-projects/spring-boot,prakashme/spring-boot,joshiste/spring-boot,donhuvy/spring-boot,Charkui/spring-boot,buobao/spring-boot,dfa1/spring-boot,mabernardo/spring-boot,herau/spring-boot,jbovet/spring-boot,candrews/spring-boot,javyzheng/spring-boot,crackien/spring-boot,philwebb/spring-boot,akmaharshi/jenkins,Chomeh/spring-boot,nareshmiriyala/spring-boot,jxblum/spring-boot,michael-simons/spring-boot,JiweiWong/spring-boot,clarklj001/spring-boot,cmsandiga/spring-boot,fogone/spring-boot,RichardCSantana/spring-boot,mike-kukla/spring-boot,herau/spring-boot,mbenson/spring-boot,kiranbpatil/spring-boot,prasenjit-net/spring-boot,joshiste/spring-boot,ollie314/spring-boot,Makhlab/spring-boot,vakninr/spring-boot,minmay/spring-boot,xc145214/spring-boot,mevasaroj/jenkins2-course-spring-boot,Buzzardo/spring-boot,wilkinsona/spring-boot,jforge/spring-boot,tbbost/spring-boot,rweisleder/spring-boot,pnambiarsf/spring-boot,roymanish/spring-boot,minmay/spring-boot,kiranbpatil/spring-boot,mdeinum/spring-boot,damoyang/spring-boot,domix/spring-boot,mohican0607/spring-boot,allyjunio/spring-boot,mackeprm/spring-boot,hklv/spring-boot,spring-projects/spring-boot,cbtpro/spring-boot,xdweleven/spring-boot,paweldolecinski/spring-boot,nurkiewicz/spring-boot,duandf35/spring-boot,smayoorans/spring-boot,lexandro/spring-boot,smilence1986/spring-boot,michael-simons/spring-boot,trecloux/spring-boot,herau/spring-boot,DeezCashews/spring-boot,mackeprm/spring-boot,end-user/spring-boot,huangyugui/spring-boot,afroje-reshma/spring-boot-sample,royclarkson/spring-boot,joshiste/spring-boot,jxblum/spring-boot,habuma/spring-boot,drumonii/spring-boot,forestqqqq/spring-boot,joansmith/spring-boot,nghiavo/spring-boot,eddumelendez/spring-boot,yhj630520/spring-boot,mrumpf/spring-boot,auvik/spring-boot,Makhlab/spring-boot,dreis2211/spring-boot,crackien/spring-boot,panbiping/spring-boot,gregturn/spring-boot,kdvolder/spring-boot,RainPlanter/spring-boot,lburgazzoli/spring-boot,rickeysu/spring-boot,tan9/spring-boot,mosoft521/spring-boot,NetoDevel/spring-boot,soul2zimate/spring-boot,tiarebalbi/spring-boot,xingguang2013/spring-boot,chrylis/spring-boot,ihoneymon/spring-boot,snicoll/spring-boot,ptahchiev/spring-boot,royclarkson/spring-boot,satheeshmb/spring-boot,RainPlanter/spring-boot,bbrouwer/spring-boot,i007422/jenkins2-course-spring-boot,aahlenst/spring-boot,herau/spring-boot,javyzheng/spring-boot,chrylis/spring-boot,PraveenkumarShethe/spring-boot,rstirling/spring-boot,jforge/spring-boot,candrews/spring-boot,rajendra-chola/jenkins2-course-spring-boot,nevenc-pivotal/spring-boot,meloncocoo/spring-boot,mebinjacob/spring-boot,RobertNickens/spring-boot,eddumelendez/spring-boot,mevasaroj/jenkins2-course-spring-boot,jjankar/spring-boot,okba1/spring-boot,ihoneymon/spring-boot,srinivasan01/spring-boot,na-na/spring-boot,gauravbrills/spring-boot,rams2588/spring-boot,jayeshmuralidharan/spring-boot,axibase/spring-boot,imranansari/spring-boot,Xaerxess/spring-boot,lcardito/spring-boot,VitDevelop/spring-boot,gauravbrills/spring-boot,Chomeh/spring-boot,murilobr/spring-boot,isopov/spring-boot,zhanhb/spring-boot,zorosteven/spring-boot,patrikbeno/spring-boot,bsodzik/spring-boot,deki/spring-boot,meloncocoo/spring-boot,Makhlab/spring-boot,lucassaldanha/spring-boot,isopov/spring-boot,jayeshmuralidharan/spring-boot,srinivasan01/spring-boot,donhuvy/spring-boot,yuxiaole/spring-boot,sbcoba/spring-boot,yangdd1205/spring-boot,kayelau/spring-boot,gauravbrills/spring-boot,PraveenkumarShethe/spring-boot,royclarkson/spring-boot,durai145/spring-boot,rweisleder/spring-boot,zorosteven/spring-boot,lif123/spring-boot,panbiping/spring-boot,JiweiWong/spring-boot,xiaoleiPENG/my-project,shakuzen/spring-boot,gregturn/spring-boot,nevenc-pivotal/spring-boot,kdvolder/spring-boot,jeremiahmarks/spring-boot,end-user/spring-boot,dnsw83/spring-boot,eonezhang/spring-boot,frost2014/spring-boot,nebhale/spring-boot,Pokbab/spring-boot,keithsjohnson/spring-boot,balajinsr/spring-boot,paddymahoney/spring-boot,olivergierke/spring-boot,jmnarloch/spring-boot,ilayaperumalg/spring-boot,simonnordberg/spring-boot,soul2zimate/spring-boot,mackeprm/spring-boot,mohican0607/spring-boot,tsachev/spring-boot,hehuabing/spring-boot,mabernardo/spring-boot,yunbian/spring-boot,166yuan/spring-boot,jack-luj/spring-boot,nelswadycki/spring-boot,auvik/spring-boot,qq83387856/spring-boot,panbiping/spring-boot,snicoll/spring-boot,jorgepgjr/spring-boot,patrikbeno/spring-boot,shakuzen/spring-boot,aahlenst/spring-boot,10045125/spring-boot,sbuettner/spring-boot,tiarebalbi/spring-boot,kiranbpatil/spring-boot,nisuhw/spring-boot,brettwooldridge/spring-boot,existmaster/spring-boot,allyjunio/spring-boot,Pokbab/spring-boot,jayeshmuralidharan/spring-boot,Charkui/spring-boot,vaseemahmed01/spring-boot,VitDevelop/spring-boot,cleverjava/jenkins2-course-spring-boot,AngusZhu/spring-boot,RishikeshDarandale/spring-boot,jjankar/spring-boot,vandan16/Vandan,drunklite/spring-boot,DONIKAN/spring-boot,Buzzardo/spring-boot,paweldolecinski/spring-boot,isopov/spring-boot,nghialunhaiha/spring-boot,rajendra-chola/jenkins2-course-spring-boot,jayarampradhan/spring-boot,artembilan/spring-boot,drumonii/spring-boot,M3lkior/spring-boot,cmsandiga/spring-boot,AstaTus/spring-boot,lucassaldanha/spring-boot,joshthornhill/spring-boot,izeye/spring-boot,krmcbride/spring-boot,rizwan18/spring-boot,christian-posta/spring-boot,huangyugui/spring-boot,lburgazzoli/spring-boot,mebinjacob/spring-boot,buobao/spring-boot,jxblum/spring-boot,nevenc-pivotal/spring-boot,shakuzen/spring-boot,tbadie/spring-boot,joansmith/spring-boot,mebinjacob/spring-boot,nelswadycki/spring-boot,mdeinum/spring-boot,mike-kukla/spring-boot,felipeg48/spring-boot,jcastaldoFoodEssentials/spring-boot,nebhale/spring-boot,Nowheresly/spring-boot,ihoneymon/spring-boot,ilayaperumalg/spring-boot,mrumpf/spring-boot,lif123/spring-boot,xdweleven/spring-boot,mouadtk/spring-boot,Chomeh/spring-boot,yunbian/spring-boot,jbovet/spring-boot,rizwan18/spring-boot,10045125/spring-boot,ralenmandao/spring-boot,gauravbrills/spring-boot,aahlenst/spring-boot,pvorb/spring-boot,eric-stanley/spring-boot,lucassaldanha/spring-boot,michael-simons/spring-boot,playleud/spring-boot,RainPlanter/spring-boot,lcardito/spring-boot,mouadtk/spring-boot,kdvolder/spring-boot,izestrea/spring-boot,cbtpro/spring-boot,patrikbeno/spring-boot,sankin/spring-boot,dfa1/spring-boot,nghiavo/spring-boot,lcardito/spring-boot,JiweiWong/spring-boot,izestrea/spring-boot,prakashme/spring-boot,designreuse/spring-boot,jack-luj/spring-boot,ydsakyclguozi/spring-boot,nurkiewicz/spring-boot,nelswadycki/spring-boot,spring-projects/spring-boot,smayoorans/spring-boot,joshiste/spring-boot,eddumelendez/spring-boot,izestrea/spring-boot,isopov/spring-boot,ChunPIG/spring-boot,sbcoba/spring-boot,aahlenst/spring-boot,tsachev/spring-boot,ydsakyclguozi/spring-boot,bijukunjummen/spring-boot,bsodzik/spring-boot,NetoDevel/spring-boot,prakashme/spring-boot,clarklj001/spring-boot,jayarampradhan/spring-boot,tiarebalbi/spring-boot,RishikeshDarandale/spring-boot,DeezCashews/spring-boot,hello2009chen/spring-boot,sbcoba/spring-boot,linead/spring-boot,lingounet/spring-boot,izeye/spring-boot,marcellodesales/spring-boot,srikalyan/spring-boot,qq83387856/spring-boot,yunbian/spring-boot,ptahchiev/spring-boot,lucassaldanha/spring-boot,rizwan18/spring-boot,hehuabing/spring-boot,okba1/spring-boot,existmaster/spring-boot,ollie314/spring-boot,aahlenst/spring-boot,hello2009chen/spring-boot,durai145/spring-boot,existmaster/spring-boot,lexandro/spring-boot,jeremiahmarks/spring-boot,rickeysu/spring-boot,tiarebalbi/spring-boot,AngusZhu/spring-boot,MasterRoots/spring-boot,smayoorans/spring-boot,end-user/spring-boot,eliudiaz/spring-boot,marcellodesales/spring-boot,nandakishorm/spring-boot,lif123/spring-boot,scottfrederick/spring-boot,bjornlindstrom/spring-boot,allyjunio/spring-boot,zhangshuangquan/spring-root,wwadge/spring-boot,drunklite/spring-boot,joshthornhill/spring-boot,tsachev/spring-boot,Pokbab/spring-boot,roberthafner/spring-boot,prasenjit-net/spring-boot,javyzheng/spring-boot,MasterRoots/spring-boot,thomasdarimont/spring-boot,tbbost/spring-boot,rmoorman/spring-boot,lingounet/spring-boot,nevenc-pivotal/spring-boot,mbnshankar/spring-boot,fogone/spring-boot,sungha/spring-boot,joshthornhill/spring-boot,crackien/spring-boot,lucassaldanha/spring-boot,lokbun/spring-boot,marcellodesales/spring-boot,mbogoevici/spring-boot,raiamber1/spring-boot,joansmith/spring-boot,nareshmiriyala/spring-boot,yhj630520/spring-boot,smilence1986/spring-boot,master-slave/spring-boot,jxblum/spring-boot,drumonii/spring-boot,MrMitchellMoore/spring-boot,designreuse/spring-boot,xdweleven/spring-boot,meloncocoo/spring-boot,Xaerxess/spring-boot,pnambiarsf/spring-boot,duandf35/spring-boot,mabernardo/spring-boot,srinivasan01/spring-boot,fireshort/spring-boot,huangyugui/spring-boot,cmsandiga/spring-boot,deki/spring-boot,duandf35/spring-boot,M3lkior/spring-boot,kamilszymanski/spring-boot,dreis2211/spring-boot,balajinsr/spring-boot,vakninr/spring-boot,drumonii/spring-boot,yuxiaole/spring-boot,ydsakyclguozi/spring-boot,christian-posta/spring-boot,neo4j-contrib/spring-boot,damoyang/spring-boot,forestqqqq/spring-boot,bclozel/spring-boot,rajendra-chola/jenkins2-course-spring-boot,mosoft521/spring-boot,xialeizhou/spring-boot,fireshort/spring-boot,christian-posta/spring-boot,donthadineshkumar/spring-boot,tiarebalbi/spring-boot,bclozel/spring-boot,nandakishorm/spring-boot,fjlopez/spring-boot,tsachev/spring-boot,Makhlab/spring-boot,RichardCSantana/spring-boot,tan9/spring-boot,ilayaperumalg/spring-boot,mbogoevici/spring-boot,rstirling/spring-boot,xingguang2013/spring-boot,DONIKAN/spring-boot,axelfontaine/spring-boot,playleud/spring-boot,nisuhw/spring-boot,krmcbride/spring-boot,jack-luj/spring-boot,master-slave/spring-boot,jjankar/spring-boot,bjornlindstrom/spring-boot,wilkinsona/spring-boot,ilayaperumalg/spring-boot,satheeshmb/spring-boot,paddymahoney/spring-boot,hklv/spring-boot,chrylis/spring-boot,NetoDevel/spring-boot,peteyan/spring-boot,simonnordberg/spring-boot,Nowheresly/spring-boot,murilobr/spring-boot,jeremiahmarks/spring-boot,auvik/spring-boot,vandan16/Vandan,donthadineshkumar/spring-boot,eliudiaz/spring-boot,tbadie/spring-boot,lexandro/spring-boot,imranansari/spring-boot,ractive/spring-boot,wilkinsona/spring-boot,meftaul/spring-boot,artembilan/spring-boot,marcellodesales/spring-boot,nelswadycki/spring-boot,navarrogabriela/spring-boot,zhanhb/spring-boot,meftaul/spring-boot,eddumelendez/spring-boot,i007422/jenkins2-course-spring-boot,minmay/spring-boot,xwjxwj30abc/spring-boot,ojacquemart/spring-boot,xiaoleiPENG/my-project,tiarebalbi/spring-boot,dnsw83/spring-boot,M3lkior/spring-boot,jjankar/spring-boot,SPNilsen/spring-boot,fogone/spring-boot,roymanish/spring-boot,JiweiWong/spring-boot,mohican0607/spring-boot,ChunPIG/spring-boot,npcode/spring-boot,ihoneymon/spring-boot,tbadie/spring-boot,krmcbride/spring-boot,shangyi0102/spring-boot,smilence1986/spring-boot,thomasdarimont/spring-boot,domix/spring-boot,fjlopez/spring-boot,xingguang2013/spring-boot,cmsandiga/spring-boot,cbtpro/spring-boot,xwjxwj30abc/spring-boot,michael-simons/spring-boot,ojacquemart/spring-boot,fireshort/spring-boot,prasenjit-net/spring-boot,sankin/spring-boot,DONIKAN/spring-boot,crackien/spring-boot,thomasdarimont/spring-boot,rstirling/spring-boot,nurkiewicz/spring-boot,DONIKAN/spring-boot,mlc0202/spring-boot,vaseemahmed01/spring-boot,jorgepgjr/spring-boot,izeye/spring-boot,mabernardo/spring-boot,zhangshuangquan/spring-root,ptahchiev/spring-boot,michael-simons/spring-boot,wwadge/spring-boot,AngusZhu/spring-boot,srikalyan/spring-boot,master-slave/spring-boot,johnktims/spring-boot,ractive/spring-boot,pnambiarsf/spring-boot,paddymahoney/spring-boot,raiamber1/spring-boot,kayelau/spring-boot,tan9/spring-boot,srikalyan/spring-boot,coolcao/spring-boot,smayoorans/spring-boot,murilobr/spring-boot,crackien/spring-boot,zorosteven/spring-boot,bsodzik/spring-boot,eddumelendez/spring-boot,gorcz/spring-boot,snicoll/spring-boot,joshiste/spring-boot,navarrogabriela/spring-boot,xc145214/spring-boot,jrrickard/spring-boot,166yuan/spring-boot,jxblum/spring-boot,durai145/spring-boot,SPNilsen/spring-boot,axibase/spring-boot,mbrukman/spring-boot,rweisleder/spring-boot,orangesdk/spring-boot,hello2009chen/spring-boot,jayarampradhan/spring-boot,zhangshuangquan/spring-root,nghialunhaiha/spring-boot,lokbun/spring-boot,scottfrederick/spring-boot,ractive/spring-boot,felipeg48/spring-boot,AngusZhu/spring-boot,166yuan/spring-boot,simonnordberg/spring-boot,ralenmandao/spring-boot,allyjunio/spring-boot,donthadineshkumar/spring-boot,rizwan18/spring-boot,simonnordberg/spring-boot,candrews/spring-boot,mbenson/spring-boot,qerub/spring-boot,spring-projects/spring-boot,zorosteven/spring-boot,nghiavo/spring-boot,RishikeshDarandale/spring-boot,mouadtk/spring-boot,mosen11/spring-boot,Buzzardo/spring-boot,pvorb/spring-boot,linead/spring-boot,xiaoleiPENG/my-project,cleverjava/jenkins2-course-spring-boot,qq83387856/spring-boot,donthadineshkumar/spring-boot,imranansari/spring-boot,rams2588/spring-boot,eric-stanley/spring-boot,gorcz/spring-boot,tbadie/spring-boot,yhj630520/spring-boot,wilkinsona/spring-boot,forestqqqq/spring-boot,coolcao/spring-boot,Xaerxess/spring-boot,olivergierke/spring-boot,trecloux/spring-boot,htynkn/spring-boot,5zzang/spring-boot,Buzzardo/spring-boot,eliudiaz/spring-boot,orangesdk/spring-boot,mdeinum/spring-boot,ptahchiev/spring-boot,deki/spring-boot,RobertNickens/spring-boot,ojacquemart/spring-boot,SaravananParthasarathy/SPSDemo,ChunPIG/spring-boot,nevenc-pivotal/spring-boot,master-slave/spring-boot,artembilan/spring-boot,philwebb/spring-boot,auvik/spring-boot,lexandro/spring-boot,imranansari/spring-boot,nghialunhaiha/spring-boot,murilobr/spring-boot,yuxiaole/spring-boot,liupd/spring-boot,M3lkior/spring-boot,existmaster/spring-boot,kamilszymanski/spring-boot,royclarkson/spring-boot,ilayaperumalg/spring-boot,deki/spring-boot,jforge/spring-boot,lburgazzoli/spring-boot,nurkiewicz/spring-boot,yunbian/spring-boot,jayarampradhan/spring-boot,mbogoevici/spring-boot,sbuettner/spring-boot,hello2009chen/spring-boot,eric-stanley/spring-boot,rickeysu/spring-boot,ojacquemart/spring-boot,bclozel/spring-boot,drunklite/spring-boot,candrews/spring-boot,eonezhang/spring-boot,mosoft521/spring-boot,mike-kukla/spring-boot,Charkui/spring-boot,navarrogabriela/spring-boot,sbuettner/spring-boot,domix/spring-boot,mlc0202/spring-boot,nareshmiriyala/spring-boot,xingguang2013/spring-boot,eric-stanley/spring-boot,lif123/spring-boot,mdeinum/spring-boot,htynkn/spring-boot,johnktims/spring-boot,ameraljovic/spring-boot,hqrt/jenkins2-course-spring-boot,huangyugui/spring-boot,duandf35/spring-boot,hehuabing/spring-boot,johnktims/spring-boot,vakninr/spring-boot,hklv/spring-boot,fireshort/spring-boot,drumonii/spring-boot,kdvolder/spring-boot,DONIKAN/spring-boot,joansmith/spring-boot,prakashme/spring-boot,RichardCSantana/spring-boot,murilobr/spring-boot,Nowheresly/spring-boot,patrikbeno/spring-boot,prasenjit-net/spring-boot,raiamber1/spring-boot,chrylis/spring-boot,peteyan/spring-boot,nisuhw/spring-boot,damoyang/spring-boot,jrrickard/spring-boot,RichardCSantana/spring-boot,felipeg48/spring-boot,pnambiarsf/spring-boot,spring-projects/spring-boot,sungha/spring-boot,SPNilsen/spring-boot,rweisleder/spring-boot,cleverjava/jenkins2-course-spring-boot,ApiSecRay/spring-boot,meloncocoo/spring-boot,frost2014/spring-boot,fulvio-m/spring-boot,rmoorman/spring-boot,soul2zimate/spring-boot,nandakishorm/spring-boot,yhj630520/spring-boot,ralenmandao/spring-boot,ractive/spring-boot,liupugong/spring-boot,mebinjacob/spring-boot,shakuzen/spring-boot,herau/spring-boot,ihoneymon/spring-boot,cmsandiga/spring-boot,playleud/spring-boot,nisuhw/spring-boot,lokbun/spring-boot,ihoneymon/spring-boot,neo4j-contrib/spring-boot,spring-projects/spring-boot,fulvio-m/spring-boot,philwebb/spring-boot,htynkn/spring-boot,rajendra-chola/jenkins2-course-spring-boot,ydsakyclguozi/spring-boot,MrMitchellMoore/spring-boot,thomasdarimont/spring-boot,roberthafner/spring-boot,izestrea/spring-boot,buobao/spring-boot,mevasaroj/jenkins2-course-spring-boot,fjlopez/spring-boot,peteyan/spring-boot,Nowheresly/spring-boot,nelswadycki/spring-boot,eric-stanley/spring-boot,hklv/spring-boot,paddymahoney/spring-boot,bclozel/spring-boot,donhuvy/spring-boot,sungha/spring-boot,fogone/spring-boot,Pokbab/spring-boot,na-na/spring-boot,eliudiaz/spring-boot,mrumpf/spring-boot,AngusZhu/spring-boot,hklv/spring-boot,linead/spring-boot,tsachev/spring-boot,rmoorman/spring-boot,lokbun/spring-boot,joansmith/spring-boot,brettwooldridge/spring-boot,lenicliu/spring-boot,donhuvy/spring-boot,paddymahoney/spring-boot,chrylis/spring-boot,vandan16/Vandan,philwebb/spring-boot-concourse,ollie314/spring-boot,durai145/spring-boot,imranansari/spring-boot,minmay/spring-boot,meftaul/spring-boot,ameraljovic/spring-boot,designreuse/spring-boot,mbogoevici/spring-boot,patrikbeno/spring-boot,mosen11/spring-boot,okba1/spring-boot,AstaTus/spring-boot,lingounet/spring-boot,i007422/jenkins2-course-spring-boot,wilkinsona/spring-boot,shakuzen/spring-boot,peteyan/spring-boot,MasterRoots/spring-boot,dreis2211/spring-boot,RainPlanter/spring-boot,gauravbrills/spring-boot,rams2588/spring-boot,cleverjava/jenkins2-course-spring-boot,Xaerxess/spring-boot,Chomeh/spring-boot,fjlopez/spring-boot,jforge/spring-boot,shangyi0102/spring-boot,axibase/spring-boot,ameraljovic/spring-boot,shangyi0102/spring-boot,thomasdarimont/spring-boot,xc145214/spring-boot,sebastiankirsch/spring-boot,eonezhang/spring-boot,pvorb/spring-boot,kayelau/spring-boot,christian-posta/spring-boot,cleverjava/jenkins2-course-spring-boot,philwebb/spring-boot,jjankar/spring-boot,navarrogabriela/spring-boot,michael-simons/spring-boot,fulvio-m/spring-boot,lenicliu/spring-boot,wwadge/spring-boot,allyjunio/spring-boot,mbenson/spring-boot,meftaul/spring-boot,mackeprm/spring-boot,rweisleder/spring-boot,akmaharshi/jenkins,npcode/spring-boot,jcastaldoFoodEssentials/spring-boot,playleud/spring-boot,mdeinum/spring-boot,akmaharshi/jenkins,shangyi0102/spring-boot,ApiSecRay/spring-boot,smayoorans/spring-boot,jrrickard/spring-boot,xdweleven/spring-boot,scottfrederick/spring-boot,rickeysu/spring-boot,lenicliu/spring-boot,jack-luj/spring-boot,sankin/spring-boot,RainPlanter/spring-boot,qerub/spring-boot,fulvio-m/spring-boot,jvz/spring-boot,javyzheng/spring-boot,mosen11/spring-boot,roberthafner/spring-boot,izeye/spring-boot,liupd/spring-boot,NetoDevel/spring-boot,na-na/spring-boot,htynkn/spring-boot,felipeg48/spring-boot,satheeshmb/spring-boot,wwadge/spring-boot,duandf35/spring-boot,soul2zimate/spring-boot,dnsw83/spring-boot,kayelau/spring-boot,keithsjohnson/spring-boot,vpavic/spring-boot,balajinsr/spring-boot,rams2588/spring-boot,bclozel/spring-boot,axelfontaine/spring-boot,vpavic/spring-boot,kamilszymanski/spring-boot,166yuan/spring-boot,jrrickard/spring-boot,M3lkior/spring-boot,yuxiaole/spring-boot,mbenson/spring-boot,MrMitchellMoore/spring-boot,RobertNickens/spring-boot,fjlopez/spring-boot,sankin/spring-boot,aahlenst/spring-boot,ChunPIG/spring-boot,jcastaldoFoodEssentials/spring-boot,bjornlindstrom/spring-boot,bsodzik/spring-boot,jmnarloch/spring-boot,krmcbride/spring-boot,ralenmandao/spring-boot,vpavic/spring-boot,jorgepgjr/spring-boot,sebastiankirsch/spring-boot,srikalyan/spring-boot,Makhlab/spring-boot,liupugong/spring-boot,Charkui/spring-boot,designreuse/spring-boot,Xaerxess/spring-boot,axibase/spring-boot,zhanhb/spring-boot,mebinjacob/spring-boot,xingguang2013/spring-boot,balajinsr/spring-boot,izeye/spring-boot,xwjxwj30abc/spring-boot,royclarkson/spring-boot,jvz/spring-boot,jack-luj/spring-boot,tbbost/spring-boot,jmnarloch/spring-boot,hqrt/jenkins2-course-spring-boot,jxblum/spring-boot,mackeprm/spring-boot,keithsjohnson/spring-boot,rizwan18/spring-boot,dreis2211/spring-boot,rstirling/spring-boot,MrMitchellMoore/spring-boot,mrumpf/spring-boot,mbogoevici/spring-boot,mbenson/spring-boot,RishikeshDarandale/spring-boot,bjornlindstrom/spring-boot,gorcz/spring-boot,smilence1986/spring-boot,bclozel/spring-boot,mrumpf/spring-boot,zhanhb/spring-boot,yangdd1205/spring-boot,vandan16/Vandan,scottfrederick/spring-boot,vpavic/spring-boot,donhuvy/spring-boot,npcode/spring-boot,mohican0607/spring-boot,jcastaldoFoodEssentials/spring-boot,mosen11/spring-boot,na-na/spring-boot,jvz/spring-boot,PraveenkumarShethe/spring-boot,PraveenkumarShethe/spring-boot,buobao/spring-boot,jrrickard/spring-boot,AstaTus/spring-boot,damoyang/spring-boot,kiranbpatil/spring-boot,nghialunhaiha/spring-boot,javyzheng/spring-boot,bjornlindstrom/spring-boot,neo4j-contrib/spring-boot,philwebb/spring-boot,nghialunhaiha/spring-boot,mbnshankar/spring-boot,olivergierke/spring-boot,lburgazzoli/spring-boot,MasterRoots/spring-boot,habuma/spring-boot,MasterRoots/spring-boot,neo4j-contrib/spring-boot,jbovet/spring-boot,afroje-reshma/spring-boot-sample,DeezCashews/spring-boot,ChunPIG/spring-boot,liupugong/spring-boot,xc145214/spring-boot,habuma/spring-boot,philwebb/spring-boot-concourse,jeremiahmarks/spring-boot,habuma/spring-boot,trecloux/spring-boot,orangesdk/spring-boot,mosen11/spring-boot,xc145214/spring-boot,tbbost/spring-boot,xiaoleiPENG/my-project,ilayaperumalg/spring-boot,qq83387856/spring-boot,lenicliu/spring-boot,lcardito/spring-boot,mevasaroj/jenkins2-course-spring-boot,mouadtk/spring-boot,sebastiankirsch/spring-boot,brettwooldridge/spring-boot,fogone/spring-boot,linead/spring-boot,deki/spring-boot,mlc0202/spring-boot,vaseemahmed01/spring-boot,bbrouwer/spring-boot,ptahchiev/spring-boot,sbcoba/spring-boot,npcode/spring-boot,bijukunjummen/spring-boot,habuma/spring-boot,joshiste/spring-boot,kamilszymanski/spring-boot,i007422/jenkins2-course-spring-boot,srinivasan01/spring-boot,lif123/spring-boot,rams2588/spring-boot,htynkn/spring-boot,eonezhang/spring-boot,chrylis/spring-boot,prakashme/spring-boot,sbuettner/spring-boot,SaravananParthasarathy/SPSDemo,SaravananParthasarathy/SPSDemo,wilkinsona/spring-boot,hqrt/jenkins2-course-spring-boot,pvorb/spring-boot,zhangshuangquan/spring-root,xialeizhou/spring-boot,mlc0202/spring-boot,sbuettner/spring-boot,PraveenkumarShethe/spring-boot,panbiping/spring-boot,lokbun/spring-boot,nareshmiriyala/spring-boot,SaravananParthasarathy/SPSDemo,qerub/spring-boot,domix/spring-boot,sankin/spring-boot,akmaharshi/jenkins,5zzang/spring-boot,liupugong/spring-boot,xwjxwj30abc/spring-boot,okba1/spring-boot,Charkui/spring-boot,artembilan/spring-boot,mohican0607/spring-boot,Buzzardo/spring-boot,hqrt/jenkins2-course-spring-boot,yunbian/spring-boot,xialeizhou/spring-boot,SPNilsen/spring-boot,rmoorman/spring-boot,clarklj001/spring-boot,habuma/spring-boot,dfa1/spring-boot,mosoft521/spring-boot,cbtpro/spring-boot,MrMitchellMoore/spring-boot,SaravananParthasarathy/SPSDemo,ollie314/spring-boot,kiranbpatil/spring-boot,forestqqqq/spring-boot,RobertNickens/spring-boot,vandan16/Vandan,raiamber1/spring-boot,frost2014/spring-boot,mabernardo/spring-boot,sebastiankirsch/spring-boot,DeezCashews/spring-boot,Pokbab/spring-boot,durai145/spring-boot,eonezhang/spring-boot,drunklite/spring-boot,peteyan/spring-boot,end-user/spring-boot,prasenjit-net/spring-boot,drunklite/spring-boot,nurkiewicz/spring-boot,marcellodesales/spring-boot,axelfontaine/spring-boot,olivergierke/spring-boot,srinivasan01/spring-boot,philwebb/spring-boot-concourse,gregturn/spring-boot,ApiSecRay/spring-boot,bijukunjummen/spring-boot,mouadtk/spring-boot,mbrukman/spring-boot,dnsw83/spring-boot,fireshort/spring-boot,i007422/jenkins2-course-spring-boot,pvorb/spring-boot,vpavic/spring-boot,dfa1/spring-boot,afroje-reshma/spring-boot-sample,navarrogabriela/spring-boot,tbbost/spring-boot,lingounet/spring-boot,vakninr/spring-boot,dreis2211/spring-boot,ApiSecRay/spring-boot,axelfontaine/spring-boot,10045125/spring-boot,mdeinum/spring-boot,SPNilsen/spring-boot,drumonii/spring-boot,kdvolder/spring-boot,donhuvy/spring-boot,Nowheresly/spring-boot,buobao/spring-boot,liupugong/spring-boot,akmaharshi/jenkins,nghiavo/spring-boot,hehuabing/spring-boot,wwadge/spring-boot,dreis2211/spring-boot,philwebb/spring-boot,scottfrederick/spring-boot,nebhale/spring-boot,jcastaldoFoodEssentials/spring-boot,roymanish/spring-boot,jmnarloch/spring-boot,keithsjohnson/spring-boot,166yuan/spring-boot,RishikeshDarandale/spring-boot,xwjxwj30abc/spring-boot,jayeshmuralidharan/spring-boot,domix/spring-boot,keithsjohnson/spring-boot,ApiSecRay/spring-boot,christian-posta/spring-boot,jvz/spring-boot,sungha/spring-boot,pnambiarsf/spring-boot,auvik/spring-boot,hello2009chen/spring-boot,mosoft521/spring-boot,clarklj001/spring-boot,nandakishorm/spring-boot,mbenson/spring-boot,afroje-reshma/spring-boot-sample,xiaoleiPENG/my-project,AstaTus/spring-boot,clarklj001/spring-boot,jorgepgjr/spring-boot,minmay/spring-boot,htynkn/spring-boot | /*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.autoconfigure.data.rest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.rest.core.config.RepositoryRestConfiguration;
import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* {@link EnableAutoConfiguration Auto-configuration} for Spring Data Rest's MVC
* integration.
* <p>
* Activates when the application is a web application and no
* {@link RepositoryRestMvcConfiguration} is found.
* <p>
* Once in effect, the auto-configuration allows to configure any property of
* {@link RepositoryRestConfiguration} using the {@code spring.data.rest} prefix.
*
* @author Rob Winch
* @author Stephane Nicoll
* @since 1.1.0
*/
@Configuration
@ConditionalOnWebApplication
@ConditionalOnMissingBean(RepositoryRestMvcConfiguration.class)
@ConditionalOnClass(RepositoryRestMvcConfiguration.class)
public class RepositoryRestMvcAutoConfiguration {
@Configuration
static class RepositoryRestMvcBootConfiguration extends
RepositoryRestMvcConfiguration {
@Autowired(required = false)
private Jackson2ObjectMapperBuilder objectMapperBuilder;
@Bean
@ConfigurationProperties(prefix = "spring.data.rest")
@Override
public RepositoryRestConfiguration config() {
return super.config();
}
@Override
protected void configureJacksonObjectMapper(ObjectMapper objectMapper) {
if (this.objectMapperBuilder != null) {
this.objectMapperBuilder.configure(objectMapper);
}
}
}
}
| spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/rest/RepositoryRestMvcAutoConfiguration.java | /*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.autoconfigure.data.rest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.rest.core.config.RepositoryRestConfiguration;
import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* {@link EnableAutoConfiguration Auto-configuration} for Spring Data Rest's MVC
* integration.
* <p>
* Activates when the application is a web application and no
* {@link RepositoryRestMvcConfiguration} is found.
* <p>
* Once in effect, the auto-configuration allows to configure any property of
* {@link RepositoryRestConfiguration} using the {@code spring.data.rest} prefix.
*
* @author Rob Winch
* @author Stephane Nicoll
* @since 1.1.0
*/
@Configuration
@ConditionalOnWebApplication
@ConditionalOnMissingBean(RepositoryRestMvcConfiguration.class)
@ConditionalOnClass(RepositoryRestMvcConfiguration.class)
public class RepositoryRestMvcAutoConfiguration {
@Configuration
static class RepositoryRestMvcBootConfiguration extends
RepositoryRestMvcConfiguration {
@Autowired(required = false)
private Jackson2ObjectMapperBuilder objectMapperBuilder;
@Bean
@ConfigurationProperties(prefix = "spring.data.rest")
@Override
public RepositoryRestConfiguration config() {
return super.config();
}
@Override
protected void configureJacksonObjectMapper(ObjectMapper objectMapper) {
if (this.objectMapperBuilder != null) {
this.objectMapperBuilder.configure(objectMapper);
}
}
}
}
| Polish
| spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/rest/RepositoryRestMvcAutoConfiguration.java | Polish | <ide><path>pring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/rest/RepositoryRestMvcAutoConfiguration.java
<ide> }
<ide>
<ide> }
<add>
<ide> } |
|
Java | apache-2.0 | 35be6bcb1d10eca539ca19bfde53eccf9deafa9b | 0 | z-yuxie/yuxie-TGD,z-yuxie/yuxie-TGD,z-yuxie/yuxie-TGD | package com.yuxie.tgd.common.util;
import com.alibaba.fastjson.JSONObject;
import com.yuxie.tgd.pojo.bean.dataMerge.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* 计算数据的状态值的工具类
*/
public class DataStatusUtils {
/**
* 获取某个要合并的数据的数据来源,该来源只取优先级最高的
* @param keySet 有效的key的集合
* @param dataJsonAndOrderList 合并前的各个来源的数据
* @return 数据来源
*/
public static int checkDataSourceByPriority(Set<String> keySet , List<DataJsonAndOrder> dataJsonAndOrderList) {
//首先对数据json按照优先级进行排序
SortDataUtils.asceSortDataJsonByPriority(dataJsonAndOrderList);
int dataSource = Integer.MIN_VALUE;
boolean hasFoundKey = Boolean.TRUE;
int i = 0;
do {
DataJsonAndOrder dataJsonAndOrder = dataJsonAndOrderList.get(i);
for (String key : keySet) {
if (JSONDataUtils.checkJsonContainsStringData(key , dataJsonAndOrder.getData())) {
dataSource = dataJsonAndOrder.getDataSource();
hasFoundKey = Boolean.FALSE;
break;
}
}
i++;
} while (hasFoundKey || i <= dataJsonAndOrderList.size());
return dataSource;
}
/**
* 根据数据来源判断数据的完善状态
* @param dataSource 作为分界点的数据来源,优先权高于或等于该来源的数据为判断数据初始完整性的数据,优先级低于该来源的数据为补充数据
* @param keySet 判断数据完善状态依据的有效key的集合
* @param dataJsonAndOrderList 元数据
* @return 完善状态
*/
public static int checkDataCompleteStatusByDataSource(int dataSource , Set<String> keySet , List<? extends DataJsonAndOrder> dataJsonAndOrderList) {
RuleReSortDataResult ruleReSortDataResult = ClassifyDataUtils.classifyDataByDataSource(dataSource , dataJsonAndOrderList);
ClassifyDataUtils.reSetDataPriority(ruleReSortDataResult.getDataJsonAndOrderList());
int rulePoint = ruleReSortDataResult.getRulePoint();
List<DataJsonAndOrder> qualifiedDataList = ruleReSortDataResult.getDataJsonAndOrderList().subList(0 , rulePoint);
JSONObject qualifiedDataMergeJson = MergeDataUtils.mergeJsonStringDataByPriority(keySet , qualifiedDataList);
JSONObject allDataMergeJson = MergeDataUtils.mergeJsonStringDataByPriority(keySet , dataJsonAndOrderList);
Set<String> qualifiedNotCompleteKeysSet = JSONDataUtils.getNotCompleteKeysSet(keySet , qualifiedDataMergeJson , Boolean.FALSE);
int completeStatus = MyConstans.IS_COMPLETED;
if (CollectionUtils.isNotEmpty(qualifiedNotCompleteKeysSet)) {
completeStatus = MyConstans.IS_NOT_COMPLETED;
Set<String> qualifiedNotBeCompleteKeysSet = JSONDataUtils.getNotCompleteKeysSet(qualifiedNotCompleteKeysSet , allDataMergeJson , Boolean.FALSE);
if (qualifiedNotBeCompleteKeysSet.size() != qualifiedNotCompleteKeysSet.size()) {
if (CollectionUtils.isEmpty(qualifiedNotBeCompleteKeysSet)) {
completeStatus = MyConstans.BECOME_COMPLETED;
} else {
completeStatus = MyConstans.BECOME_NOT_COMPLETED;
}
}
}
return completeStatus;
}
/**
* 获取数据的认证状态
* @param dataSource 作为区分标准的数据来源分界点,优先权高于或等于该来源的数据为判断数据初始完整性的数据,优先级低于该来源的数据为补充数据
* @param keySet 判断数据完善状态依据的有效key的集合
* @param dataJsonAndOrderList 元数据
* @return 数据的认证状态
*/
public static int checkDataHasVerifiedByDataSource(int dataSource , Set<String> keySet , List<? extends DataJsonAndOrder> dataJsonAndOrderList) {
int hasVerified = MyConstans.NOT_HAS_VERIFIED;
RuleReSortDataResult ruleReSortDataResult = ClassifyDataUtils.classifyDataByDataSource(dataSource , dataJsonAndOrderList);
ClassifyDataUtils.reSetDataPriority(ruleReSortDataResult.getDataJsonAndOrderList());
int rulePoint = ruleReSortDataResult.getRulePoint();
if (rulePoint <= 0) {
return hasVerified;
}
List<DataJsonAndOrder> qualifiedDataList = ruleReSortDataResult.getDataJsonAndOrderList().subList(0 , rulePoint);
ruleReSortDataResult = ClassifyDataUtils.classifyDataByHasVerified(qualifiedDataList);
rulePoint = ruleReSortDataResult.getRulePoint();
if (rulePoint <= 0) {
return hasVerified;
}
qualifiedDataList = ruleReSortDataResult.getDataJsonAndOrderList().subList(0 , rulePoint);
JSONObject qualifiedDataMergeJson = MergeDataUtils.mergeJsonStringDataByPriority(keySet , qualifiedDataList);
Set<String> qualifiedNotCompleteKeysSet = JSONDataUtils.getNotCompleteKeysSet(keySet , qualifiedDataMergeJson , Boolean.FALSE);
if (CollectionUtils.isEmpty(qualifiedNotCompleteKeysSet)) {
hasVerified = MyConstans.ALL_HAS_VERIFIED;
} else {
hasVerified = MyConstans.PARTIAL_HAS_VERIFIED;
}
return hasVerified;
}
/**
* 根据过期时间字段是否作为初始数据且被认证过的值来判断该数据是否有过期时间
* @param dataSource 作为区分标准的数据来源分界点,优先权高于或等于该来源的数据为判断数据初始完整性的数据,优先级低于该来源的数据为补充数据
* @param expirationDateKey 该数据的过期时间字段的key
* @param keySet 判断数据完善状态依据的有效key的集合
* @param dataJsonAndOrderList 元数据
* @return 该数据是否具有过期时间
*/
public static int checkDataHasExpirationDateByDataSource(int dataSource , String expirationDateKey , Set<String> keySet
, List<? extends DataJsonAndOrder> dataJsonAndOrderList) {
int expirationDate = MyConstans.NOT_HAS_EXPIRATION_DATE;
RuleReSortDataResult ruleReSortDataResult = ClassifyDataUtils.classifyDataByDataSource(dataSource , dataJsonAndOrderList);
ClassifyDataUtils.reSetDataPriority(ruleReSortDataResult.getDataJsonAndOrderList());
int rulePoint = ruleReSortDataResult.getRulePoint();
if (rulePoint <= 0) {
return expirationDate;
}
Map<String , DataUnit> dataUnitMap = MergeDataUtils.mergeJsonStringDataToDataUnitByPriority(keySet , dataJsonAndOrderList);
if (!dataUnitMap.containsKey(expirationDateKey) || dataUnitMap.get(expirationDateKey) == null
|| StringUtils.isBlank(dataUnitMap.get(expirationDateKey).getData().toString())) {
return expirationDate;
}
DataUnit dataUnit = dataUnitMap.get(expirationDateKey);
if (MyConstans.ALL_HAS_VERIFIED == dataUnit.getHasVerified() && dataUnit.getPriority() < rulePoint) {
expirationDate = MyConstans.HAS_EXPIRATION_DATE;
}
return expirationDate;
}
/**
* 计算数据的创建和更新时间
* @param keySet 判断数据完善状态依据的有效key的集合
* @param dataJsonAndOrderList 元数据
* @return 整合后的所有数据中优先级最高来源数据的创建及更新时间(String类型 yyyyMMdd格式)
*/
public static DateUnit checkDataDateByPriority(Set<String> keySet , List<DataJsonAndOrder> dataJsonAndOrderList) {
//首先对数据json按照优先级进行排序
SortDataUtils.asceSortDataJsonByPriority(dataJsonAndOrderList);
DateUnit dataUnit = new DateUnit();
boolean hasFoundData = Boolean.TRUE;
int i = 0;
do {
DataJsonAndOrder dataJsonAndOrder = dataJsonAndOrderList.get(i);
for (String key : keySet) {
if (JSONDataUtils.checkJsonContainsStringData(key , dataJsonAndOrder.getData())) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(MyConstans.DATA_FORMAT);
dataUnit.setCreataTime(simpleDateFormat.format(dataJsonAndOrder.getCreataTime()));
dataUnit.setUpdateTime(simpleDateFormat.format(dataJsonAndOrder.getUpdateTime()));
hasFoundData = Boolean.FALSE;
break;
}
}
i++;
} while (hasFoundData || i <= dataJsonAndOrderList.size());
return dataUnit;
}
}
| tgd-interface/src/main/java/com/yuxie/tgd/common/util/DataStatusUtils.java | package com.yuxie.tgd.common.util;
import com.alibaba.fastjson.JSONObject;
import com.yuxie.tgd.pojo.bean.dataMerge.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class DataStatusUtils {
/**
* 获取某个要合并的数据的数据来源,该来源只取优先级最高的
* @param keySet 有效的key的集合
* @param dataJsonAndOrderList 合并前的各个来源的数据
* @return 数据来源
*/
public static int checkDataSourceByPriority(Set<String> keySet , List<DataJsonAndOrder> dataJsonAndOrderList) {
//首先对数据json按照优先级进行排序
SortDataUtils.asceSortDataJsonByPriority(dataJsonAndOrderList);
int dataSource = Integer.MIN_VALUE;
boolean hasFoundKey = Boolean.TRUE;
int i = 0;
do {
DataJsonAndOrder dataJsonAndOrder = dataJsonAndOrderList.get(i);
for (String key : keySet) {
if (JSONDataUtils.checkJsonContainsStringData(key , dataJsonAndOrder.getData())) {
dataSource = dataJsonAndOrder.getDataSource();
hasFoundKey = Boolean.FALSE;
break;
}
}
i++;
} while (hasFoundKey || i <= dataJsonAndOrderList.size());
return dataSource;
}
/**
* 根据数据来源判断数据的完善状态
* @param dataSource 作为分界点的数据来源,优先权高于或等于该来源的数据为判断数据初始完整性的数据,优先级低于该来源的数据为补充数据
* @param keySet 判断数据完善状态依据的有效key的集合
* @param dataJsonAndOrderList 元数据
* @return 完善状态
*/
public static int checkDataCompleteStatusByDataSource(int dataSource , Set<String> keySet , List<? extends DataJsonAndOrder> dataJsonAndOrderList) {
RuleReSortDataResult ruleReSortDataResult = ClassifyDataUtils.classifyDataByDataSource(dataSource , dataJsonAndOrderList);
ClassifyDataUtils.reSetDataPriority(ruleReSortDataResult.getDataJsonAndOrderList());
int rulePoint = ruleReSortDataResult.getRulePoint();
List<DataJsonAndOrder> qualifiedDataList = ruleReSortDataResult.getDataJsonAndOrderList().subList(0 , rulePoint);
JSONObject qualifiedDataMergeJson = MergeDataUtils.mergeJsonStringDataByPriority(keySet , qualifiedDataList);
JSONObject allDataMergeJson = MergeDataUtils.mergeJsonStringDataByPriority(keySet , dataJsonAndOrderList);
Set<String> qualifiedNotCompleteKeysSet = JSONDataUtils.getNotCompleteKeysSet(keySet , qualifiedDataMergeJson , Boolean.FALSE);
int completeStatus = MyConstans.IS_COMPLETED;
if (CollectionUtils.isNotEmpty(qualifiedNotCompleteKeysSet)) {
completeStatus = MyConstans.IS_NOT_COMPLETED;
Set<String> qualifiedNotBeCompleteKeysSet = JSONDataUtils.getNotCompleteKeysSet(qualifiedNotCompleteKeysSet , allDataMergeJson , Boolean.FALSE);
if (qualifiedNotBeCompleteKeysSet.size() != qualifiedNotCompleteKeysSet.size()) {
if (CollectionUtils.isEmpty(qualifiedNotBeCompleteKeysSet)) {
completeStatus = MyConstans.BECOME_COMPLETED;
} else {
completeStatus = MyConstans.BECOME_NOT_COMPLETED;
}
}
}
return completeStatus;
}
/**
* 获取数据的认证状态
* @param dataSource 作为区分标准的数据来源分界点,优先权高于或等于该来源的数据为判断数据初始完整性的数据,优先级低于该来源的数据为补充数据
* @param keySet 判断数据完善状态依据的有效key的集合
* @param dataJsonAndOrderList 元数据
* @return 数据的认证状态
*/
public static int checkDataHasVerifiedByDataSource(int dataSource , Set<String> keySet , List<? extends DataJsonAndOrder> dataJsonAndOrderList) {
int hasVerified = MyConstans.NOT_HAS_VERIFIED;
RuleReSortDataResult ruleReSortDataResult = ClassifyDataUtils.classifyDataByDataSource(dataSource , dataJsonAndOrderList);
ClassifyDataUtils.reSetDataPriority(ruleReSortDataResult.getDataJsonAndOrderList());
int rulePoint = ruleReSortDataResult.getRulePoint();
if (rulePoint <= 0) {
return hasVerified;
}
List<DataJsonAndOrder> qualifiedDataList = ruleReSortDataResult.getDataJsonAndOrderList().subList(0 , rulePoint);
ruleReSortDataResult = ClassifyDataUtils.classifyDataByHasVerified(qualifiedDataList);
rulePoint = ruleReSortDataResult.getRulePoint();
if (rulePoint <= 0) {
return hasVerified;
}
qualifiedDataList = ruleReSortDataResult.getDataJsonAndOrderList().subList(0 , rulePoint);
JSONObject qualifiedDataMergeJson = MergeDataUtils.mergeJsonStringDataByPriority(keySet , qualifiedDataList);
Set<String> qualifiedNotCompleteKeysSet = JSONDataUtils.getNotCompleteKeysSet(keySet , qualifiedDataMergeJson , Boolean.FALSE);
if (CollectionUtils.isEmpty(qualifiedNotCompleteKeysSet)) {
hasVerified = MyConstans.ALL_HAS_VERIFIED;
} else {
hasVerified = MyConstans.PARTIAL_HAS_VERIFIED;
}
return hasVerified;
}
/**
* 根据过期时间字段是否作为初始数据且被认证过的值来判断该数据是否有过期时间
* @param dataSource 作为区分标准的数据来源分界点,优先权高于或等于该来源的数据为判断数据初始完整性的数据,优先级低于该来源的数据为补充数据
* @param expirationDateKey 该数据的过期时间字段的key
* @param keySet 判断数据完善状态依据的有效key的集合
* @param dataJsonAndOrderList 元数据
* @return 该数据是否具有过期时间
*/
public static int checkDataHasExpirationDateByDataSource(int dataSource , String expirationDateKey , Set<String> keySet
, List<? extends DataJsonAndOrder> dataJsonAndOrderList) {
int expirationDate = MyConstans.NOT_HAS_EXPIRATION_DATE;
RuleReSortDataResult ruleReSortDataResult = ClassifyDataUtils.classifyDataByDataSource(dataSource , dataJsonAndOrderList);
ClassifyDataUtils.reSetDataPriority(ruleReSortDataResult.getDataJsonAndOrderList());
int rulePoint = ruleReSortDataResult.getRulePoint();
if (rulePoint <= 0) {
return expirationDate;
}
Map<String , DataUnit> dataUnitMap = MergeDataUtils.mergeJsonStringDataToDataUnitByPriority(keySet , dataJsonAndOrderList);
if (!dataUnitMap.containsKey(expirationDateKey) || dataUnitMap.get(expirationDateKey) == null
|| StringUtils.isBlank(dataUnitMap.get(expirationDateKey).getData().toString())) {
return expirationDate;
}
DataUnit dataUnit = dataUnitMap.get(expirationDateKey);
if (MyConstans.ALL_HAS_VERIFIED == dataUnit.getHasVerified() && dataUnit.getPriority() < rulePoint) {
expirationDate = MyConstans.HAS_EXPIRATION_DATE;
}
return expirationDate;
}
/**
* 计算数据的创建和更新时间
* @param keySet 判断数据完善状态依据的有效key的集合
* @param dataJsonAndOrderList 元数据
* @return 整合后的所有数据中优先级最高来源数据的创建及更新时间(String类型 yyyyMMdd格式)
*/
public static DateUnit checkDataDateByPriority(Set<String> keySet , List<DataJsonAndOrder> dataJsonAndOrderList) {
//首先对数据json按照优先级进行排序
SortDataUtils.asceSortDataJsonByPriority(dataJsonAndOrderList);
DateUnit dataUnit = new DateUnit();
boolean hasFoundData = Boolean.TRUE;
int i = 0;
do {
DataJsonAndOrder dataJsonAndOrder = dataJsonAndOrderList.get(i);
for (String key : keySet) {
if (JSONDataUtils.checkJsonContainsStringData(key , dataJsonAndOrder.getData())) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(MyConstans.DATA_FORMAT);
dataUnit.setCreataTime(simpleDateFormat.format(dataJsonAndOrder.getCreataTime()));
dataUnit.setUpdateTime(simpleDateFormat.format(dataJsonAndOrder.getUpdateTime()));
hasFoundData = Boolean.FALSE;
break;
}
}
i++;
} while (hasFoundData || i <= dataJsonAndOrderList.size());
return dataUnit;
}
}
| 增加了一个用于测试git连接性的注释
| tgd-interface/src/main/java/com/yuxie/tgd/common/util/DataStatusUtils.java | 增加了一个用于测试git连接性的注释 | <ide><path>gd-interface/src/main/java/com/yuxie/tgd/common/util/DataStatusUtils.java
<ide> import java.util.Map;
<ide> import java.util.Set;
<ide>
<add>/**
<add> * 计算数据的状态值的工具类
<add> */
<ide> public class DataStatusUtils {
<ide>
<ide> /** |
|
JavaScript | mit | a06de06cbfc943785c87f5a7ec577b8b91e7002d | 0 | rossanag/bicimapuy,rossanag/bicimapuy | var routeControl = null;
var showControl = false;
var line = null;
function convertirKM(distancia)
{
var distanciaConvertida = '';
if (distancia >= 1000)
{
distancia = distancia/1000;
distanciaConvertida = distancia.toString() + ' km';
}
else
distanciaConvertida = distancia.toString() + ' m';
return distanciaConvertida;
}
function borrar()
{
if (marker1 !== null)
{
mapa.removeLayer(marker1);
marker1 = null;
}
if (marker2 !== null)
{
mapa.removeLayer(marker2);
marker2 = null;
}
waypoints.length = 0;
coords.length = 0;
if (line !== null)
mapa.removeLayer(line);
}
function borrarRuta()
{
routeControl.getPlan().setWaypoints([]);
}
function esconderMostrar()
{
if (showControl) // control despleagdo
{
routeControl.hide();
showControl = false;
/*$(".btnBorrar").css({
'right': '11px', //antes 37% 6
'top': '70px' //antes 13%* 5
}); */
}
else
{
routeControl.show();
showControl = true;
/*$(".btnBorrar").css({
'right': '27%', //antes 37% 6
'top': '70px' //antes 13%* 5
}); */
}
}
function displayRoutingControl()
{
if (routeControl == null)
{
crearControlRouting();
/*$(".btnBorrar").css({
'display': 'inline',
'right': '37%', //antes 37% 6
'top': '70px' //antes 13%* 5
}); */
showControl = true;
}
}
function removeRouting()
{
if (routeControl != null)
{
mapa.removeControl(routeControl); //remueve el camino tb
routeControl = null;
/*$(".btnBorrar").css({
'display': 'none',
'right': '-44px', //antes 37% 6
'left': 'auto',
'top': '70px' //antes 13%* 5
}); */
}
}
// function crearControlRouting() {
//
// routeControl = L.Routing.control({
//
//
// router: L.Routing.mapzen('mapzen-3indRB', {
// costing: 'bicycle',
// directions_options: {
// language: 'es'
// }
// }),
//
// plan: L.Routing.plan([], {
// geocoder: L.Control.Geocoder.nominatim({
// geocodingQueryParams: { countrycodes: 'uy'}
// }),
// reverseWaypoints: true,
// city:'Montevideo',
// language: 'sp'
// }),
// lineOptions: {
// styles:
// [
// {color: 'black', opacity: 0.15, weight: 9}, //sombra
// {color: 'white', opacity: 0.8, weight: 6}, // Contorno
// {color: 'red', opacity: 1, weight: 4}] // Centro
// },
// summaryTemplate: '<h2>Trayectoria: {name}</h2><h3>Distancia: {distance}</h3>',
// language: 'sp',
// //city: 'Montevideo', //si no va plan, debe agregarse si se desea afinar búsquedas.
// routeWhileDragging: true,
// waypointMode: 'snap',
// collapsible: true //nuevo
// }).addTo(mapa);
//
// }
function crearControlRouting() {
var control = L.Routing.control({
routeLine: function (route, options) { return L.Routing.mapzenLine(route, options); },
// waypoints: routingData.waypoints,
// You can get your own Mapzen turn-by-turn & search API key from the Mapzen developer portal (https://mapzen.com/developers/)
geocoder: L.Control.Geocoder.mapzen('mapzen-3indRB'),
reverseWaypoints: true,
router: L.Routing.mapzen('mapzen-3indRB', {
costing: 'bicycle',
directions_options: {
language: 'es'
}
}),
collapsible: true,
show: (map.getSize().x > 768)? true: false,
formatter: new L.Routing.mapzenFormatter(),
lineOptions: {
styles:
[
{color: 'black', opacity: 0.15, weight: 9}, //sombra
{color: 'white', opacity: 0.8, weight: 6}, // Contorno
{color: 'red', opacity: 1, weight: 4}] // Centro
},
summaryTemplate:'<div class="start">{name}</div><div class="info {costing}">{distance}</div>'
//summaryTemplate: '<h2>Trayectoria: {name}</h2><h3>Distancia: {distance}</h3>',
}).addTo(map);
L.Routing.errorControl(control).addTo(map);
// to show where waypoints are even if there is no routing data
control.on('routingerror', function () {
var waypoints = control.getWaypoints();
map.fitBounds([
waypoints[0].latLng,
waypoints[waypoints.length-1].latLng
]);
})
}
function calcRoute() // esto para cuando no se usa el control
{
waypoints.length = 0;
coords.length = 0;
waysp.length = 0;
if ((marker1 !== null) && (marker2 !== null))
{
waypoints.push({latLng: marker1.getLatLng()});
waypoints.push({latLng: marker2.getLatLng()});
router.route(waypoints, function(err, routes) {
if (line) {
map.removeLayer(line);
}
if (err) {
alert(err);
} else {
coords = routes[0].coordinates;
waysp = routes[0].waypoints;
alert(routes[0].summary.totalTime);
alert(routes[0].summary.totalDistance);
line = L.Routing.line(routes[0],{styles:[{color: 'black', opacity: 0.15, weight: 7}, {color: 'white', opacity: 0.8, weight: 4}, {color: 'red', opacity: 1, weight: 4}]}).addTo(map);
}
});
}
else
alert("Se necesita el par Origen-Destino para calcular la ruta");
}
function rutaAB(latA, latB) // esto para cuando no se usa el control
{
var waypoints = [];
var coords = [];
var waysp = [];
waypoints.length = 0;
coords.length = 0;
waysp.length = 0;
if ((latA != null) && (latB != null))
//if ((marker1 !== null) && (marker2 !== null))
{
//var router = L.Routing.osrm();
var latlngA = L.Routing.waypoint(latA);
var latlngB = L.Routing.waypoint(latB);
// waypoints.push({latLng: latA});
// waypoints.push({latLng: latB});
waypoints.push(latlngA);
waypoints.push(latlngB);
var routes = null;
//routes = L.Routing.osrmv1({addWaypoints: false});
router: L.Routing.mapzen('mapzen-3indRB', {
addWaypoints: false,
costing: 'bicycle'
}),
routes.route(waypoints, function(err, routes) {
if (line) {
mapa.removeLayer(line);
}
if (err) {
console.log(err);
}
else {
coords = routes[0].coordinates;
waysp = routes[0].waypoints;
line = L.Routing.line(routes[0],{styles:[{color: 'black', opacity: 0.15, weight: 7}, {color: 'white', opacity: 0.8, weight: 4}, {color: '#1652F4', opacity: 1, weight: 3}]}).addTo(mapa);
var distanciaCerc = convertirKM(routes[0].summary.totalDistance);
popup = L.popup({offset: L.point(0, -30)})
.setLatLng(latB)
.setContent('<p>Distancia: <b>' + distanciaCerc + '</b></p>')
.openOn(mapa);
}
});
}
else
{
alert("Se necesita el par Origen-Destino para calcular la ruta");
}
}
| public/js/controlrouting.js | var routeControl = null;
var showControl = false;
var line = null;
function convertirKM(distancia)
{
var distanciaConvertida = '';
if (distancia >= 1000)
{
distancia = distancia/1000;
distanciaConvertida = distancia.toString() + ' km';
}
else
distanciaConvertida = distancia.toString() + ' m';
return distanciaConvertida;
}
function borrar()
{
if (marker1 !== null)
{
mapa.removeLayer(marker1);
marker1 = null;
}
if (marker2 !== null)
{
mapa.removeLayer(marker2);
marker2 = null;
}
waypoints.length = 0;
coords.length = 0;
if (line !== null)
mapa.removeLayer(line);
}
function borrarRuta()
{
routeControl.getPlan().setWaypoints([]);
}
function esconderMostrar()
{
if (showControl) // control despleagdo
{
routeControl.hide();
showControl = false;
/*$(".btnBorrar").css({
'right': '11px', //antes 37% 6
'top': '70px' //antes 13%* 5
}); */
}
else
{
routeControl.show();
showControl = true;
/*$(".btnBorrar").css({
'right': '27%', //antes 37% 6
'top': '70px' //antes 13%* 5
}); */
}
}
function displayRoutingControl()
{
if (routeControl == null)
{
crearControlRouting();
/*$(".btnBorrar").css({
'display': 'inline',
'right': '37%', //antes 37% 6
'top': '70px' //antes 13%* 5
}); */
showControl = true;
}
}
function removeRouting()
{
if (routeControl != null)
{
mapa.removeControl(routeControl); //remueve el camino tb
routeControl = null;
/*$(".btnBorrar").css({
'display': 'none',
'right': '-44px', //antes 37% 6
'left': 'auto',
'top': '70px' //antes 13%* 5
}); */
}
}
// function crearControlRouting() {
//
// routeControl = L.Routing.control({
//
//
// router: L.Routing.mapzen('mapzen-3indRB', {
// costing: 'bicycle',
// directions_options: {
// language: 'es'
// }
// }),
//
// plan: L.Routing.plan([], {
// geocoder: L.Control.Geocoder.nominatim({
// geocodingQueryParams: { countrycodes: 'uy'}
// }),
// reverseWaypoints: true,
// city:'Montevideo',
// language: 'sp'
// }),
// lineOptions: {
// styles:
// [
// {color: 'black', opacity: 0.15, weight: 9}, //sombra
// {color: 'white', opacity: 0.8, weight: 6}, // Contorno
// {color: 'red', opacity: 1, weight: 4}] // Centro
// },
// summaryTemplate: '<h2>Trayectoria: {name}</h2><h3>Distancia: {distance}</h3>',
// language: 'sp',
// //city: 'Montevideo', //si no va plan, debe agregarse si se desea afinar búsquedas.
// routeWhileDragging: true,
// waypointMode: 'snap',
// collapsible: true //nuevo
// }).addTo(mapa);
//
// }
function crearControlRouting() {
var control = L.Routing.control({
routeLine: function (route, options) { return L.Routing.mapzenLine(route, options); },
waypoints: routingData.waypoints,
// You can get your own Mapzen turn-by-turn & search API key from the Mapzen developer portal (https://mapzen.com/developers/)
geocoder: L.Control.Geocoder.mapzen('mapzen-3indRB'),
reverseWaypoints: true,
router: L.Routing.mapzen('mapzen-3indRB', {
costing: 'bicycle',
directions_options: {
language: 'es'
}
}),
collapsible: true,
show: (map.getSize().x > 768)? true: false,
formatter: new L.Routing.mapzenFormatter(),
lineOptions: {
styles:
[
{color: 'black', opacity: 0.15, weight: 9}, //sombra
{color: 'white', opacity: 0.8, weight: 6}, // Contorno
{color: 'red', opacity: 1, weight: 4}] // Centro
},
summaryTemplate:'<div class="start">{name}</div><div class="info {costing}">{distance}</div>'
//summaryTemplate: '<h2>Trayectoria: {name}</h2><h3>Distancia: {distance}</h3>',
}).addTo(map);
L.Routing.errorControl(control).addTo(map);
// to show where waypoints are even if there is no routing data
control.on('routingerror', function () {
var waypoints = control.getWaypoints();
map.fitBounds([
waypoints[0].latLng,
waypoints[waypoints.length-1].latLng
]);
})
}
function calcRoute() // esto para cuando no se usa el control
{
waypoints.length = 0;
coords.length = 0;
waysp.length = 0;
if ((marker1 !== null) && (marker2 !== null))
{
waypoints.push({latLng: marker1.getLatLng()});
waypoints.push({latLng: marker2.getLatLng()});
router.route(waypoints, function(err, routes) {
if (line) {
map.removeLayer(line);
}
if (err) {
alert(err);
} else {
coords = routes[0].coordinates;
waysp = routes[0].waypoints;
alert(routes[0].summary.totalTime);
alert(routes[0].summary.totalDistance);
line = L.Routing.line(routes[0],{styles:[{color: 'black', opacity: 0.15, weight: 7}, {color: 'white', opacity: 0.8, weight: 4}, {color: 'red', opacity: 1, weight: 4}]}).addTo(map);
}
});
}
else
alert("Se necesita el par Origen-Destino para calcular la ruta");
}
function rutaAB(latA, latB) // esto para cuando no se usa el control
{
var waypoints = [];
var coords = [];
var waysp = [];
waypoints.length = 0;
coords.length = 0;
waysp.length = 0;
if ((latA != null) && (latB != null))
//if ((marker1 !== null) && (marker2 !== null))
{
//var router = L.Routing.osrm();
var latlngA = L.Routing.waypoint(latA);
var latlngB = L.Routing.waypoint(latB);
// waypoints.push({latLng: latA});
// waypoints.push({latLng: latB});
waypoints.push(latlngA);
waypoints.push(latlngB);
var routes = null;
//routes = L.Routing.osrmv1({addWaypoints: false});
router: L.Routing.mapzen('mapzen-3indRB', {
addWaypoints: false,
costing: 'bicycle'
}),
routes.route(waypoints, function(err, routes) {
if (line) {
mapa.removeLayer(line);
}
if (err) {
console.log(err);
}
else {
coords = routes[0].coordinates;
waysp = routes[0].waypoints;
line = L.Routing.line(routes[0],{styles:[{color: 'black', opacity: 0.15, weight: 7}, {color: 'white', opacity: 0.8, weight: 4}, {color: '#1652F4', opacity: 1, weight: 3}]}).addTo(mapa);
var distanciaCerc = convertirKM(routes[0].summary.totalDistance);
popup = L.popup({offset: L.point(0, -30)})
.setLatLng(latB)
.setContent('<p>Distancia: <b>' + distanciaCerc + '</b></p>')
.openOn(mapa);
}
});
}
else
{
alert("Se necesita el par Origen-Destino para calcular la ruta");
}
}
| ruteo con mapzen
| public/js/controlrouting.js | ruteo con mapzen | <ide><path>ublic/js/controlrouting.js
<ide> function crearControlRouting() {
<ide> var control = L.Routing.control({
<ide> routeLine: function (route, options) { return L.Routing.mapzenLine(route, options); },
<del> waypoints: routingData.waypoints,
<add> // waypoints: routingData.waypoints,
<ide> // You can get your own Mapzen turn-by-turn & search API key from the Mapzen developer portal (https://mapzen.com/developers/)
<ide>
<ide> geocoder: L.Control.Geocoder.mapzen('mapzen-3indRB'), |
|
JavaScript | mit | eba89a63eebfc52e7050ebe5103f58d7e5a16979 | 0 | opendatacity/zeitungssterben,opendatacity/zeitungssterben | $(function () {
var initialTitle = document.title;
$(Z).on('Z:publicationchange', function (ev, publication) {
document.title = [publication.title, initialTitle].join(': ');
if (typeof history.replaceState === 'function') {
history.replaceState(publication, publication.title, Z.slugify(publication));
$(Z).trigger('Z:statechange');
}
});
// Check if document was loaded with a path
$(Z).on('Z:ready', function (ev, publications) {
var initialSlug = window.location.pathname.split('/').pop();
if (initialSlug !== '') {
for (var i=0, l=publications.length; i<l; i++) {
if (initialSlug === Z.slugify(publications[i])) {
$(Z).trigger('Z:publicationchange', publications[i]);
break;
}
}
}
});
});
| app/scripts/state.js | $(function () {
var base = '/';
var initialTitle = document.title;
$(Z).on('Z:publicationchange', function (ev, publication) {
document.title = [publication.title, initialTitle].join(': ');
if (typeof history.replaceState === 'function') {
history.replaceState(publication, publication.title, Z.slugify(publication));
$(Z).trigger('Z:statechange');
}
});
// Check if document was loaded with a path
$(Z).on('Z:ready', function (ev, publications) {
var initialSlug = window.location.pathname.replace(base, '');
if (initialSlug.length !== '') {
for (var i=0, l=publications.length; i<l; i++) {
if (initialSlug === Z.slugify(publications[i])) {
$(Z).trigger('Z:publicationchange', publications[i]);
break;
}
}
}
});
});
| Fix generated pages not showing publication on load
| app/scripts/state.js | Fix generated pages not showing publication on load | <ide><path>pp/scripts/state.js
<ide> $(function () {
<del> var base = '/';
<ide> var initialTitle = document.title;
<ide>
<ide> $(Z).on('Z:publicationchange', function (ev, publication) {
<ide>
<ide> // Check if document was loaded with a path
<ide> $(Z).on('Z:ready', function (ev, publications) {
<del> var initialSlug = window.location.pathname.replace(base, '');
<del> if (initialSlug.length !== '') {
<add> var initialSlug = window.location.pathname.split('/').pop();
<add> if (initialSlug !== '') {
<ide> for (var i=0, l=publications.length; i<l; i++) {
<ide> if (initialSlug === Z.slugify(publications[i])) {
<ide> $(Z).trigger('Z:publicationchange', publications[i]); |
|
Java | apache-2.0 | 8b2365baba9007d66526beae0431ad3c0d9884f0 | 0 | mojohaus/cassandra-maven-plugin | package org.codehaus.mojo.cassandra;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.cassandra.config.ConfigurationException;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.db.marshal.AbstractType;
import org.apache.cassandra.db.marshal.TypeParser;
import org.apache.cassandra.thrift.Column;
import org.apache.cassandra.thrift.Compression;
import org.apache.cassandra.thrift.CqlResult;
import org.apache.cassandra.thrift.CqlRow;
import org.apache.cassandra.thrift.Cassandra.Client;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
/**
* Executes cql statements from maven.
*
* @author zznate
* @goal cql-exec
* @threadSafe
* @phase pre-integration-test
*/
public class CqlExecCassandraMojo extends AbstractCassandraMojo {
/**
* The CQL script which will be executed
*
* @parameter expression="${cassandra.cql.script}" default-value="${basedir}/src/cassandra/cql/exec.cql"
*/
protected File cqlScript;
/**
* The CQL statement to execute singularly
*
* @parameter expression="${cql.statement}"
*/
protected String cqlStatement;
/**
* Expected type of the column value
* @parameter expression="${cql.defaultValidator}"
*/
protected String defaultValidator = "BytesType";
/**
* Expected type of the key
* @parameter expression="${cql.keyValidator}"
*/
protected String keyValidator = "BytesType";
/**
* Expected type of the column name
* @parameter expression="${cql.comparator}"
*/
protected String comparator = "BytesType";
private AbstractType<?> comparatorVal;
private AbstractType<?> keyValidatorVal;
private AbstractType<?> defaultValidatorVal;
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
if (skip)
{
getLog().info("Skipping cassandra: cassandra.skip==true");
return;
}
try
{
comparatorVal = TypeParser.parse(comparator);
keyValidatorVal = TypeParser.parse(keyValidator);
defaultValidatorVal = TypeParser.parse(defaultValidator);
} catch (ConfigurationException e) {
throw new MojoExecutionException("Could not parse comparator value: " + comparator, e);
}
List<CqlExecOperation> cqlOps = new ArrayList<CqlExecOperation>();
// file vs. statement switch
if ( cqlScript != null && cqlScript.isFile() )
{
BufferedReader br;
try {
br = new BufferedReader(new FileReader(cqlScript));
String curLine = br.readLine();
while (curLine != null)
{
cqlOps.add(doExec(curLine));
}
} catch (IOException e) {
throw new MojoExecutionException("Could not parse or load cql file", e);
}
} else
{
// TODO accept keyFormat, columnFormat, valueFormat
// ^ are these relevant on file load?
if ( cqlStatement.contains(";") )
{
String[] ops = StringUtils.split(cqlStatement, ";");
for (int i = 0; i < ops.length; i++)
{
cqlOps.add(doExec(ops[i]));
}
} else
{
cqlOps.add(doExec(cqlStatement));
}
}
printResults(cqlOps);
}
/*
* Encapsulate print of CqlResult. Uses specified configuration options to format results
*/
private void printResults(List<CqlExecOperation> cqlOps)
{
// TODO fix ghetto formatting
getLog().info("-----------------------------------------------");
for (CqlExecOperation cqlExecOperation : cqlOps)
{
while ( cqlExecOperation.hasNext() )
{
CqlRow cqlRow = cqlExecOperation.next();
getLog().info("Row key: "+keyValidatorVal.getString(cqlRow.key));
getLog().info("-----------------------------------------------");
for (Column column : cqlRow.getColumns() )
{
getLog().info(" name: "+comparatorVal.getString(column.name));
getLog().info(" value: "+defaultValidatorVal.getString(column.value));
getLog().info("-----------------------------------------------");
}
}
}
}
/*
* Encapsulate op execution for file vs. statement
*/
private CqlExecOperation doExec(String cqlStatement) throws MojoExecutionException
{
CqlExecOperation cqlOp = new CqlExecOperation(rpcAddress, rpcPort, cqlStatement);
if ( StringUtils.isNotBlank(keyspace))
{
getLog().info("setting keyspace: " + keyspace);
cqlOp.setKeyspace(keyspace);
}
try
{
Utils.executeThrift(cqlOp);
} catch (ThriftApiExecutionException taee)
{
throw new MojoExecutionException(taee.getMessage(), taee);
}
return cqlOp;
}
class CqlExecOperation extends ThriftApiOperation implements Iterator<CqlRow> {
CqlResult result;
final ByteBuffer statementBuf;
CqlRow current;
Iterator<CqlRow> rowIter;
public CqlExecOperation(String rpcAddress, int rpcPort, String cqlStatement)
{
super(rpcAddress, rpcPort);
this.statementBuf = ByteBufferUtil.bytes(cqlStatement);
}
@Override
void executeOperation(Client client) throws ThriftApiExecutionException
{
try
{
result = client.execute_cql_query(statementBuf, Compression.NONE);
rowIter = result.getRowsIterator();
} catch (Exception e)
{
throw new ThriftApiExecutionException(e);
}
}
@Override
public boolean hasNext()
{
return rowIter != null && rowIter.hasNext();
}
@Override
public CqlRow next()
{
current = rowIter.next();
return current;
}
@Override
public void remove()
{
rowIter.remove();
}
List<Column> getColumns()
{
return current.getColumns();
}
ByteBuffer getKey()
{
return current.bufferForKey();
}
}
}
| src/main/java/org/codehaus/mojo/cassandra/CqlExecCassandraMojo.java | package org.codehaus.mojo.cassandra;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.cassandra.config.ConfigurationException;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.db.marshal.AbstractType;
import org.apache.cassandra.db.marshal.TypeParser;
import org.apache.cassandra.thrift.Column;
import org.apache.cassandra.thrift.Compression;
import org.apache.cassandra.thrift.CqlResult;
import org.apache.cassandra.thrift.CqlRow;
import org.apache.cassandra.thrift.Cassandra.Client;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
/**
* Loads a {@code cassandra-cli} bscript into a Cassandra instance.
*
* @author zznate
* @goal cql-exec
* @threadSafe
* @phase pre-integration-test
*/
public class CqlExecCassandraMojo extends AbstractCassandraMojo {
/**
* The CQL script which will be executed
*
* @parameter expression="${cassandra.cql.script}" default-value="${basedir}/src/cassandra/cql/exec.cql"
*/
protected File cqlScript;
/**
* The CQL statement to execute singularly
*
* @parameter expression="${cql.statement}"
*/
protected String cqlStatement;
/**
* Expected type of the column value
* @parameter expression="${cql.defaultValidator}"
*/
protected String defaultValidator = "BytesType";
/**
* Expected type of the key
* @parameter expression="${cql.keyValidator}"
*/
protected String keyValidator = "BytesType";
/**
* Expected type of the column name
* @parameter expression="${cql.comparator}"
*/
protected String comparator = "BytesType";
private AbstractType<?> comparatorVal;
private AbstractType<?> keyValidatorVal;
private AbstractType<?> defaultValidatorVal;
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
if (skip)
{
getLog().info("Skipping cassandra: cassandra.skip==true");
return;
}
try
{
comparatorVal = TypeParser.parse(comparator);
keyValidatorVal = TypeParser.parse(keyValidator);
defaultValidatorVal = TypeParser.parse(defaultValidator);
} catch (ConfigurationException e) {
throw new MojoExecutionException("Could not parse comparator value: " + comparator, e);
}
List<CqlExecOperation> cqlOps = new ArrayList<CqlExecOperation>();
// file vs. statement switch
if ( cqlScript != null && cqlScript.isFile() )
{
BufferedReader br;
try {
br = new BufferedReader(new FileReader(cqlScript));
String curLine = br.readLine();
while (curLine != null)
{
cqlOps.add(doExec(curLine));
}
} catch (IOException e) {
throw new MojoExecutionException("Could not parse or load cql file", e);
}
} else
{
// TODO accept keyFormat, columnFormat, valueFormat
// ^ are these relevant on file load?
if ( cqlStatement.contains(";") )
{
String[] ops = StringUtils.split(cqlStatement, ";");
for (int i = 0; i < ops.length; i++)
{
cqlOps.add(doExec(ops[i]));
}
} else
{
cqlOps.add(doExec(cqlStatement));
}
}
printResults(cqlOps);
}
/*
* Encapsulate print of CqlResult. Uses specified configuration options to format results
*/
private void printResults(List<CqlExecOperation> cqlOps)
{
// TODO fix ghetto formatting
getLog().info("-----------------------------------------------");
for (CqlExecOperation cqlExecOperation : cqlOps)
{
while ( cqlExecOperation.hasNext() )
{
CqlRow cqlRow = cqlExecOperation.next();
getLog().info("Row key: "+keyValidatorVal.getString(cqlRow.key));
getLog().info("-----------------------------------------------");
for (Column column : cqlRow.getColumns() )
{
getLog().info(" name: "+comparatorVal.getString(column.name));
getLog().info(" value: "+defaultValidatorVal.getString(column.value));
getLog().info("-----------------------------------------------");
}
}
}
}
/*
* Encapsulate op execution for file vs. statement
*/
private CqlExecOperation doExec(String cqlStatement) throws MojoExecutionException
{
CqlExecOperation cqlOp = new CqlExecOperation(rpcAddress, rpcPort, cqlStatement);
if ( StringUtils.isNotBlank(keyspace))
{
getLog().info("setting keyspace: " + keyspace);
cqlOp.setKeyspace(keyspace);
}
try
{
Utils.executeThrift(cqlOp);
} catch (ThriftApiExecutionException taee)
{
throw new MojoExecutionException(taee.getMessage(), taee);
}
return cqlOp;
}
class CqlExecOperation extends ThriftApiOperation implements Iterator<CqlRow> {
CqlResult result;
final ByteBuffer statementBuf;
CqlRow current;
Iterator<CqlRow> rowIter;
public CqlExecOperation(String rpcAddress, int rpcPort, String cqlStatement)
{
super(rpcAddress, rpcPort);
this.statementBuf = ByteBufferUtil.bytes(cqlStatement);
}
@Override
void executeOperation(Client client) throws ThriftApiExecutionException
{
try
{
result = client.execute_cql_query(statementBuf, Compression.NONE);
rowIter = result.getRowsIterator();
} catch (Exception e)
{
throw new ThriftApiExecutionException(e);
}
}
@Override
public boolean hasNext()
{
return rowIter != null && rowIter.hasNext();
}
@Override
public CqlRow next()
{
current = rowIter.next();
return current;
}
@Override
public void remove()
{
rowIter.remove();
}
List<Column> getColumns()
{
return current.getColumns();
}
ByteBuffer getKey()
{
return current.bufferForKey();
}
}
}
| updated class level comment
git-svn-id: 3c5bcc91f03ddbd5081d7a010ad2cafa7df6e15e@14706 52ab4f32-60fc-0310-b215-8acea882cd1b
| src/main/java/org/codehaus/mojo/cassandra/CqlExecCassandraMojo.java | updated class level comment | <ide><path>rc/main/java/org/codehaus/mojo/cassandra/CqlExecCassandraMojo.java
<ide> import org.apache.maven.plugin.MojoFailureException;
<ide>
<ide> /**
<del> * Loads a {@code cassandra-cli} bscript into a Cassandra instance.
<add> * Executes cql statements from maven.
<ide> *
<ide> * @author zznate
<ide> * @goal cql-exec |
|
JavaScript | mit | 80071b76829d9df02335c69cb6e303e12063dd50 | 0 | hezedu/express-jade-compiled | var fs = require('fs');
var path = require('path');
var jade = require('jade');
var uglify = require("uglify-js");
var etag = require('etag');
function server(tpl_path, opts) {
if (!tpl_path) {
//默认目录
tpl_path = path.join(process.cwd(), 'jade_compiled');
}
opts = opts || {};
opts.tpl_path = tpl_path; //模版目录
//缓存期限 默认0
opts.maxAge = typeof opts.maxAge === 'undefined' ? 0 : opts.maxAge;
//监测模版文件是否修改 默认:测试环境 是 , 生产环境 否
opts.watch = typeof opts.watch === 'undefined' ?
('production' === process.env.NODE_ENV ? false : true ): opts.watch;
//是否压缩 默认:测试环境 否 , 生产环境 是
opts.uglify = typeof opts.uglify === 'undefined' ?
(process.env.NODE_ENV === 'production' ? true : false) : opts.watch;
//server.conf = opts;
return function(req, res, next) {
var multiple = req.query.multiple;
var real_path = path.join(tpl_path, req.path);
var cache_key = '';
if(multiple){
cache_key = real_path + ':multiple:client';
}else{
var cache_key = real_path + ':client';
}
var _etag = '';
if (!jade.cache[cache_key]) { //如果没有缓存的话.
//console.log('multiple');
var is_first = (undefined === jade.cache[cache_key]);
if(!multiple){
var jsFunctionString = jade.compileFileClient(real_path, {
cache: true
});
if (opts.uglify) {
jade.cache[cache_key] = uglify.minify(jsFunctionString, {
fromString: true
}).code;
}
}else{
try{
var doc = fs.readFileSync(real_path, 'utf-8');
}catch(err){
err.name = 'jade_compiled MULTIPLE: ' + err.name;
return next(err);
}
var dump = [];
doc = doc.split('//-$MULTIPLE:');
for (var i = 1, len = doc.length; i < len; i++) {
var curr = doc[i];
var first_n = curr.indexOf('\n');
var key = curr.substr(0, first_n-1);
var v = curr.substr(first_n + 1);
v = jade.compileClient(v, {name:'tpl'+ i});
if (opts.uglify) {
v = uglify.minify(v, {
fromString: true
}).code;
}
dump.push('"' + key + '":' + v);
}
dump = dump.join(',');
dump = '{' + dump + '}';
jade.cache[cache_key] = dump;
}
//server.create_cache(real_path, cache_key);
_etag = etag(jade.cache[cache_key]);
if (is_first && opts.watch) {
var is_change = false;
fs.watch(real_path, function() {
if (!is_change) {
is_change = true;
jade.cache[cache_key] = null;
//console.log('缓存已销毁!');
setTimeout(function() {
is_change = false
}, 1000);
}
});
}
//console.log('server 索引创建!');
} else {
_etag = etag(jade.cache[cache_key]);
}
res.setHeader('Content-Type', 'application/javascript');
if (opts.maxAge > 0) {
res.setHeader('Cache-Control', "max-age=" + opts.maxAge);
}
res.setHeader('Etag', _etag);
var outstr = 'define(function(){return ' + jade.cache[cache_key] + '})'
res.send(outstr);
}
}
server.jade_runtime_min_path = path.join(__dirname, 'jade-runtime-min.js');
module.exports = server; | index.js | var fs = require('fs');
var path = require('path');
var jade = require('jade');
var uglify = require("uglify-js");
var etag = require('etag');
function server(tpl_path, opts) {
if (!tpl_path) {
//默认目录
tpl_path = path.join(process.cwd(), 'jade_compiled');
}
opts = opts || {};
opts.tpl_path = tpl_path; //模版目录
//缓存期限 默认0
opts.maxAge = typeof opts.maxAge === 'undefined' ? 0 : opts.maxAge;
//监测模版文件是否修改 默认:测试环境 是 , 生产环境 否
opts.watch = typeof opts.watch === 'undefined' ?
('production' === process.env.NODE_ENV ? false : true ): opts.watch;
//是否压缩 默认:测试环境 否 , 生产环境 是
opts.uglify = typeof opts.uglify === 'undefined' ?
(process.env.NODE_ENV === 'production' ? true : false) : opts.watch;
//server.conf = opts;
return function(req, res, next) {
var real_path = path.join(tpl_path, req.path);
var cache_key = real_path + ':client';
var _etag = '';
if (!jade.cache[cache_key]) { //如果没有缓存的话.
var is_first = (undefined === jade.cache[cache_key]);
var jsFunctionString = jade.compileFileClient(real_path, {
cache: true
});
if (opts.uglify) {
jade.cache[cache_key] = uglify.minify(jsFunctionString, {
fromString: true
}).code;
}
//server.create_cache(real_path, cache_key);
_etag = etag(jade.cache[cache_key]);
if (is_first && opts.watch) {
var is_change = false;
fs.watch(real_path, function() {
if (!is_change) {
is_change = true;
jade.cache[cache_key] = null;
//console.log('缓存已销毁!');
setTimeout(function() {
is_change = false
}, 1000);
}
});
}
//console.log('server 索引创建!');
} else {
_etag = etag(jade.cache[cache_key]);
}
res.setHeader('Content-Type', 'application/javascript');
if (opts.maxAge > 0) {
res.setHeader('Cache-Control', "max-age=" + opts.maxAge);
}
res.setHeader('Etag', _etag);
var outstr = 'define(function(){return ' + jade.cache[cache_key] + '})'
res.send(outstr);
}
}
server.jade_runtime_min_path = path.join(__dirname, 'jade-runtime-min.js');
module.exports = server; | multiple
| index.js | multiple | <ide><path>ndex.js
<ide>
<ide> return function(req, res, next) {
<ide>
<add> var multiple = req.query.multiple;
<ide> var real_path = path.join(tpl_path, req.path);
<del> var cache_key = real_path + ':client';
<add>
<add> var cache_key = '';
<add> if(multiple){
<add> cache_key = real_path + ':multiple:client';
<add> }else{
<add> var cache_key = real_path + ':client';
<add> }
<add>
<ide> var _etag = '';
<ide>
<ide> if (!jade.cache[cache_key]) { //如果没有缓存的话.
<add>
<add> //console.log('multiple');
<ide> var is_first = (undefined === jade.cache[cache_key]);
<del> var jsFunctionString = jade.compileFileClient(real_path, {
<del> cache: true
<del> });
<del> if (opts.uglify) {
<del> jade.cache[cache_key] = uglify.minify(jsFunctionString, {
<del> fromString: true
<del> }).code;
<add> if(!multiple){
<add> var jsFunctionString = jade.compileFileClient(real_path, {
<add> cache: true
<add> });
<add> if (opts.uglify) {
<add> jade.cache[cache_key] = uglify.minify(jsFunctionString, {
<add> fromString: true
<add> }).code;
<add> }
<add> }else{
<add>
<add> try{
<add> var doc = fs.readFileSync(real_path, 'utf-8');
<add> }catch(err){
<add> err.name = 'jade_compiled MULTIPLE: ' + err.name;
<add> return next(err);
<add> }
<add>
<add> var dump = [];
<add> doc = doc.split('//-$MULTIPLE:');
<add> for (var i = 1, len = doc.length; i < len; i++) {
<add> var curr = doc[i];
<add> var first_n = curr.indexOf('\n');
<add>
<add> var key = curr.substr(0, first_n-1);
<add>
<add> var v = curr.substr(first_n + 1);
<add> v = jade.compileClient(v, {name:'tpl'+ i});
<add>
<add> if (opts.uglify) {
<add> v = uglify.minify(v, {
<add> fromString: true
<add> }).code;
<add> }
<add> dump.push('"' + key + '":' + v);
<add> }
<add>
<add> dump = dump.join(',');
<add> dump = '{' + dump + '}';
<add> jade.cache[cache_key] = dump;
<ide> }
<ide>
<ide> //server.create_cache(real_path, cache_key);
<ide>
<ide> });
<ide> }
<add>
<ide> //console.log('server 索引创建!');
<ide> } else {
<ide> _etag = etag(jade.cache[cache_key]); |
|
Java | apache-2.0 | f8c0051e66daa7466bdf0c80f2454a32b73cf5e8 | 0 | uweschaefer/factcast,uweschaefer/factcast,uweschaefer/factcast | /*
* Copyright © 2018 Mercateo AG (http://www.mercateo.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.factcast.client.grpc.cli.util;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.factcast.client.grpc.cli.conv.Converters;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.JCommander.Builder;
import com.beust.jcommander.Parameter;
import lombok.Getter;
public class Parser {
private static final String HOST_SYSPROP_NAME = "grpc.client.factstore.host";
private static final String PORT_SYSPROP_NAME = "grpc.client.factstore.port";
final JCommander jc;
@Getter
final Options options = new Options();
public Parser(Command... commands) {
Builder builder = JCommander.newBuilder().addConverterInstanceFactory(Converters.factory());
builder.addObject(options);
builder.programName("fc-cli");
Arrays.asList(commands).forEach(builder::addCommand);
this.jc = builder.build();
}
public Command parse(String[] args) {
jc.parse(args);
JCommander parsedCommand = jc.getCommands().get(jc.getParsedCommand());
if (parsedCommand != null) {
init();
List<Object> objects = parsedCommand.getObjects();
return (Command) objects.get(0);
}
jc.usage();
return null;
}
private void init() {
System.setProperty(HOST_SYSPROP_NAME, options.host);
System.setProperty(PORT_SYSPROP_NAME, String.valueOf(options.port));
if (options.debug) {
System.setProperty("debug", Boolean.TRUE.toString());
}
}
public static class Options {
@Parameter(names = { "--help", "-help", "-?", "--?" }, help = true, hidden = true)
boolean help;
@Getter
@Parameter(names = { "--pretty" }, help = true, description = "format JSON output")
boolean pretty = false;
@Getter
@Parameter(
names = { "--debug" },
help = true,
description = "show debug-level debug messages",
order = 0)
boolean debug = false;
@Parameter(names = "--host", description = "the hostname to connect to", order = 1)
String host = "localhost";
@Parameter(names = "--port", description = "the port to connect to", order = 2)
int port = 9090;
public Options() {
String fc = System.getenv("FACTCAST_SERVER");
if (fc != null) {
Iterator<String> i = Arrays.asList(fc.split(":")).iterator();
if (i.hasNext()) {
String h = i.next();
if (h != null && h.trim().length() > 0)
host = h;
}
if (i.hasNext()) {
String p = i.next();
if (p != null && p.trim().length() > 0)
port = Integer.parseInt(p);
}
}
}
}
public void usage() {
jc.usage();
}
}
| factcast-client-grpc-cli/src/main/java/org/factcast/client/grpc/cli/util/Parser.java | /*
* Copyright © 2018 Mercateo AG (http://www.mercateo.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.factcast.client.grpc.cli.util;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.factcast.client.grpc.cli.conv.Converters;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.JCommander.Builder;
import com.beust.jcommander.Parameter;
import lombok.Getter;
public class Parser {
private static final String HOST_SYSPROP_NAME = "grpc.client.factstore.host";
private static final String PORT_SYSPROP_NAME = "grpc.client.factstore.port";
final JCommander jc;
@Getter
final Options options = new Options();
public Parser(Command... commands) {
Builder builder = JCommander.newBuilder().addConverterInstanceFactory(Converters.factory());
builder.addObject(options);
builder.programName("fc-cli");
Arrays.asList(commands).forEach(builder::addCommand);
this.jc = builder.build();
}
public Command parse(String[] args) {
jc.parse(args);
if (options.help) {
jc.usage();
return null;
}
init();
List<Object> objects = jc.getCommands().get(jc.getParsedCommand()).getObjects();
return (Command) objects.get(0);
}
private void init() {
System.setProperty(HOST_SYSPROP_NAME, options.host);
System.setProperty(PORT_SYSPROP_NAME, String.valueOf(options.port));
if (options.debug) {
System.setProperty("debug", Boolean.TRUE.toString());
}
}
public static class Options {
@Parameter(names = { "--help", "-help", "-?", "--?" }, help = true, hidden = true)
boolean help;
@Getter
@Parameter(names = { "--pretty" }, help = true, description = "format JSON output")
boolean pretty = false;
@Getter
@Parameter(
names = { "--debug" },
help = true,
description = "show debug-level debug messages",
order = 0)
boolean debug = false;
@Parameter(names = "--host", description = "the hostname to connect to", order = 1)
String host = "localhost";
@Parameter(names = "--port", description = "the port to connect to", order = 2)
int port = 9090;
public Options() {
String fc = System.getenv("FACTCAST_SERVER");
if (fc != null) {
Iterator<String> i = Arrays.asList(fc.split(":")).iterator();
if (i.hasNext()) {
String h = i.next();
if (h != null && h.trim().length() > 0)
host = h;
}
if (i.hasNext()) {
String p = i.next();
if (p != null && p.trim().length() > 0)
port = Integer.parseInt(p);
}
}
}
}
public void usage() {
jc.usage();
}
}
| print usage when cli options incomplete (#269)
closes #268 | factcast-client-grpc-cli/src/main/java/org/factcast/client/grpc/cli/util/Parser.java | print usage when cli options incomplete (#269) | <ide><path>actcast-client-grpc-cli/src/main/java/org/factcast/client/grpc/cli/util/Parser.java
<ide>
<ide> public Command parse(String[] args) {
<ide> jc.parse(args);
<del> if (options.help) {
<del> jc.usage();
<del> return null;
<add>
<add> JCommander parsedCommand = jc.getCommands().get(jc.getParsedCommand());
<add> if (parsedCommand != null) {
<add> init();
<add> List<Object> objects = parsedCommand.getObjects();
<add> return (Command) objects.get(0);
<ide> }
<del> init();
<del> List<Object> objects = jc.getCommands().get(jc.getParsedCommand()).getObjects();
<del> return (Command) objects.get(0);
<add> jc.usage();
<add> return null;
<ide> }
<ide>
<ide> private void init() { |
|
Java | apache-2.0 | 5e2d8377fea8b49e7fb5e5ebb6ac801ddaf96e95 | 0 | nonamejx/vmv2,nonamejx/vmv2 | package controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.bean.User;
import model.bo.UserBO;
import utils.MyUtils;
/**
* Servlet implementation class LoginServlet
*/
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public LoginServlet() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
request.setCharacterEncoding("UTF-8");
String submit = request.getParameter("login");
UserBO userBO = new UserBO();
if (submit != null) {
String username = request.getParameter("username");
String password = request.getParameter("password");
String rememberMe = request.getParameter("rememberMe");
User userLogin = userBO.getUserByUsernamePassword(username, password);
if (userLogin != null) {
// checked remember
if ("on".equals(rememberMe)) {
if (MyUtils.getInstance(request).isRememberMeSelected()) {
String idStr = MyUtils.getInstance(request).getDetailCookieRemember();
if (!idStr.equals(String.valueOf(userLogin.getUserId()))) {
MyUtils.getInstance(request).editCookieRemember(userLogin.getUserId(), response);
}
} else {
MyUtils.getInstance(request).createValueCookieRemember(userLogin.getUserId(), response);
}
} else {
if (MyUtils.getInstance(request).isRememberMeSelected()) {
String idStr = MyUtils.getInstance(request).getDetailCookieRemember();
if (idStr.equals(String.valueOf(userLogin.getUserId()))) {
MyUtils.getInstance(request).deleteCookieRemember(response);
}
}
}
// Tạo session
MyUtils.getInstance(request).createLoginSession(userLogin);
if (MyUtils.getInstance(request).isLoggedIn()) {
response.sendRedirect("home");
} else {
response.sendRedirect("user/login");
}
} else {
javax.servlet.RequestDispatcher rd = request.getRequestDispatcher("/user/login.jsp?msg=1");
rd.forward(request, response);
}
} else {
// Lấy cookie remember
if (MyUtils.getInstance(request).isRememberMeSelected()) {
String idStr = MyUtils.getInstance(request).getDetailCookieRemember();
try {
int id = Integer.parseInt(idStr);
request.setAttribute("userRemember", userBO.getUserById(id));
} catch (NumberFormatException ex) {
}
}
javax.servlet.RequestDispatcher rd = request.getRequestDispatcher("/user/login.jsp");
rd.forward(request, response);
}
}
}
| VMV2/src/controller/LoginServlet.java | package controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.bean.User;
import model.bo.UserBO;
import utils.MyUtils;
/**
* Servlet implementation class LoginServlet
*/
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public LoginServlet() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
request.setCharacterEncoding("UTF-8");
String submit = request.getParameter("login");
UserBO userBO = new UserBO();
if (submit != null) {
String username = request.getParameter("username");
String password = request.getParameter("password");
String rememberMe = request.getParameter("rememberMe");
User userLogin = userBO.getUserByUsernamePassword(username, password);
if (userLogin != null) {
// checked remember
if ("on".equals(rememberMe)) {
if (MyUtils.getInstance(request).isRememberMeSelected()) {
String idStr = MyUtils.getInstance(request).getDetailCookieRemember();
if (!idStr.equals(String.valueOf(userLogin.getUserId()))) {
MyUtils.getInstance(request).editCookieRemember(userLogin.getUserId(), response);
}
} else {
MyUtils.getInstance(request).createValueCookieRemember(userLogin.getUserId(), response);
}
} else {
if (MyUtils.getInstance(request).isRememberMeSelected()) {
String idStr = MyUtils.getInstance(request).getDetailCookieRemember();
if (idStr.equals(String.valueOf(userLogin.getUserId()))) {
MyUtils.getInstance(request).deleteCookieRemember(response);
}
}
}
// Tạo session
MyUtils.getInstance(request).createLoginSession(userLogin);
if (MyUtils.getInstance(request).isLoggedIn()) {
response.sendRedirect("home");
} else {
response.sendRedirect("user/login");
}
} else {
javax.servlet.RequestDispatcher rd = request.getRequestDispatcher("/user/login.jsp?msg=1");
rd.forward(request, response);
}
} else {
// Lấy cookie remember
if (MyUtils.getInstance(request).isRememberMeSelected()) {
String idStr = MyUtils.getInstance(request).getDetailCookieRemember();
try {
int id = Integer.parseInt(idStr);
request.setAttribute("userRemember", userBO.getUserById(id));
} catch (NumberFormatException ex) {
javax.servlet.RequestDispatcher rd = request.getRequestDispatcher("/user/login.jsp");
rd.forward(request, response);
}
}
javax.servlet.RequestDispatcher rd = request.getRequestDispatcher("/user/login.jsp");
rd.forward(request, response);
}
}
}
| feature-fix_to_test-huyhm-171016
| VMV2/src/controller/LoginServlet.java | feature-fix_to_test-huyhm-171016 | <ide><path>MV2/src/controller/LoginServlet.java
<ide> int id = Integer.parseInt(idStr);
<ide> request.setAttribute("userRemember", userBO.getUserById(id));
<ide> } catch (NumberFormatException ex) {
<del> javax.servlet.RequestDispatcher rd = request.getRequestDispatcher("/user/login.jsp");
<del> rd.forward(request, response);
<add>
<ide> }
<ide> }
<add>
<ide> javax.servlet.RequestDispatcher rd = request.getRequestDispatcher("/user/login.jsp");
<ide> rd.forward(request, response);
<ide> } |
|
Java | bsd-3-clause | e8a1dd31b471451de35949dec992140fb19f443f | 0 | vivo-project/Vitro,vivo-project/Vitro,vivo-project/Vitro,vivo-project/Vitro | /* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vedit.beans;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class FormObject implements Serializable {
private HashMap<String, String> values = new HashMap<String, String>();
private HashMap<String, List<Option>> optionLists = new HashMap<String, List<Option>>();
private HashMap<String, List<Checkbox>> checkboxLists = new HashMap<String, List<Checkbox>>();
private HashMap<String, String> errorMap = new HashMap<String, String>();
private List<DynamicField> dynamicFields = new ArrayList<DynamicField>();
public HashMap<String, String> getValues(){
return values;
}
public void setValues(HashMap<String, String> values){
this.values = values;
}
public String valueByName(String name){
return values.get(name);
}
public HashMap<String, List<Option>> getOptionLists() {
return optionLists;
}
public void setOptionLists(HashMap<String, List<Option>> optionLists) {
this.optionLists = optionLists;
}
public List<Option> optionListByName(String key){
return optionLists.get(key);
}
public HashMap<String, List<Checkbox>> getCheckboxLists(){
return checkboxLists;
}
public HashMap<String, String> getErrorMap(){
return errorMap;
}
public void setErrorMap(HashMap<String, String> errorMap){
this.errorMap = errorMap;
}
public List<DynamicField> getDynamicFields() {
return dynamicFields;
}
public void setDynamicFields(List<DynamicField> dynamicFields){
this.dynamicFields = dynamicFields;
}
}
| webapp/src/edu/cornell/mannlib/vedit/beans/FormObject.java | /* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vedit.beans;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import edu.cornell.mannlib.vedit.beans.Option;
public class FormObject implements Serializable {
private HashMap values = new HashMap();
private HashMap optionLists = new HashMap();
private HashMap checkboxLists = new HashMap();
private HashMap errorMap = new HashMap();
private List dynamicFields = null;
public HashMap getValues(){
return values;
}
public void setValues(HashMap values){
this.values = values;
}
public String valueByName(String name){
return (String) values.get(name);
}
public HashMap getOptionLists() {
return optionLists;
}
public void setOptionLists(HashMap optionLists) {
this.optionLists = optionLists;
}
public List optionListByName(String key){
return (List) optionLists.get(key);
}
public HashMap getCheckboxLists(){
return checkboxLists;
}
public HashMap getErrorMap(){
return errorMap;
}
public void setErrorMap(HashMap errorMap){
this.errorMap = errorMap;
}
public List getDynamicFields() {
return dynamicFields;
}
public void setDynamicFields(List dynamicFields){
this.dynamicFields = dynamicFields;
}
}
| NIHVIVO-1385 Add toString() method to help in debugging. As long as we are here, use proper generics.
| webapp/src/edu/cornell/mannlib/vedit/beans/FormObject.java | NIHVIVO-1385 Add toString() method to help in debugging. As long as we are here, use proper generics. | <ide><path>ebapp/src/edu/cornell/mannlib/vedit/beans/FormObject.java
<ide> package edu.cornell.mannlib.vedit.beans;
<ide>
<ide> import java.io.Serializable;
<add>import java.util.ArrayList;
<ide> import java.util.HashMap;
<ide> import java.util.List;
<del>import edu.cornell.mannlib.vedit.beans.Option;
<ide>
<ide> public class FormObject implements Serializable {
<ide>
<del> private HashMap values = new HashMap();
<del> private HashMap optionLists = new HashMap();
<del> private HashMap checkboxLists = new HashMap();
<del> private HashMap errorMap = new HashMap();
<del> private List dynamicFields = null;
<add> private HashMap<String, String> values = new HashMap<String, String>();
<add> private HashMap<String, List<Option>> optionLists = new HashMap<String, List<Option>>();
<add> private HashMap<String, List<Checkbox>> checkboxLists = new HashMap<String, List<Checkbox>>();
<add> private HashMap<String, String> errorMap = new HashMap<String, String>();
<add> private List<DynamicField> dynamicFields = new ArrayList<DynamicField>();
<ide>
<del> public HashMap getValues(){
<add> public HashMap<String, String> getValues(){
<ide> return values;
<ide> }
<ide>
<del> public void setValues(HashMap values){
<add> public void setValues(HashMap<String, String> values){
<ide> this.values = values;
<ide> }
<ide>
<ide> public String valueByName(String name){
<del> return (String) values.get(name);
<add> return values.get(name);
<ide> }
<ide>
<del> public HashMap getOptionLists() {
<add> public HashMap<String, List<Option>> getOptionLists() {
<ide> return optionLists;
<ide> }
<ide>
<del> public void setOptionLists(HashMap optionLists) {
<add> public void setOptionLists(HashMap<String, List<Option>> optionLists) {
<ide> this.optionLists = optionLists;
<ide> }
<ide>
<del> public List optionListByName(String key){
<del> return (List) optionLists.get(key);
<add> public List<Option> optionListByName(String key){
<add> return optionLists.get(key);
<ide> }
<ide>
<del> public HashMap getCheckboxLists(){
<add> public HashMap<String, List<Checkbox>> getCheckboxLists(){
<ide> return checkboxLists;
<ide> }
<ide>
<del> public HashMap getErrorMap(){
<add> public HashMap<String, String> getErrorMap(){
<ide> return errorMap;
<ide> }
<ide>
<del> public void setErrorMap(HashMap errorMap){
<add> public void setErrorMap(HashMap<String, String> errorMap){
<ide> this.errorMap = errorMap;
<ide> }
<ide>
<del> public List getDynamicFields() {
<add> public List<DynamicField> getDynamicFields() {
<ide> return dynamicFields;
<ide> }
<ide>
<del> public void setDynamicFields(List dynamicFields){
<add> public void setDynamicFields(List<DynamicField> dynamicFields){
<ide> this.dynamicFields = dynamicFields;
<ide> }
<ide> |
|
Java | lgpl-2.1 | cd120969aecf1265f89a51840fa776c871b80bd4 | 0 | sbonoc/opencms-core,victos/opencms-core,mediaworx/opencms-core,sbonoc/opencms-core,MenZil/opencms-core,alkacon/opencms-core,victos/opencms-core,it-tavis/opencms-core,it-tavis/opencms-core,gallardo/opencms-core,MenZil/opencms-core,ggiudetti/opencms-core,alkacon/opencms-core,gallardo/opencms-core,mediaworx/opencms-core,it-tavis/opencms-core,ggiudetti/opencms-core,it-tavis/opencms-core,ggiudetti/opencms-core,mediaworx/opencms-core,victos/opencms-core,sbonoc/opencms-core,mediaworx/opencms-core,sbonoc/opencms-core,ggiudetti/opencms-core,MenZil/opencms-core,alkacon/opencms-core,victos/opencms-core,gallardo/opencms-core,MenZil/opencms-core,alkacon/opencms-core,gallardo/opencms-core | /*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (c) Alkacon Software GmbH (http://www.alkacon.com)
*
* 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.
*
* For further information about Alkacon Software GmbH, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.opencms.main;
import org.opencms.ade.configuration.CmsADEManager;
import org.opencms.configuration.CmsConfigurationException;
import org.opencms.configuration.CmsConfigurationManager;
import org.opencms.configuration.CmsImportExportConfiguration;
import org.opencms.configuration.CmsModuleConfiguration;
import org.opencms.configuration.CmsParameterConfiguration;
import org.opencms.configuration.CmsSearchConfiguration;
import org.opencms.configuration.CmsSystemConfiguration;
import org.opencms.configuration.CmsVfsConfiguration;
import org.opencms.configuration.CmsWorkplaceConfiguration;
import org.opencms.db.CmsAliasManager;
import org.opencms.db.CmsDbEntryNotFoundException;
import org.opencms.db.CmsDefaultUsers;
import org.opencms.db.CmsExportPoint;
import org.opencms.db.CmsLoginManager;
import org.opencms.db.CmsSecurityManager;
import org.opencms.db.CmsSqlManager;
import org.opencms.db.CmsSubscriptionManager;
import org.opencms.db.CmsUserSettings;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsProject;
import org.opencms.file.CmsProperty;
import org.opencms.file.CmsPropertyDefinition;
import org.opencms.file.CmsRequestContext;
import org.opencms.file.CmsResource;
import org.opencms.file.CmsUser;
import org.opencms.file.CmsVfsResourceNotFoundException;
import org.opencms.flex.CmsFlexCache;
import org.opencms.flex.CmsFlexCacheConfiguration;
import org.opencms.flex.CmsFlexController;
import org.opencms.gwt.CmsGwtService;
import org.opencms.gwt.CmsGwtServiceContext;
import org.opencms.i18n.CmsEncoder;
import org.opencms.i18n.CmsI18nInfo;
import org.opencms.i18n.CmsLocaleManager;
import org.opencms.i18n.CmsMessageContainer;
import org.opencms.importexport.CmsImportExportManager;
import org.opencms.jsp.util.CmsErrorBean;
import org.opencms.loader.CmsResourceManager;
import org.opencms.loader.CmsTemplateContextManager;
import org.opencms.loader.I_CmsFlexCacheEnabledLoader;
import org.opencms.loader.I_CmsResourceLoader;
import org.opencms.lock.CmsLockManager;
import org.opencms.module.CmsModuleManager;
import org.opencms.monitor.CmsMemoryMonitor;
import org.opencms.monitor.CmsMemoryMonitorConfiguration;
import org.opencms.publish.CmsPublishEngine;
import org.opencms.publish.CmsPublishManager;
import org.opencms.repository.CmsRepositoryManager;
import org.opencms.scheduler.CmsScheduleManager;
import org.opencms.search.CmsSearchManager;
import org.opencms.security.CmsOrgUnitManager;
import org.opencms.security.CmsRole;
import org.opencms.security.CmsRoleManager;
import org.opencms.security.CmsRoleViolationException;
import org.opencms.security.CmsSecurityException;
import org.opencms.security.I_CmsAuthorizationHandler;
import org.opencms.security.I_CmsCredentialsResolver;
import org.opencms.security.I_CmsPasswordHandler;
import org.opencms.security.I_CmsValidationHandler;
import org.opencms.site.CmsSite;
import org.opencms.site.CmsSiteManagerImpl;
import org.opencms.staticexport.CmsDefaultLinkSubstitutionHandler;
import org.opencms.staticexport.CmsLinkManager;
import org.opencms.staticexport.CmsStaticExportManager;
import org.opencms.util.CmsRequestUtil;
import org.opencms.util.CmsStringUtil;
import org.opencms.util.CmsUUID;
import org.opencms.workflow.CmsDefaultWorkflowManager;
import org.opencms.workflow.I_CmsWorkflowManager;
import org.opencms.workplace.CmsWorkplace;
import org.opencms.workplace.CmsWorkplaceManager;
import org.opencms.xml.CmsXmlContentTypeManager;
import org.opencms.xml.containerpage.CmsFormatterConfiguration;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
/**
* The internal implementation of the core OpenCms "operating system" functions.<p>
*
* All access to this class must be done through the public static methods
* of the <code>{@link org.opencms.main.OpenCms}</code> object.
* Under no circumstances should you ever try to access this class directly.<p>
*
* This class is so OpenCms internal you should not even be reading this documentation ;-)<p>
*
* Any request to the <code>{@link org.opencms.main.OpenCmsServlet}</code> will be forwarded to this core class.
* The core will then try to map the request to a VFS (Virtual File System) URI,
* that is a <code>{@link org.opencms.file.CmsResource}</code> in the OpenCms database.
* If a resource is found, it will be read and forwarded to
* to the corresponding <code>{@link org.opencms.loader.I_CmsResourceLoader}</code>,
* which will then generate the output for the requested resource and return it to the requesting client.<p>
*
* There will be only one singleton instance of this object created for
* this core class. This means that in the default configuration, where
* OpenCms is accessed through a servlet context, there will be only one instance of
* the core in that servlet context.<p>
*
* @since 6.0.0
*/
public final class OpenCmsCore {
/** Lock object for synchronization. */
private static final Object LOCK = new Object();
/** The static log object for this class. */
private static final Log LOG = CmsLog.getLog(OpenCmsCore.class);
/** Indicates if the configuration was successfully finished or not. */
private static CmsMessageContainer m_errorCondition;
/** One instance to rule them all, one instance to find them... */
private static OpenCmsCore m_instance;
/** The ADE manager instance. */
private CmsADEManager m_adeManager;
/** The manager for page aliases. */
private CmsAliasManager m_aliasManager;
/** The configured authorization handler. */
private I_CmsAuthorizationHandler m_authorizationHandler;
/** The configuration manager that contains the information from the XML configuration. */
private CmsConfigurationManager m_configurationManager;
/** The object used for resolving database user credentials. */
private I_CmsCredentialsResolver m_credentialsResolver;
/** List of configured directory default file names. */
private List<String> m_defaultFiles;
/** The default user and group names. */
private CmsDefaultUsers m_defaultUsers;
/** The event manager for the event handling. */
private CmsEventManager m_eventManager;
/** The set of configured export points. */
private Set<CmsExportPoint> m_exportPoints;
/** The context objects for GWT services. */
private Map<String, CmsGwtServiceContext> m_gwtServiceContexts;
/** The site manager contains information about the Cms import/export. */
private CmsImportExportManager m_importExportManager;
/** The link manager to resolve links in <cms:link> tags. */
private CmsLinkManager m_linkManager;
/** The locale manager used for obtaining the current locale. */
private CmsLocaleManager m_localeManager;
/** The login manager. */
private CmsLoginManager m_loginManager;
/** The memory monitor for the collection of memory and runtime statistics. */
private CmsMemoryMonitor m_memoryMonitor;
/** The module manager. */
private CmsModuleManager m_moduleManager;
/** The organizational unit manager. */
private CmsOrgUnitManager m_orgUnitManager;
/** The password handler used to digest and validate passwords. */
private I_CmsPasswordHandler m_passwordHandler;
/** The publish engine. */
private CmsPublishEngine m_publishEngine;
/** The publish manager instance. */
private CmsPublishManager m_publishManager;
/** The repository manager. */
private CmsRepositoryManager m_repositoryManager;
/** The configured request handlers that handle "special" requests, for example in the static export on demand. */
private Map<String, I_CmsRequestHandler> m_requestHandlers;
/** Stores the resource init handlers that allow modification of the requested resource. */
private List<I_CmsResourceInit> m_resourceInitHandlers;
/** The resource manager. */
private CmsResourceManager m_resourceManager;
/** The role manager. */
private CmsRoleManager m_roleManager;
/** The runlevel of this OpenCmsCore object instance. */
private int m_runLevel;
/** The runtime properties allow storage of system wide accessible runtime information. */
private Map<Object, Object> m_runtimeProperties;
/** The configured scheduler manager. */
private CmsScheduleManager m_scheduleManager;
/** The search manager provides indexing and searching. */
private CmsSearchManager m_searchManager;
/** The security manager to access the database and validate user permissions. */
private CmsSecurityManager m_securityManager;
/** The session manager. */
private CmsSessionManager m_sessionManager;
/** The site manager contains information about all configured sites. */
private CmsSiteManagerImpl m_siteManager;
/** The static export manager. */
private CmsStaticExportManager m_staticExportManager;
/** The subscription manager. */
private CmsSubscriptionManager m_subscriptionManager;
/** The system information container for "read only" system settings. */
private CmsSystemInfo m_systemInfo;
/** The template context manager. */
private CmsTemplateContextManager m_templateContextManager;
/** The thread store. */
private CmsThreadStore m_threadStore;
/** The runtime validation handler. */
private I_CmsValidationHandler m_validationHandler;
/** The workflow manager instance. */
private I_CmsWorkflowManager m_workflowManager;
/** The workplace manager contains information about the global workplace settings. */
private CmsWorkplaceManager m_workplaceManager;
/** The XML content type manager that contains the initialized XML content types. */
private CmsXmlContentTypeManager m_xmlContentTypeManager;
/**
* Protected constructor that will initialize the singleton OpenCms instance
* with runlevel {@link OpenCms#RUNLEVEL_1_CORE_OBJECT}.<p>
*
* @throws CmsInitException in case of errors during the initialization
*/
private OpenCmsCore()
throws CmsInitException {
synchronized (LOCK) {
if ((m_instance != null) && (m_instance.getRunLevel() > OpenCms.RUNLEVEL_0_OFFLINE)) {
throw new CmsInitException(Messages.get().container(Messages.ERR_ALREADY_INITIALIZED_0));
}
initMembers();
m_instance = this;
setRunLevel(OpenCms.RUNLEVEL_1_CORE_OBJECT);
}
}
/**
* Returns the initialized OpenCms singleton instance.<p>
*
* @return the initialized OpenCms singleton instance
*/
protected static OpenCmsCore getInstance() {
if (m_errorCondition != null) {
// OpenCms is not properly initialized
throw new CmsInitException(m_errorCondition, false);
}
if (m_instance == null) {
try {
// create a new core object with runlevel 1
m_instance = new OpenCmsCore();
} catch (CmsInitException e) {
// already initialized, this is all we need
}
}
return m_instance;
}
/**
* Sets the error condition.<p>
*
* @param errorCondition the error condition to set
*/
protected static void setErrorCondition(CmsMessageContainer errorCondition) {
// init exceptions should only be thrown during setup process
if ((m_instance != null) && (m_instance.getRunLevel() < OpenCms.RUNLEVEL_3_SHELL_ACCESS)) {
if (!Messages.ERR_CRITICAL_INIT_WIZARD_0.equals(errorCondition.getKey())) {
// if wizard is still enabled allow retry of initialization (for setup wizard)
m_errorCondition = errorCondition;
// output an error message to the console
System.err.println(Messages.get().getBundle().key(
Messages.LOG_INIT_FAILURE_MESSAGE_1,
errorCondition.key()));
}
LOG.error(errorCondition.key(), new CmsException(errorCondition));
m_instance = null;
} else if (m_instance != null) {
// OpenCms already was successful initialized
LOG.warn(Messages.get().getBundle().key(
Messages.LOG_INIT_INVALID_ERROR_2,
new Integer(m_instance.getRunLevel()),
errorCondition.key()));
}
}
/**
* Adds the specified request handler to the Map of OpenCms request handlers. <p>
*
* @param handler the handler to add
*/
protected void addRequestHandler(I_CmsRequestHandler handler) {
if (handler == null) {
return;
}
String[] names = handler.getHandlerNames();
for (int i = 0; i < names.length; i++) {
String name = names[i];
if (m_requestHandlers.get(name) != null) {
CmsLog.INIT.error(Messages.get().getBundle().key(Messages.LOG_DUPLICATE_REQUEST_HANDLER_1, name));
continue;
}
m_requestHandlers.put(name, handler);
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(Messages.get().getBundle().key(
Messages.INIT_ADDED_REQUEST_HANDLER_2,
name,
handler.getClass().getName()));
}
}
}
/**
* Gets the ADE manager, and makes sure it is initialized.<p>
*
* @return the initialized ADE manager
*/
protected CmsADEManager getADEManager() {
m_adeManager.initialize();
return m_adeManager;
}
/**
* Returns the alias manager.<p>
*
* @return the alias manager
*/
protected CmsAliasManager getAliasManager() {
return m_aliasManager;
}
/**
* Returns the configured authorization handler.<p>
*
* @return the configured authorization handler
*/
protected I_CmsAuthorizationHandler getAuthorizationHandler() {
return m_authorizationHandler;
}
/**
* Returns the initialized OpenCms configuration manager.<p>
*
* @return the initialized OpenCms configuration manager
*/
protected CmsConfigurationManager getConfigurationManager() {
return m_configurationManager;
}
/**
* Gets the configured credentials resolver instance.<p>
*
* @return the credentials resolver
*/
protected I_CmsCredentialsResolver getCredentialsResolver() {
return m_credentialsResolver;
}
/**
* Returns the configured list of default directory file names.<p>
*
* @return the configured list of default directory file names
*/
protected List<String> getDefaultFiles() {
return m_defaultFiles;
}
/**
* Returns the default user and group name configuration.<p>
*
* @return the default user and group name configuration
*/
protected CmsDefaultUsers getDefaultUsers() {
return m_defaultUsers;
}
/**
* Returns the OpenCms event manager.<p>
*
* @return the OpenCms event manager
*/
protected CmsEventManager getEventManager() {
return m_eventManager;
}
/**
* Returns the configured export points,
* the returned set being an unmodifiable set.<p>
*
* @return an unmodifiable set of the configured export points
*/
protected Set<CmsExportPoint> getExportPoints() {
return m_exportPoints;
}
/**
* Returns the initialized import/export manager,
* which contains information about the Cms import/export.<p>
*
* @return the initialized import/export manager
*/
protected CmsImportExportManager getImportExportManager() {
return m_importExportManager;
}
/**
* Returns the link manager to resolve links in <link> tags.<p>
*
* @return the link manager to resolve links in <link> tags
*/
protected CmsLinkManager getLinkManager() {
return m_linkManager;
}
/**
* Returns the locale manager used for obtaining the current locale.<p>
*
* @return the locale manager
*/
protected CmsLocaleManager getLocaleManager() {
return m_localeManager;
}
/**
* Returns the lock manager used for the locking mechanism.<p>
*
* @return the lock manager used for the locking mechanism
*/
protected CmsLockManager getLockManager() {
return m_securityManager.getLockManager();
}
/**
* Returns the login manager used to check the validity of a login.<p>
*
* @return the login manager
*/
protected CmsLoginManager getLoginManager() {
return m_loginManager;
}
/**
* Returns the memory monitor.<p>
*
* @return the memory monitor
*/
protected CmsMemoryMonitor getMemoryMonitor() {
return m_memoryMonitor;
}
/**
* Returns the module manager.<p>
*
* @return the module manager
*/
protected CmsModuleManager getModuleManager() {
return m_moduleManager;
}
/**
* Returns the organizational unit manager.<p>
*
* @return the organizational unit manager
*/
protected CmsOrgUnitManager getOrgUnitManager() {
return m_orgUnitManager;
}
/**
* Return the password handler.<p>
*
* @return the password handler
*/
protected I_CmsPasswordHandler getPasswordHandler() {
return m_passwordHandler;
}
/**
* Returns the path for the request.<p>
*
* First checks the {@link HttpServletRequest#getPathInfo()}, then
* the configured request error page attribute (if set), and then
* if still undefined the <code>/</code> is returned as path info.<p>
*
* This is only needed when the {@link HttpServletRequest#getPathInfo()}
* is not really working as expected like in BEA WLS 9.x, where we have
* to use the 'weblogic.servlet.errorPage' request attribute.<p>
*
* @param req the http request context
*
* @return the path for the request
*/
protected String getPathInfo(HttpServletRequest req) {
String path = req.getPathInfo();
if (path == null) {
// if the HttpServletRequest#getPathInfo() method does not work properly
String requestErrorPageAttribute = getSystemInfo().getServletContainerSettings().getRequestErrorPageAttribute();
if (requestErrorPageAttribute != null) {
// use the proper page attribute
path = (String)req.getAttribute(requestErrorPageAttribute);
if (path != null) {
int pos = path.indexOf("/", 1);
if (pos > 0) {
// cut off the servlet name
path = path.substring(pos);
}
}
}
}
if (path == null) {
path = "/";
}
return path;
}
/**
* Returns the publish manager instance.<p>
*
* @return the publish manager instance
*/
protected CmsPublishManager getPublishManager() {
return m_publishManager;
}
/**
* Returns the repository manager.<p>
*
* @return the repository manager
*/
protected CmsRepositoryManager getRepositoryManager() {
return m_repositoryManager;
}
/**
* Returns the handler instance for the specified name,
* or null if the name does not match any handler name.<p>
*
* @param name the name of the handler instance to return
* @return the handler instance for the specified name
*/
protected I_CmsRequestHandler getRequestHandler(String name) {
return m_requestHandlers.get(name);
}
/**
* Returns the resource manager.<p>
*
* @return the resource manager
*/
protected CmsResourceManager getResourceManager() {
return m_resourceManager;
}
/**
* Returns the role manager.<p>
*
* @return the role manager
*/
protected CmsRoleManager getRoleManager() {
return m_roleManager;
}
/**
* Returns the runlevel of this OpenCmsCore object instance.<p>
*
* For a detailed description about the possible run levels,
* please see {@link OpenCms#getRunLevel()}.<p>
*
* @return the runlevel of this OpenCmsCore object instance
*
* @see OpenCms#getRunLevel()
*/
protected int getRunLevel() {
return m_runLevel;
}
/**
* Looks up a value in the runtime property Map.<p>
*
* @param key the key to look up in the runtime properties
* @return the value for the key, or null if the key was not found
*/
protected Object getRuntimeProperty(Object key) {
return m_runtimeProperties.get(key);
}
/**
* Returns the configured schedule manager.<p>
*
* @return the configured schedule manager
*/
protected CmsScheduleManager getScheduleManager() {
return m_scheduleManager;
}
/**
* Returns the initialized search manager,
* which provides indexing and searching operations.<p>
*
* @return the initialized search manager
*/
protected CmsSearchManager getSearchManager() {
return m_searchManager;
}
/**
* Returns the initialized OpenCms security manager.<p>
*
* @return the initialized OpenCms security manager
*/
protected CmsSecurityManager getSecurityManager() {
return m_securityManager;
}
/**
* Returns the session manager.<p>
*
* @return the session manager
*/
protected CmsSessionManager getSessionManager() {
return m_sessionManager;
}
/**
* Returns the initialized site manager,
* which contains information about all configured sites.<p>
*
* @return the initialized site manager
*/
protected CmsSiteManagerImpl getSiteManager() {
return m_siteManager;
}
/**
* Returns an instance of the common sql manager.<p>
*
* @return an instance of the common sql manager
*/
protected CmsSqlManager getSqlManager() {
return m_securityManager.getSqlManager();
}
/**
* Returns the properties for the static export.<p>
*
* @return the properties for the static export
*/
protected CmsStaticExportManager getStaticExportManager() {
return m_staticExportManager;
}
/**
* Returns the subscription manager.<p>
*
* @return the subscription manager
*/
protected CmsSubscriptionManager getSubscriptionManager() {
return m_subscriptionManager;
}
/**
* Returns the system information storage.<p>
*
* @return the system information storage
*/
protected CmsSystemInfo getSystemInfo() {
return m_systemInfo;
}
/**
* Gets the template context manager instance.<p>
*
* @return the template context manager instance
*/
protected CmsTemplateContextManager getTemplateContextManager() {
return m_templateContextManager;
}
/**
* Returns the OpenCms Thread store.<p>
*
* @return the OpenCms Thread store
*/
protected CmsThreadStore getThreadStore() {
return m_threadStore;
}
/**
* Returns the runtime validation handler.<p>
*
* @return the validation handler
*/
protected I_CmsValidationHandler getValidationHandler() {
return m_validationHandler;
}
/**
* Returns the workflow manager instance.<p>
*
* @return the workflow manager
*/
protected I_CmsWorkflowManager getWorkflowManager() {
return m_workflowManager;
}
/**
* Returns the initialized workplace manager,
* which contains information about the global workplace settings.<p>
*
* @return the initialized workplace manager
*/
protected CmsWorkplaceManager getWorkplaceManager() {
return m_workplaceManager;
}
/**
* Returns the XML content type manager.<p>
*
* @return the XML content type manager
*/
protected CmsXmlContentTypeManager getXmlContentTypeManager() {
if (m_xmlContentTypeManager != null) {
return m_xmlContentTypeManager;
}
if (getRunLevel() == OpenCms.RUNLEVEL_1_CORE_OBJECT) {
// this is only to enable test cases to run
m_xmlContentTypeManager = CmsXmlContentTypeManager.createTypeManagerForTestCases();
}
return m_xmlContentTypeManager;
}
/**
* Returns an independent copy of the provided CmsObject.<p>
*
* This can be useful in case a permanent reference to a CmsObject is stored.
* Changing the request context values (for example project, siteroot) in the new CmsObject
* will have no side effects to the CmsObject it was copied form.<p>
*
* The request time (<code>{@link CmsRequestContext#getRequestTime()}</code>)
* is set to the current time.<p>
*
* @param cms the CmsObject to create a copy of
*
* @return an independent copy of the provided CmsObject
*
* @throws CmsException in case the initialization failed
*
* @see OpenCms#initCmsObject(CmsObject)
* @see OpenCms#initCmsObject(CmsObject, CmsContextInfo)
* @see OpenCms#initCmsObject(String)
*/
protected CmsObject initCmsObject(CmsObject cms) throws CmsException {
CmsContextInfo contextInfo = new CmsContextInfo(cms.getRequestContext());
contextInfo.setRequestTime(CmsContextInfo.CURRENT_TIME);
return initCmsObject(contextInfo);
}
/**
* Returns an initialized CmsObject with the user and context initialized as provided.<p>
*
* Note: Only if the provided <code>adminCms</code> CmsObject has admin permissions,
* this method allows the creation a CmsObject for any existing user. Otherwise
* only the default users 'Guest' and 'Export' can initialized with
* this method, all other user names will throw an Exception.<p>
*
* @param adminCms must either be initialized with "Admin" permissions, or null
* @param contextInfo the context info to create a CmsObject for
*
* @return an initialized CmsObject with the given users permissions
*
* @throws CmsException if an invalid user name was provided
* @throws CmsRoleViolationException if the current user does not have the role permissions to create a context for the requested user
*
* @see org.opencms.db.CmsDefaultUsers#getUserGuest()
* @see org.opencms.db.CmsDefaultUsers#getUserExport()
* @see OpenCms#initCmsObject(CmsObject)
* @see OpenCms#initCmsObject(CmsObject, CmsContextInfo)
* @see OpenCms#initCmsObject(String)
*/
protected CmsObject initCmsObject(CmsObject adminCms, CmsContextInfo contextInfo)
throws CmsRoleViolationException, CmsException {
String userName = contextInfo.getUserName();
if ((adminCms == null) || !m_roleManager.hasRole(adminCms, CmsRole.ROOT_ADMIN)) {
if (!userName.endsWith(getDefaultUsers().getUserGuest())
&& !userName.endsWith(getDefaultUsers().getUserExport())) {
// if no admin object is provided, only "Guest" or "Export" user can be generated
CmsMessageContainer message = Messages.get().container(
Messages.ERR_INVALID_INIT_USER_2,
userName,
((adminCms != null) ? (adminCms.getRequestContext().getCurrentUser().getName()) : ""));
if (LOG.isWarnEnabled()) {
LOG.warn(message.key());
}
throw new CmsRoleViolationException(message);
}
}
return initCmsObject(contextInfo);
}
/**
* Returns an initialized CmsObject with the user initialized as provided,
* with the "Online" project selected and "/" set as the current site root.<p>
*
* Note: Only the default users 'Guest' and 'Export' can initialized with
* this method, all other user names will throw an Exception.<p>
*
* @param user the user name to initialize, can only be
* {@link org.opencms.db.CmsDefaultUsers#getUserGuest()} or
* {@link org.opencms.db.CmsDefaultUsers#getUserExport()}
*
* @return an initialized CmsObject with the given users permissions
*
* @throws CmsException if an invalid user name was provided, or if something else goes wrong
*
* @see org.opencms.db.CmsDefaultUsers#getUserGuest()
* @see org.opencms.db.CmsDefaultUsers#getUserExport()
* @see OpenCms#initCmsObject(String)
* @see #initCmsObject(CmsObject, CmsContextInfo)
*/
protected CmsObject initCmsObject(String user) throws CmsException {
return initCmsObject(null, new CmsContextInfo(user));
}
/**
* Initializes a new cms object from the session data of the request.<p>
*
* If no session data is found, <code>null</code> is returned.<p>
*
* @param req the request
*
* @return the new initialized cms object
*
* @throws CmsException if something goes wrong
*/
protected CmsObject initCmsObjectFromSession(HttpServletRequest req) throws CmsException {
if (LOG.isDebugEnabled()) {
LOG.debug("Trying to init cms object from session for request \"" + req.toString() + "\".");
}
// try to get an OpenCms user session info object for this request
CmsSessionInfo sessionInfo = m_sessionManager.getSessionInfo(req);
if (sessionInfo == null) {
if (LOG.isDebugEnabled()) {
LOG.debug("No session info found.");
}
return null;
}
// initialize the requested site root
CmsSite site = getSiteManager().matchRequest(req);
// a user name is found in the session manager, reuse this user information
CmsUUID project = sessionInfo.getProject();
// initialize site root from request
String siteroot = null;
// a dedicated workplace site is configured
if ((getSiteManager().getWorkplaceSiteMatcher().equals(site.getSiteMatcher()))) {
// if no dedicated workplace site is configured,
// or for the dedicated workplace site, use the site root from the session attribute
siteroot = sessionInfo.getSiteRoot();
} else if (site.hasSecureServer()
&& getSiteManager().getWorkplaceSiteMatcher().getUrl().equals(site.getSecureUrl())) {
// if the workplace is using the secured site
siteroot = sessionInfo.getSiteRoot();
} else {
siteroot = site.getSiteRoot();
}
// initialize user from request
CmsUser user = m_securityManager.readUser(null, sessionInfo.getUserId());
if (LOG.isDebugEnabled()) {
LOG.debug("Initializing cms object with user \"" + user.getName() + "\".");
}
return initCmsObject(req, user, siteroot, project, sessionInfo.getOrganizationalUnitFqn());
}
/**
* Constructor to create a new OpenCms object.<p>
*
* It reads the configurations from the <code>opencms.properties</code>
* file in the <code>config/</code> subdirectory. With the information
* from this file is inits a ResourceBroker (Database access module),
* various caching systems and other options.<p>
*
* This will only be done once per accessing class.
*
* @param configuration the configurations from the <code>opencms.properties</code> file
* @throws CmsInitException in case OpenCms can not be initialized
*/
protected synchronized void initConfiguration(CmsParameterConfiguration configuration) throws CmsInitException {
String systemEncoding = null;
try {
systemEncoding = System.getProperty("file.encoding");
} catch (SecurityException se) {
// security manager is active, but we will try other options before giving up
}
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_FILE_ENCODING_1, systemEncoding));
}
// read server ethernet address (MAC) and init UUID generator
String ethernetAddress = configuration.getString("server.ethernet.address", CmsUUID.getDummyEthernetAddress());
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_ETHERNET_ADDRESS_1, ethernetAddress));
}
CmsUUID.init(ethernetAddress);
// set the server name
String serverName = configuration.getString("server.name", "OpenCmsServer");
getSystemInfo().setServerName(serverName);
// check the installed Java SDK
try {
if (CmsLog.INIT.isInfoEnabled()) {
String jdkinfo = System.getProperty("java.vm.name") + " ";
jdkinfo += System.getProperty("java.vm.version") + " ";
jdkinfo += System.getProperty("java.vm.info") + " ";
jdkinfo += System.getProperty("java.vm.vendor") + " ";
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_JAVA_VM_1, jdkinfo));
String osinfo = System.getProperty("os.name") + " ";
osinfo += System.getProperty("os.version") + " ";
osinfo += System.getProperty("os.arch") + " ";
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_OPERATING_SYSTEM_1, osinfo));
}
} catch (Exception e) {
throw new CmsInitException(Messages.get().container(Messages.ERR_CRITICAL_INIT_PROP_0), e);
}
// create the configuration manager instance
m_configurationManager = new CmsConfigurationManager(getSystemInfo().getConfigFolder());
// store the configuration read from "opencms.properties" in the configuration manager
m_configurationManager.setConfiguration(configuration);
// now load the XML configuration
try {
m_configurationManager.loadXmlConfiguration();
} catch (Exception e) {
throw new CmsInitException(Messages.get().container(Messages.ERR_CRITICAL_INIT_XML_0), e);
}
// get the system configuration
CmsSystemConfiguration systemConfiguration = (CmsSystemConfiguration)m_configurationManager.getConfiguration(CmsSystemConfiguration.class);
// initialize the memory monitor
CmsMemoryMonitorConfiguration memoryMonitorConfiguration = systemConfiguration.getCmsMemoryMonitorConfiguration();
// initialize the memory monitor
try {
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(memoryMonitorConfiguration.getClassName())) {
m_memoryMonitor = (CmsMemoryMonitor)Class.forName(memoryMonitorConfiguration.getClassName()).newInstance();
} else {
m_memoryMonitor = new CmsMemoryMonitor();
}
} catch (Exception e) {
// we can not start without a valid memory monitor
throw new CmsInitException(Messages.get().container(
Messages.ERR_CRITICAL_INIT_MEMORY_MONITOR_1,
memoryMonitorConfiguration.getClassName()), e);
}
m_memoryMonitor.initialize(systemConfiguration);
// get the event manager from the configuration and initialize it with the events already registered
CmsEventManager configuredEventManager = systemConfiguration.getEventManager();
configuredEventManager.initialize(m_eventManager);
m_eventManager = configuredEventManager;
// check if the encoding setting is valid
String setEncoding = systemConfiguration.getDefaultContentEncoding();
String defaultEncoding = CmsEncoder.lookupEncoding(setEncoding, null);
if (defaultEncoding == null) {
// we can not start without a valid encoding setting
throw new CmsInitException(Messages.get().container(Messages.ERR_CRITICAL_INIT_ENCODING_1, setEncoding));
}
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_OPENCMS_ENCODING_1, defaultEncoding));
}
getSystemInfo().setDefaultEncoding(defaultEncoding);
// set version history information
getSystemInfo().setVersionHistorySettings(
systemConfiguration.isHistoryEnabled(),
systemConfiguration.getHistoryVersions(),
systemConfiguration.getHistoryVersionsAfterDeletion());
// set mail configuration
getSystemInfo().setMailSettings(systemConfiguration.getMailSettings());
// set HTTP authentication settings
getSystemInfo().setHttpAuthenticationSettings(systemConfiguration.getHttpAuthenticationSettings());
// set content notification settings
getSystemInfo().setNotificationTime(systemConfiguration.getNotificationTime());
getSystemInfo().setNotificationProject(systemConfiguration.getNotificationProject());
// set the scheduler manager
m_scheduleManager = systemConfiguration.getScheduleManager();
// set resource init classes
m_resourceInitHandlers = systemConfiguration.getResourceInitHandlers();
// register request handler classes
Iterator<I_CmsRequestHandler> it = systemConfiguration.getRequestHandlers().iterator();
while (it.hasNext()) {
I_CmsRequestHandler handler = it.next();
addRequestHandler(handler);
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(Messages.get().getBundle().key(
Messages.INIT_REQUEST_HANDLER_CLASS_1,
handler.getClass().getName()));
}
}
// read the default user configuration
m_defaultUsers = systemConfiguration.getCmsDefaultUsers();
// get the site manager from the configuration
m_siteManager = systemConfiguration.getSiteManager();
// get the VFS / resource configuration
CmsVfsConfiguration vfsConfiguation = (CmsVfsConfiguration)m_configurationManager.getConfiguration(CmsVfsConfiguration.class);
m_resourceManager = vfsConfiguation.getResourceManager();
m_xmlContentTypeManager = vfsConfiguation.getXmlContentTypeManager();
m_defaultFiles = vfsConfiguation.getDefaultFiles();
// initialize translation engines
m_resourceManager.setTranslators(
vfsConfiguation.getFolderTranslator(),
vfsConfiguation.getFileTranslator(),
vfsConfiguation.getXsdTranslator());
// try to initialize the flex cache
CmsFlexCache flexCache = null;
try {
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_FLEX_CACHE_STARTING_0));
}
// get the flex cache configuration from the SystemConfiguration
CmsFlexCacheConfiguration flexCacheConfiguration = systemConfiguration.getCmsFlexCacheConfiguration();
// pass configuration to flex cache for initialization
flexCache = new CmsFlexCache(flexCacheConfiguration);
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_FLEX_CACHE_FINISHED_0));
}
} catch (Exception e) {
if (CmsLog.INIT.isWarnEnabled()) {
CmsLog.INIT.warn(Messages.get().getBundle().key(Messages.INIT_FLEX_CACHE_ERROR_1, e.getMessage()));
}
}
if (flexCache != null) {
// check all resource loaders if they require the Flex cache
Iterator<I_CmsResourceLoader> i = m_resourceManager.getLoaders().iterator();
while (i.hasNext()) {
Object o = i.next();
if (o instanceof I_CmsFlexCacheEnabledLoader) {
// this resource loader requires the Flex cache
((I_CmsFlexCacheEnabledLoader)o).setFlexCache(flexCache);
}
}
}
// get the import/export configuration
CmsImportExportConfiguration importExportConfiguration = (CmsImportExportConfiguration)m_configurationManager.getConfiguration(CmsImportExportConfiguration.class);
m_importExportManager = importExportConfiguration.getImportExportManager();
m_staticExportManager = importExportConfiguration.getStaticExportManager();
m_repositoryManager = importExportConfiguration.getRepositoryManager();
// get the search configuration
CmsSearchConfiguration searchConfiguration = (CmsSearchConfiguration)m_configurationManager.getConfiguration(CmsSearchConfiguration.class);
m_searchManager = searchConfiguration.getSearchManager();
// get the workplace configuration
CmsWorkplaceConfiguration workplaceConfiguration = (CmsWorkplaceConfiguration)m_configurationManager.getConfiguration(CmsWorkplaceConfiguration.class);
m_workplaceManager = workplaceConfiguration.getWorkplaceManager();
// add the export points from the workplace
addExportPoints(m_workplaceManager.getExportPoints());
// get the module configuration
CmsModuleConfiguration moduleConfiguration = (CmsModuleConfiguration)m_configurationManager.getConfiguration(CmsModuleConfiguration.class);
m_moduleManager = moduleConfiguration.getModuleManager();
// get the password handler
m_passwordHandler = systemConfiguration.getPasswordHandler();
// get the validation handler
m_validationHandler = systemConfiguration.getValidationHandler();
// get the authorization handler
m_authorizationHandler = systemConfiguration.getAuthorizationHandler();
// get the login manager
m_loginManager = systemConfiguration.getLoginManager();
// initialize the publish engine
m_publishEngine = new CmsPublishEngine(systemConfiguration.getRuntimeInfoFactory());
// Credentials resolver - needs to be set before the driver manager is initialized
m_credentialsResolver = systemConfiguration.getCredentialsResolver();
// init the OpenCms security manager
m_securityManager = CmsSecurityManager.newInstance(
m_configurationManager,
systemConfiguration.getRuntimeInfoFactory(),
m_publishEngine);
// get the publish manager
m_publishManager = systemConfiguration.getPublishManager();
// get the subscription manager
m_subscriptionManager = systemConfiguration.getSubscriptionManager();
// initialize the role manager
m_roleManager = new CmsRoleManager(m_securityManager);
// initialize the organizational unit manager
m_orgUnitManager = new CmsOrgUnitManager(m_securityManager);
// initialize the Thread store
m_threadStore = new CmsThreadStore(m_securityManager);
// initialize the link manager
m_linkManager = new CmsLinkManager(m_staticExportManager.getLinkSubstitutionHandler());
m_aliasManager = new CmsAliasManager(m_securityManager);
// store the runtime properties
m_runtimeProperties.putAll(systemConfiguration.getRuntimeProperties());
// initialize the session storage provider
I_CmsSessionStorageProvider sessionStorageProvider = systemConfiguration.getSessionStorageProvider();
// get an Admin cms context object with site root set to "/"
CmsObject adminCms;
try {
adminCms = initCmsObject(null, null, getDefaultUsers().getUserAdmin(), (String)null, (String)null);
} catch (CmsException e) {
throw new CmsInitException(Messages.get().container(Messages.ERR_CRITICAL_INIT_ADMINCMS_0), e);
}
m_repositoryManager.initializeCms(adminCms);
// now initialize the other managers
try {
// initialize the scheduler
m_scheduleManager.initialize(initCmsObject(adminCms));
// initialize the locale manager
m_localeManager = systemConfiguration.getLocaleManager();
m_localeManager.initialize(initCmsObject(adminCms));
// initialize the site manager
m_siteManager.initialize(initCmsObject(adminCms));
// initialize the static export manager
m_staticExportManager.initialize(initCmsObject(adminCms));
// initialize the XML content type manager
m_xmlContentTypeManager.initialize(initCmsObject(adminCms));
// initialize the module manager
m_moduleManager.initialize(initCmsObject(adminCms), m_configurationManager);
// initialize the resource manager
m_resourceManager.initialize(initCmsObject(adminCms));
// initialize the publish manager
m_publishManager.setPublishEngine(m_publishEngine);
m_publishManager.setSecurityManager(m_securityManager);
m_publishManager.initialize(initCmsObject(adminCms));
// initialize the search manager
m_searchManager.initialize(initCmsObject(adminCms));
// initialize the workplace manager
m_workplaceManager.initialize(initCmsObject(adminCms));
// initialize the session manager
m_sessionManager.initialize(sessionStorageProvider);
m_sessionManager.setUserSessionMode(systemConfiguration.getUserSessionMode(true));
// initialize the subscription manager
m_subscriptionManager.setSecurityManager(m_securityManager);
m_subscriptionManager.initialize(adminCms);
// initialize ade manager
// initialize the formatter configuration
CmsFormatterConfiguration.initialize(adminCms);
//m_adeManager = new CmsADEManager(initCmsObject(adminCms), m_memoryMonitor, systemConfiguration);
m_adeManager = new CmsADEManager(adminCms, m_memoryMonitor, systemConfiguration);
m_templateContextManager = new CmsTemplateContextManager(adminCms);
m_workflowManager = systemConfiguration.getWorkflowManager();
if (m_workflowManager == null) {
m_workflowManager = new CmsDefaultWorkflowManager();
m_workflowManager.setParameters(new HashMap<String, String>());
}
m_workflowManager.initialize(adminCms);
} catch (CmsException e) {
throw new CmsInitException(Messages.get().container(Messages.ERR_CRITICAL_INIT_MANAGERS_0), e);
}
}
/**
* Initialization of the OpenCms runtime environment.<p>
*
* The connection information for the database is read
* from the <code>opencms.properties</code> configuration file and all
* driver manager are initialized via the initializer,
* which usually will be an instance of a <code>OpenCms</code> class.
*
* @param context configuration of OpenCms from <code>web.xml</code>
* @throws CmsInitException in case OpenCms can not be initialized
*/
protected synchronized void initContext(ServletContext context) throws CmsInitException {
m_gwtServiceContexts = new HashMap<String, CmsGwtServiceContext>();
// automatic servlet container recognition and specific behavior:
CmsServletContainerSettings servletContainerSettings = new CmsServletContainerSettings(context);
getSystemInfo().init(servletContainerSettings);
// Collect the configurations
CmsParameterConfiguration configuration;
try {
configuration = new CmsParameterConfiguration(getSystemInfo().getConfigurationFileRfsPath());
} catch (Exception e) {
throw new CmsInitException(Messages.get().container(
Messages.ERR_CRITICAL_INIT_PROPFILE_1,
getSystemInfo().getConfigurationFileRfsPath()), e);
}
String throwException = configuration.getString("servlet.exception.enabled", "auto");
if (!throwException.equals("auto")) {
// set the parameter is not automatic, the rest of the servlet container dependent parameters
// will be set when reading the system configuration, if not set to auto
boolean throwExc = Boolean.valueOf(throwException).booleanValue();
getSystemInfo().getServletContainerSettings().setServletThrowsException(throwExc);
}
// check if the wizard is enabled, if so stop initialization
if (configuration.getBoolean("wizard.enabled", true)) {
throw new CmsInitException(Messages.get().container(Messages.ERR_CRITICAL_INIT_WIZARD_0));
}
// output startup message and copyright to STDERR
System.err.println(Messages.get().getBundle().key(
Messages.LOG_STARTUP_CONSOLE_NOTE_2,
OpenCms.getSystemInfo().getVersionNumber(),
getSystemInfo().getWebApplicationName()));
for (int i = 0; i < Messages.COPYRIGHT_BY_ALKACON.length; i++) {
System.err.println(Messages.COPYRIGHT_BY_ALKACON[i]);
}
System.err.println();
// output startup message to log file
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_DOT_0));
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_DOT_0));
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_DOT_0));
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_DOT_0));
for (int i = 0; i < Messages.COPYRIGHT_BY_ALKACON.length; i++) {
CmsLog.INIT.info(". " + Messages.COPYRIGHT_BY_ALKACON[i]);
}
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_LINE_0));
CmsLog.INIT.info(Messages.get().getBundle().key(
Messages.INIT_STARTUP_TIME_1,
new Date(System.currentTimeMillis())));
CmsLog.INIT.info(Messages.get().getBundle().key(
Messages.INIT_OPENCMS_VERSION_1,
OpenCms.getSystemInfo().getVersionNumber()));
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_SERVLET_CONTAINER_1, context.getServerInfo()));
CmsLog.INIT.info(Messages.get().getBundle().key(
Messages.INIT_WEBAPP_NAME_1,
getSystemInfo().getWebApplicationName()));
CmsLog.INIT.info(Messages.get().getBundle().key(
Messages.INIT_SERVLET_PATH_1,
getSystemInfo().getServletPath()));
CmsLog.INIT.info(Messages.get().getBundle().key(
Messages.INIT_OPENCMS_CONTEXT_1,
getSystemInfo().getOpenCmsContext()));
CmsLog.INIT.info(Messages.get().getBundle().key(
Messages.INIT_WEBINF_PATH_1,
getSystemInfo().getWebInfRfsPath()));
CmsLog.INIT.info(Messages.get().getBundle().key(
Messages.INIT_PROPERTY_FILE_1,
getSystemInfo().getConfigurationFileRfsPath()));
CmsLog.INIT.info(Messages.get().getBundle().key(
Messages.INIT_LOG_FILE_1,
getSystemInfo().getLogFileRfsPath()));
}
// initialize the configuration
initConfiguration(configuration);
}
/**
* Initialize member variables.<p>
*/
protected void initMembers() {
synchronized (LOCK) {
m_resourceInitHandlers = new ArrayList<I_CmsResourceInit>();
m_requestHandlers = new HashMap<String, I_CmsRequestHandler>();
m_systemInfo = new CmsSystemInfo();
m_exportPoints = Collections.emptySet();
m_defaultUsers = new CmsDefaultUsers();
m_localeManager = new CmsLocaleManager(Locale.ENGLISH);
m_sessionManager = new CmsSessionManager();
m_runtimeProperties = new Hashtable<Object, Object>();
// the default event manager must be available because the configuration already registers events
m_eventManager = new CmsEventManager();
// default link manager is required for test cases
m_linkManager = new CmsLinkManager(new CmsDefaultLinkSubstitutionHandler());
}
}
/**
* Reads the requested resource from the OpenCms VFS,
* in case a directory name is requested, the default files of the
* directory will be looked up and the first match is returned.<p>
*
* The resource that is returned is always a <code>{@link org.opencms.file.CmsFile}</code>,
* even though the content will usually not be loaded in the result. Folders are never returned since
* the point of this method is really to load the default file if just a folder name is requested. If
* there is no default file in a folder, then the return value is null and no CmsException is thrown.<p>
*
* The URI stored in the given OpenCms user context will be changed to the URI of the resource
* that was found and returned.<p>
*
* Implementing and configuring an <code>{@link I_CmsResourceInit}</code> handler
* allows to customize the process of default resource selection.<p>
*
* @param cms the current users OpenCms context
* @param resourceName the path of the requested resource in the OpenCms VFS
* @param req the current http request
* @param res the current http response
*
* @return the requested resource read from the VFS
*
* @throws CmsException in case the requested file does not exist or the user has insufficient access permissions
*
* @see OpenCms#initResource(CmsObject, String, HttpServletRequest, HttpServletResponse)
*/
protected CmsResource initResource(
CmsObject cms,
String resourceName,
HttpServletRequest req,
HttpServletResponse res) throws CmsException {
CmsException tmpException = null;
CmsResource resource;
try {
// try to read the requested resource
resource = cms.readDefaultFile(resourceName);
} catch (CmsException e) {
// file or folder with given name does not exist, store exception
tmpException = e;
resource = null;
}
if (resource != null) {
// set the request uri to the right file
cms.getRequestContext().setUri(cms.getSitePath(resource));
// test if this file is only available for internal access operations
if (resource.isInternal()) {
throw new CmsException(Messages.get().container(
Messages.ERR_READ_INTERNAL_RESOURCE_1,
cms.getRequestContext().getUri()));
}
// check online project
if (cms.getRequestContext().getCurrentProject().isOnlineProject()) {
// check if resource is secure
boolean secure = Boolean.valueOf(
cms.readPropertyObject(cms.getSitePath(resource), CmsPropertyDefinition.PROPERTY_SECURE, true).getValue()).booleanValue();
if (secure) {
// resource is secure, check site config
CmsSite site = OpenCms.getSiteManager().getCurrentSite(cms);
// check the secure url
String secureUrl = null;
try {
secureUrl = site.getSecureUrl();
} catch (Exception e) {
LOG.error(Messages.get().getBundle().key(
Messages.ERR_SECURE_SITE_NOT_CONFIGURED_1,
resourceName), e);
throw new CmsException(Messages.get().container(
Messages.ERR_SECURE_SITE_NOT_CONFIGURED_1,
resourceName), e);
}
boolean usingSec = true;
if (req != null) {
usingSec = req.getRequestURL().toString().toUpperCase().startsWith(secureUrl.toUpperCase());
}
if (site.isExclusiveUrl() && !usingSec) {
resource = null;
// secure resource without secure protocol, check error config
if (site.isExclusiveError()) {
// trigger 404 error
throw new CmsVfsResourceNotFoundException(Messages.get().container(
Messages.ERR_REQUEST_SECURE_RESOURCE_0));
} else {
// redirect
String target = OpenCms.getLinkManager().getOnlineLink(
cms,
cms.getRequestContext().getUri());
try {
res.sendRedirect(target);
} catch (Exception e) {
// ignore, but should never happen
}
}
}
}
}
}
// test if this file has to be checked or modified
for (I_CmsResourceInit handler : m_resourceInitHandlers) {
try {
resource = handler.initResource(resource, cms, req, res);
// the loop has to be interrupted when the exception is thrown!
} catch (CmsResourceInitException e) {
if (e.isClearErrors()) {
tmpException = null;
}
break;
} catch (CmsSecurityException e) {
tmpException = e;
break;
}
}
// file is still null and not found exception was thrown, so throw original exception
if ((resource == null) && (tmpException != null)) {
throw tmpException;
}
// return the resource read from the VFS
return resource;
}
/**
* Initializes the system with the OpenCms servlet.<p>
*
* This is the final step that is called on the servlets "init()" method.
* It registers the servlets request handler and also outputs the final
* startup message. The servlet should auto-load since the <load-on-startup>
* parameter is set in the 'web.xml' by default.<p>
*
* @param servlet the OpenCms servlet
*/
protected void initServlet(OpenCmsServlet servlet) {
synchronized (LOCK) {
// add the servlets request handler
addRequestHandler(servlet);
// output the final 'startup is finished' message
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(Messages.get().getBundle().key(
Messages.INIT_SYSTEM_RUNNING_1,
CmsStringUtil.formatRuntime(getSystemInfo().getRuntime())));
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_LINE_0));
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_DOT_0));
}
}
}
/**
* Invokes the GWT servlet from within OpenCms.<p>
*
* @param serviceName the GWT PRC service class name
* @param req the current servlet request
* @param res the current servlet response
* @param servletConfig the servlet configuration
*/
protected void invokeGwtService(
String serviceName,
HttpServletRequest req,
HttpServletResponse res,
ServletConfig servletConfig) {
CmsObject cms = null;
try {
// instantiate CMS context
cms = initCmsObject(req, res);
// instantiate GWT RPC service
CmsGwtService rpcService = getGwtService(serviceName, servletConfig);
// check permissions
rpcService.checkPermissions(cms);
// set runtime variables
rpcService.setCms(cms);
try {
Object lock = req.getSession();
if (lock == null) {
lock = new Object();
}
synchronized (lock) {
rpcService.service(req, res);
}
// update the session info
m_sessionManager.updateSessionInfo(cms, req);
} finally {
// be sure to clear the cms context
rpcService.setCms(null);
}
} catch (CmsRoleViolationException rv) {
// don't log these into the error channel
LOG.debug(rv.getLocalizedMessage(), rv);
// error code not set - set "internal server error" (500)
int status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
res.setStatus(status);
try {
res.sendError(status, rv.toString());
} catch (IOException e) {
// can be ignored
LOG.error(e.getLocalizedMessage(), e);
}
} catch (Throwable t) {
// error code not set - set "internal server error" (500)
LOG.error(t.getLocalizedMessage(), t);
int status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
res.setStatus(status);
try {
res.sendError(status, t.toString());
} catch (IOException e) {
// can be ignored
LOG.error(e.getLocalizedMessage(), e);
}
}
}
/**
* This method adds an Object to the OpenCms runtime properties.
* The runtime properties can be used to store Objects that are shared
* in the whole system.<p>
*
* @param key the key to add the Object with
* @param value the value of the Object to add
*/
protected void setRuntimeProperty(Object key, Object value) {
m_runtimeProperties.put(key, value);
}
/**
* Displays a resource from the OpenCms by writing the result to the provided
* Servlet response output stream.<p>
*
* @param req the current servlet request
* @param res the current servlet response
*/
protected void showResource(HttpServletRequest req, HttpServletResponse res) {
CmsObject cms = null;
try {
cms = initCmsObject(req, res);
if (cms.getRequestContext().getCurrentProject().isOnlineProject()) {
String uri = cms.getRequestContext().getUri();
if (OpenCms.getStaticExportManager().isExportLink(cms, uri)) {
String url = OpenCms.getStaticExportManager().getRfsName(cms, uri);
String siteRoot = cms.getRequestContext().getSiteRoot();
url = OpenCms.getSiteManager().getSiteForSiteRoot(siteRoot).getUrl() + url;
res.sendRedirect(url);
return;
}
}
// user is initialized, now deliver the requested resource
CmsResource resource = initResource(cms, cms.getRequestContext().getUri(), req, res);
if (resource != null) {
// a file was read, go on process it
m_resourceManager.loadResource(cms, resource, req, res);
m_sessionManager.updateSessionInfo(cms, req);
}
} catch (Throwable t) {
errorHandling(cms, req, res, t);
}
}
/**
* Destroys this OpenCms instance, called if the servlet (or shell) is shut down.<p>
*/
protected void shutDown() {
synchronized (LOCK) {
if (getRunLevel() > OpenCms.RUNLEVEL_0_OFFLINE) {
System.err.println(Messages.get().getBundle().key(
Messages.LOG_SHUTDOWN_CONSOLE_NOTE_2,
getSystemInfo().getVersionNumber(),
getSystemInfo().getWebApplicationName()));
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_DOT_0));
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_DOT_0));
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_LINE_0));
CmsLog.INIT.info(Messages.get().getBundle().key(
Messages.INIT_SHUTDOWN_START_1,
getSystemInfo().getVersionNumber()));
CmsLog.INIT.info(Messages.get().getBundle().key(
Messages.INIT_CURRENT_RUNLEVEL_1,
new Integer(getRunLevel())));
CmsLog.INIT.info(Messages.get().getBundle().key(
Messages.INIT_SHUTDOWN_TIME_1,
new Date(System.currentTimeMillis())));
}
// take the system offline
setRunLevel(OpenCms.RUNLEVEL_0_OFFLINE);
if (LOG.isDebugEnabled()) {
// log exception to see which method did call the shutdown
LOG.debug(Messages.get().getBundle().key(Messages.LOG_SHUTDOWN_TRACE_0), new Exception());
}
try {
// the first thing we have to do is to wait until the current publish process finishes
m_publishEngine.shutDown();
} catch (Throwable e) {
CmsLog.INIT.error(Messages.get().getBundle().key(
Messages.LOG_ERROR_PUBLISH_SHUTDOWN_1,
e.getMessage()), e);
}
try {
// search manager must be shut down early since there may be background indexing still ongoing
if (m_searchManager != null) {
m_searchManager.shutDown();
}
} catch (Throwable e) {
CmsLog.INIT.error(Messages.get().getBundle().key(
Messages.LOG_ERROR_SEARCH_MANAGER_SHUTDOWN_1,
e.getMessage()), e);
}
try {
if (m_staticExportManager != null) {
m_staticExportManager.shutDown();
}
} catch (Throwable e) {
CmsLog.INIT.error(Messages.get().getBundle().key(
Messages.LOG_ERROR_EXPORT_SHUTDOWN_1,
e.getMessage()), e);
}
try {
if (m_moduleManager != null) {
m_moduleManager.shutDown();
}
} catch (Throwable e) {
CmsLog.INIT.error(Messages.get().getBundle().key(
Messages.LOG_ERROR_MODULE_SHUTDOWN_1,
e.getMessage()), e);
}
try {
if (m_scheduleManager != null) {
m_scheduleManager.shutDown();
}
} catch (Throwable e) {
CmsLog.INIT.error(Messages.get().getBundle().key(
Messages.LOG_ERROR_SCHEDULE_SHUTDOWN_1,
e.getMessage()), e);
}
try {
if (m_resourceManager != null) {
m_resourceManager.shutDown();
}
} catch (Throwable e) {
CmsLog.INIT.error(Messages.get().getBundle().key(
Messages.LOG_ERROR_RESOURCE_SHUTDOWN_1,
e.getMessage()), e);
}
try {
// has to be stopped before the security manager, since this thread uses it
if (m_threadStore != null) {
m_threadStore.shutDown();
}
} catch (Throwable e) {
CmsLog.INIT.error(Messages.get().getBundle().key(
Messages.LOG_ERROR_THREAD_SHUTDOWN_1,
e.getMessage()), e);
}
try {
if (m_securityManager != null) {
m_securityManager.destroy();
}
} catch (Throwable e) {
CmsLog.INIT.error(Messages.get().getBundle().key(
Messages.LOG_ERROR_SECURITY_SHUTDOWN_1,
e.getMessage()), e);
}
try {
if (m_sessionManager != null) {
m_sessionManager.shutdown();
}
} catch (Throwable e) {
CmsLog.INIT.error(Messages.get().getBundle().key(
Messages.LOG_ERROR_SESSION_MANAGER_SHUTDOWN_1,
e.getMessage()), e);
}
try {
if (m_memoryMonitor != null) {
m_memoryMonitor.shutdown();
}
} catch (Throwable e) {
CmsLog.INIT.error(Messages.get().getBundle().key(
Messages.LOG_ERROR_MEMORY_MONITOR_SHUTDOWN_1,
e.getMessage()), e);
}
try {
if (m_adeManager != null) {
m_adeManager.shutdown();
}
} catch (Throwable e) {
CmsLog.INIT.error(Messages.get().getBundle().key(
Messages.LOG_ERROR_ADE_MANAGER_SHUTDOWN_1,
e.getMessage()), e);
}
String runtime = CmsStringUtil.formatRuntime(getSystemInfo().getRuntime());
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_OPENCMS_STOPPED_1, runtime));
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_LINE_0));
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_DOT_0));
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_DOT_0));
}
System.err.println(Messages.get().getBundle().key(Messages.LOG_CONSOLE_TOTAL_RUNTIME_1, runtime));
}
m_instance = null;
}
}
/**
* This method updates the request context information.<p>
*
* The update information is:<br>
* <ul>
* <li>Requested Url</li>
* <li>Locale</li>
* <li>Encoding</li>
* <li>Remote Address</li>
* <li>Request Time</li>
* </ul>
*
* @param request the current request
* @param cms the cms object to update the request context for
*
* @return a new updated cms context
*
* @throws CmsException if something goes wrong
*/
protected CmsObject updateContext(HttpServletRequest request, CmsObject cms) throws CmsException {
// get the right site for the request
CmsSite site = OpenCms.getSiteManager().matchRequest(request);
return initCmsObject(
request,
cms.getRequestContext().getCurrentUser(),
site.getSiteRoot(),
cms.getRequestContext().getCurrentProject().getUuid(),
cms.getRequestContext().getOuFqn());
}
/**
* Upgrades to runlevel {@link OpenCms#RUNLEVEL_3_SHELL_ACCESS},
* this is shell access to the database but no Servlet context.<p>
*
* To upgrade the runlevel, the system must be in runlevel {@link OpenCms#RUNLEVEL_1_CORE_OBJECT},
* otherwise an exception is thrown.<p>
*
* @param configuration the configuration
* @throws CmsInitException in case OpenCms can not be initialized
* @return the initialized OpenCmsCore
*/
protected OpenCmsCore upgradeRunlevel(CmsParameterConfiguration configuration) throws CmsInitException {
synchronized (LOCK) {
if ((m_instance != null) && (getRunLevel() >= OpenCms.RUNLEVEL_2_INITIALIZING)) {
// instance already in runlevel 3 or 4
return m_instance;
}
if (getRunLevel() != OpenCms.RUNLEVEL_1_CORE_OBJECT) {
CmsLog.INIT.error(Messages.get().getBundle().key(
Messages.LOG_WRONG_INIT_SEQUENCE_2,
new Integer(3),
new Integer(getRunLevel())));
return m_instance;
}
// set the runlevel to "initializing OpenCms"
setRunLevel(OpenCms.RUNLEVEL_2_INITIALIZING);
// initialize the configuration
m_instance.initConfiguration(configuration);
// upgrade the runlevel - OpenCms shell is available
setRunLevel(OpenCms.RUNLEVEL_3_SHELL_ACCESS);
afterUpgradeRunlevel();
return m_instance;
}
}
/**
* Upgrades to runlevel {@link OpenCms#RUNLEVEL_4_SERVLET_ACCESS},
* this is the final runlevel with an initialized database and Servlet context.<p>
*
* To upgrade the runlevel, the system must be in runlevel {@link OpenCms#RUNLEVEL_1_CORE_OBJECT},
* otherwise an exception is thrown.<p>
*
* @param context the current servlet context
* @throws CmsInitException in case OpenCms can not be initialized
* @return the initialized OpenCmsCore
*/
protected OpenCmsCore upgradeRunlevel(ServletContext context) throws CmsInitException {
synchronized (LOCK) {
if ((m_instance != null) && (getRunLevel() >= OpenCms.RUNLEVEL_4_SERVLET_ACCESS)) {
// instance already in runlevel 5 or 6
return m_instance;
}
if (getRunLevel() != OpenCms.RUNLEVEL_1_CORE_OBJECT) {
CmsLog.INIT.error(Messages.get().getBundle().key(
Messages.LOG_WRONG_INIT_SEQUENCE_2,
new Integer(4),
new Integer(getRunLevel())));
return m_instance;
}
// set the runlevel to "initializing OpenCms"
setRunLevel(OpenCms.RUNLEVEL_2_INITIALIZING);
// initialize the servlet context
m_instance.initContext(context);
// initialization successfully finished - OpenCms servlet is online
// the runlevel will change from 2 directly to 4, this is on purpose
setRunLevel(OpenCms.RUNLEVEL_4_SERVLET_ACCESS);
afterUpgradeRunlevel();
return m_instance;
}
}
/**
* Writes the XML configuration for the provided configuration class.<p>
*
* @param clazz the configuration class to write the XML for
*/
protected void writeConfiguration(Class<?> clazz) {
// exception handling is provided here to ensure identical log messages
try {
m_configurationManager.writeConfiguration(clazz);
} catch (IOException e) {
CmsLog.getLog(CmsConfigurationManager.class).error(
Messages.get().getBundle().key(Messages.LOG_ERROR_WRITING_CONFIG_1, clazz.getName()),
e);
} catch (CmsConfigurationException e) {
CmsLog.getLog(CmsConfigurationManager.class).error(
Messages.get().getBundle().key(Messages.LOG_ERROR_WRITING_CONFIG_1, clazz.getName()),
e);
}
}
/**
* Adds the given set of export points to the list of all configured export points.<p>
*
* @param exportPoints the export points to add
*/
private void addExportPoints(Set<CmsExportPoint> exportPoints) {
// create a new immutable set of export points
HashSet<CmsExportPoint> newSet = new HashSet<CmsExportPoint>(m_exportPoints.size() + exportPoints.size());
newSet.addAll(exportPoints);
newSet.addAll(m_exportPoints);
m_exportPoints = Collections.unmodifiableSet(newSet);
}
/**
* Finishes the startup sequence after last runlevel upgrade.<p>
*/
private void afterUpgradeRunlevel() {
try {
// read the persistent locks
m_instance.m_securityManager.readLocks();
} catch (CmsException e) {
if (LOG.isErrorEnabled()) {
LOG.error(
org.opencms.lock.Messages.get().getBundle().key(org.opencms.lock.Messages.ERR_READ_LOCKS_0),
e);
}
}
// everything is initialized, now start publishing
m_publishManager.startPublishing();
}
/**
* Generates a formated exception output.<p>
*
* Because the exception could be thrown while accessing the system files,
* the complete HTML code must be added here!<p>
*
* @param t the caught Exception
* @param request the servlet request
* @param cms the CmsObject
* @return String containing the HTML code of the error message
*/
private String createErrorBox(Throwable t, HttpServletRequest request, CmsObject cms) {
String errorUri = CmsFlexController.getThrowableResourceUri(request);
if (errorUri == null) {
errorUri = cms.getRequestContext().getUri();
}
// try to get the exception root cause
Throwable cause = CmsFlexController.getThrowable(request);
if (cause == null) {
cause = t;
}
CmsErrorBean errorBean = new CmsErrorBean(cms, cause);
errorBean.setParamAction(errorUri);
return errorBean.toHtml();
}
/**
* This method performs the error handling for OpenCms.<p>
*
* @param cms the current cms context, might be null !
* @param req the client request
* @param res the client response
* @param t the exception that occurred
*/
private void errorHandling(CmsObject cms, HttpServletRequest req, HttpServletResponse res, Throwable t) {
// remove the controller attribute from the request
CmsFlexController.removeController(req);
boolean canWrite = (!res.isCommitted() && !res.containsHeader("Location"));
int status = -1;
boolean isGuest = true;
if (t instanceof ServletException) {
ServletException s = (ServletException)t;
if (s.getRootCause() != null) {
t = s.getRootCause();
}
} else if (t instanceof CmsSecurityException) {
// access error - display login dialog
if (canWrite) {
try {
m_authorizationHandler.requestAuthorization(req, res, getLoginFormURL(req, res));
} catch (IOException ioe) {
// there is nothing we can do about this
}
return;
}
} else if (t instanceof CmsDbEntryNotFoundException) {
// user or group does not exist
status = HttpServletResponse.SC_SERVICE_UNAVAILABLE;
isGuest = false;
} else if (t instanceof CmsVfsResourceNotFoundException) {
// file not found - display 404 error.
status = HttpServletResponse.SC_NOT_FOUND;
} else if (t instanceof CmsException) {
if (t.getCause() != null) {
t = t.getCause();
}
LOG.error(t.getLocalizedMessage() + " rendering URL " + req.getRequestURL(), t);
} else {
LOG.error(t.getLocalizedMessage() + " rendering URL " + req.getRequestURL(), t);
}
if (status < 1) {
// error code not set - set "internal server error" (500)
status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
}
res.setStatus(status);
try {
if ((cms != null) && (cms.getRequestContext().getCurrentUser() != null)) {
isGuest = isGuest
&& (cms.getRequestContext().getCurrentUser().isGuestUser() || cms.userInGroup(
cms.getRequestContext().getCurrentUser().getName(),
OpenCms.getDefaultUsers().getGroupGuests()));
}
} catch (CmsException e) {
// result is false
LOG.error(e.getLocalizedMessage(), e);
}
if (canWrite) {
res.setContentType("text/html");
CmsRequestUtil.setNoCacheHeaders(res);
if (!isGuest && (cms != null) && !cms.getRequestContext().getCurrentProject().isOnlineProject()) {
try {
res.setStatus(HttpServletResponse.SC_OK);
res.getWriter().print(createErrorBox(t, req, cms));
} catch (IOException e) {
// can be ignored
LOG.error(e.getLocalizedMessage(), e);
}
} else {
try {
res.sendError(status, t.toString());
} catch (IOException e) {
// can be ignored
LOG.error(e.getLocalizedMessage(), e);
}
}
}
}
/**
*
*
* @param serviceName the GWT PRC service class name
* @param servletConfig the servlet configuration
*
* @return the GWT service instance
*
* @throws Throwable if something goes wrong
*/
private synchronized CmsGwtService getGwtService(String serviceName, ServletConfig servletConfig) throws Throwable {
CmsGwtServiceContext context = m_gwtServiceContexts.get(serviceName);
if (context == null) {
context = new CmsGwtServiceContext(serviceName);
m_gwtServiceContexts.put(serviceName, context);
}
CmsGwtService gwtService = (CmsGwtService)Class.forName(serviceName).newInstance();
gwtService.init(servletConfig);
gwtService.setContext(context);
return gwtService;
}
/**
* Reads the login form which should be used for authenticating the current request.<p>
*
* @param req current request
* @param res current response
*
* @return the URL of the login form or <code>null</code> if not set
*
* @throws IOException
*/
private String getLoginFormURL(HttpServletRequest req, HttpServletResponse res) throws IOException {
CmsHttpAuthenticationSettings httpAuthenticationSettings = OpenCms.getSystemInfo().getHttpAuthenticationSettings();
String loginFormURL = null;
// this will create an admin user with the "right" site root already set
CmsObject adminCms;
try {
adminCms = initCmsObject(req, res, OpenCms.getDefaultUsers().getUserAdmin(), null, null);
} catch (CmsException e) {
// this should never happen, if it does we can't continue
throw new IOException(Messages.get().getBundle().key(
Messages.ERR_INVALID_INIT_USER_2,
OpenCms.getDefaultUsers().getUserAdmin(),
null));
}
// get the requested resource
String path = adminCms.getRequestContext().getUri();
CmsProperty propertyLoginForm = null;
try {
propertyLoginForm = adminCms.readPropertyObject(path, CmsPropertyDefinition.PROPERTY_LOGIN_FORM, true);
} catch (Throwable t) {
if (LOG.isWarnEnabled()) {
LOG.warn(Messages.get().getBundle().key(
Messages.LOG_ERROR_READING_AUTH_PROP_2,
CmsPropertyDefinition.PROPERTY_LOGIN_FORM,
path), t);
}
}
String params = null;
if ((propertyLoginForm != null)
&& (propertyLoginForm != CmsProperty.getNullProperty())
&& CmsStringUtil.isNotEmpty(propertyLoginForm.getValue())) {
// login form property value was found
// build a redirect URL using the value of the property
// "__loginform" is a dummy request parameter that could be used in a JSP template to trigger
// if the template should display a login formular or not
loginFormURL = propertyLoginForm.getValue();
params = "__loginform=true";
} else if (!httpAuthenticationSettings.useBrowserBasedHttpAuthentication()
&& CmsStringUtil.isNotEmpty(httpAuthenticationSettings.getFormBasedHttpAuthenticationUri())) {
// login form property value not set, but form login set in configuration
// build a redirect URL to the default login form URI configured in opencms.properties
loginFormURL = httpAuthenticationSettings.getFormBasedHttpAuthenticationUri();
}
String callbackURL = CmsRequestUtil.encodeParamsWithUri(path, req);
if (loginFormURL != null) {
if (!loginFormURL.startsWith("http")) {
loginFormURL = m_linkManager.substituteLink(adminCms, loginFormURL, null, true);
} else {
callbackURL = m_linkManager.getServerLink(adminCms, path);
callbackURL = CmsRequestUtil.encodeParamsWithUri(callbackURL, req);
}
}
return m_authorizationHandler.getLoginFormURL(loginFormURL, params, callbackURL);
}
/**
* Initializes a CmsObject with the given context information.<p>
*
* @param contextInfo the information for the CmsObject context to create
*
* @return the initialized CmsObject
*
* @throws CmsException if something goes wrong
*/
private CmsObject initCmsObject(CmsContextInfo contextInfo) throws CmsException {
CmsUser user = contextInfo.getUser();
if (user == null) {
user = m_securityManager.readUser(null, contextInfo.getUserName());
}
CmsProject project = contextInfo.getProject();
if (project == null) {
project = m_securityManager.readProject(contextInfo.getProjectName());
}
// first create the request context
CmsRequestContext context = new CmsRequestContext(
user,
project,
contextInfo.getRequestedUri(),
contextInfo.getSiteRoot(),
contextInfo.getLocale(),
contextInfo.getEncoding(),
contextInfo.getRemoteAddr(),
contextInfo.getRequestTime(),
m_resourceManager.getFolderTranslator(),
m_resourceManager.getFileTranslator(),
contextInfo.getOuFqn());
// now initialize and return the CmsObject
return new CmsObject(m_securityManager, context);
}
/**
* Initializes a {@link CmsObject} with the given users information.<p>
*
* @param request the current http request (or <code>null</code>)
* @param user the initialized user
* @param siteRoot the users current site
* @param projectId the id of the users current project
* @param ouFqn the organizational unit
*
* @return the initialized CmsObject
*
* @throws CmsException in case something goes wrong
*/
private CmsObject initCmsObject(
HttpServletRequest request,
CmsUser user,
String siteRoot,
CmsUUID projectId,
String ouFqn) throws CmsException {
CmsProject project = null;
try {
project = m_securityManager.readProject(projectId);
} catch (CmsDbEntryNotFoundException e) {
// project not found, switch to online project
project = m_securityManager.readProject(CmsProject.ONLINE_PROJECT_ID);
}
// get requested resource uri and remote IP address, as well as time for "time warp" browsing
String requestedResource = null;
Long requestTimeAttr = null;
String remoteAddr;
if (request != null) {
// get path info from request
requestedResource = getPathInfo(request);
// check for special header for remote address
remoteAddr = request.getHeader(CmsRequestUtil.HEADER_X_FORWARDED_FOR);
if (remoteAddr == null) {
// if header is not available, use default remote address
remoteAddr = request.getRemoteAddr();
}
// check for special "time warp" browsing
HttpSession session = request.getSession(false);
if (session != null) {
// no new session must be created here
requestTimeAttr = (Long)session.getAttribute(CmsContextInfo.ATTRIBUTE_REQUEST_TIME);
}
} else {
// if no request is available, the IP is always set to localhost
remoteAddr = CmsContextInfo.LOCALHOST;
}
if (requestedResource == null) {
// path info can still be null
requestedResource = "/";
}
// calculate the request time
long requestTime;
if (requestTimeAttr == null) {
requestTime = System.currentTimeMillis();
} else {
requestTime = requestTimeAttr.longValue();
}
// get locale and encoding
CmsI18nInfo i18nInfo;
if (m_localeManager.isInitialized()) {
// locale manager is initialized
// resolve locale and encoding
if (requestedResource.endsWith(OpenCmsServlet.HANDLE_GWT) && (request != null)) {
// GWT RPC call, always keep the request encoding and use the default locale
i18nInfo = new CmsI18nInfo(CmsLocaleManager.getDefaultLocale(), request.getCharacterEncoding());
} else {
String resourceName;
if (requestedResource.startsWith(CmsWorkplace.VFS_PATH_SYSTEM)) {
// add site root only if resource name does not start with "/system"
resourceName = requestedResource;
} else if (OpenCms.getSiteManager().startsWithShared(requestedResource)) {
resourceName = requestedResource;
} else {
resourceName = siteRoot.concat(requestedResource);
}
i18nInfo = m_localeManager.getI18nInfo(request, user, project, resourceName);
}
} else {
// locale manager not initialized, this will be true _only_ during system startup
// the values set does not matter, no locale information form VFS is used on system startup
// this is just to protect against null pointer exceptions
i18nInfo = new CmsI18nInfo(Locale.ENGLISH, getSystemInfo().getDefaultEncoding());
}
// decode the requested resource, always using UTF-8
requestedResource = CmsEncoder.decode(requestedResource);
// initialize the context info
CmsContextInfo contextInfo = new CmsContextInfo(
user,
project,
requestedResource,
siteRoot,
i18nInfo.getLocale(),
i18nInfo.getEncoding(),
remoteAddr,
requestTime,
ouFqn);
// now generate and return the CmsObject
return initCmsObject(contextInfo);
}
/**
* Handles the user authentification for each request sent to OpenCms.<p>
*
* User authentification is done in three steps:
* <ol>
* <li>Session authentification: OpenCms stores information of all authentificated
* users in an internal storage based on the users session.</li>
* <li>Authorization handler authentification: If the session authentification fails,
* the current configured authorization handler is called.</li>
* <li>Default user: When both authentification methods fail, the user is set to
* the default (Guest) user.</li>
* </ol>
*
* @param req the current http request
* @param res the current http response
*
* @return the initialized cms context
*
* @throws IOException if user authentication fails
* @throws CmsException in case something goes wrong
*/
private CmsObject initCmsObject(HttpServletRequest req, HttpServletResponse res) throws IOException, CmsException {
// first try to restore a stored session
CmsObject cms = initCmsObjectFromSession(req);
if (cms != null) {
return cms;
}
// if does not work, try to authorize the request
I_CmsAuthorizationHandler.I_PrivilegedLoginAction loginAction = new I_CmsAuthorizationHandler.I_PrivilegedLoginAction() {
private CmsObject m_adminCms;
/**
* @see org.opencms.security.I_CmsAuthorizationHandler.I_PrivilegedLoginAction#doLogin(javax.servlet.http.HttpServletRequest, java.lang.String)
*/
public CmsObject doLogin(HttpServletRequest request, String principal) throws CmsException {
try {
CmsUser user = m_adminCms.readUser(principal);
if (!user.isEnabled()) {
throw new CmsException(Messages.get().container(
Messages.ERR_INVALID_INIT_USER_2,
user.getName(),
"-"));
}
// initialize the new cms object
CmsContextInfo contextInfo = new CmsContextInfo(m_adminCms.getRequestContext());
contextInfo.setUserName(principal);
CmsObject newCms = initCmsObject(m_adminCms, contextInfo);
if (contextInfo.getRequestedUri().startsWith("/system/workplace/")
&& getRoleManager().hasRole(newCms, CmsRole.WORKPLACE_USER)) {
// set the default project of the user for workplace users
CmsUserSettings settings = new CmsUserSettings(newCms);
try {
CmsProject project = newCms.readProject(settings.getStartProject());
if (getOrgUnitManager().getAllAccessibleProjects(newCms, project.getOuFqn(), false).contains(
project)) {
// user has access to the project, set this as current project
newCms.getRequestContext().setCurrentProject(project);
}
} catch (CmsException e) {
// unable to set the startup project, bad but not critical
}
}
return newCms;
} finally {
m_adminCms = null;
}
}
/**
* @see org.opencms.security.I_CmsAuthorizationHandler.I_PrivilegedLoginAction#getCmsObject()
*/
public CmsObject getCmsObject() {
return m_adminCms;
}
/**
* @see org.opencms.security.I_CmsAuthorizationHandler.I_PrivilegedLoginAction#setCmsObject(org.opencms.file.CmsObject)
*/
public void setCmsObject(CmsObject adminCms) {
m_adminCms = adminCms;
}
};
loginAction.setCmsObject(initCmsObject(req, res, OpenCms.getDefaultUsers().getUserAdmin(), null, null));
cms = m_authorizationHandler.initCmsObject(req, loginAction);
if (cms != null) {
return cms;
}
// authentification failed or not enough permissions, so display a login screen
m_authorizationHandler.requestAuthorization(req, res, getLoginFormURL(req, res));
cms = initCmsObject(
req,
m_securityManager.readUser(null, OpenCms.getDefaultUsers().getUserGuest()),
getSiteManager().matchRequest(req).getSiteRoot(),
CmsProject.ONLINE_PROJECT_ID,
"");
// return the initialized cms user context object
return cms;
}
/**
* Returns an initialized CmsObject with the given users permissions.<p>
*
* In case the password is <code>null</code>, or the user is the <code>Guest</code> user,
* no password check is done. Therefore you can initialize all users without knowing their passwords
* by just supplying <code>null</code> as password. This is intended only for
* internal operation in the core.<p>
*
* @param req the current request
* @param res the current response
* @param user the user to initialize the CmsObject with
* @param password the password of the user
* @param ouFqn the organizational unit, if <code>null</code> the users ou is used
*
* @return a cms context that has been initialized with "Guest" permissions
*
* @throws CmsException in case the CmsObject could not be initialized
*/
private CmsObject initCmsObject(
HttpServletRequest req,
HttpServletResponse res,
String user,
String password,
String ouFqn) throws CmsException {
String siteroot = null;
// gather information from request if provided
if (req != null) {
siteroot = OpenCms.getSiteManager().matchRequest(req).getSiteRoot();
}
// initialize the user
if (user == null) {
user = getDefaultUsers().getUserGuest();
}
if (siteroot == null) {
siteroot = "/";
}
CmsObject cms = initCmsObject(
req,
m_securityManager.readUser(null, user),
siteroot,
CmsProject.ONLINE_PROJECT_ID,
ouFqn);
// login the user if different from Guest and password was provided
if ((password != null) && !getDefaultUsers().isUserGuest(user)) {
cms.loginUser(user, password, CmsContextInfo.LOCALHOST);
}
return cms;
}
/**
* Sets the init level of this OpenCmsCore object instance.<p>
*
* For a detailed description about the possible run levels,
* please see {@link OpenCms#getRunLevel()}.<p>
*
* @param level the level to set
*/
private void setRunLevel(int level) {
if (m_instance != null) {
if (m_instance.m_runLevel >= OpenCms.RUNLEVEL_1_CORE_OBJECT) {
// otherwise the log is not available
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(Messages.get().getBundle().key(
Messages.INIT_RUNLEVEL_CHANGE_2,
new Integer(m_instance.m_runLevel),
new Integer(level)));
}
}
m_instance.m_runLevel = level;
}
}
}
| src/org/opencms/main/OpenCmsCore.java | /*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (c) Alkacon Software GmbH (http://www.alkacon.com)
*
* 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.
*
* For further information about Alkacon Software GmbH, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.opencms.main;
import org.opencms.ade.configuration.CmsADEManager;
import org.opencms.configuration.CmsConfigurationException;
import org.opencms.configuration.CmsConfigurationManager;
import org.opencms.configuration.CmsImportExportConfiguration;
import org.opencms.configuration.CmsModuleConfiguration;
import org.opencms.configuration.CmsParameterConfiguration;
import org.opencms.configuration.CmsSearchConfiguration;
import org.opencms.configuration.CmsSystemConfiguration;
import org.opencms.configuration.CmsVfsConfiguration;
import org.opencms.configuration.CmsWorkplaceConfiguration;
import org.opencms.db.CmsAliasManager;
import org.opencms.db.CmsDbEntryNotFoundException;
import org.opencms.db.CmsDefaultUsers;
import org.opencms.db.CmsExportPoint;
import org.opencms.db.CmsLoginManager;
import org.opencms.db.CmsSecurityManager;
import org.opencms.db.CmsSqlManager;
import org.opencms.db.CmsSubscriptionManager;
import org.opencms.db.CmsUserSettings;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsProject;
import org.opencms.file.CmsProperty;
import org.opencms.file.CmsPropertyDefinition;
import org.opencms.file.CmsRequestContext;
import org.opencms.file.CmsResource;
import org.opencms.file.CmsUser;
import org.opencms.file.CmsVfsResourceNotFoundException;
import org.opencms.flex.CmsFlexCache;
import org.opencms.flex.CmsFlexCacheConfiguration;
import org.opencms.flex.CmsFlexController;
import org.opencms.gwt.CmsGwtService;
import org.opencms.gwt.CmsGwtServiceContext;
import org.opencms.i18n.CmsEncoder;
import org.opencms.i18n.CmsI18nInfo;
import org.opencms.i18n.CmsLocaleManager;
import org.opencms.i18n.CmsMessageContainer;
import org.opencms.importexport.CmsImportExportManager;
import org.opencms.jsp.util.CmsErrorBean;
import org.opencms.loader.CmsResourceManager;
import org.opencms.loader.CmsTemplateContextManager;
import org.opencms.loader.I_CmsFlexCacheEnabledLoader;
import org.opencms.loader.I_CmsResourceLoader;
import org.opencms.lock.CmsLockManager;
import org.opencms.module.CmsModuleManager;
import org.opencms.monitor.CmsMemoryMonitor;
import org.opencms.monitor.CmsMemoryMonitorConfiguration;
import org.opencms.publish.CmsPublishEngine;
import org.opencms.publish.CmsPublishManager;
import org.opencms.repository.CmsRepositoryManager;
import org.opencms.scheduler.CmsScheduleManager;
import org.opencms.search.CmsSearchManager;
import org.opencms.security.CmsOrgUnitManager;
import org.opencms.security.CmsRole;
import org.opencms.security.CmsRoleManager;
import org.opencms.security.CmsRoleViolationException;
import org.opencms.security.CmsSecurityException;
import org.opencms.security.I_CmsAuthorizationHandler;
import org.opencms.security.I_CmsCredentialsResolver;
import org.opencms.security.I_CmsPasswordHandler;
import org.opencms.security.I_CmsValidationHandler;
import org.opencms.site.CmsSite;
import org.opencms.site.CmsSiteManagerImpl;
import org.opencms.staticexport.CmsDefaultLinkSubstitutionHandler;
import org.opencms.staticexport.CmsLinkManager;
import org.opencms.staticexport.CmsStaticExportManager;
import org.opencms.util.CmsRequestUtil;
import org.opencms.util.CmsStringUtil;
import org.opencms.util.CmsUUID;
import org.opencms.workflow.CmsDefaultWorkflowManager;
import org.opencms.workflow.I_CmsWorkflowManager;
import org.opencms.workplace.CmsWorkplace;
import org.opencms.workplace.CmsWorkplaceManager;
import org.opencms.xml.CmsXmlContentTypeManager;
import org.opencms.xml.containerpage.CmsFormatterConfiguration;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
/**
* The internal implementation of the core OpenCms "operating system" functions.<p>
*
* All access to this class must be done through the public static methods
* of the <code>{@link org.opencms.main.OpenCms}</code> object.
* Under no circumstances should you ever try to access this class directly.<p>
*
* This class is so OpenCms internal you should not even be reading this documentation ;-)<p>
*
* Any request to the <code>{@link org.opencms.main.OpenCmsServlet}</code> will be forwarded to this core class.
* The core will then try to map the request to a VFS (Virtual File System) URI,
* that is a <code>{@link org.opencms.file.CmsResource}</code> in the OpenCms database.
* If a resource is found, it will be read and forwarded to
* to the corresponding <code>{@link org.opencms.loader.I_CmsResourceLoader}</code>,
* which will then generate the output for the requested resource and return it to the requesting client.<p>
*
* There will be only one singleton instance of this object created for
* this core class. This means that in the default configuration, where
* OpenCms is accessed through a servlet context, there will be only one instance of
* the core in that servlet context.<p>
*
* @since 6.0.0
*/
public final class OpenCmsCore {
/** Lock object for synchronization. */
private static final Object LOCK = new Object();
/** The static log object for this class. */
private static final Log LOG = CmsLog.getLog(OpenCmsCore.class);
/** Indicates if the configuration was successfully finished or not. */
private static CmsMessageContainer m_errorCondition;
/** One instance to rule them all, one instance to find them... */
private static OpenCmsCore m_instance;
/** The ADE manager instance. */
private CmsADEManager m_adeManager;
/** The manager for page aliases. */
private CmsAliasManager m_aliasManager;
/** The configured authorization handler. */
private I_CmsAuthorizationHandler m_authorizationHandler;
/** The configuration manager that contains the information from the XML configuration. */
private CmsConfigurationManager m_configurationManager;
/** The object used for resolving database user credentials. */
private I_CmsCredentialsResolver m_credentialsResolver;
/** List of configured directory default file names. */
private List<String> m_defaultFiles;
/** The default user and group names. */
private CmsDefaultUsers m_defaultUsers;
/** The event manager for the event handling. */
private CmsEventManager m_eventManager;
/** The set of configured export points. */
private Set<CmsExportPoint> m_exportPoints;
/** The context objects for GWT services. */
private Map<String, CmsGwtServiceContext> m_gwtServiceContexts;
/** The site manager contains information about the Cms import/export. */
private CmsImportExportManager m_importExportManager;
/** The link manager to resolve links in <cms:link> tags. */
private CmsLinkManager m_linkManager;
/** The locale manager used for obtaining the current locale. */
private CmsLocaleManager m_localeManager;
/** The login manager. */
private CmsLoginManager m_loginManager;
/** The memory monitor for the collection of memory and runtime statistics. */
private CmsMemoryMonitor m_memoryMonitor;
/** The module manager. */
private CmsModuleManager m_moduleManager;
/** The organizational unit manager. */
private CmsOrgUnitManager m_orgUnitManager;
/** The password handler used to digest and validate passwords. */
private I_CmsPasswordHandler m_passwordHandler;
/** The publish engine. */
private CmsPublishEngine m_publishEngine;
/** The publish manager instance. */
private CmsPublishManager m_publishManager;
/** The repository manager. */
private CmsRepositoryManager m_repositoryManager;
/** The configured request handlers that handle "special" requests, for example in the static export on demand. */
private Map<String, I_CmsRequestHandler> m_requestHandlers;
/** Stores the resource init handlers that allow modification of the requested resource. */
private List<I_CmsResourceInit> m_resourceInitHandlers;
/** The resource manager. */
private CmsResourceManager m_resourceManager;
/** The role manager. */
private CmsRoleManager m_roleManager;
/** The runlevel of this OpenCmsCore object instance. */
private int m_runLevel;
/** The runtime properties allow storage of system wide accessible runtime information. */
private Map<Object, Object> m_runtimeProperties;
/** The configured scheduler manager. */
private CmsScheduleManager m_scheduleManager;
/** The search manager provides indexing and searching. */
private CmsSearchManager m_searchManager;
/** The security manager to access the database and validate user permissions. */
private CmsSecurityManager m_securityManager;
/** The session manager. */
private CmsSessionManager m_sessionManager;
/** The site manager contains information about all configured sites. */
private CmsSiteManagerImpl m_siteManager;
/** The static export manager. */
private CmsStaticExportManager m_staticExportManager;
/** The subscription manager. */
private CmsSubscriptionManager m_subscriptionManager;
/** The system information container for "read only" system settings. */
private CmsSystemInfo m_systemInfo;
/** The template context manager. */
private CmsTemplateContextManager m_templateContextManager;
/** The thread store. */
private CmsThreadStore m_threadStore;
/** The runtime validation handler. */
private I_CmsValidationHandler m_validationHandler;
/** The workflow manager instance. */
private I_CmsWorkflowManager m_workflowManager;
/** The workplace manager contains information about the global workplace settings. */
private CmsWorkplaceManager m_workplaceManager;
/** The XML content type manager that contains the initialized XML content types. */
private CmsXmlContentTypeManager m_xmlContentTypeManager;
/**
* Protected constructor that will initialize the singleton OpenCms instance
* with runlevel {@link OpenCms#RUNLEVEL_1_CORE_OBJECT}.<p>
*
* @throws CmsInitException in case of errors during the initialization
*/
private OpenCmsCore()
throws CmsInitException {
synchronized (LOCK) {
if ((m_instance != null) && (m_instance.getRunLevel() > OpenCms.RUNLEVEL_0_OFFLINE)) {
throw new CmsInitException(Messages.get().container(Messages.ERR_ALREADY_INITIALIZED_0));
}
initMembers();
m_instance = this;
setRunLevel(OpenCms.RUNLEVEL_1_CORE_OBJECT);
}
}
/**
* Returns the initialized OpenCms singleton instance.<p>
*
* @return the initialized OpenCms singleton instance
*/
protected static OpenCmsCore getInstance() {
if (m_errorCondition != null) {
// OpenCms is not properly initialized
throw new CmsInitException(m_errorCondition, false);
}
if (m_instance == null) {
try {
// create a new core object with runlevel 1
m_instance = new OpenCmsCore();
} catch (CmsInitException e) {
// already initialized, this is all we need
}
}
return m_instance;
}
/**
* Sets the error condition.<p>
*
* @param errorCondition the error condition to set
*/
protected static void setErrorCondition(CmsMessageContainer errorCondition) {
// init exceptions should only be thrown during setup process
if ((m_instance != null) && (m_instance.getRunLevel() < OpenCms.RUNLEVEL_3_SHELL_ACCESS)) {
if (!Messages.ERR_CRITICAL_INIT_WIZARD_0.equals(errorCondition.getKey())) {
// if wizard is still enabled allow retry of initialization (for setup wizard)
m_errorCondition = errorCondition;
// output an error message to the console
System.err.println(Messages.get().getBundle().key(
Messages.LOG_INIT_FAILURE_MESSAGE_1,
errorCondition.key()));
}
LOG.error(errorCondition.key(), new CmsException(errorCondition));
m_instance = null;
} else if (m_instance != null) {
// OpenCms already was successful initialized
LOG.warn(Messages.get().getBundle().key(
Messages.LOG_INIT_INVALID_ERROR_2,
new Integer(m_instance.getRunLevel()),
errorCondition.key()));
}
}
/**
* Adds the specified request handler to the Map of OpenCms request handlers. <p>
*
* @param handler the handler to add
*/
protected void addRequestHandler(I_CmsRequestHandler handler) {
if (handler == null) {
return;
}
String[] names = handler.getHandlerNames();
for (int i = 0; i < names.length; i++) {
String name = names[i];
if (m_requestHandlers.get(name) != null) {
CmsLog.INIT.error(Messages.get().getBundle().key(Messages.LOG_DUPLICATE_REQUEST_HANDLER_1, name));
continue;
}
m_requestHandlers.put(name, handler);
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(Messages.get().getBundle().key(
Messages.INIT_ADDED_REQUEST_HANDLER_2,
name,
handler.getClass().getName()));
}
}
}
/**
* Gets the ADE manager, and makes sure it is initialized.<p>
*
* @return the initialized ADE manager
*/
protected CmsADEManager getADEManager() {
m_adeManager.initialize();
return m_adeManager;
}
/**
* Returns the alias manager.<p>
*
* @return the alias manager
*/
protected CmsAliasManager getAliasManager() {
return m_aliasManager;
}
/**
* Returns the configured authorization handler.<p>
*
* @return the configured authorization handler
*/
protected I_CmsAuthorizationHandler getAuthorizationHandler() {
return m_authorizationHandler;
}
/**
* Returns the initialized OpenCms configuration manager.<p>
*
* @return the initialized OpenCms configuration manager
*/
protected CmsConfigurationManager getConfigurationManager() {
return m_configurationManager;
}
/**
* Gets the configured credentials resolver instance.<p>
*
* @return the credentials resolver
*/
protected I_CmsCredentialsResolver getCredentialsResolver() {
return m_credentialsResolver;
}
/**
* Returns the configured list of default directory file names.<p>
*
* @return the configured list of default directory file names
*/
protected List<String> getDefaultFiles() {
return m_defaultFiles;
}
/**
* Returns the default user and group name configuration.<p>
*
* @return the default user and group name configuration
*/
protected CmsDefaultUsers getDefaultUsers() {
return m_defaultUsers;
}
/**
* Returns the OpenCms event manager.<p>
*
* @return the OpenCms event manager
*/
protected CmsEventManager getEventManager() {
return m_eventManager;
}
/**
* Returns the configured export points,
* the returned set being an unmodifiable set.<p>
*
* @return an unmodifiable set of the configured export points
*/
protected Set<CmsExportPoint> getExportPoints() {
return m_exportPoints;
}
/**
* Returns the initialized import/export manager,
* which contains information about the Cms import/export.<p>
*
* @return the initialized import/export manager
*/
protected CmsImportExportManager getImportExportManager() {
return m_importExportManager;
}
/**
* Returns the link manager to resolve links in <link> tags.<p>
*
* @return the link manager to resolve links in <link> tags
*/
protected CmsLinkManager getLinkManager() {
return m_linkManager;
}
/**
* Returns the locale manager used for obtaining the current locale.<p>
*
* @return the locale manager
*/
protected CmsLocaleManager getLocaleManager() {
return m_localeManager;
}
/**
* Returns the lock manager used for the locking mechanism.<p>
*
* @return the lock manager used for the locking mechanism
*/
protected CmsLockManager getLockManager() {
return m_securityManager.getLockManager();
}
/**
* Returns the login manager used to check the validity of a login.<p>
*
* @return the login manager
*/
protected CmsLoginManager getLoginManager() {
return m_loginManager;
}
/**
* Returns the memory monitor.<p>
*
* @return the memory monitor
*/
protected CmsMemoryMonitor getMemoryMonitor() {
return m_memoryMonitor;
}
/**
* Returns the module manager.<p>
*
* @return the module manager
*/
protected CmsModuleManager getModuleManager() {
return m_moduleManager;
}
/**
* Returns the organizational unit manager.<p>
*
* @return the organizational unit manager
*/
protected CmsOrgUnitManager getOrgUnitManager() {
return m_orgUnitManager;
}
/**
* Return the password handler.<p>
*
* @return the password handler
*/
protected I_CmsPasswordHandler getPasswordHandler() {
return m_passwordHandler;
}
/**
* Returns the path for the request.<p>
*
* First checks the {@link HttpServletRequest#getPathInfo()}, then
* the configured request error page attribute (if set), and then
* if still undefined the <code>/</code> is returned as path info.<p>
*
* This is only needed when the {@link HttpServletRequest#getPathInfo()}
* is not really working as expected like in BEA WLS 9.x, where we have
* to use the 'weblogic.servlet.errorPage' request attribute.<p>
*
* @param req the http request context
*
* @return the path for the request
*/
protected String getPathInfo(HttpServletRequest req) {
String path = req.getPathInfo();
if (path == null) {
// if the HttpServletRequest#getPathInfo() method does not work properly
String requestErrorPageAttribute = getSystemInfo().getServletContainerSettings().getRequestErrorPageAttribute();
if (requestErrorPageAttribute != null) {
// use the proper page attribute
path = (String)req.getAttribute(requestErrorPageAttribute);
if (path != null) {
int pos = path.indexOf("/", 1);
if (pos > 0) {
// cut off the servlet name
path = path.substring(pos);
}
}
}
}
if (path == null) {
path = "/";
}
return path;
}
/**
* Returns the publish manager instance.<p>
*
* @return the publish manager instance
*/
protected CmsPublishManager getPublishManager() {
return m_publishManager;
}
/**
* Returns the repository manager.<p>
*
* @return the repository manager
*/
protected CmsRepositoryManager getRepositoryManager() {
return m_repositoryManager;
}
/**
* Returns the handler instance for the specified name,
* or null if the name does not match any handler name.<p>
*
* @param name the name of the handler instance to return
* @return the handler instance for the specified name
*/
protected I_CmsRequestHandler getRequestHandler(String name) {
return m_requestHandlers.get(name);
}
/**
* Returns the resource manager.<p>
*
* @return the resource manager
*/
protected CmsResourceManager getResourceManager() {
return m_resourceManager;
}
/**
* Returns the role manager.<p>
*
* @return the role manager
*/
protected CmsRoleManager getRoleManager() {
return m_roleManager;
}
/**
* Returns the runlevel of this OpenCmsCore object instance.<p>
*
* For a detailed description about the possible run levels,
* please see {@link OpenCms#getRunLevel()}.<p>
*
* @return the runlevel of this OpenCmsCore object instance
*
* @see OpenCms#getRunLevel()
*/
protected int getRunLevel() {
return m_runLevel;
}
/**
* Looks up a value in the runtime property Map.<p>
*
* @param key the key to look up in the runtime properties
* @return the value for the key, or null if the key was not found
*/
protected Object getRuntimeProperty(Object key) {
return m_runtimeProperties.get(key);
}
/**
* Returns the configured schedule manager.<p>
*
* @return the configured schedule manager
*/
protected CmsScheduleManager getScheduleManager() {
return m_scheduleManager;
}
/**
* Returns the initialized search manager,
* which provides indexing and searching operations.<p>
*
* @return the initialized search manager
*/
protected CmsSearchManager getSearchManager() {
return m_searchManager;
}
/**
* Returns the initialized OpenCms security manager.<p>
*
* @return the initialized OpenCms security manager
*/
protected CmsSecurityManager getSecurityManager() {
return m_securityManager;
}
/**
* Returns the session manager.<p>
*
* @return the session manager
*/
protected CmsSessionManager getSessionManager() {
return m_sessionManager;
}
/**
* Returns the initialized site manager,
* which contains information about all configured sites.<p>
*
* @return the initialized site manager
*/
protected CmsSiteManagerImpl getSiteManager() {
return m_siteManager;
}
/**
* Returns an instance of the common sql manager.<p>
*
* @return an instance of the common sql manager
*/
protected CmsSqlManager getSqlManager() {
return m_securityManager.getSqlManager();
}
/**
* Returns the properties for the static export.<p>
*
* @return the properties for the static export
*/
protected CmsStaticExportManager getStaticExportManager() {
return m_staticExportManager;
}
/**
* Returns the subscription manager.<p>
*
* @return the subscription manager
*/
protected CmsSubscriptionManager getSubscriptionManager() {
return m_subscriptionManager;
}
/**
* Returns the system information storage.<p>
*
* @return the system information storage
*/
protected CmsSystemInfo getSystemInfo() {
return m_systemInfo;
}
/**
* Gets the template context manager instance.<p>
*
* @return the template context manager instance
*/
protected CmsTemplateContextManager getTemplateContextManager() {
return m_templateContextManager;
}
/**
* Returns the OpenCms Thread store.<p>
*
* @return the OpenCms Thread store
*/
protected CmsThreadStore getThreadStore() {
return m_threadStore;
}
/**
* Returns the runtime validation handler.<p>
*
* @return the validation handler
*/
protected I_CmsValidationHandler getValidationHandler() {
return m_validationHandler;
}
/**
* Returns the workflow manager instance.<p>
*
* @return the workflow manager
*/
protected I_CmsWorkflowManager getWorkflowManager() {
return m_workflowManager;
}
/**
* Returns the initialized workplace manager,
* which contains information about the global workplace settings.<p>
*
* @return the initialized workplace manager
*/
protected CmsWorkplaceManager getWorkplaceManager() {
return m_workplaceManager;
}
/**
* Returns the XML content type manager.<p>
*
* @return the XML content type manager
*/
protected CmsXmlContentTypeManager getXmlContentTypeManager() {
if (m_xmlContentTypeManager != null) {
return m_xmlContentTypeManager;
}
if (getRunLevel() == OpenCms.RUNLEVEL_1_CORE_OBJECT) {
// this is only to enable test cases to run
m_xmlContentTypeManager = CmsXmlContentTypeManager.createTypeManagerForTestCases();
}
return m_xmlContentTypeManager;
}
/**
* Returns an independent copy of the provided CmsObject.<p>
*
* This can be useful in case a permanent reference to a CmsObject is stored.
* Changing the request context values (for example project, siteroot) in the new CmsObject
* will have no side effects to the CmsObject it was copied form.<p>
*
* The request time (<code>{@link CmsRequestContext#getRequestTime()}</code>)
* is set to the current time.<p>
*
* @param cms the CmsObject to create a copy of
*
* @return an independent copy of the provided CmsObject
*
* @throws CmsException in case the initialization failed
*
* @see OpenCms#initCmsObject(CmsObject)
* @see OpenCms#initCmsObject(CmsObject, CmsContextInfo)
* @see OpenCms#initCmsObject(String)
*/
protected CmsObject initCmsObject(CmsObject cms) throws CmsException {
CmsContextInfo contextInfo = new CmsContextInfo(cms.getRequestContext());
contextInfo.setRequestTime(CmsContextInfo.CURRENT_TIME);
return initCmsObject(contextInfo);
}
/**
* Returns an initialized CmsObject with the user and context initialized as provided.<p>
*
* Note: Only if the provided <code>adminCms</code> CmsObject has admin permissions,
* this method allows the creation a CmsObject for any existing user. Otherwise
* only the default users 'Guest' and 'Export' can initialized with
* this method, all other user names will throw an Exception.<p>
*
* @param adminCms must either be initialized with "Admin" permissions, or null
* @param contextInfo the context info to create a CmsObject for
*
* @return an initialized CmsObject with the given users permissions
*
* @throws CmsException if an invalid user name was provided
* @throws CmsRoleViolationException if the current user does not have the role permissions to create a context for the requested user
*
* @see org.opencms.db.CmsDefaultUsers#getUserGuest()
* @see org.opencms.db.CmsDefaultUsers#getUserExport()
* @see OpenCms#initCmsObject(CmsObject)
* @see OpenCms#initCmsObject(CmsObject, CmsContextInfo)
* @see OpenCms#initCmsObject(String)
*/
protected CmsObject initCmsObject(CmsObject adminCms, CmsContextInfo contextInfo)
throws CmsRoleViolationException, CmsException {
String userName = contextInfo.getUserName();
if ((adminCms == null) || !m_roleManager.hasRole(adminCms, CmsRole.ROOT_ADMIN)) {
if (!userName.endsWith(getDefaultUsers().getUserGuest())
&& !userName.endsWith(getDefaultUsers().getUserExport())) {
// if no admin object is provided, only "Guest" or "Export" user can be generated
CmsMessageContainer message = Messages.get().container(
Messages.ERR_INVALID_INIT_USER_2,
userName,
((adminCms != null) ? (adminCms.getRequestContext().getCurrentUser().getName()) : ""));
if (LOG.isWarnEnabled()) {
LOG.warn(message.key());
}
throw new CmsRoleViolationException(message);
}
}
return initCmsObject(contextInfo);
}
/**
* Returns an initialized CmsObject with the user initialized as provided,
* with the "Online" project selected and "/" set as the current site root.<p>
*
* Note: Only the default users 'Guest' and 'Export' can initialized with
* this method, all other user names will throw an Exception.<p>
*
* @param user the user name to initialize, can only be
* {@link org.opencms.db.CmsDefaultUsers#getUserGuest()} or
* {@link org.opencms.db.CmsDefaultUsers#getUserExport()}
*
* @return an initialized CmsObject with the given users permissions
*
* @throws CmsException if an invalid user name was provided, or if something else goes wrong
*
* @see org.opencms.db.CmsDefaultUsers#getUserGuest()
* @see org.opencms.db.CmsDefaultUsers#getUserExport()
* @see OpenCms#initCmsObject(String)
* @see #initCmsObject(CmsObject, CmsContextInfo)
*/
protected CmsObject initCmsObject(String user) throws CmsException {
return initCmsObject(null, new CmsContextInfo(user));
}
/**
* Initializes a new cms object from the session data of the request.<p>
*
* If no session data is found, <code>null</code> is returned.<p>
*
* @param req the request
*
* @return the new initialized cms object
*
* @throws CmsException if something goes wrong
*/
protected CmsObject initCmsObjectFromSession(HttpServletRequest req) throws CmsException {
if (LOG.isDebugEnabled()) {
LOG.debug("Trying to init cms object from session for request \"" + req.toString() + "\".");
}
// try to get an OpenCms user session info object for this request
CmsSessionInfo sessionInfo = m_sessionManager.getSessionInfo(req);
if (sessionInfo == null) {
if (LOG.isDebugEnabled()) {
LOG.debug("No session info found.");
}
return null;
}
// initialize the requested site root
CmsSite site = getSiteManager().matchRequest(req);
// a user name is found in the session manager, reuse this user information
CmsUUID project = sessionInfo.getProject();
// initialize site root from request
String siteroot = null;
// a dedicated workplace site is configured
if ((getSiteManager().getWorkplaceSiteMatcher().equals(site.getSiteMatcher()))) {
// if no dedicated workplace site is configured,
// or for the dedicated workplace site, use the site root from the session attribute
siteroot = sessionInfo.getSiteRoot();
} else if (site.hasSecureServer()
&& getSiteManager().getWorkplaceSiteMatcher().getUrl().equals(site.getSecureUrl())) {
// if the workplace is using the secured site
siteroot = sessionInfo.getSiteRoot();
} else {
siteroot = site.getSiteRoot();
}
// initialize user from request
CmsUser user = m_securityManager.readUser(null, sessionInfo.getUserId());
if (LOG.isDebugEnabled()) {
LOG.debug("Initializing cms object with user \"" + user.getName() + "\".");
}
return initCmsObject(req, user, siteroot, project, sessionInfo.getOrganizationalUnitFqn());
}
/**
* Constructor to create a new OpenCms object.<p>
*
* It reads the configurations from the <code>opencms.properties</code>
* file in the <code>config/</code> subdirectory. With the information
* from this file is inits a ResourceBroker (Database access module),
* various caching systems and other options.<p>
*
* This will only be done once per accessing class.
*
* @param configuration the configurations from the <code>opencms.properties</code> file
* @throws CmsInitException in case OpenCms can not be initialized
*/
protected synchronized void initConfiguration(CmsParameterConfiguration configuration) throws CmsInitException {
String systemEncoding = null;
try {
systemEncoding = System.getProperty("file.encoding");
} catch (SecurityException se) {
// security manager is active, but we will try other options before giving up
}
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_FILE_ENCODING_1, systemEncoding));
}
// read server ethernet address (MAC) and init UUID generator
String ethernetAddress = configuration.getString("server.ethernet.address", CmsUUID.getDummyEthernetAddress());
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_ETHERNET_ADDRESS_1, ethernetAddress));
}
CmsUUID.init(ethernetAddress);
// set the server name
String serverName = configuration.getString("server.name", "OpenCmsServer");
getSystemInfo().setServerName(serverName);
// check the installed Java SDK
try {
if (CmsLog.INIT.isInfoEnabled()) {
String jdkinfo = System.getProperty("java.vm.name") + " ";
jdkinfo += System.getProperty("java.vm.version") + " ";
jdkinfo += System.getProperty("java.vm.info") + " ";
jdkinfo += System.getProperty("java.vm.vendor") + " ";
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_JAVA_VM_1, jdkinfo));
String osinfo = System.getProperty("os.name") + " ";
osinfo += System.getProperty("os.version") + " ";
osinfo += System.getProperty("os.arch") + " ";
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_OPERATING_SYSTEM_1, osinfo));
}
} catch (Exception e) {
throw new CmsInitException(Messages.get().container(Messages.ERR_CRITICAL_INIT_PROP_0), e);
}
// create the configuration manager instance
m_configurationManager = new CmsConfigurationManager(getSystemInfo().getConfigFolder());
// store the configuration read from "opencms.properties" in the configuration manager
m_configurationManager.setConfiguration(configuration);
// now load the XML configuration
try {
m_configurationManager.loadXmlConfiguration();
} catch (Exception e) {
throw new CmsInitException(Messages.get().container(Messages.ERR_CRITICAL_INIT_XML_0), e);
}
// get the system configuration
CmsSystemConfiguration systemConfiguration = (CmsSystemConfiguration)m_configurationManager.getConfiguration(CmsSystemConfiguration.class);
// initialize the memory monitor
CmsMemoryMonitorConfiguration memoryMonitorConfiguration = systemConfiguration.getCmsMemoryMonitorConfiguration();
// initialize the memory monitor
try {
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(memoryMonitorConfiguration.getClassName())) {
m_memoryMonitor = (CmsMemoryMonitor)Class.forName(memoryMonitorConfiguration.getClassName()).newInstance();
} else {
m_memoryMonitor = new CmsMemoryMonitor();
}
} catch (Exception e) {
// we can not start without a valid memory monitor
throw new CmsInitException(Messages.get().container(
Messages.ERR_CRITICAL_INIT_MEMORY_MONITOR_1,
memoryMonitorConfiguration.getClassName()), e);
}
m_memoryMonitor.initialize(systemConfiguration);
// get the event manager from the configuration and initialize it with the events already registered
CmsEventManager configuredEventManager = systemConfiguration.getEventManager();
configuredEventManager.initialize(m_eventManager);
m_eventManager = configuredEventManager;
// check if the encoding setting is valid
String setEncoding = systemConfiguration.getDefaultContentEncoding();
String defaultEncoding = CmsEncoder.lookupEncoding(setEncoding, null);
if (defaultEncoding == null) {
// we can not start without a valid encoding setting
throw new CmsInitException(Messages.get().container(Messages.ERR_CRITICAL_INIT_ENCODING_1, setEncoding));
}
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_OPENCMS_ENCODING_1, defaultEncoding));
}
getSystemInfo().setDefaultEncoding(defaultEncoding);
// set version history information
getSystemInfo().setVersionHistorySettings(
systemConfiguration.isHistoryEnabled(),
systemConfiguration.getHistoryVersions(),
systemConfiguration.getHistoryVersionsAfterDeletion());
// set mail configuration
getSystemInfo().setMailSettings(systemConfiguration.getMailSettings());
// set HTTP authentication settings
getSystemInfo().setHttpAuthenticationSettings(systemConfiguration.getHttpAuthenticationSettings());
// set content notification settings
getSystemInfo().setNotificationTime(systemConfiguration.getNotificationTime());
getSystemInfo().setNotificationProject(systemConfiguration.getNotificationProject());
// set the scheduler manager
m_scheduleManager = systemConfiguration.getScheduleManager();
// set resource init classes
m_resourceInitHandlers = systemConfiguration.getResourceInitHandlers();
// register request handler classes
Iterator<I_CmsRequestHandler> it = systemConfiguration.getRequestHandlers().iterator();
while (it.hasNext()) {
I_CmsRequestHandler handler = it.next();
addRequestHandler(handler);
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(Messages.get().getBundle().key(
Messages.INIT_REQUEST_HANDLER_CLASS_1,
handler.getClass().getName()));
}
}
// read the default user configuration
m_defaultUsers = systemConfiguration.getCmsDefaultUsers();
// get the site manager from the configuration
m_siteManager = systemConfiguration.getSiteManager();
// get the VFS / resource configuration
CmsVfsConfiguration vfsConfiguation = (CmsVfsConfiguration)m_configurationManager.getConfiguration(CmsVfsConfiguration.class);
m_resourceManager = vfsConfiguation.getResourceManager();
m_xmlContentTypeManager = vfsConfiguation.getXmlContentTypeManager();
m_defaultFiles = vfsConfiguation.getDefaultFiles();
// initialize translation engines
m_resourceManager.setTranslators(
vfsConfiguation.getFolderTranslator(),
vfsConfiguation.getFileTranslator(),
vfsConfiguation.getXsdTranslator());
// try to initialize the flex cache
CmsFlexCache flexCache = null;
try {
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_FLEX_CACHE_STARTING_0));
}
// get the flex cache configuration from the SystemConfiguration
CmsFlexCacheConfiguration flexCacheConfiguration = systemConfiguration.getCmsFlexCacheConfiguration();
// pass configuration to flex cache for initialization
flexCache = new CmsFlexCache(flexCacheConfiguration);
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_FLEX_CACHE_FINISHED_0));
}
} catch (Exception e) {
if (CmsLog.INIT.isWarnEnabled()) {
CmsLog.INIT.warn(Messages.get().getBundle().key(Messages.INIT_FLEX_CACHE_ERROR_1, e.getMessage()));
}
}
if (flexCache != null) {
// check all resource loaders if they require the Flex cache
Iterator<I_CmsResourceLoader> i = m_resourceManager.getLoaders().iterator();
while (i.hasNext()) {
Object o = i.next();
if (o instanceof I_CmsFlexCacheEnabledLoader) {
// this resource loader requires the Flex cache
((I_CmsFlexCacheEnabledLoader)o).setFlexCache(flexCache);
}
}
}
// get the import/export configuration
CmsImportExportConfiguration importExportConfiguration = (CmsImportExportConfiguration)m_configurationManager.getConfiguration(CmsImportExportConfiguration.class);
m_importExportManager = importExportConfiguration.getImportExportManager();
m_staticExportManager = importExportConfiguration.getStaticExportManager();
m_repositoryManager = importExportConfiguration.getRepositoryManager();
// get the search configuration
CmsSearchConfiguration searchConfiguration = (CmsSearchConfiguration)m_configurationManager.getConfiguration(CmsSearchConfiguration.class);
m_searchManager = searchConfiguration.getSearchManager();
// get the workplace configuration
CmsWorkplaceConfiguration workplaceConfiguration = (CmsWorkplaceConfiguration)m_configurationManager.getConfiguration(CmsWorkplaceConfiguration.class);
m_workplaceManager = workplaceConfiguration.getWorkplaceManager();
// add the export points from the workplace
addExportPoints(m_workplaceManager.getExportPoints());
// get the module configuration
CmsModuleConfiguration moduleConfiguration = (CmsModuleConfiguration)m_configurationManager.getConfiguration(CmsModuleConfiguration.class);
m_moduleManager = moduleConfiguration.getModuleManager();
// get the password handler
m_passwordHandler = systemConfiguration.getPasswordHandler();
// get the validation handler
m_validationHandler = systemConfiguration.getValidationHandler();
// get the authorization handler
m_authorizationHandler = systemConfiguration.getAuthorizationHandler();
// get the login manager
m_loginManager = systemConfiguration.getLoginManager();
// initialize the publish engine
m_publishEngine = new CmsPublishEngine(systemConfiguration.getRuntimeInfoFactory());
// Credentials resolver - needs to be set before the driver manager is initialized
m_credentialsResolver = systemConfiguration.getCredentialsResolver();
// init the OpenCms security manager
m_securityManager = CmsSecurityManager.newInstance(
m_configurationManager,
systemConfiguration.getRuntimeInfoFactory(),
m_publishEngine);
// get the publish manager
m_publishManager = systemConfiguration.getPublishManager();
// get the subscription manager
m_subscriptionManager = systemConfiguration.getSubscriptionManager();
// initialize the role manager
m_roleManager = new CmsRoleManager(m_securityManager);
// initialize the organizational unit manager
m_orgUnitManager = new CmsOrgUnitManager(m_securityManager);
// initialize the Thread store
m_threadStore = new CmsThreadStore(m_securityManager);
// initialize the link manager
m_linkManager = new CmsLinkManager(m_staticExportManager.getLinkSubstitutionHandler());
m_aliasManager = new CmsAliasManager(m_securityManager);
// store the runtime properties
m_runtimeProperties.putAll(systemConfiguration.getRuntimeProperties());
// initialize the session storage provider
I_CmsSessionStorageProvider sessionStorageProvider = systemConfiguration.getSessionStorageProvider();
// get an Admin cms context object with site root set to "/"
CmsObject adminCms;
try {
adminCms = initCmsObject(null, null, getDefaultUsers().getUserAdmin(), (String)null, (String)null);
} catch (CmsException e) {
throw new CmsInitException(Messages.get().container(Messages.ERR_CRITICAL_INIT_ADMINCMS_0), e);
}
m_repositoryManager.initializeCms(adminCms);
// now initialize the other managers
try {
// initialize the scheduler
m_scheduleManager.initialize(initCmsObject(adminCms));
// initialize the locale manager
m_localeManager = systemConfiguration.getLocaleManager();
m_localeManager.initialize(initCmsObject(adminCms));
// initialize the site manager
m_siteManager.initialize(initCmsObject(adminCms));
// initialize the static export manager
m_staticExportManager.initialize(initCmsObject(adminCms));
// initialize the XML content type manager
m_xmlContentTypeManager.initialize(initCmsObject(adminCms));
// initialize the module manager
m_moduleManager.initialize(initCmsObject(adminCms), m_configurationManager);
// initialize the resource manager
m_resourceManager.initialize(initCmsObject(adminCms));
// initialize the publish manager
m_publishManager.setPublishEngine(m_publishEngine);
m_publishManager.setSecurityManager(m_securityManager);
m_publishManager.initialize(initCmsObject(adminCms));
// initialize the search manager
m_searchManager.initialize(initCmsObject(adminCms));
// initialize the workplace manager
m_workplaceManager.initialize(initCmsObject(adminCms));
// initialize the session manager
m_sessionManager.initialize(sessionStorageProvider);
m_sessionManager.setUserSessionMode(systemConfiguration.getUserSessionMode(true));
// initialize the subscription manager
m_subscriptionManager.setSecurityManager(m_securityManager);
m_subscriptionManager.initialize(adminCms);
// initialize ade manager
// initialize the formatter configuration
CmsFormatterConfiguration.initialize(adminCms);
//m_adeManager = new CmsADEManager(initCmsObject(adminCms), m_memoryMonitor, systemConfiguration);
m_adeManager = new CmsADEManager(adminCms, m_memoryMonitor, systemConfiguration);
m_templateContextManager = new CmsTemplateContextManager(adminCms);
m_workflowManager = systemConfiguration.getWorkflowManager();
if (m_workflowManager == null) {
m_workflowManager = new CmsDefaultWorkflowManager();
m_workflowManager.setParameters(new HashMap<String, String>());
}
m_workflowManager.initialize(adminCms);
} catch (CmsException e) {
throw new CmsInitException(Messages.get().container(Messages.ERR_CRITICAL_INIT_MANAGERS_0), e);
}
}
/**
* Initialization of the OpenCms runtime environment.<p>
*
* The connection information for the database is read
* from the <code>opencms.properties</code> configuration file and all
* driver manager are initialized via the initializer,
* which usually will be an instance of a <code>OpenCms</code> class.
*
* @param context configuration of OpenCms from <code>web.xml</code>
* @throws CmsInitException in case OpenCms can not be initialized
*/
protected synchronized void initContext(ServletContext context) throws CmsInitException {
m_gwtServiceContexts = new HashMap<String, CmsGwtServiceContext>();
// automatic servlet container recognition and specific behavior:
CmsServletContainerSettings servletContainerSettings = new CmsServletContainerSettings(context);
getSystemInfo().init(servletContainerSettings);
// Collect the configurations
CmsParameterConfiguration configuration;
try {
configuration = new CmsParameterConfiguration(getSystemInfo().getConfigurationFileRfsPath());
} catch (Exception e) {
throw new CmsInitException(Messages.get().container(
Messages.ERR_CRITICAL_INIT_PROPFILE_1,
getSystemInfo().getConfigurationFileRfsPath()), e);
}
String throwException = configuration.getString("servlet.exception.enabled", "auto");
if (!throwException.equals("auto")) {
// set the parameter is not automatic, the rest of the servlet container dependent parameters
// will be set when reading the system configuration, if not set to auto
boolean throwExc = Boolean.valueOf(throwException).booleanValue();
getSystemInfo().getServletContainerSettings().setServletThrowsException(throwExc);
}
// check if the wizard is enabled, if so stop initialization
if (configuration.getBoolean("wizard.enabled", true)) {
throw new CmsInitException(Messages.get().container(Messages.ERR_CRITICAL_INIT_WIZARD_0));
}
// output startup message and copyright to STDERR
System.err.println(Messages.get().getBundle().key(
Messages.LOG_STARTUP_CONSOLE_NOTE_2,
OpenCms.getSystemInfo().getVersionNumber(),
getSystemInfo().getWebApplicationName()));
for (int i = 0; i < Messages.COPYRIGHT_BY_ALKACON.length; i++) {
System.err.println(Messages.COPYRIGHT_BY_ALKACON[i]);
}
System.err.println();
// output startup message to log file
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_DOT_0));
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_DOT_0));
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_DOT_0));
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_DOT_0));
for (int i = 0; i < Messages.COPYRIGHT_BY_ALKACON.length; i++) {
CmsLog.INIT.info(". " + Messages.COPYRIGHT_BY_ALKACON[i]);
}
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_LINE_0));
CmsLog.INIT.info(Messages.get().getBundle().key(
Messages.INIT_STARTUP_TIME_1,
new Date(System.currentTimeMillis())));
CmsLog.INIT.info(Messages.get().getBundle().key(
Messages.INIT_OPENCMS_VERSION_1,
OpenCms.getSystemInfo().getVersionNumber()));
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_SERVLET_CONTAINER_1, context.getServerInfo()));
CmsLog.INIT.info(Messages.get().getBundle().key(
Messages.INIT_WEBAPP_NAME_1,
getSystemInfo().getWebApplicationName()));
CmsLog.INIT.info(Messages.get().getBundle().key(
Messages.INIT_SERVLET_PATH_1,
getSystemInfo().getServletPath()));
CmsLog.INIT.info(Messages.get().getBundle().key(
Messages.INIT_OPENCMS_CONTEXT_1,
getSystemInfo().getOpenCmsContext()));
CmsLog.INIT.info(Messages.get().getBundle().key(
Messages.INIT_WEBINF_PATH_1,
getSystemInfo().getWebInfRfsPath()));
CmsLog.INIT.info(Messages.get().getBundle().key(
Messages.INIT_PROPERTY_FILE_1,
getSystemInfo().getConfigurationFileRfsPath()));
CmsLog.INIT.info(Messages.get().getBundle().key(
Messages.INIT_LOG_FILE_1,
getSystemInfo().getLogFileRfsPath()));
}
// initialize the configuration
initConfiguration(configuration);
}
/**
* Initialize member variables.<p>
*/
protected void initMembers() {
synchronized (LOCK) {
m_resourceInitHandlers = new ArrayList<I_CmsResourceInit>();
m_requestHandlers = new HashMap<String, I_CmsRequestHandler>();
m_systemInfo = new CmsSystemInfo();
m_exportPoints = Collections.emptySet();
m_defaultUsers = new CmsDefaultUsers();
m_localeManager = new CmsLocaleManager(Locale.ENGLISH);
m_sessionManager = new CmsSessionManager();
m_runtimeProperties = new Hashtable<Object, Object>();
// the default event manager must be available because the configuration already registers events
m_eventManager = new CmsEventManager();
// default link manager is required for test cases
m_linkManager = new CmsLinkManager(new CmsDefaultLinkSubstitutionHandler());
}
}
/**
* Reads the requested resource from the OpenCms VFS,
* in case a directory name is requested, the default files of the
* directory will be looked up and the first match is returned.<p>
*
* The resource that is returned is always a <code>{@link org.opencms.file.CmsFile}</code>,
* even though the content will usually not be loaded in the result. Folders are never returned since
* the point of this method is really to load the default file if just a folder name is requested. If
* there is no default file in a folder, then the return value is null and no CmsException is thrown.<p>
*
* The URI stored in the given OpenCms user context will be changed to the URI of the resource
* that was found and returned.<p>
*
* Implementing and configuring an <code>{@link I_CmsResourceInit}</code> handler
* allows to customize the process of default resource selection.<p>
*
* @param cms the current users OpenCms context
* @param resourceName the path of the requested resource in the OpenCms VFS
* @param req the current http request
* @param res the current http response
*
* @return the requested resource read from the VFS
*
* @throws CmsException in case the requested file does not exist or the user has insufficient access permissions
*
* @see OpenCms#initResource(CmsObject, String, HttpServletRequest, HttpServletResponse)
*/
protected CmsResource initResource(
CmsObject cms,
String resourceName,
HttpServletRequest req,
HttpServletResponse res) throws CmsException {
CmsException tmpException = null;
CmsResource resource;
try {
// try to read the requested resource
resource = cms.readDefaultFile(resourceName);
} catch (CmsException e) {
// file or folder with given name does not exist, store exception
tmpException = e;
resource = null;
}
if (resource != null) {
// set the request uri to the right file
cms.getRequestContext().setUri(cms.getSitePath(resource));
// test if this file is only available for internal access operations
if (resource.isInternal()) {
throw new CmsException(Messages.get().container(
Messages.ERR_READ_INTERNAL_RESOURCE_1,
cms.getRequestContext().getUri()));
}
// check online project
if (cms.getRequestContext().getCurrentProject().isOnlineProject()) {
// check if resource is secure
boolean secure = Boolean.valueOf(
cms.readPropertyObject(cms.getSitePath(resource), CmsPropertyDefinition.PROPERTY_SECURE, true).getValue()).booleanValue();
if (secure) {
// resource is secure, check site config
CmsSite site = OpenCms.getSiteManager().getCurrentSite(cms);
// check the secure url
String secureUrl = null;
try {
secureUrl = site.getSecureUrl();
} catch (Exception e) {
LOG.error(
Messages.get().getBundle().key(Messages.ERR_SECURE_SITE_NOT_CONFIGURED_1, resourceName),
e);
throw new CmsException(Messages.get().container(
Messages.ERR_SECURE_SITE_NOT_CONFIGURED_1,
resourceName), e);
}
boolean usingSec = req.getRequestURL().toString().toUpperCase().startsWith(secureUrl.toUpperCase());
if (site.isExclusiveUrl() && !usingSec) {
resource = null;
// secure resource without secure protocol, check error config
if (site.isExclusiveError()) {
// trigger 404 error
throw new CmsVfsResourceNotFoundException(Messages.get().container(
Messages.ERR_REQUEST_SECURE_RESOURCE_0));
} else {
// redirect
String target = OpenCms.getLinkManager().getOnlineLink(
cms,
cms.getRequestContext().getUri());
try {
res.sendRedirect(target);
} catch (Exception e) {
// ignore, but should never happen
}
}
}
}
}
}
// test if this file has to be checked or modified
for (I_CmsResourceInit handler : m_resourceInitHandlers) {
try {
resource = handler.initResource(resource, cms, req, res);
// the loop has to be interrupted when the exception is thrown!
} catch (CmsResourceInitException e) {
if (e.isClearErrors()) {
tmpException = null;
}
break;
} catch (CmsSecurityException e) {
tmpException = e;
break;
}
}
// file is still null and not found exception was thrown, so throw original exception
if ((resource == null) && (tmpException != null)) {
throw tmpException;
}
// return the resource read from the VFS
return resource;
}
/**
* Initializes the system with the OpenCms servlet.<p>
*
* This is the final step that is called on the servlets "init()" method.
* It registers the servlets request handler and also outputs the final
* startup message. The servlet should auto-load since the <load-on-startup>
* parameter is set in the 'web.xml' by default.<p>
*
* @param servlet the OpenCms servlet
*/
protected void initServlet(OpenCmsServlet servlet) {
synchronized (LOCK) {
// add the servlets request handler
addRequestHandler(servlet);
// output the final 'startup is finished' message
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(Messages.get().getBundle().key(
Messages.INIT_SYSTEM_RUNNING_1,
CmsStringUtil.formatRuntime(getSystemInfo().getRuntime())));
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_LINE_0));
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_DOT_0));
}
}
}
/**
* Invokes the GWT servlet from within OpenCms.<p>
*
* @param serviceName the GWT PRC service class name
* @param req the current servlet request
* @param res the current servlet response
* @param servletConfig the servlet configuration
*/
protected void invokeGwtService(
String serviceName,
HttpServletRequest req,
HttpServletResponse res,
ServletConfig servletConfig) {
CmsObject cms = null;
try {
// instantiate CMS context
cms = initCmsObject(req, res);
// instantiate GWT RPC service
CmsGwtService rpcService = getGwtService(serviceName, servletConfig);
// check permissions
rpcService.checkPermissions(cms);
// set runtime variables
rpcService.setCms(cms);
try {
Object lock = req.getSession();
if (lock == null) {
lock = new Object();
}
synchronized (lock) {
rpcService.service(req, res);
}
// update the session info
m_sessionManager.updateSessionInfo(cms, req);
} finally {
// be sure to clear the cms context
rpcService.setCms(null);
}
} catch (CmsRoleViolationException rv) {
// don't log these into the error channel
LOG.debug(rv.getLocalizedMessage(), rv);
// error code not set - set "internal server error" (500)
int status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
res.setStatus(status);
try {
res.sendError(status, rv.toString());
} catch (IOException e) {
// can be ignored
LOG.error(e.getLocalizedMessage(), e);
}
} catch (Throwable t) {
// error code not set - set "internal server error" (500)
LOG.error(t.getLocalizedMessage(), t);
int status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
res.setStatus(status);
try {
res.sendError(status, t.toString());
} catch (IOException e) {
// can be ignored
LOG.error(e.getLocalizedMessage(), e);
}
}
}
/**
* This method adds an Object to the OpenCms runtime properties.
* The runtime properties can be used to store Objects that are shared
* in the whole system.<p>
*
* @param key the key to add the Object with
* @param value the value of the Object to add
*/
protected void setRuntimeProperty(Object key, Object value) {
m_runtimeProperties.put(key, value);
}
/**
* Displays a resource from the OpenCms by writing the result to the provided
* Servlet response output stream.<p>
*
* @param req the current servlet request
* @param res the current servlet response
*/
protected void showResource(HttpServletRequest req, HttpServletResponse res) {
CmsObject cms = null;
try {
cms = initCmsObject(req, res);
if (cms.getRequestContext().getCurrentProject().isOnlineProject()) {
String uri = cms.getRequestContext().getUri();
if (OpenCms.getStaticExportManager().isExportLink(cms, uri)) {
String url = OpenCms.getStaticExportManager().getRfsName(cms, uri);
String siteRoot = cms.getRequestContext().getSiteRoot();
url = OpenCms.getSiteManager().getSiteForSiteRoot(siteRoot).getUrl() + url;
res.sendRedirect(url);
return;
}
}
// user is initialized, now deliver the requested resource
CmsResource resource = initResource(cms, cms.getRequestContext().getUri(), req, res);
if (resource != null) {
// a file was read, go on process it
m_resourceManager.loadResource(cms, resource, req, res);
m_sessionManager.updateSessionInfo(cms, req);
}
} catch (Throwable t) {
errorHandling(cms, req, res, t);
}
}
/**
* Destroys this OpenCms instance, called if the servlet (or shell) is shut down.<p>
*/
protected void shutDown() {
synchronized (LOCK) {
if (getRunLevel() > OpenCms.RUNLEVEL_0_OFFLINE) {
System.err.println(Messages.get().getBundle().key(
Messages.LOG_SHUTDOWN_CONSOLE_NOTE_2,
getSystemInfo().getVersionNumber(),
getSystemInfo().getWebApplicationName()));
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_DOT_0));
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_DOT_0));
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_LINE_0));
CmsLog.INIT.info(Messages.get().getBundle().key(
Messages.INIT_SHUTDOWN_START_1,
getSystemInfo().getVersionNumber()));
CmsLog.INIT.info(Messages.get().getBundle().key(
Messages.INIT_CURRENT_RUNLEVEL_1,
new Integer(getRunLevel())));
CmsLog.INIT.info(Messages.get().getBundle().key(
Messages.INIT_SHUTDOWN_TIME_1,
new Date(System.currentTimeMillis())));
}
// take the system offline
setRunLevel(OpenCms.RUNLEVEL_0_OFFLINE);
if (LOG.isDebugEnabled()) {
// log exception to see which method did call the shutdown
LOG.debug(Messages.get().getBundle().key(Messages.LOG_SHUTDOWN_TRACE_0), new Exception());
}
try {
// the first thing we have to do is to wait until the current publish process finishes
m_publishEngine.shutDown();
} catch (Throwable e) {
CmsLog.INIT.error(
Messages.get().getBundle().key(Messages.LOG_ERROR_PUBLISH_SHUTDOWN_1, e.getMessage()),
e);
}
try {
// search manager must be shut down early since there may be background indexing still ongoing
if (m_searchManager != null) {
m_searchManager.shutDown();
}
} catch (Throwable e) {
CmsLog.INIT.error(
Messages.get().getBundle().key(Messages.LOG_ERROR_SEARCH_MANAGER_SHUTDOWN_1, e.getMessage()),
e);
}
try {
if (m_staticExportManager != null) {
m_staticExportManager.shutDown();
}
} catch (Throwable e) {
CmsLog.INIT.error(
Messages.get().getBundle().key(Messages.LOG_ERROR_EXPORT_SHUTDOWN_1, e.getMessage()),
e);
}
try {
if (m_moduleManager != null) {
m_moduleManager.shutDown();
}
} catch (Throwable e) {
CmsLog.INIT.error(
Messages.get().getBundle().key(Messages.LOG_ERROR_MODULE_SHUTDOWN_1, e.getMessage()),
e);
}
try {
if (m_scheduleManager != null) {
m_scheduleManager.shutDown();
}
} catch (Throwable e) {
CmsLog.INIT.error(
Messages.get().getBundle().key(Messages.LOG_ERROR_SCHEDULE_SHUTDOWN_1, e.getMessage()),
e);
}
try {
if (m_resourceManager != null) {
m_resourceManager.shutDown();
}
} catch (Throwable e) {
CmsLog.INIT.error(
Messages.get().getBundle().key(Messages.LOG_ERROR_RESOURCE_SHUTDOWN_1, e.getMessage()),
e);
}
try {
// has to be stopped before the security manager, since this thread uses it
if (m_threadStore != null) {
m_threadStore.shutDown();
}
} catch (Throwable e) {
CmsLog.INIT.error(
Messages.get().getBundle().key(Messages.LOG_ERROR_THREAD_SHUTDOWN_1, e.getMessage()),
e);
}
try {
if (m_securityManager != null) {
m_securityManager.destroy();
}
} catch (Throwable e) {
CmsLog.INIT.error(
Messages.get().getBundle().key(Messages.LOG_ERROR_SECURITY_SHUTDOWN_1, e.getMessage()),
e);
}
try {
if (m_sessionManager != null) {
m_sessionManager.shutdown();
}
} catch (Throwable e) {
CmsLog.INIT.error(
Messages.get().getBundle().key(Messages.LOG_ERROR_SESSION_MANAGER_SHUTDOWN_1, e.getMessage()),
e);
}
try {
if (m_memoryMonitor != null) {
m_memoryMonitor.shutdown();
}
} catch (Throwable e) {
CmsLog.INIT.error(
Messages.get().getBundle().key(Messages.LOG_ERROR_MEMORY_MONITOR_SHUTDOWN_1, e.getMessage()),
e);
}
try {
if (m_adeManager != null) {
m_adeManager.shutdown();
}
} catch (Throwable e) {
CmsLog.INIT.error(
Messages.get().getBundle().key(Messages.LOG_ERROR_ADE_MANAGER_SHUTDOWN_1, e.getMessage()),
e);
}
String runtime = CmsStringUtil.formatRuntime(getSystemInfo().getRuntime());
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_OPENCMS_STOPPED_1, runtime));
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_LINE_0));
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_DOT_0));
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_DOT_0));
}
System.err.println(Messages.get().getBundle().key(Messages.LOG_CONSOLE_TOTAL_RUNTIME_1, runtime));
}
m_instance = null;
}
}
/**
* This method updates the request context information.<p>
*
* The update information is:<br>
* <ul>
* <li>Requested Url</li>
* <li>Locale</li>
* <li>Encoding</li>
* <li>Remote Address</li>
* <li>Request Time</li>
* </ul>
*
* @param request the current request
* @param cms the cms object to update the request context for
*
* @return a new updated cms context
*
* @throws CmsException if something goes wrong
*/
protected CmsObject updateContext(HttpServletRequest request, CmsObject cms) throws CmsException {
// get the right site for the request
CmsSite site = OpenCms.getSiteManager().matchRequest(request);
return initCmsObject(
request,
cms.getRequestContext().getCurrentUser(),
site.getSiteRoot(),
cms.getRequestContext().getCurrentProject().getUuid(),
cms.getRequestContext().getOuFqn());
}
/**
* Upgrades to runlevel {@link OpenCms#RUNLEVEL_3_SHELL_ACCESS},
* this is shell access to the database but no Servlet context.<p>
*
* To upgrade the runlevel, the system must be in runlevel {@link OpenCms#RUNLEVEL_1_CORE_OBJECT},
* otherwise an exception is thrown.<p>
*
* @param configuration the configuration
* @throws CmsInitException in case OpenCms can not be initialized
* @return the initialized OpenCmsCore
*/
protected OpenCmsCore upgradeRunlevel(CmsParameterConfiguration configuration) throws CmsInitException {
synchronized (LOCK) {
if ((m_instance != null) && (getRunLevel() >= OpenCms.RUNLEVEL_2_INITIALIZING)) {
// instance already in runlevel 3 or 4
return m_instance;
}
if (getRunLevel() != OpenCms.RUNLEVEL_1_CORE_OBJECT) {
CmsLog.INIT.error(Messages.get().getBundle().key(
Messages.LOG_WRONG_INIT_SEQUENCE_2,
new Integer(3),
new Integer(getRunLevel())));
return m_instance;
}
// set the runlevel to "initializing OpenCms"
setRunLevel(OpenCms.RUNLEVEL_2_INITIALIZING);
// initialize the configuration
m_instance.initConfiguration(configuration);
// upgrade the runlevel - OpenCms shell is available
setRunLevel(OpenCms.RUNLEVEL_3_SHELL_ACCESS);
afterUpgradeRunlevel();
return m_instance;
}
}
/**
* Upgrades to runlevel {@link OpenCms#RUNLEVEL_4_SERVLET_ACCESS},
* this is the final runlevel with an initialized database and Servlet context.<p>
*
* To upgrade the runlevel, the system must be in runlevel {@link OpenCms#RUNLEVEL_1_CORE_OBJECT},
* otherwise an exception is thrown.<p>
*
* @param context the current servlet context
* @throws CmsInitException in case OpenCms can not be initialized
* @return the initialized OpenCmsCore
*/
protected OpenCmsCore upgradeRunlevel(ServletContext context) throws CmsInitException {
synchronized (LOCK) {
if ((m_instance != null) && (getRunLevel() >= OpenCms.RUNLEVEL_4_SERVLET_ACCESS)) {
// instance already in runlevel 5 or 6
return m_instance;
}
if (getRunLevel() != OpenCms.RUNLEVEL_1_CORE_OBJECT) {
CmsLog.INIT.error(Messages.get().getBundle().key(
Messages.LOG_WRONG_INIT_SEQUENCE_2,
new Integer(4),
new Integer(getRunLevel())));
return m_instance;
}
// set the runlevel to "initializing OpenCms"
setRunLevel(OpenCms.RUNLEVEL_2_INITIALIZING);
// initialize the servlet context
m_instance.initContext(context);
// initialization successfully finished - OpenCms servlet is online
// the runlevel will change from 2 directly to 4, this is on purpose
setRunLevel(OpenCms.RUNLEVEL_4_SERVLET_ACCESS);
afterUpgradeRunlevel();
return m_instance;
}
}
/**
* Writes the XML configuration for the provided configuration class.<p>
*
* @param clazz the configuration class to write the XML for
*/
protected void writeConfiguration(Class<?> clazz) {
// exception handling is provided here to ensure identical log messages
try {
m_configurationManager.writeConfiguration(clazz);
} catch (IOException e) {
CmsLog.getLog(CmsConfigurationManager.class).error(
Messages.get().getBundle().key(Messages.LOG_ERROR_WRITING_CONFIG_1, clazz.getName()),
e);
} catch (CmsConfigurationException e) {
CmsLog.getLog(CmsConfigurationManager.class).error(
Messages.get().getBundle().key(Messages.LOG_ERROR_WRITING_CONFIG_1, clazz.getName()),
e);
}
}
/**
* Adds the given set of export points to the list of all configured export points.<p>
*
* @param exportPoints the export points to add
*/
private void addExportPoints(Set<CmsExportPoint> exportPoints) {
// create a new immutable set of export points
HashSet<CmsExportPoint> newSet = new HashSet<CmsExportPoint>(m_exportPoints.size() + exportPoints.size());
newSet.addAll(exportPoints);
newSet.addAll(m_exportPoints);
m_exportPoints = Collections.unmodifiableSet(newSet);
}
/**
* Finishes the startup sequence after last runlevel upgrade.<p>
*/
private void afterUpgradeRunlevel() {
try {
// read the persistent locks
m_instance.m_securityManager.readLocks();
} catch (CmsException e) {
if (LOG.isErrorEnabled()) {
LOG.error(
org.opencms.lock.Messages.get().getBundle().key(org.opencms.lock.Messages.ERR_READ_LOCKS_0),
e);
}
}
// everything is initialized, now start publishing
m_publishManager.startPublishing();
}
/**
* Generates a formated exception output.<p>
*
* Because the exception could be thrown while accessing the system files,
* the complete HTML code must be added here!<p>
*
* @param t the caught Exception
* @param request the servlet request
* @param cms the CmsObject
* @return String containing the HTML code of the error message
*/
private String createErrorBox(Throwable t, HttpServletRequest request, CmsObject cms) {
String errorUri = CmsFlexController.getThrowableResourceUri(request);
if (errorUri == null) {
errorUri = cms.getRequestContext().getUri();
}
// try to get the exception root cause
Throwable cause = CmsFlexController.getThrowable(request);
if (cause == null) {
cause = t;
}
CmsErrorBean errorBean = new CmsErrorBean(cms, cause);
errorBean.setParamAction(errorUri);
return errorBean.toHtml();
}
/**
* This method performs the error handling for OpenCms.<p>
*
* @param cms the current cms context, might be null !
* @param req the client request
* @param res the client response
* @param t the exception that occurred
*/
private void errorHandling(CmsObject cms, HttpServletRequest req, HttpServletResponse res, Throwable t) {
// remove the controller attribute from the request
CmsFlexController.removeController(req);
boolean canWrite = (!res.isCommitted() && !res.containsHeader("Location"));
int status = -1;
boolean isGuest = true;
if (t instanceof ServletException) {
ServletException s = (ServletException)t;
if (s.getRootCause() != null) {
t = s.getRootCause();
}
} else if (t instanceof CmsSecurityException) {
// access error - display login dialog
if (canWrite) {
try {
m_authorizationHandler.requestAuthorization(req, res, getLoginFormURL(req, res));
} catch (IOException ioe) {
// there is nothing we can do about this
}
return;
}
} else if (t instanceof CmsDbEntryNotFoundException) {
// user or group does not exist
status = HttpServletResponse.SC_SERVICE_UNAVAILABLE;
isGuest = false;
} else if (t instanceof CmsVfsResourceNotFoundException) {
// file not found - display 404 error.
status = HttpServletResponse.SC_NOT_FOUND;
} else if (t instanceof CmsException) {
if (t.getCause() != null) {
t = t.getCause();
}
LOG.error(t.getLocalizedMessage() + " rendering URL " + req.getRequestURL(), t);
} else {
LOG.error(t.getLocalizedMessage() + " rendering URL " + req.getRequestURL(), t);
}
if (status < 1) {
// error code not set - set "internal server error" (500)
status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
}
res.setStatus(status);
try {
if ((cms != null) && (cms.getRequestContext().getCurrentUser() != null)) {
isGuest = isGuest
&& (cms.getRequestContext().getCurrentUser().isGuestUser() || cms.userInGroup(
cms.getRequestContext().getCurrentUser().getName(),
OpenCms.getDefaultUsers().getGroupGuests()));
}
} catch (CmsException e) {
// result is false
LOG.error(e.getLocalizedMessage(), e);
}
if (canWrite) {
res.setContentType("text/html");
CmsRequestUtil.setNoCacheHeaders(res);
if (!isGuest && (cms != null) && !cms.getRequestContext().getCurrentProject().isOnlineProject()) {
try {
res.setStatus(HttpServletResponse.SC_OK);
res.getWriter().print(createErrorBox(t, req, cms));
} catch (IOException e) {
// can be ignored
LOG.error(e.getLocalizedMessage(), e);
}
} else {
try {
res.sendError(status, t.toString());
} catch (IOException e) {
// can be ignored
LOG.error(e.getLocalizedMessage(), e);
}
}
}
}
/**
*
*
* @param serviceName the GWT PRC service class name
* @param servletConfig the servlet configuration
*
* @return the GWT service instance
*
* @throws Throwable if something goes wrong
*/
private synchronized CmsGwtService getGwtService(String serviceName, ServletConfig servletConfig) throws Throwable {
CmsGwtServiceContext context = m_gwtServiceContexts.get(serviceName);
if (context == null) {
context = new CmsGwtServiceContext(serviceName);
m_gwtServiceContexts.put(serviceName, context);
}
CmsGwtService gwtService = (CmsGwtService)Class.forName(serviceName).newInstance();
gwtService.init(servletConfig);
gwtService.setContext(context);
return gwtService;
}
/**
* Reads the login form which should be used for authenticating the current request.<p>
*
* @param req current request
* @param res current response
*
* @return the URL of the login form or <code>null</code> if not set
*
* @throws IOException
*/
private String getLoginFormURL(HttpServletRequest req, HttpServletResponse res) throws IOException {
CmsHttpAuthenticationSettings httpAuthenticationSettings = OpenCms.getSystemInfo().getHttpAuthenticationSettings();
String loginFormURL = null;
// this will create an admin user with the "right" site root already set
CmsObject adminCms;
try {
adminCms = initCmsObject(req, res, OpenCms.getDefaultUsers().getUserAdmin(), null, null);
} catch (CmsException e) {
// this should never happen, if it does we can't continue
throw new IOException(Messages.get().getBundle().key(
Messages.ERR_INVALID_INIT_USER_2,
OpenCms.getDefaultUsers().getUserAdmin(),
null));
}
// get the requested resource
String path = adminCms.getRequestContext().getUri();
CmsProperty propertyLoginForm = null;
try {
propertyLoginForm = adminCms.readPropertyObject(path, CmsPropertyDefinition.PROPERTY_LOGIN_FORM, true);
} catch (Throwable t) {
if (LOG.isWarnEnabled()) {
LOG.warn(
Messages.get().getBundle().key(
Messages.LOG_ERROR_READING_AUTH_PROP_2,
CmsPropertyDefinition.PROPERTY_LOGIN_FORM,
path),
t);
}
}
String params = null;
if ((propertyLoginForm != null)
&& (propertyLoginForm != CmsProperty.getNullProperty())
&& CmsStringUtil.isNotEmpty(propertyLoginForm.getValue())) {
// login form property value was found
// build a redirect URL using the value of the property
// "__loginform" is a dummy request parameter that could be used in a JSP template to trigger
// if the template should display a login formular or not
loginFormURL = propertyLoginForm.getValue();
params = "__loginform=true";
} else if (!httpAuthenticationSettings.useBrowserBasedHttpAuthentication()
&& CmsStringUtil.isNotEmpty(httpAuthenticationSettings.getFormBasedHttpAuthenticationUri())) {
// login form property value not set, but form login set in configuration
// build a redirect URL to the default login form URI configured in opencms.properties
loginFormURL = httpAuthenticationSettings.getFormBasedHttpAuthenticationUri();
}
String callbackURL = CmsRequestUtil.encodeParamsWithUri(path, req);
if (loginFormURL != null) {
if (!loginFormURL.startsWith("http")) {
loginFormURL = m_linkManager.substituteLink(adminCms, loginFormURL, null, true);
} else {
callbackURL = m_linkManager.getServerLink(adminCms, path);
callbackURL = CmsRequestUtil.encodeParamsWithUri(callbackURL, req);
}
}
return m_authorizationHandler.getLoginFormURL(loginFormURL, params, callbackURL);
}
/**
* Initializes a CmsObject with the given context information.<p>
*
* @param contextInfo the information for the CmsObject context to create
*
* @return the initialized CmsObject
*
* @throws CmsException if something goes wrong
*/
private CmsObject initCmsObject(CmsContextInfo contextInfo) throws CmsException {
CmsUser user = contextInfo.getUser();
if (user == null) {
user = m_securityManager.readUser(null, contextInfo.getUserName());
}
CmsProject project = contextInfo.getProject();
if (project == null) {
project = m_securityManager.readProject(contextInfo.getProjectName());
}
// first create the request context
CmsRequestContext context = new CmsRequestContext(
user,
project,
contextInfo.getRequestedUri(),
contextInfo.getSiteRoot(),
contextInfo.getLocale(),
contextInfo.getEncoding(),
contextInfo.getRemoteAddr(),
contextInfo.getRequestTime(),
m_resourceManager.getFolderTranslator(),
m_resourceManager.getFileTranslator(),
contextInfo.getOuFqn());
// now initialize and return the CmsObject
return new CmsObject(m_securityManager, context);
}
/**
* Initializes a {@link CmsObject} with the given users information.<p>
*
* @param request the current http request (or <code>null</code>)
* @param user the initialized user
* @param siteRoot the users current site
* @param projectId the id of the users current project
* @param ouFqn the organizational unit
*
* @return the initialized CmsObject
*
* @throws CmsException in case something goes wrong
*/
private CmsObject initCmsObject(
HttpServletRequest request,
CmsUser user,
String siteRoot,
CmsUUID projectId,
String ouFqn) throws CmsException {
CmsProject project = null;
try {
project = m_securityManager.readProject(projectId);
} catch (CmsDbEntryNotFoundException e) {
// project not found, switch to online project
project = m_securityManager.readProject(CmsProject.ONLINE_PROJECT_ID);
}
// get requested resource uri and remote IP address, as well as time for "time warp" browsing
String requestedResource = null;
Long requestTimeAttr = null;
String remoteAddr;
if (request != null) {
// get path info from request
requestedResource = getPathInfo(request);
// check for special header for remote address
remoteAddr = request.getHeader(CmsRequestUtil.HEADER_X_FORWARDED_FOR);
if (remoteAddr == null) {
// if header is not available, use default remote address
remoteAddr = request.getRemoteAddr();
}
// check for special "time warp" browsing
HttpSession session = request.getSession(false);
if (session != null) {
// no new session must be created here
requestTimeAttr = (Long)session.getAttribute(CmsContextInfo.ATTRIBUTE_REQUEST_TIME);
}
} else {
// if no request is available, the IP is always set to localhost
remoteAddr = CmsContextInfo.LOCALHOST;
}
if (requestedResource == null) {
// path info can still be null
requestedResource = "/";
}
// calculate the request time
long requestTime;
if (requestTimeAttr == null) {
requestTime = System.currentTimeMillis();
} else {
requestTime = requestTimeAttr.longValue();
}
// get locale and encoding
CmsI18nInfo i18nInfo;
if (m_localeManager.isInitialized()) {
// locale manager is initialized
// resolve locale and encoding
if (requestedResource.endsWith(OpenCmsServlet.HANDLE_GWT) && (request != null)) {
// GWT RPC call, always keep the request encoding and use the default locale
i18nInfo = new CmsI18nInfo(CmsLocaleManager.getDefaultLocale(), request.getCharacterEncoding());
} else {
String resourceName;
if (requestedResource.startsWith(CmsWorkplace.VFS_PATH_SYSTEM)) {
// add site root only if resource name does not start with "/system"
resourceName = requestedResource;
} else if (OpenCms.getSiteManager().startsWithShared(requestedResource)) {
resourceName = requestedResource;
} else {
resourceName = siteRoot.concat(requestedResource);
}
i18nInfo = m_localeManager.getI18nInfo(request, user, project, resourceName);
}
} else {
// locale manager not initialized, this will be true _only_ during system startup
// the values set does not matter, no locale information form VFS is used on system startup
// this is just to protect against null pointer exceptions
i18nInfo = new CmsI18nInfo(Locale.ENGLISH, getSystemInfo().getDefaultEncoding());
}
// decode the requested resource, always using UTF-8
requestedResource = CmsEncoder.decode(requestedResource);
// initialize the context info
CmsContextInfo contextInfo = new CmsContextInfo(
user,
project,
requestedResource,
siteRoot,
i18nInfo.getLocale(),
i18nInfo.getEncoding(),
remoteAddr,
requestTime,
ouFqn);
// now generate and return the CmsObject
return initCmsObject(contextInfo);
}
/**
* Handles the user authentification for each request sent to OpenCms.<p>
*
* User authentification is done in three steps:
* <ol>
* <li>Session authentification: OpenCms stores information of all authentificated
* users in an internal storage based on the users session.</li>
* <li>Authorization handler authentification: If the session authentification fails,
* the current configured authorization handler is called.</li>
* <li>Default user: When both authentification methods fail, the user is set to
* the default (Guest) user.</li>
* </ol>
*
* @param req the current http request
* @param res the current http response
*
* @return the initialized cms context
*
* @throws IOException if user authentication fails
* @throws CmsException in case something goes wrong
*/
private CmsObject initCmsObject(HttpServletRequest req, HttpServletResponse res) throws IOException, CmsException {
// first try to restore a stored session
CmsObject cms = initCmsObjectFromSession(req);
if (cms != null) {
return cms;
}
// if does not work, try to authorize the request
I_CmsAuthorizationHandler.I_PrivilegedLoginAction loginAction = new I_CmsAuthorizationHandler.I_PrivilegedLoginAction() {
private CmsObject m_adminCms;
/**
* @see org.opencms.security.I_CmsAuthorizationHandler.I_PrivilegedLoginAction#doLogin(javax.servlet.http.HttpServletRequest, java.lang.String)
*/
public CmsObject doLogin(HttpServletRequest request, String principal) throws CmsException {
try {
CmsUser user = m_adminCms.readUser(principal);
if (!user.isEnabled()) {
throw new CmsException(Messages.get().container(
Messages.ERR_INVALID_INIT_USER_2,
user.getName(),
"-"));
}
// initialize the new cms object
CmsContextInfo contextInfo = new CmsContextInfo(m_adminCms.getRequestContext());
contextInfo.setUserName(principal);
CmsObject newCms = initCmsObject(m_adminCms, contextInfo);
if (contextInfo.getRequestedUri().startsWith("/system/workplace/")
&& getRoleManager().hasRole(newCms, CmsRole.WORKPLACE_USER)) {
// set the default project of the user for workplace users
CmsUserSettings settings = new CmsUserSettings(newCms);
try {
CmsProject project = newCms.readProject(settings.getStartProject());
if (getOrgUnitManager().getAllAccessibleProjects(newCms, project.getOuFqn(), false).contains(
project)) {
// user has access to the project, set this as current project
newCms.getRequestContext().setCurrentProject(project);
}
} catch (CmsException e) {
// unable to set the startup project, bad but not critical
}
}
return newCms;
} finally {
m_adminCms = null;
}
}
/**
* @see org.opencms.security.I_CmsAuthorizationHandler.I_PrivilegedLoginAction#getCmsObject()
*/
public CmsObject getCmsObject() {
return m_adminCms;
}
/**
* @see org.opencms.security.I_CmsAuthorizationHandler.I_PrivilegedLoginAction#setCmsObject(org.opencms.file.CmsObject)
*/
public void setCmsObject(CmsObject adminCms) {
m_adminCms = adminCms;
}
};
loginAction.setCmsObject(initCmsObject(req, res, OpenCms.getDefaultUsers().getUserAdmin(), null, null));
cms = m_authorizationHandler.initCmsObject(req, loginAction);
if (cms != null) {
return cms;
}
// authentification failed or not enough permissions, so display a login screen
m_authorizationHandler.requestAuthorization(req, res, getLoginFormURL(req, res));
cms = initCmsObject(
req,
m_securityManager.readUser(null, OpenCms.getDefaultUsers().getUserGuest()),
getSiteManager().matchRequest(req).getSiteRoot(),
CmsProject.ONLINE_PROJECT_ID,
"");
// return the initialized cms user context object
return cms;
}
/**
* Returns an initialized CmsObject with the given users permissions.<p>
*
* In case the password is <code>null</code>, or the user is the <code>Guest</code> user,
* no password check is done. Therefore you can initialize all users without knowing their passwords
* by just supplying <code>null</code> as password. This is intended only for
* internal operation in the core.<p>
*
* @param req the current request
* @param res the current response
* @param user the user to initialize the CmsObject with
* @param password the password of the user
* @param ouFqn the organizational unit, if <code>null</code> the users ou is used
*
* @return a cms context that has been initialized with "Guest" permissions
*
* @throws CmsException in case the CmsObject could not be initialized
*/
private CmsObject initCmsObject(
HttpServletRequest req,
HttpServletResponse res,
String user,
String password,
String ouFqn) throws CmsException {
String siteroot = null;
// gather information from request if provided
if (req != null) {
siteroot = OpenCms.getSiteManager().matchRequest(req).getSiteRoot();
}
// initialize the user
if (user == null) {
user = getDefaultUsers().getUserGuest();
}
if (siteroot == null) {
siteroot = "/";
}
CmsObject cms = initCmsObject(
req,
m_securityManager.readUser(null, user),
siteroot,
CmsProject.ONLINE_PROJECT_ID,
ouFqn);
// login the user if different from Guest and password was provided
if ((password != null) && !getDefaultUsers().isUserGuest(user)) {
cms.loginUser(user, password, CmsContextInfo.LOCALHOST);
}
return cms;
}
/**
* Sets the init level of this OpenCmsCore object instance.<p>
*
* For a detailed description about the possible run levels,
* please see {@link OpenCms#getRunLevel()}.<p>
*
* @param level the level to set
*/
private void setRunLevel(int level) {
if (m_instance != null) {
if (m_instance.m_runLevel >= OpenCms.RUNLEVEL_1_CORE_OBJECT) {
// otherwise the log is not available
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(Messages.get().getBundle().key(
Messages.INIT_RUNLEVEL_CHANGE_2,
new Integer(m_instance.m_runLevel),
new Integer(level)));
}
}
m_instance.m_runLevel = level;
}
}
}
| Correct issues if the requested URL is null. | src/org/opencms/main/OpenCmsCore.java | Correct issues if the requested URL is null. | <ide><path>rc/org/opencms/main/OpenCmsCore.java
<ide> try {
<ide> secureUrl = site.getSecureUrl();
<ide> } catch (Exception e) {
<del> LOG.error(
<del> Messages.get().getBundle().key(Messages.ERR_SECURE_SITE_NOT_CONFIGURED_1, resourceName),
<del> e);
<add> LOG.error(Messages.get().getBundle().key(
<add> Messages.ERR_SECURE_SITE_NOT_CONFIGURED_1,
<add> resourceName), e);
<ide> throw new CmsException(Messages.get().container(
<ide> Messages.ERR_SECURE_SITE_NOT_CONFIGURED_1,
<ide> resourceName), e);
<ide> }
<del> boolean usingSec = req.getRequestURL().toString().toUpperCase().startsWith(secureUrl.toUpperCase());
<add> boolean usingSec = true;
<add> if (req != null) {
<add> usingSec = req.getRequestURL().toString().toUpperCase().startsWith(secureUrl.toUpperCase());
<add> }
<ide> if (site.isExclusiveUrl() && !usingSec) {
<ide> resource = null;
<ide> // secure resource without secure protocol, check error config
<ide> // the first thing we have to do is to wait until the current publish process finishes
<ide> m_publishEngine.shutDown();
<ide> } catch (Throwable e) {
<del> CmsLog.INIT.error(
<del> Messages.get().getBundle().key(Messages.LOG_ERROR_PUBLISH_SHUTDOWN_1, e.getMessage()),
<del> e);
<add> CmsLog.INIT.error(Messages.get().getBundle().key(
<add> Messages.LOG_ERROR_PUBLISH_SHUTDOWN_1,
<add> e.getMessage()), e);
<ide> }
<ide> try {
<ide> // search manager must be shut down early since there may be background indexing still ongoing
<ide> m_searchManager.shutDown();
<ide> }
<ide> } catch (Throwable e) {
<del> CmsLog.INIT.error(
<del> Messages.get().getBundle().key(Messages.LOG_ERROR_SEARCH_MANAGER_SHUTDOWN_1, e.getMessage()),
<del> e);
<add> CmsLog.INIT.error(Messages.get().getBundle().key(
<add> Messages.LOG_ERROR_SEARCH_MANAGER_SHUTDOWN_1,
<add> e.getMessage()), e);
<ide> }
<ide> try {
<ide> if (m_staticExportManager != null) {
<ide> m_staticExportManager.shutDown();
<ide> }
<ide> } catch (Throwable e) {
<del> CmsLog.INIT.error(
<del> Messages.get().getBundle().key(Messages.LOG_ERROR_EXPORT_SHUTDOWN_1, e.getMessage()),
<del> e);
<add> CmsLog.INIT.error(Messages.get().getBundle().key(
<add> Messages.LOG_ERROR_EXPORT_SHUTDOWN_1,
<add> e.getMessage()), e);
<ide> }
<ide> try {
<ide> if (m_moduleManager != null) {
<ide> m_moduleManager.shutDown();
<ide> }
<ide> } catch (Throwable e) {
<del> CmsLog.INIT.error(
<del> Messages.get().getBundle().key(Messages.LOG_ERROR_MODULE_SHUTDOWN_1, e.getMessage()),
<del> e);
<add> CmsLog.INIT.error(Messages.get().getBundle().key(
<add> Messages.LOG_ERROR_MODULE_SHUTDOWN_1,
<add> e.getMessage()), e);
<ide> }
<ide> try {
<ide> if (m_scheduleManager != null) {
<ide> m_scheduleManager.shutDown();
<ide> }
<ide> } catch (Throwable e) {
<del> CmsLog.INIT.error(
<del> Messages.get().getBundle().key(Messages.LOG_ERROR_SCHEDULE_SHUTDOWN_1, e.getMessage()),
<del> e);
<add> CmsLog.INIT.error(Messages.get().getBundle().key(
<add> Messages.LOG_ERROR_SCHEDULE_SHUTDOWN_1,
<add> e.getMessage()), e);
<ide> }
<ide> try {
<ide> if (m_resourceManager != null) {
<ide> m_resourceManager.shutDown();
<ide> }
<ide> } catch (Throwable e) {
<del> CmsLog.INIT.error(
<del> Messages.get().getBundle().key(Messages.LOG_ERROR_RESOURCE_SHUTDOWN_1, e.getMessage()),
<del> e);
<add> CmsLog.INIT.error(Messages.get().getBundle().key(
<add> Messages.LOG_ERROR_RESOURCE_SHUTDOWN_1,
<add> e.getMessage()), e);
<ide> }
<ide> try {
<ide> // has to be stopped before the security manager, since this thread uses it
<ide> m_threadStore.shutDown();
<ide> }
<ide> } catch (Throwable e) {
<del> CmsLog.INIT.error(
<del> Messages.get().getBundle().key(Messages.LOG_ERROR_THREAD_SHUTDOWN_1, e.getMessage()),
<del> e);
<add> CmsLog.INIT.error(Messages.get().getBundle().key(
<add> Messages.LOG_ERROR_THREAD_SHUTDOWN_1,
<add> e.getMessage()), e);
<ide> }
<ide> try {
<ide> if (m_securityManager != null) {
<ide> m_securityManager.destroy();
<ide> }
<ide> } catch (Throwable e) {
<del> CmsLog.INIT.error(
<del> Messages.get().getBundle().key(Messages.LOG_ERROR_SECURITY_SHUTDOWN_1, e.getMessage()),
<del> e);
<add> CmsLog.INIT.error(Messages.get().getBundle().key(
<add> Messages.LOG_ERROR_SECURITY_SHUTDOWN_1,
<add> e.getMessage()), e);
<ide> }
<ide> try {
<ide> if (m_sessionManager != null) {
<ide> m_sessionManager.shutdown();
<ide> }
<ide> } catch (Throwable e) {
<del> CmsLog.INIT.error(
<del> Messages.get().getBundle().key(Messages.LOG_ERROR_SESSION_MANAGER_SHUTDOWN_1, e.getMessage()),
<del> e);
<add> CmsLog.INIT.error(Messages.get().getBundle().key(
<add> Messages.LOG_ERROR_SESSION_MANAGER_SHUTDOWN_1,
<add> e.getMessage()), e);
<ide> }
<ide> try {
<ide> if (m_memoryMonitor != null) {
<ide> m_memoryMonitor.shutdown();
<ide> }
<ide> } catch (Throwable e) {
<del> CmsLog.INIT.error(
<del> Messages.get().getBundle().key(Messages.LOG_ERROR_MEMORY_MONITOR_SHUTDOWN_1, e.getMessage()),
<del> e);
<add> CmsLog.INIT.error(Messages.get().getBundle().key(
<add> Messages.LOG_ERROR_MEMORY_MONITOR_SHUTDOWN_1,
<add> e.getMessage()), e);
<ide> }
<ide> try {
<ide> if (m_adeManager != null) {
<ide> m_adeManager.shutdown();
<ide> }
<ide> } catch (Throwable e) {
<del> CmsLog.INIT.error(
<del> Messages.get().getBundle().key(Messages.LOG_ERROR_ADE_MANAGER_SHUTDOWN_1, e.getMessage()),
<del> e);
<add> CmsLog.INIT.error(Messages.get().getBundle().key(
<add> Messages.LOG_ERROR_ADE_MANAGER_SHUTDOWN_1,
<add> e.getMessage()), e);
<ide> }
<ide> String runtime = CmsStringUtil.formatRuntime(getSystemInfo().getRuntime());
<ide> if (CmsLog.INIT.isInfoEnabled()) {
<ide> propertyLoginForm = adminCms.readPropertyObject(path, CmsPropertyDefinition.PROPERTY_LOGIN_FORM, true);
<ide> } catch (Throwable t) {
<ide> if (LOG.isWarnEnabled()) {
<del> LOG.warn(
<del> Messages.get().getBundle().key(
<del> Messages.LOG_ERROR_READING_AUTH_PROP_2,
<del> CmsPropertyDefinition.PROPERTY_LOGIN_FORM,
<del> path),
<del> t);
<add> LOG.warn(Messages.get().getBundle().key(
<add> Messages.LOG_ERROR_READING_AUTH_PROP_2,
<add> CmsPropertyDefinition.PROPERTY_LOGIN_FORM,
<add> path), t);
<ide> }
<ide> }
<ide> |
|
Java | apache-2.0 | 8b065f39d6bcf18ee441cb975505a7fce62add32 | 0 | dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android | package org.commcare.dalvik.utils;
import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
/**
* Util for turning URIs into a normal file path strings Needed because new
* versions of Android have a content resolution abstraction layer that doesn't
* use vanilla file system paths.
*
* Taken from aFileChooser by Paul Burke (paulburke.co)
* https://github.com/iPaulPro/aFileChooser
* Under the Apache 2.0 license
*/
public class UriToFilePath {
/**
* Get a file path from a Uri. This will get the the path for Storage
* Access Framework Documents, as well as the _data field for the
* MediaStore and other file-based ContentProviders. Doesn't handle
* document Uri's on secondary storage.
*
* @param context The context.
* @param uri The Uri to query.
* @return Filepath string extracted from the Uri argument. Returns null if
* filepath couldn't be succesfully extracted.
*/
@SuppressLint("NewApi")
public static String getPathFromUri(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
// XXX PLM: Doesn't handle non-primary volumes
} else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
} else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[]{
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
} else if ("content".equalsIgnoreCase(uri.getScheme())) {
return getDataColumn(context, uri, null, null);
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @param selection (Optional) Filter used in the query.
* @param selectionArgs (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
*/
private static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection,
selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* @param uri Check this Uri's authority.
* @return Is this Uri's authority ExternalStorageProvider?
*/
private static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* @param uri Check this Uri's authority.
* @return Is this Uri's authority DownloadsProvider?
*/
private static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* @param uri Check this Uri's authority.
* @return Is this Uri's authority MediaProvider?
*/
private static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
}
| app/src/org/commcare/dalvik/utils/UriToFilePath.java | package org.commcare.dalvik.utils;
import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
/**
* Util for turning URIs into a normal file path strings Needed because new
* versions of Android have a content resolution abstraction layer that doesn't
* use vanilla file system paths.
*
* Taken from aFileChooser by Paul Burke (paulburke.co)
* https://github.com/iPaulPro/aFileChooser
* Which is under Apache 2.0 license
*/
public class UriToFilePath {
/**
* Get a file path from a Uri. This will get the the path for Storage Access
* Framework Documents, as well as the _data field for the MediaStore and
* other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @author paulburke
*/
@SuppressLint("NewApi")
public static String getPathFromUri(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// DocumentProvider
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
// TODO handle non-primary volumes
} else if (isDownloadsDocument(uri)) {
// DownloadsProvider
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
} else if (isMediaDocument(uri)) {
// MediaProvider
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] {
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
} else if ("content".equalsIgnoreCase(uri.getScheme())) {
// MediaStore (and general)
return getDataColumn(context, uri, null, null);
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
// File
return uri.getPath();
}
return null;
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @param selection (Optional) Filter used in the query.
* @param selectionArgs (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
*/
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
}
| comments
| app/src/org/commcare/dalvik/utils/UriToFilePath.java | comments | <ide><path>pp/src/org/commcare/dalvik/utils/UriToFilePath.java
<ide> *
<ide> * Taken from aFileChooser by Paul Burke (paulburke.co)
<ide> * https://github.com/iPaulPro/aFileChooser
<del> * Which is under Apache 2.0 license
<add> * Under the Apache 2.0 license
<ide> */
<ide> public class UriToFilePath {
<ide> /**
<del> * Get a file path from a Uri. This will get the the path for Storage Access
<del> * Framework Documents, as well as the _data field for the MediaStore and
<del> * other file-based ContentProviders.
<add> * Get a file path from a Uri. This will get the the path for Storage
<add> * Access Framework Documents, as well as the _data field for the
<add> * MediaStore and other file-based ContentProviders. Doesn't handle
<add> * document Uri's on secondary storage.
<ide> *
<ide> * @param context The context.
<del> * @param uri The Uri to query.
<del> * @author paulburke
<add> * @param uri The Uri to query.
<add> * @return Filepath string extracted from the Uri argument. Returns null if
<add> * filepath couldn't be succesfully extracted.
<ide> */
<ide> @SuppressLint("NewApi")
<ide> public static String getPathFromUri(final Context context, final Uri uri) {
<ide> final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
<ide>
<ide> if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
<del> // DocumentProvider
<del> // ExternalStorageProvider
<ide> if (isExternalStorageDocument(uri)) {
<ide> final String docId = DocumentsContract.getDocumentId(uri);
<ide> final String[] split = docId.split(":");
<ide> if ("primary".equalsIgnoreCase(type)) {
<ide> return Environment.getExternalStorageDirectory() + "/" + split[1];
<ide> }
<del> // TODO handle non-primary volumes
<add> // XXX PLM: Doesn't handle non-primary volumes
<ide> } else if (isDownloadsDocument(uri)) {
<del> // DownloadsProvider
<ide> final String id = DocumentsContract.getDocumentId(uri);
<ide> final Uri contentUri = ContentUris.withAppendedId(
<ide> Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
<ide>
<ide> return getDataColumn(context, contentUri, null, null);
<ide> } else if (isMediaDocument(uri)) {
<del> // MediaProvider
<ide> final String docId = DocumentsContract.getDocumentId(uri);
<ide> final String[] split = docId.split(":");
<ide> final String type = split[0];
<ide> }
<ide>
<ide> final String selection = "_id=?";
<del> final String[] selectionArgs = new String[] {
<add> final String[] selectionArgs = new String[]{
<ide> split[1]
<ide> };
<ide>
<ide> return getDataColumn(context, contentUri, selection, selectionArgs);
<ide> }
<ide> } else if ("content".equalsIgnoreCase(uri.getScheme())) {
<del> // MediaStore (and general)
<ide> return getDataColumn(context, uri, null, null);
<ide> } else if ("file".equalsIgnoreCase(uri.getScheme())) {
<del> // File
<ide> return uri.getPath();
<ide> }
<ide>
<ide> * Get the value of the data column for this Uri. This is useful for
<ide> * MediaStore Uris, and other file-based ContentProviders.
<ide> *
<del> * @param context The context.
<del> * @param uri The Uri to query.
<del> * @param selection (Optional) Filter used in the query.
<add> * @param context The context.
<add> * @param uri The Uri to query.
<add> * @param selection (Optional) Filter used in the query.
<ide> * @param selectionArgs (Optional) Selection arguments used in the query.
<ide> * @return The value of the _data column, which is typically a file path.
<ide> */
<del> public static String getDataColumn(Context context, Uri uri, String selection,
<del> String[] selectionArgs) {
<add> private static String getDataColumn(Context context, Uri uri, String selection,
<add> String[] selectionArgs) {
<ide> Cursor cursor = null;
<ide> final String column = "_data";
<ide> final String[] projection = {
<ide> };
<ide>
<ide> try {
<del> cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
<del> null);
<add> cursor = context.getContentResolver().query(uri, projection,
<add> selection, selectionArgs, null);
<ide> if (cursor != null && cursor.moveToFirst()) {
<ide> final int column_index = cursor.getColumnIndexOrThrow(column);
<ide> return cursor.getString(column_index);
<ide> }
<ide>
<ide> /**
<del> * @param uri The Uri to check.
<del> * @return Whether the Uri authority is ExternalStorageProvider.
<add> * @param uri Check this Uri's authority.
<add> * @return Is this Uri's authority ExternalStorageProvider?
<ide> */
<del> public static boolean isExternalStorageDocument(Uri uri) {
<add> private static boolean isExternalStorageDocument(Uri uri) {
<ide> return "com.android.externalstorage.documents".equals(uri.getAuthority());
<ide> }
<ide>
<ide> /**
<del> * @param uri The Uri to check.
<del> * @return Whether the Uri authority is DownloadsProvider.
<add> * @param uri Check this Uri's authority.
<add> * @return Is this Uri's authority DownloadsProvider?
<ide> */
<del> public static boolean isDownloadsDocument(Uri uri) {
<add> private static boolean isDownloadsDocument(Uri uri) {
<ide> return "com.android.providers.downloads.documents".equals(uri.getAuthority());
<ide> }
<ide>
<ide> /**
<del> * @param uri The Uri to check.
<del> * @return Whether the Uri authority is MediaProvider.
<add> * @param uri Check this Uri's authority.
<add> * @return Is this Uri's authority MediaProvider?
<ide> */
<del> public static boolean isMediaDocument(Uri uri) {
<add> private static boolean isMediaDocument(Uri uri) {
<ide> return "com.android.providers.media.documents".equals(uri.getAuthority());
<ide> }
<ide> } |
|
Java | apache-2.0 | efd0f0b457a1ff7f1ce498289227e25cbdd6680b | 0 | boundary/boundary-event-sdk,boundary/boundary-event-sdk,boundary/boundary-event-sdk,boundary/boundary-event-sdk,boundary/boundary-event-sdk,boundary/boundary-event-sdk,boundary/boundary-event-sdk | package com.boundary.sdk.event.service;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import com.boundary.camel.component.ping.PingConfiguration;
import com.boundary.camel.component.port.PortConfiguration;
import com.boundary.camel.component.ssh.SshxConfiguration;
import static com.boundary.sdk.event.service.ServiceCheckPropertyNames.*;
public class ExtractServiceTestConfiguration {
public PingConfiguration getPingConfiguration(ServiceTest<PingConfiguration> serviceTest) {
return serviceTest.getConfiguration();
}
/**
* Extract the {@link PortConfiguration} from the {@link ServiceTest} and
* set as header in {@link Message}
* @param exchange {@link Exchange} from Camel route
*/
public void extractPortConfiguration(Exchange exchange) {
Message message = exchange.getIn();
ServiceTest<PortConfiguration> serviceTest = message.getBody(ServiceTest.class);
PortConfiguration configuration = serviceTest.getConfiguration();
message.setHeader(SERVICE_TEST_INSTANCE, serviceTest);
message.setBody(configuration);
}
/**
* Extract the {@link PingConfiguration} from the {@link ServiceTest} and
* set as header in {@link Message}
* @param exchange {@link Exchange} from Camel route
*/
public void extractPingConfiguration(Exchange exchange) {
Message message = exchange.getIn();
ServiceTest<PingConfiguration> serviceTest = message.getBody(ServiceTest.class);
PingConfiguration configuration = serviceTest.getConfiguration();
message.setHeader(SERVICE_TEST_INSTANCE, serviceTest);
message.setBody(configuration);
}
/**
* Extract the {@link SshxConfiguration} from the {@link ServiceTest} and
* set as header in {@link Message}
* @param exchange {@link Exchange} from Camel route
*/
public void extractSshConfiguration(Exchange exchange) {
Message message = exchange.getIn();
ServiceTest<SshxConfiguration> serviceTest = message.getBody(ServiceTest.class);
SshxConfiguration configuration = serviceTest.getConfiguration();
message.setHeader(SERVICE_TEST_INSTANCE, serviceTest);
message.setBody(configuration);
}
}
| src/main/java/com/boundary/sdk/event/service/ExtractServiceTestConfiguration.java | package com.boundary.sdk.event.service;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import com.boundary.camel.component.ping.PingConfiguration;
import com.boundary.camel.component.port.PortConfiguration;
import static com.boundary.sdk.event.service.ServiceCheckPropertyNames.*;
public class ExtractServiceTestConfiguration {
public PingConfiguration getPingConfiguration(ServiceTest<PingConfiguration> serviceTest) {
return serviceTest.getConfiguration();
}
/**
* Extract the {@link PortConfiguration} from the {@link ServiceTest} and
* set as header in {@link Message}
* @param exchange {@link Exchange} from Camel route
*/
public void extractPortConfiguration(Exchange exchange) {
Message message = exchange.getIn();
ServiceTest<PortConfiguration> serviceTest = message.getBody(ServiceTest.class);
PortConfiguration configuration = serviceTest.getConfiguration();
message.setHeader(SERVICE_TEST_INSTANCE, serviceTest);
message.setBody(configuration);
}
/**
* Extract the {@link PingConfiguration} from the {@link ServiceTest} and
* set as header in {@link Message}
* @param exchange {@link Exchange} from Camel route
*/
public void extractPingConfiguration(Exchange exchange) {
Message message = exchange.getIn();
ServiceTest<PingConfiguration> serviceTest = message.getBody(ServiceTest.class);
PingConfiguration configuration = serviceTest.getConfiguration();
message.setHeader(SERVICE_TEST_INSTANCE, serviceTest);
message.setBody(configuration);
}
}
| Add extraction of SSH configuration
Former-commit-id: bb649e2ef87277739d1fba3c01ba02ee35c40238 | src/main/java/com/boundary/sdk/event/service/ExtractServiceTestConfiguration.java | Add extraction of SSH configuration | <ide><path>rc/main/java/com/boundary/sdk/event/service/ExtractServiceTestConfiguration.java
<ide>
<ide> import com.boundary.camel.component.ping.PingConfiguration;
<ide> import com.boundary.camel.component.port.PortConfiguration;
<add>import com.boundary.camel.component.ssh.SshxConfiguration;
<ide>
<ide> import static com.boundary.sdk.event.service.ServiceCheckPropertyNames.*;
<ide>
<ide> message.setHeader(SERVICE_TEST_INSTANCE, serviceTest);
<ide> message.setBody(configuration);
<ide> }
<add>
<add> /**
<add> * Extract the {@link SshxConfiguration} from the {@link ServiceTest} and
<add> * set as header in {@link Message}
<add> * @param exchange {@link Exchange} from Camel route
<add> */
<add> public void extractSshConfiguration(Exchange exchange) {
<add> Message message = exchange.getIn();
<add> ServiceTest<SshxConfiguration> serviceTest = message.getBody(ServiceTest.class);
<add> SshxConfiguration configuration = serviceTest.getConfiguration();
<add>
<add> message.setHeader(SERVICE_TEST_INSTANCE, serviceTest);
<add> message.setBody(configuration);
<add> }
<ide> } |
|
Java | apache-2.0 | 7229f1fa71760320758dc4a4274f48ecc2ab01fc | 0 | mamewotoko/podplayer,mamewotoko/podplayer,mamewotoko/podplayer | package com.mamewo.podplayer0;
import java.io.IOException;
import java.util.List;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
/**
* @author Takashi Masuyama <[email protected]>
* http://www002.upp.so-net.ne.jp/mamewo/
*/
public class PlayerService
extends Service
implements MediaPlayer.OnCompletionListener,
MediaPlayer.OnErrorListener,
MediaPlayer.OnPreparedListener
{
final static
public String PACKAGE_NAME = PlayerService.class.getPackage().getName();
final static
public String STOP_MUSIC_ACTION = PACKAGE_NAME + ".STOP_MUSIC_ACTION";
final static
private Class<PodplayerActivity> userClass_ = PodplayerActivity.class;
final static
private String TAG = "podcast";
final static
private int NOTIFY_PLAYING_ID = 1;
private final IBinder binder_ = new LocalBinder();
private List<PodInfo> currentPlaylist_;
private int playCursor_;
private MediaPlayer player_;
private PlayerStateListener listener_;
@Override
public int onStartCommand(Intent intent, int flags, int startId){
String action = intent.getAction();
if (STOP_MUSIC_ACTION.equals(action)) {
stopMusic();
}
return START_STICKY;
}
public boolean isPlaying() {
return player_.isPlaying();
}
public void playNext() {
if (isPlaying()) {
stopMusic();
}
playCursor_ = (playCursor_ + 1) % currentPlaylist_.size();
playMusic();
}
public void setPlaylist(List<PodInfo> playlist) {
currentPlaylist_ = playlist;
}
public boolean playNth(int pos) {
playCursor_ = pos % currentPlaylist_.size();
return playMusic();
}
public boolean playMusic() {
if (null == currentPlaylist_ || currentPlaylist_.isEmpty()) {
Log.i(TAG, "playMusic: playlist is null");
return false;
}
if (player_.isPlaying()) {
return false;
}
PodInfo info = currentPlaylist_.get(playCursor_);
//skip unsupported files filtering by filename ...
Log.i(TAG, "playMusic: " + info.url_);
try {
player_.reset();
player_.setDataSource(info.url_);
player_.prepareAsync();
if(null != listener_){
listener_.onStartLoadingMusic(info);
}
}
catch (IOException e) {
return false;
}
//TODO: localize
startForeground("Playing podcast", info.title_);
return true;
}
public void startForeground(String title, String description) {
//TODO: localize
String podTitle = "playing podcast";
Notification note =
new Notification(R.drawable.ic_launcher, podTitle, 0);
Intent ni = new Intent(this, userClass_);
PendingIntent npi = PendingIntent.getActivity(this, 0, ni, 0);
//TODO: localize
note.setLatestEventInfo(this, title, description, npi);
startForeground(NOTIFY_PLAYING_ID, note);
}
public void stopMusic() {
if(player_.isPlaying()){
player_.stop();
}
stopForeground(true);
}
public void pauseMusic() {
if(player_.isPlaying()){
player_.pause();
}
stopForeground(true);
}
public class LocalBinder
extends Binder
{
public PlayerService getService() {
return PlayerService.this;
}
}
@Override
public void onCreate(){
super.onCreate();
currentPlaylist_ = null;
listener_ = null;
player_ = new MediaPlayer();
player_.setOnCompletionListener(this);
player_.setOnErrorListener(this);
player_.setOnPreparedListener(this);
}
@Override
public void onDestroy() {
stopForeground(false);
player_ = null;
listener_ = null;
currentPlaylist_ = null;
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
return binder_;
}
public static class PodInfo {
public String url_;
public String title_;
public PodInfo(String url, String title) {
url_ = url;
title_ = title;
}
@Override
public String toString() {
return title_;
}
}
@Override
public void onPrepared(MediaPlayer player) {
Log.d(TAG, "onPrepared");
player_.start();
if(null != listener_){
listener_.onStartMusic(currentPlaylist_.get(playCursor_));
}
}
@Override
public void onCompletion(MediaPlayer mp) {
playNext();
}
// This method is not called when DRM error occurs
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
//TODO: show error message to GUI
Log.i(TAG, "onError is called, cannot play this media");
//TODO: call playNext if error occurred while playing music
playNext();
return true;
}
//use intent instead?
public void setOnStartMusicListener(PlayerStateListener listener) {
listener_ = listener;
}
public interface PlayerStateListener {
public void onStartLoadingMusic(PodInfo info);
public void onStartMusic(PodInfo info);
}
} | src/com/mamewo/podplayer0/PlayerService.java | package com.mamewo.podplayer0;
import java.io.IOException;
import java.util.List;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
/**
* @author Takashi Masuyama <[email protected]>
* http://www002.upp.so-net.ne.jp/mamewo/
*/
public class PlayerService
extends Service
implements MediaPlayer.OnCompletionListener,
MediaPlayer.OnErrorListener,
MediaPlayer.OnPreparedListener
{
final static
public String PACKAGE_NAME = PlayerService.class.getPackage().getName();
final static
public String STOP_MUSIC_ACTION = PACKAGE_NAME + ".STOP_MUSIC_ACTION";
final static
private Class<PodplayerActivity> userClass_ = PodplayerActivity.class;
final static
private String TAG = "podcast";
final static
private int NOTIFY_PLAYING_ID = 1;
private final IBinder binder_ = new LocalBinder();
private List<PodInfo> currentPlaylist_;
private int playCursor_;
private MediaPlayer player_;
private PlayerStateListener listener_;
@Override
public int onStartCommand(Intent intent, int flags, int startId){
String action = intent.getAction();
if (STOP_MUSIC_ACTION.equals(action)) {
stopMusic();
}
return START_STICKY;
}
public boolean isPlaying() {
return player_.isPlaying();
}
public void playNext() {
if (isPlaying()) {
stopMusic();
}
playCursor_ = (playCursor_ + 1) % currentPlaylist_.size();
playMusic();
}
public void setPlaylist(List<PodInfo> playlist) {
currentPlaylist_ = playlist;
}
public boolean playNth(int pos) {
playCursor_ = pos % currentPlaylist_.size();
return playMusic();
}
public boolean playMusic() {
if (null == currentPlaylist_ || currentPlaylist_.isEmpty()) {
Log.i(TAG, "playMusic: playlist is null");
return false;
}
if (player_.isPlaying()) {
return false;
}
PodInfo info = currentPlaylist_.get(playCursor_);
//skip unsupported files filtering by filename ...
Log.i(TAG, "playMusic: " + info.url_);
try {
player_.reset();
player_.setDataSource(info.url_);
player_.prepareAsync();
if(null != listener_){
listener_.onStartLoadingMusic(info);
}
}
catch (IOException e) {
return false;
}
startForeground();
return true;
}
public void startForeground() {
//TODO: localize
String podTitle = "playing podcast";
Notification note =
new Notification(R.drawable.ic_launcher, podTitle, 0);
Intent ni = new Intent(this, userClass_);
PendingIntent npi = PendingIntent.getActivity(this, 0, ni, 0);
//TODO: localize
note.setLatestEventInfo(this, podTitle, "", npi);
startForeground(NOTIFY_PLAYING_ID, note);
}
public void stopMusic() {
if(player_.isPlaying()){
player_.stop();
}
stopForeground(true);
}
public void pauseMusic() {
if(player_.isPlaying()){
player_.pause();
}
stopForeground(true);
}
public class LocalBinder
extends Binder
{
public PlayerService getService() {
return PlayerService.this;
}
}
@Override
public void onCreate(){
super.onCreate();
currentPlaylist_ = null;
listener_ = null;
player_ = new MediaPlayer();
player_.setOnCompletionListener(this);
player_.setOnErrorListener(this);
player_.setOnPreparedListener(this);
}
@Override
public void onDestroy() {
stopForeground(false);
player_ = null;
listener_ = null;
currentPlaylist_ = null;
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
return binder_;
}
public static class PodInfo {
public String url_;
public String title_;
public PodInfo(String url, String title) {
url_ = url;
title_ = title;
}
@Override
public String toString() {
return title_;
}
}
@Override
public void onPrepared(MediaPlayer player) {
Log.d(TAG, "onPrepared");
player_.start();
if(null != listener_){
listener_.onStartMusic(currentPlaylist_.get(playCursor_));
}
}
@Override
public void onCompletion(MediaPlayer mp) {
playNext();
}
// This method is not called when DRM error occurs
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
//TODO: show error message to GUI
Log.i(TAG, "onError is called, cannot play this media");
//TODO: call playNext if error occurred while playing music
playNext();
return true;
}
//use intent instead?
public void setOnStartMusicListener(PlayerStateListener listener) {
listener_ = listener;
}
public interface PlayerStateListener {
public void onStartLoadingMusic(PodInfo info);
public void onStartMusic(PodInfo info);
}
} | modify notification method | src/com/mamewo/podplayer0/PlayerService.java | modify notification method | <ide><path>rc/com/mamewo/podplayer0/PlayerService.java
<ide> catch (IOException e) {
<ide> return false;
<ide> }
<del> startForeground();
<add> //TODO: localize
<add> startForeground("Playing podcast", info.title_);
<ide> return true;
<ide> }
<ide>
<del> public void startForeground() {
<add> public void startForeground(String title, String description) {
<ide> //TODO: localize
<ide> String podTitle = "playing podcast";
<ide> Notification note =
<ide> Intent ni = new Intent(this, userClass_);
<ide> PendingIntent npi = PendingIntent.getActivity(this, 0, ni, 0);
<ide> //TODO: localize
<del> note.setLatestEventInfo(this, podTitle, "", npi);
<add> note.setLatestEventInfo(this, title, description, npi);
<ide> startForeground(NOTIFY_PLAYING_ID, note);
<ide> }
<ide> |
|
Java | apache-2.0 | aba3042a6482e751fc7f0c54180809b99596f29c | 0 | mikeb01/Aeron,real-logic/Aeron,real-logic/Aeron,real-logic/Aeron,EvilMcJerkface/Aeron,EvilMcJerkface/Aeron,EvilMcJerkface/Aeron,galderz/Aeron,galderz/Aeron,EvilMcJerkface/Aeron,real-logic/Aeron,mikeb01/Aeron,mikeb01/Aeron,galderz/Aeron,mikeb01/Aeron,galderz/Aeron | /*
* Copyright 2014-2019 Real Logic Ltd.
*
* 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.aeron.cluster;
import io.aeron.*;
import io.aeron.archive.client.AeronArchive;
import io.aeron.archive.codecs.SourceLocation;
import io.aeron.archive.status.RecordingPos;
import io.aeron.cluster.client.AeronCluster;
import io.aeron.cluster.client.ClusterException;
import io.aeron.cluster.codecs.*;
import io.aeron.cluster.service.Cluster;
import io.aeron.cluster.service.ClusterMarkFile;
import io.aeron.cluster.service.RecoveryState;
import io.aeron.exceptions.TimeoutException;
import io.aeron.logbuffer.ControlledFragmentHandler;
import io.aeron.logbuffer.FrameDescriptor;
import io.aeron.logbuffer.Header;
import io.aeron.protocol.DataHeaderFlyweight;
import io.aeron.security.Authenticator;
import io.aeron.status.ReadableCounter;
import org.agrona.*;
import org.agrona.collections.ArrayListUtil;
import org.agrona.collections.Int2ObjectHashMap;
import org.agrona.collections.Long2ObjectHashMap;
import org.agrona.collections.LongHashSet;
import org.agrona.concurrent.Agent;
import org.agrona.concurrent.AgentInvoker;
import org.agrona.concurrent.EpochClock;
import org.agrona.concurrent.IdleStrategy;
import org.agrona.concurrent.status.CountersReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.TimeUnit;
import static io.aeron.Aeron.NULL_VALUE;
import static io.aeron.ChannelUri.SPY_QUALIFIER;
import static io.aeron.CommonContext.*;
import static io.aeron.archive.client.AeronArchive.NULL_LENGTH;
import static io.aeron.archive.client.AeronArchive.NULL_POSITION;
import static io.aeron.archive.codecs.SourceLocation.LOCAL;
import static io.aeron.cluster.ClusterSession.State.*;
import static io.aeron.cluster.ConsensusModule.Configuration.*;
class ConsensusModuleAgent implements Agent, MemberStatusListener
{
private final long sessionTimeoutMs;
private final long leaderHeartbeatIntervalMs;
private final long leaderHeartbeatTimeoutMs;
private final long serviceHeartbeatTimeoutMs;
private long nextSessionId = 1;
private long leadershipTermId = NULL_VALUE;
private long expectedAckPosition = 0;
private long serviceAckId = 0;
private long lastAppendedPosition = 0;
private long followerCommitPosition = 0;
private long terminationPosition = NULL_POSITION;
private long timeOfLastLogUpdateMs = 0;
private long timeOfLastAppendPosition = 0;
private long cachedTimeMs;
private long clusterTimeMs = NULL_VALUE;
private long lastRecordingId = RecordingPos.NULL_RECORDING_ID;
private int logInitialTermId = NULL_VALUE;
private int logTermBufferLength = NULL_VALUE;
private int logMtuLength = NULL_VALUE;
private int memberId;
private int highMemberId;
private int pendingMemberRemovals = 0;
private ReadableCounter appendedPosition;
private final Counter commitPosition;
private ConsensusModule.State state = ConsensusModule.State.INIT;
private Cluster.Role role;
private ClusterMember[] clusterMembers;
private ClusterMember[] passiveMembers = ClusterMember.EMPTY_CLUSTER_MEMBER_ARRAY;
private ClusterMember leaderMember;
private ClusterMember thisMember;
private long[] rankedPositions;
private final ServiceAck[] serviceAcks;
private final Counter clusterRoleCounter;
private final ClusterMarkFile markFile;
private final AgentInvoker aeronClientInvoker;
private final EpochClock epochClock;
private final Counter moduleState;
private final Counter controlToggle;
private final TimerService timerService;
private final ConsensusModuleAdapter consensusModuleAdapter;
private final ServiceProxy serviceProxy;
private final IngressAdapter ingressAdapter;
private final EgressPublisher egressPublisher;
private final LogPublisher logPublisher;
private LogAdapter logAdapter;
private final MemberStatusAdapter memberStatusAdapter;
private final MemberStatusPublisher memberStatusPublisher = new MemberStatusPublisher();
private final Long2ObjectHashMap<ClusterSession> sessionByIdMap = new Long2ObjectHashMap<>();
private final ArrayList<ClusterSession> pendingSessions = new ArrayList<>();
private final ArrayList<ClusterSession> rejectedSessions = new ArrayList<>();
private final ArrayList<ClusterSession> redirectSessions = new ArrayList<>();
private final Int2ObjectHashMap<ClusterMember> clusterMemberByIdMap = new Int2ObjectHashMap<>();
private final LongHashSet missedTimersSet = new LongHashSet();
private final Authenticator authenticator;
private final ClusterSessionProxy sessionProxy;
private final Aeron aeron;
private AeronArchive archive;
private final ConsensusModule.Context ctx;
private final MutableDirectBuffer tempBuffer;
private final Counter[] serviceHeartbeats;
private final IdleStrategy idleStrategy;
private final RecordingLog recordingLog;
private final ArrayList<RecordingLog.Snapshot> dynamicJoinSnapshots = new ArrayList<>();
private RecordingLog.RecoveryPlan recoveryPlan;
private Election election;
private DynamicJoin dynamicJoin;
private ClusterTermination clusterTermination;
private String logRecordingChannel;
private String liveLogDestination;
private String replayLogDestination;
private String clientFacingEndpoints;
ConsensusModuleAgent(final ConsensusModule.Context ctx)
{
this.ctx = ctx;
this.aeron = ctx.aeron();
this.epochClock = ctx.epochClock();
this.sessionTimeoutMs = TimeUnit.NANOSECONDS.toMillis(ctx.sessionTimeoutNs());
this.leaderHeartbeatIntervalMs = TimeUnit.NANOSECONDS.toMillis(ctx.leaderHeartbeatIntervalNs());
this.leaderHeartbeatTimeoutMs = TimeUnit.NANOSECONDS.toMillis(ctx.leaderHeartbeatTimeoutNs());
this.serviceHeartbeatTimeoutMs = TimeUnit.NANOSECONDS.toMillis(ctx.serviceHeartbeatTimeoutNs());
this.egressPublisher = ctx.egressPublisher();
this.moduleState = ctx.moduleStateCounter();
this.commitPosition = ctx.commitPositionCounter();
this.controlToggle = ctx.controlToggleCounter();
this.logPublisher = ctx.logPublisher();
this.idleStrategy = ctx.idleStrategy();
this.timerService = new TimerService(this);
this.clusterMembers = ClusterMember.parse(ctx.clusterMembers());
this.sessionProxy = new ClusterSessionProxy(egressPublisher);
this.memberId = ctx.clusterMemberId();
this.clusterRoleCounter = ctx.clusterNodeCounter();
this.markFile = ctx.clusterMarkFile();
this.recordingLog = ctx.recordingLog();
this.tempBuffer = ctx.tempBuffer();
this.serviceHeartbeats = ctx.serviceHeartbeatCounters();
this.serviceAcks = ServiceAck.newArray(ctx.serviceCount());
this.highMemberId = ClusterMember.highMemberId(clusterMembers);
aeronClientInvoker = aeron.conductorAgentInvoker();
aeronClientInvoker.invoke();
rankedPositions = new long[ClusterMember.quorumThreshold(clusterMembers.length)];
role(Cluster.Role.FOLLOWER);
ClusterMember.addClusterMemberIds(clusterMembers, clusterMemberByIdMap);
thisMember = determineMemberAndCheckEndpoints(clusterMembers);
leaderMember = thisMember;
final ChannelUri memberStatusUri = ChannelUri.parse(ctx.memberStatusChannel());
memberStatusUri.put(ENDPOINT_PARAM_NAME, thisMember.memberFacingEndpoint());
final int statusStreamId = ctx.memberStatusStreamId();
memberStatusAdapter = new MemberStatusAdapter(
aeron.addSubscription(memberStatusUri.toString(), statusStreamId), this);
ClusterMember.addMemberStatusPublications(clusterMembers, thisMember, memberStatusUri, statusStreamId, aeron);
ingressAdapter = new IngressAdapter(this, ctx.invalidRequestCounter());
consensusModuleAdapter = new ConsensusModuleAdapter(
aeron.addSubscription(ctx.serviceControlChannel(), ctx.consensusModuleStreamId()), this);
serviceProxy = new ServiceProxy(aeron.addPublication(ctx.serviceControlChannel(), ctx.serviceStreamId()));
authenticator = ctx.authenticatorSupplier().get();
}
public void onClose()
{
if (!ctx.ownsAeronClient())
{
for (final ClusterSession session : sessionByIdMap.values())
{
session.close();
}
CloseHelper.close(memberStatusAdapter);
ClusterMember.closeMemberPublications(clusterMembers);
logPublisher.disconnect();
CloseHelper.close(ingressAdapter);
CloseHelper.close(serviceProxy);
CloseHelper.close(consensusModuleAdapter);
}
CloseHelper.close(archive);
ctx.close();
}
public void onStart()
{
final ChannelUri archiveUri = ChannelUri.parse(ctx.archiveContext().controlRequestChannel());
ClusterMember.checkArchiveEndpoint(thisMember, archiveUri);
archiveUri.put(ENDPOINT_PARAM_NAME, thisMember.archiveEndpoint());
ctx.archiveContext().controlRequestChannel(archiveUri.toString());
archive = AeronArchive.connect(ctx.archiveContext().clone());
recoveryPlan = recordingLog.createRecoveryPlan(archive, ctx.serviceCount());
if (null == (dynamicJoin = requiresDynamicJoin()))
{
try (Counter ignore = addRecoveryStateCounter(recoveryPlan))
{
if (!recoveryPlan.snapshots.isEmpty())
{
recoverFromSnapshot(recoveryPlan.snapshots.get(0), archive);
}
awaitServiceAcks(expectedAckPosition);
}
if (ConsensusModule.State.SUSPENDED != state)
{
state(ConsensusModule.State.ACTIVE);
}
timeOfLastLogUpdateMs = cachedTimeMs = epochClock.time();
timeOfLastAppendPosition = cachedTimeMs;
leadershipTermId = recoveryPlan.lastLeadershipTermId;
election = new Election(
true,
leadershipTermId,
recoveryPlan.appendedLogPosition,
clusterMembers,
clusterMemberByIdMap,
thisMember,
memberStatusAdapter,
memberStatusPublisher,
ctx,
this);
}
}
public int doWork()
{
int workCount = 0;
final long nowMs = epochClock.time();
if (cachedTimeMs != nowMs)
{
cachedTimeMs = nowMs;
if (Cluster.Role.LEADER == role)
{
clusterTimeMs(nowMs);
}
workCount += slowTickWork(nowMs);
}
if (null != dynamicJoin)
{
workCount += dynamicJoin.doWork(nowMs);
}
else if (null != election)
{
workCount += election.doWork(nowMs);
}
else
{
workCount += consensusWork(nowMs);
}
return workCount;
}
public String roleName()
{
return "consensus-module";
}
public void onSessionConnect(
final long correlationId,
final int responseStreamId,
final int version,
final String responseChannel,
final byte[] encodedCredentials)
{
final long clusterSessionId = Cluster.Role.LEADER == role ? nextSessionId++ : NULL_VALUE;
final ClusterSession session = new ClusterSession(clusterSessionId, responseStreamId, responseChannel);
session.lastActivity(cachedTimeMs, correlationId);
session.connect(aeron);
if (Cluster.Role.LEADER != role)
{
redirectSessions.add(session);
}
else
{
if (AeronCluster.Configuration.MAJOR_VERSION != SemanticVersion.major(version))
{
final String detail = SESSION_INVALID_VERSION_MSG + " " + SemanticVersion.toString(version) +
", cluster is " + SemanticVersion.toString(AeronCluster.Configuration.SEMANTIC_VERSION);
session.reject(EventCode.ERROR, detail);
rejectedSessions.add(session);
}
else if (pendingSessions.size() + sessionByIdMap.size() >= ctx.maxConcurrentSessions())
{
session.reject(EventCode.ERROR, SESSION_LIMIT_MSG);
rejectedSessions.add(session);
}
else
{
authenticator.onConnectRequest(session.id(), encodedCredentials, clusterTimeMs);
pendingSessions.add(session);
}
}
}
public void onSessionClose(final long clusterSessionId)
{
final ClusterSession session = sessionByIdMap.get(clusterSessionId);
if (null != session && Cluster.Role.LEADER == role)
{
session.close(CloseReason.CLIENT_ACTION);
if (logPublisher.appendSessionClose(session, leadershipTermId, clusterTimeMs))
{
sessionByIdMap.remove(clusterSessionId);
}
}
}
public ControlledFragmentAssembler.Action onIngressMessage(
final long leadershipTermId,
final long clusterSessionId,
final DirectBuffer buffer,
final int offset,
final int length)
{
if (leadershipTermId != this.leadershipTermId || Cluster.Role.LEADER != role)
{
return ControlledFragmentHandler.Action.CONTINUE;
}
final ClusterSession session = sessionByIdMap.get(clusterSessionId);
if (null == session || session.state() == CLOSED)
{
return ControlledFragmentHandler.Action.CONTINUE;
}
if (session.state() == OPEN &&
logPublisher.appendMessage(leadershipTermId, clusterSessionId, clusterTimeMs, buffer, offset, length))
{
session.timeOfLastActivityMs(clusterTimeMs);
return ControlledFragmentHandler.Action.CONTINUE;
}
return ControlledFragmentHandler.Action.ABORT;
}
public void onSessionKeepAlive(final long clusterSessionId, final long leadershipTermId)
{
if (Cluster.Role.LEADER == role && leadershipTermId == this.leadershipTermId)
{
final ClusterSession session = sessionByIdMap.get(clusterSessionId);
if (null != session && session.state() == OPEN)
{
session.timeOfLastActivityMs(clusterTimeMs);
}
}
}
public void onChallengeResponse(
final long correlationId, final long clusterSessionId, final byte[] encodedCredentials)
{
if (Cluster.Role.LEADER == role)
{
for (int lastIndex = pendingSessions.size() - 1, i = lastIndex; i >= 0; i--)
{
final ClusterSession session = pendingSessions.get(i);
if (session.id() == clusterSessionId && session.state() == CHALLENGED)
{
session.lastActivity(clusterTimeMs, correlationId);
authenticator.onChallengeResponse(clusterSessionId, encodedCredentials, clusterTimeMs);
break;
}
}
}
}
public boolean onTimerEvent(final long correlationId, final long nowMs)
{
return Cluster.Role.LEADER != role || logPublisher.appendTimer(correlationId, leadershipTermId, nowMs);
}
public void onCanvassPosition(final long logLeadershipTermId, final long logPosition, final int followerMemberId)
{
if (null != election)
{
election.onCanvassPosition(logLeadershipTermId, logPosition, followerMemberId);
}
else if (Cluster.Role.LEADER == role)
{
final ClusterMember follower = clusterMemberByIdMap.get(followerMemberId);
if (null != follower)
{
final long position = logLeadershipTermId == this.leadershipTermId ?
this.logPosition() :
recordingLog.getTermEntry(this.leadershipTermId).termBaseLogPosition;
memberStatusPublisher.newLeadershipTerm(
follower.publication(),
this.leadershipTermId,
position,
this.leadershipTermId,
this.logPosition(),
thisMember.id(),
logPublisher.sessionId());
}
}
}
public void onRequestVote(
final long logLeadershipTermId, final long logPosition, final long candidateTermId, final int candidateId)
{
if (null != election)
{
election.onRequestVote(logLeadershipTermId, logPosition, candidateTermId, candidateId);
}
else if (candidateTermId > this.leadershipTermId)
{
ctx.countedErrorHandler().onError(new ClusterException("unexpected vote request"));
enterElection(cachedTimeMs);
election.onRequestVote(logLeadershipTermId, logPosition, candidateTermId, candidateId);
}
}
public void onVote(
final long candidateTermId,
final long logLeadershipTermId,
final long logPosition,
final int candidateMemberId,
final int followerMemberId,
final boolean vote)
{
if (null != election)
{
election.onVote(
candidateTermId, logLeadershipTermId, logPosition, candidateMemberId, followerMemberId, vote);
}
}
public void onNewLeadershipTerm(
final long logLeadershipTermId,
final long logPosition,
final long leadershipTermId,
final long maxLogPosition,
final int leaderMemberId,
final int logSessionId)
{
if (null != election)
{
election.onNewLeadershipTerm(
logLeadershipTermId, logPosition, leadershipTermId, maxLogPosition, leaderMemberId, logSessionId);
}
else if (leadershipTermId > this.leadershipTermId)
{
ctx.countedErrorHandler().onError(new ClusterException("unexpected new leadership term"));
enterElection(cachedTimeMs);
}
}
public void onAppendedPosition(final long leadershipTermId, final long logPosition, final int followerMemberId)
{
if (null != election)
{
election.onAppendedPosition(leadershipTermId, logPosition, followerMemberId);
}
else if (Cluster.Role.LEADER == role && leadershipTermId == this.leadershipTermId)
{
final ClusterMember follower = clusterMemberByIdMap.get(followerMemberId);
if (null != follower)
{
follower
.logPosition(logPosition)
.timeOfLastAppendPositionMs(cachedTimeMs);
checkCatchupStop(follower);
}
}
}
public void onCommitPosition(final long leadershipTermId, final long logPosition, final int leaderMemberId)
{
if (null != election)
{
election.onCommitPosition(leadershipTermId, logPosition, leaderMemberId);
}
else if (Cluster.Role.FOLLOWER == role && leadershipTermId == this.leadershipTermId)
{
timeOfLastLogUpdateMs = cachedTimeMs;
followerCommitPosition = logPosition;
}
else if (leadershipTermId > this.leadershipTermId)
{
ctx.countedErrorHandler().onError(new ClusterException("unexpected commit position from new leader"));
enterElection(cachedTimeMs);
}
}
public void onCatchupPosition(final long leadershipTermId, final long logPosition, final int followerMemberId)
{
if (Cluster.Role.LEADER == role && leadershipTermId == this.leadershipTermId)
{
final ClusterMember follower = clusterMemberByIdMap.get(followerMemberId);
if (null != follower)
{
final String replayChannel = new ChannelUriStringBuilder()
.media(CommonContext.UDP_MEDIA)
.endpoint(follower.transferEndpoint())
.isSessionIdTagged(true)
.sessionId(ConsensusModule.Configuration.LOG_PUBLICATION_SESSION_ID_TAG)
.build();
if (follower.catchupReplaySessionId() == Aeron.NULL_VALUE)
{
follower.catchupReplaySessionId(archive.startReplay(
logRecordingId(), logPosition, Long.MAX_VALUE, replayChannel, ctx.logStreamId()));
}
}
}
}
public void onStopCatchup(final long leadershipTermId, final long logPosition, final int followerMemberId)
{
if (null != logAdapter && null != replayLogDestination && followerMemberId == memberId)
{
logAdapter.removeDestination(replayLogDestination);
replayLogDestination = null;
}
}
public void onAddPassiveMember(final long correlationId, final String memberEndpoints)
{
if (null == election && Cluster.Role.LEADER == role)
{
if (ClusterMember.isNotDuplicateEndpoints(passiveMembers, memberEndpoints))
{
final ClusterMember newMember = ClusterMember.parseEndpoints(++highMemberId, memberEndpoints);
newMember.correlationId(correlationId);
passiveMembers = ClusterMember.addMember(passiveMembers, newMember);
clusterMemberByIdMap.put(newMember.id(), newMember);
final ChannelUri memberStatusUri = ChannelUri.parse(ctx.memberStatusChannel());
ClusterMember.addMemberStatusPublication(
newMember, memberStatusUri, ctx.memberStatusStreamId(), aeron);
logPublisher.addPassiveFollower(newMember.logEndpoint());
}
}
else if (null == election && Cluster.Role.FOLLOWER == role)
{
// redirect add to leader. Leader will respond
memberStatusPublisher.addPassiveMember(leaderMember.publication(), correlationId, memberEndpoints);
}
}
public void onClusterMembersChange(
final long correlationId, final int leaderMemberId, final String activeMembers, final String passiveMembers)
{
if (null != dynamicJoin)
{
dynamicJoin.onClusterMembersChange(correlationId, leaderMemberId, activeMembers, passiveMembers);
}
}
public void onSnapshotRecordingQuery(final long correlationId, final int requestMemberId)
{
if (null == election && Cluster.Role.LEADER == role)
{
final ClusterMember requester = clusterMemberByIdMap.get(requestMemberId);
if (null != requester)
{
final RecordingLog.RecoveryPlan currentRecoveryPlan =
recordingLog.createRecoveryPlan(archive, ctx.serviceCount());
memberStatusPublisher.snapshotRecording(
requester.publication(),
correlationId,
currentRecoveryPlan,
ClusterMember.encodeAsString(clusterMembers));
}
}
}
public void onSnapshotRecordings(final long correlationId, final SnapshotRecordingsDecoder decoder)
{
if (null != dynamicJoin)
{
dynamicJoin.onSnapshotRecordings(correlationId, decoder);
}
}
@SuppressWarnings("unused")
public void onJoinCluster(final long leadershipTermId, final int memberId)
{
final ClusterMember member = clusterMemberByIdMap.get(memberId);
if (null == election && Cluster.Role.LEADER == role && null != member && !member.hasRequestedJoin())
{
if (null == member.publication())
{
final ChannelUri memberStatusUri = ChannelUri.parse(ctx.memberStatusChannel());
ClusterMember.addMemberStatusPublication(member, memberStatusUri, ctx.memberStatusStreamId(), aeron);
logPublisher.addPassiveFollower(member.logEndpoint());
}
member.hasRequestedJoin(true);
}
}
public void onTerminationPosition(final long logPosition)
{
if (Cluster.Role.FOLLOWER == role)
{
terminationPosition = logPosition;
}
}
public void onTerminationAck(final long logPosition, final int memberId)
{
if (Cluster.Role.LEADER == role && logPosition == terminationPosition)
{
final ClusterMember member = clusterMemberByIdMap.get(memberId);
if (null != member)
{
member.hasSentTerminationAck(true);
if (clusterTermination.canTerminate(clusterMembers, terminationPosition, cachedTimeMs))
{
recordingLog.commitLogPosition(leadershipTermId, logPosition);
state(ConsensusModule.State.CLOSED);
ctx.terminationHook().run();
}
}
}
}
void state(final ConsensusModule.State state)
{
this.state = state;
moduleState.set(state.code());
}
void role(final Cluster.Role role)
{
this.role = role;
clusterRoleCounter.setOrdered(role.code());
}
Cluster.Role role()
{
return role;
}
void prepareForNewLeadership(final long logPosition)
{
long recordingId = RecordingPos.NULL_RECORDING_ID;
if (null != appendedPosition)
{
recordingId = RecordingPos.getRecordingId(aeron.countersReader(), appendedPosition.counterId());
}
if (RecordingPos.NULL_RECORDING_ID == recordingId)
{
recordingId = recordingLog.findLastTermRecordingId();
if (RecordingPos.NULL_RECORDING_ID == recordingId)
{
return;
}
}
stopLogRecording();
long stopPosition;
idleStrategy.reset();
while (AeronArchive.NULL_POSITION == (stopPosition = archive.getStopPosition(recordingId)))
{
idle();
}
if (stopPosition > logPosition)
{
archive.truncateRecording(recordingId, logPosition);
}
if (NULL_VALUE == logInitialTermId)
{
final RecordingExtent recordingExtent = new RecordingExtent();
if (0 == archive.listRecording(recordingId, recordingExtent))
{
throw new ClusterException("recording not found id=" + recordingId);
}
logInitialTermId = recordingExtent.initialTermId;
logTermBufferLength = recordingExtent.termBufferLength;
logMtuLength = recordingExtent.mtuLength;
}
lastAppendedPosition = logPosition;
followerCommitPosition = logPosition;
lastRecordingId = recordingId;
commitPosition.setOrdered(logPosition);
clearSessionsAfter(logPosition);
}
void stopLogRecording()
{
if (null != logRecordingChannel)
{
archive.stopRecording(logRecordingChannel, ctx.logStreamId());
logRecordingChannel = null;
}
if (null != logAdapter && null != replayLogDestination)
{
logAdapter.removeDestination(replayLogDestination);
replayLogDestination = null;
}
if (null != logAdapter && null != liveLogDestination)
{
logAdapter.removeDestination(liveLogDestination);
liveLogDestination = null;
}
}
void appendedPositionCounter(final ReadableCounter appendedPositionCounter)
{
this.appendedPosition = appendedPositionCounter;
}
void clearSessionsAfter(final long logPosition)
{
for (final Iterator<ClusterSession> i = sessionByIdMap.values().iterator(); i.hasNext(); )
{
final ClusterSession session = i.next();
if (session.openedLogPosition() > logPosition)
{
i.remove();
session.close();
}
}
for (final ClusterSession session : pendingSessions)
{
session.close();
}
pendingSessions.clear();
}
void onServiceCloseSession(final long clusterSessionId)
{
final ClusterSession session = sessionByIdMap.get(clusterSessionId);
if (null != session)
{
if (session.isResponsePublicationConnected())
{
egressPublisher.sendEvent(
session, leadershipTermId, leaderMember.id(), EventCode.ERROR, SESSION_TERMINATED_MSG);
}
session.close(CloseReason.SERVICE_ACTION);
if (Cluster.Role.LEADER == role &&
logPublisher.appendSessionClose(session, leadershipTermId, clusterTimeMs))
{
sessionByIdMap.remove(clusterSessionId);
}
}
}
void onScheduleTimer(final long correlationId, final long deadlineMs)
{
timerService.scheduleTimer(correlationId, deadlineMs);
}
void onCancelTimer(final long correlationId)
{
timerService.cancelTimer(correlationId);
}
void onServiceAck(final long logPosition, final long ackId, final long relevantId, final int serviceId)
{
validateServiceAck(logPosition, ackId, serviceId);
serviceAcks[serviceId].logPosition(logPosition).ackId(ackId).relevantId(relevantId);
if (ServiceAck.hasReachedPosition(logPosition, serviceAckId, serviceAcks))
{
switch (state)
{
case SNAPSHOT:
++serviceAckId;
takeSnapshot(clusterTimeMs, logPosition);
if (NULL_POSITION == terminationPosition)
{
state(ConsensusModule.State.ACTIVE);
ClusterControl.ToggleState.reset(controlToggle);
for (final ClusterSession session : sessionByIdMap.values())
{
session.timeOfLastActivityMs(clusterTimeMs);
}
}
else
{
serviceProxy.terminationPosition(terminationPosition);
if (null != clusterTermination)
{
clusterTermination.deadlineMs(
cachedTimeMs + TimeUnit.NANOSECONDS.toMillis(ctx.terminationTimeoutNs()));
}
state(ConsensusModule.State.TERMINATING);
}
break;
case LEAVING:
recordingLog.commitLogPosition(leadershipTermId, logPosition);
state(ConsensusModule.State.CLOSED);
ctx.terminationHook().run();
break;
case TERMINATING:
final boolean canTerminate;
if (null == clusterTermination)
{
memberStatusPublisher.terminationAck(leaderMember.publication(), logPosition, memberId);
canTerminate = true;
}
else
{
clusterTermination.hasServiceTerminated(true);
canTerminate = clusterTermination.canTerminate(
clusterMembers, terminationPosition, cachedTimeMs);
}
if (canTerminate)
{
recordingLog.commitLogPosition(leadershipTermId, logPosition);
state(ConsensusModule.State.CLOSED);
ctx.terminationHook().run();
}
break;
}
}
}
public void onClusterMembersQuery(final long correlationId)
{
serviceProxy.clusterMembersResponse(
correlationId,
leaderMember.id(),
ClusterMember.encodeAsString(clusterMembers),
ClusterMember.encodeAsString(passiveMembers));
}
public void onRemoveMember(
@SuppressWarnings("unused") final long correlationId, final int memberId, final boolean isPassive)
{
final ClusterMember member = clusterMemberByIdMap.get(memberId);
if (null == election && Cluster.Role.LEADER == role && null != member)
{
if (isPassive)
{
passiveMembers = ClusterMember.removeMember(passiveMembers, memberId);
member.publication().close();
member.publication(null);
logPublisher.removePassiveFollower(member.logEndpoint());
clusterMemberByIdMap.remove(memberId);
clusterMemberByIdMap.compact();
}
else
{
final ClusterMember[] newClusterMembers = ClusterMember.removeMember(clusterMembers, memberId);
final String newClusterMembersString = ClusterMember.encodeAsString(newClusterMembers);
final long position = logPublisher.calculatePositionForMembershipChangeEvent(newClusterMembersString);
if (logPublisher.appendMembershipChangeEvent(
leadershipTermId,
position,
clusterTimeMs,
thisMember.id(),
clusterMembers.length,
ChangeType.QUIT,
memberId,
newClusterMembersString))
{
timeOfLastLogUpdateMs = cachedTimeMs - leaderHeartbeatIntervalMs;
member.removalPosition(logPublisher.position());
pendingMemberRemovals++;
}
}
}
}
@SuppressWarnings("unused")
void onReplaySessionMessage(
final long clusterSessionId,
final long timestamp,
final DirectBuffer buffer,
final int offset,
final int length,
final Header header)
{
clusterTimeMs(timestamp);
sessionByIdMap.get(clusterSessionId).timeOfLastActivityMs(timestamp);
}
void onReplayTimerEvent(final long correlationId, final long timestamp)
{
clusterTimeMs(timestamp);
if (!timerService.cancelTimer(correlationId))
{
missedTimersSet.add(correlationId);
}
}
void onReplaySessionOpen(
final long logPosition,
final long correlationId,
final long clusterSessionId,
final long timestamp,
final int responseStreamId,
final String responseChannel)
{
clusterTimeMs(timestamp);
final ClusterSession session = new ClusterSession(clusterSessionId, responseStreamId, responseChannel);
session.open(logPosition);
session.lastActivity(timestamp, correlationId);
sessionByIdMap.put(clusterSessionId, session);
if (clusterSessionId >= nextSessionId)
{
nextSessionId = clusterSessionId + 1;
}
}
void onLoadSession(
final long clusterSessionId,
final long correlationId,
final long openedPosition,
final long timeOfLastActivity,
final CloseReason closeReason,
final int responseStreamId,
final String responseChannel)
{
sessionByIdMap.put(clusterSessionId, new ClusterSession(
clusterSessionId,
correlationId,
openedPosition,
timeOfLastActivity,
responseStreamId,
responseChannel,
closeReason));
if (clusterSessionId >= nextSessionId)
{
nextSessionId = clusterSessionId + 1;
}
}
void onReplaySessionClose(final long clusterSessionId, final long timestamp, final CloseReason closeReason)
{
clusterTimeMs(timestamp);
sessionByIdMap.remove(clusterSessionId).close(closeReason);
}
@SuppressWarnings("unused")
void onReplayClusterAction(
final long leadershipTermId, final long logPosition, final long timestamp, final ClusterAction action)
{
clusterTimeMs(timestamp);
switch (action)
{
case SUSPEND:
state(ConsensusModule.State.SUSPENDED);
break;
case RESUME:
state(ConsensusModule.State.ACTIVE);
break;
case SNAPSHOT:
expectedAckPosition = logPosition;
state(ConsensusModule.State.SNAPSHOT);
break;
}
}
@SuppressWarnings("unused")
void onReplayNewLeadershipTermEvent(
final long leadershipTermId,
final long logPosition,
final long timestamp,
final int leaderMemberId,
final int logSessionId)
{
clusterTimeMs(timestamp);
this.leadershipTermId = leadershipTermId;
if (null != election && null != appendedPosition)
{
final long recordingId = RecordingPos.getRecordingId(aeron.countersReader(), appendedPosition.counterId());
election.onReplayNewLeadershipTermEvent(recordingId, leadershipTermId, logPosition, cachedTimeMs);
}
}
@SuppressWarnings("unused")
void onMembershipClusterChange(
final long leadershipTermId,
final long logPosition,
final long timestamp,
final int leaderMemberId,
final int clusterSize,
final ChangeType changeType,
final int memberId,
final String clusterMembers)
{
clusterTimeMs(timestamp);
this.leadershipTermId = leadershipTermId;
final ClusterMember[] newMembers = ClusterMember.parse(clusterMembers);
if (ChangeType.JOIN == changeType)
{
if (memberId == this.memberId)
{
this.clusterMembers = newMembers;
clusterMemberByIdMap.clear();
clusterMemberByIdMap.compact();
ClusterMember.addClusterMemberIds(newMembers, clusterMemberByIdMap);
thisMember = ClusterMember.findMember(this.clusterMembers, memberId);
leaderMember = ClusterMember.findMember(this.clusterMembers, leaderMemberId);
ClusterMember.addMemberStatusPublications(
newMembers,
thisMember,
ChannelUri.parse(ctx.memberStatusChannel()),
ctx.memberStatusStreamId(),
aeron);
}
else
{
clusterMemberJoined(memberId, newMembers);
}
}
else if (ChangeType.QUIT == changeType)
{
if (memberId == this.memberId)
{
expectedAckPosition = logPosition;
state(ConsensusModule.State.LEAVING);
}
else
{
final boolean hasCurrentLeaderSteppedDown = leaderMemberId == memberId;
clusterMemberQuit(memberId);
if (hasCurrentLeaderSteppedDown)
{
enterElection(cachedTimeMs);
}
}
}
}
void onReloadState(final long nextSessionId)
{
this.nextSessionId = nextSessionId;
}
void onReloadClusterMembers(final int memberId, final int highMemberId, final String members)
{
if (ctx.clusterMembersIgnoreSnapshot() || null != dynamicJoin)
{
return;
}
// TODO: this must be superset of any configured cluster members, unless being overridden
final ClusterMember[] snapshotClusterMembers = ClusterMember.parse(members);
if (Aeron.NULL_VALUE == this.memberId)
{
this.memberId = memberId;
ctx.clusterMarkFile().memberId(memberId);
}
if (ClusterMember.EMPTY_CLUSTER_MEMBER_ARRAY == this.clusterMembers)
{
clusterMembers = snapshotClusterMembers;
this.highMemberId = Math.max(ClusterMember.highMemberId(clusterMembers), highMemberId);
rankedPositions = new long[ClusterMember.quorumThreshold(clusterMembers.length)];
thisMember = clusterMemberByIdMap.get(this.memberId);
final ChannelUri memberStatusUri = ChannelUri.parse(ctx.memberStatusChannel());
memberStatusUri.put(ENDPOINT_PARAM_NAME, thisMember.memberFacingEndpoint());
ClusterMember.addMemberStatusPublications(
clusterMembers, thisMember, memberStatusUri, ctx.memberStatusStreamId(), aeron);
}
}
Publication addNewLogPublication()
{
closeExistingLog();
final ChannelUri channelUri = ChannelUri.parse(ctx.logChannel());
final Publication publication = createLogPublication(channelUri, recoveryPlan, election.logPosition());
logPublisher.connect(publication);
return publication;
}
void becomeLeader(final long leadershipTermId, final long logPosition, final int logSessionId)
{
this.leadershipTermId = leadershipTermId;
final ChannelUri channelUri = ChannelUri.parse(ctx.logChannel());
channelUri.put(CommonContext.SESSION_ID_PARAM_NAME, Integer.toString(logSessionId));
startLogRecording(channelUri.toString(), SourceLocation.LOCAL);
createAppendPosition(logSessionId);
awaitServicesReady(channelUri, logSessionId, logPosition);
for (final ClusterSession session : sessionByIdMap.values())
{
if (session.state() != CLOSED)
{
session.connect(aeron);
}
}
final long nowMs = epochClock.time();
for (final ClusterSession session : sessionByIdMap.values())
{
if (session.state() != CLOSED)
{
session.timeOfLastActivityMs(nowMs);
session.hasNewLeaderEventPending(true);
}
}
}
void followerCommitPosition(final long position)
{
followerCommitPosition = position;
}
void updateMemberDetails(final Election election)
{
leaderMember = election.leader();
sessionProxy.leaderMemberId(leaderMember.id()).leadershipTermId(leadershipTermId);
for (final ClusterMember clusterMember : clusterMembers)
{
clusterMember.isLeader(clusterMember.id() == leaderMember.id());
}
updateClientFacingEndpoints(clusterMembers);
}
void liveLogDestination(final String liveLogDestination)
{
this.liveLogDestination = liveLogDestination;
}
void replayLogDestination(final String replayLogDestination)
{
this.replayLogDestination = replayLogDestination;
}
Subscription createAndRecordLogSubscriptionAsFollower(final String logChannel)
{
closeExistingLog();
final Subscription subscription = aeron.addSubscription(logChannel, ctx.logStreamId());
startLogRecording(logChannel, SourceLocation.REMOTE);
return subscription;
}
void appendDynamicJoinTermAndSnapshots()
{
if (!dynamicJoinSnapshots.isEmpty())
{
final long logRecordingId = logRecordingId();
final RecordingLog.Snapshot lastSnapshot = dynamicJoinSnapshots.get(dynamicJoinSnapshots.size() - 1);
recordingLog.appendTerm(
logRecordingId,
lastSnapshot.leadershipTermId,
lastSnapshot.termBaseLogPosition,
lastSnapshot.timestamp);
for (int i = dynamicJoinSnapshots.size() - 1; i >= 0; i--)
{
final RecordingLog.Snapshot snapshot = dynamicJoinSnapshots.get(i);
recordingLog.appendSnapshot(
snapshot.recordingId,
snapshot.leadershipTermId,
snapshot.termBaseLogPosition,
snapshot.logPosition,
snapshot.timestamp,
snapshot.serviceId);
}
dynamicJoinSnapshots.clear();
}
}
boolean pollImageAndLogAdapter(final Subscription subscription, final int logSessionId)
{
boolean result = false;
if (null == logAdapter)
{
final Image image = subscription.imageBySessionId(logSessionId);
if (null != image)
{
logAdapter = new LogAdapter(image, this);
lastAppendedPosition = 0;
createAppendPosition(logSessionId);
appendDynamicJoinTermAndSnapshots();
result = true;
}
}
else
{
result = true;
}
return result;
}
void awaitImageAndCreateFollowerLogAdapter(final Subscription subscription, final int logSessionId)
{
leadershipTermId = election.leadershipTermId();
idleStrategy.reset();
while (!pollImageAndLogAdapter(subscription, logSessionId))
{
idle();
}
}
void awaitServicesReady(final ChannelUri logChannelUri, final int logSessionId, final long logPosition)
{
final String channel = Cluster.Role.LEADER == role && UDP_MEDIA.equals(logChannelUri.media()) ?
logChannelUri.prefix(SPY_QUALIFIER).toString() : logChannelUri.toString();
serviceProxy.joinLog(
leadershipTermId, logPosition, Long.MAX_VALUE, memberId, logSessionId, ctx.logStreamId(), channel);
expectedAckPosition = logPosition;
awaitServiceAcks(logPosition);
}
LogReplay newLogReplay(final long electionCommitPosition)
{
final RecordingLog.RecoveryPlan plan = recoveryPlan;
LogReplay logReplay = null;
if (!plan.logs.isEmpty())
{
final RecordingLog.Log log = plan.logs.get(0);
final long startPosition = log.startPosition;
final long stopPosition = Math.min(log.stopPosition, electionCommitPosition);
leadershipTermId = log.leadershipTermId;
if (log.logPosition < 0)
{
recordingLog.commitLogPosition(leadershipTermId, stopPosition);
}
if (plan.hasReplay())
{
logReplay = new LogReplay(
archive,
log.recordingId,
startPosition,
stopPosition,
leadershipTermId,
log.sessionId,
this,
ctx);
}
}
return logReplay;
}
void awaitServicesReadyForReplay(
final String channel,
final int streamId,
final int logSessionId,
final long leadershipTermId,
final long logPosition,
final long maxLogPosition)
{
serviceProxy.joinLog(leadershipTermId, logPosition, maxLogPosition, memberId, logSessionId, streamId, channel);
expectedAckPosition = logPosition;
awaitServiceAcks(logPosition);
}
void awaitServicesReplayComplete(final long stopPosition)
{
expectedAckPosition = stopPosition;
awaitServiceAcks(stopPosition);
while (0 != timerService.poll(clusterTimeMs) ||
(timerService.currentTickTimeMs() < clusterTimeMs && timerService.timerCount() > 0))
{
idle();
}
}
void replayLogPoll(final LogAdapter logAdapter, final long stopPosition)
{
final int workCount = logAdapter.poll(stopPosition);
if (0 == workCount)
{
if (logAdapter.isImageClosed() && logAdapter.position() != stopPosition)
{
throw new ClusterException("unexpected close of image when replaying log");
}
}
commitPosition.setOrdered(logAdapter.position());
consensusModuleAdapter.poll();
cancelMissedTimers();
}
long logRecordingId()
{
if (!recoveryPlan.logs.isEmpty())
{
return recoveryPlan.logs.get(0).recordingId;
}
return RecordingPos.getRecordingId(aeron.countersReader(), appendedPosition.counterId());
}
long logStopPosition(final long leadershipTermId)
{
if (NULL_VALUE == leadershipTermId)
{
return 0;
}
return recordingLog.getTermEntry(leadershipTermId).logPosition;
}
void truncateLogEntry(final long leadershipTermId, final long logPosition)
{
archive.truncateRecording(logRecordingId(), logPosition);
recordingLog.commitLogPosition(leadershipTermId, logPosition);
}
public void checkCatchupStop(final ClusterMember member)
{
if (null != member && Aeron.NULL_VALUE != member.catchupReplaySessionId())
{
if (member.logPosition() >= logPublisher.position())
{
archive.stopReplay(member.catchupReplaySessionId());
if (memberStatusPublisher.stopCatchup(
member.publication(), leadershipTermId, logPublisher.position(), member.id()))
{
member.catchupReplaySessionId(Aeron.NULL_VALUE);
}
}
}
}
boolean electionComplete(final long nowMs)
{
boolean result = false;
if (Cluster.Role.LEADER == role)
{
if (logPublisher.appendNewLeadershipTermEvent(
leadershipTermId, election.logPosition(), nowMs, memberId, logPublisher.sessionId()))
{
timeOfLastLogUpdateMs = cachedTimeMs - leaderHeartbeatIntervalMs;
election = null;
result = true;
}
}
else
{
timeOfLastLogUpdateMs = cachedTimeMs;
timeOfLastAppendPosition = cachedTimeMs;
election = null;
result = true;
}
if (!ctx.ingressChannel().contains(ENDPOINT_PARAM_NAME))
{
final ChannelUri ingressUri = ChannelUri.parse(ctx.ingressChannel());
ingressUri.put(ENDPOINT_PARAM_NAME, thisMember.clientFacingEndpoint());
ingressAdapter.connect(aeron.addSubscription(
ingressUri.toString(), ctx.ingressStreamId(), null, this::onUnavailableIngressImage));
}
else if (Cluster.Role.LEADER == role)
{
ingressAdapter.connect(aeron.addSubscription(
ctx.ingressChannel(), ctx.ingressStreamId(), null, this::onUnavailableIngressImage));
}
cancelMissedTimers();
if (missedTimersSet.capacity() > LongHashSet.DEFAULT_INITIAL_CAPACITY)
{
missedTimersSet.compact();
}
return result;
}
boolean dynamicJoinComplete()
{
if (0 == clusterMembers.length)
{
clusterMembers = dynamicJoin.clusterMembers();
ClusterMember.addClusterMemberIds(clusterMembers, clusterMemberByIdMap);
leaderMember = dynamicJoin.leader();
final ChannelUri memberStatusUri = ChannelUri.parse(ctx.memberStatusChannel());
ClusterMember.addMemberStatusPublications(
clusterMembers, thisMember, memberStatusUri, ctx.memberStatusStreamId(), aeron);
}
if (NULL_VALUE == memberId)
{
memberId = dynamicJoin.memberId();
ctx.clusterMarkFile().memberId(memberId);
thisMember.id(dynamicJoin.memberId());
}
election = new Election(
true,
leadershipTermId,
recoveryPlan.appendedLogPosition,
clusterMembers,
clusterMemberByIdMap,
thisMember,
memberStatusAdapter,
memberStatusPublisher,
ctx,
this);
dynamicJoin = null;
return true;
}
void catchupLogPoll(final Subscription subscription, final int logSessionId, final long stopPosition)
{
if (pollImageAndLogAdapter(subscription, logSessionId))
{
final Image image = logAdapter.image();
if (logAdapter.poll(stopPosition) == 0 && image.isClosed())
{
throw new ClusterException("unexpected close of image when replaying log");
}
final long appendedPosition = this.appendedPosition.get();
if (appendedPosition != lastAppendedPosition)
{
final Publication publication = election.leader().publication();
if (memberStatusPublisher.appendedPosition(publication, leadershipTermId, appendedPosition, memberId))
{
lastAppendedPosition = appendedPosition;
timeOfLastAppendPosition = cachedTimeMs;
}
}
commitPosition.setOrdered(Math.min(image.position(), appendedPosition));
consensusModuleAdapter.poll();
cancelMissedTimers();
}
}
boolean hasAppendReachedPosition(final Subscription subscription, final int logSessionId, final long position)
{
return pollImageAndLogAdapter(subscription, logSessionId) && appendedPosition.get() >= position;
}
boolean hasAppendReachedLivePosition(final Subscription subscription, final int logSessionId, final long position)
{
boolean result = false;
if (pollImageAndLogAdapter(subscription, logSessionId))
{
final long appendPosition = appendedPosition.get();
final long window = logAdapter.image().termBufferLength() * 2L;
result = appendPosition >= (position - window);
}
return result;
}
void stopAllCatchups()
{
for (final ClusterMember member : clusterMembers)
{
if (member.catchupReplaySessionId() != Aeron.NULL_VALUE)
{
try
{
archive.stopReplay(member.catchupReplaySessionId());
}
catch (final Exception ex)
{
ctx.countedErrorHandler().onError(ex);
}
member.catchupReplaySessionId(Aeron.NULL_VALUE);
}
}
}
void retrievedSnapshot(final long localRecordingId, final RecordingLog.Snapshot leaderSnapshot)
{
dynamicJoinSnapshots.add(new RecordingLog.Snapshot(
localRecordingId,
leaderSnapshot.leadershipTermId,
leaderSnapshot.termBaseLogPosition,
leaderSnapshot.logPosition,
leaderSnapshot.timestamp,
leaderSnapshot.serviceId));
}
Counter loadSnapshotsFromDynamicJoin()
{
recoveryPlan = RecordingLog.createRecoveryPlan(dynamicJoinSnapshots);
final Counter recoveryStateCounter = addRecoveryStateCounter(recoveryPlan);
if (!recoveryPlan.snapshots.isEmpty())
{
recoverFromSnapshot(recoveryPlan.snapshots.get(0), archive);
}
return recoveryStateCounter;
}
boolean pollForEndOfSnapshotLoad(final Counter recoveryStateCounter)
{
consensusModuleAdapter.poll();
if (ServiceAck.hasReachedPosition(expectedAckPosition, serviceAckId, serviceAcks))
{
++serviceAckId;
recoveryStateCounter.close();
if (ConsensusModule.State.SUSPENDED != state)
{
state(ConsensusModule.State.ACTIVE);
}
timeOfLastLogUpdateMs = cachedTimeMs = epochClock.time();
leadershipTermId = recoveryPlan.lastLeadershipTermId;
return true;
}
return false;
}
private int slowTickWork(final long nowMs)
{
int workCount = 0;
markFile.updateActivityTimestamp(nowMs);
checkServiceHeartbeats(nowMs);
workCount += aeronClientInvoker.invoke();
workCount += processRedirectSessions(redirectSessions, nowMs);
workCount += processRejectedSessions(rejectedSessions, nowMs);
if (Cluster.Role.LEADER == role && null == election)
{
workCount += checkControlToggle(nowMs);
if (ConsensusModule.State.ACTIVE == state)
{
workCount += processPendingSessions(pendingSessions, nowMs);
workCount += checkSessions(sessionByIdMap, nowMs);
workCount += processPassiveMembers(passiveMembers);
if (!ClusterMember.hasActiveQuorum(clusterMembers, nowMs, leaderHeartbeatTimeoutMs))
{
ctx.countedErrorHandler().onError(new ClusterException("lost connection to quorum of followers"));
enterElection(nowMs);
workCount += 1;
}
}
else if (ConsensusModule.State.TERMINATING == state)
{
if (clusterTermination.canTerminate(clusterMembers, terminationPosition, cachedTimeMs))
{
recordingLog.commitLogPosition(leadershipTermId, terminationPosition);
state(ConsensusModule.State.CLOSED);
ctx.terminationHook().run();
}
}
}
else
{
cancelMissedTimers();
}
if (null != archive)
{
archive.checkForErrorResponse();
}
return workCount;
}
private int consensusWork(final long nowMs)
{
int workCount = 0;
if (Cluster.Role.LEADER == role && ConsensusModule.State.ACTIVE == state)
{
workCount += ingressAdapter.poll();
workCount += timerService.poll(nowMs);
}
else if (Cluster.Role.FOLLOWER == role &&
(ConsensusModule.State.ACTIVE == state || ConsensusModule.State.SUSPENDED == state))
{
workCount += ingressAdapter.poll();
final int count = logAdapter.poll(followerCommitPosition);
if (0 == count && logAdapter.isImageClosed())
{
ctx.countedErrorHandler().onError(new ClusterException("lost connection to leader"));
enterElection(nowMs);
return 1;
}
workCount += count;
if (NULL_POSITION != terminationPosition)
{
if (logAdapter.position() >= terminationPosition && ConsensusModule.State.SNAPSHOT != state)
{
serviceProxy.terminationPosition(terminationPosition);
expectedAckPosition = terminationPosition;
state(ConsensusModule.State.TERMINATING);
}
}
}
workCount += memberStatusAdapter.poll();
workCount += updateMemberPosition(nowMs);
workCount += consensusModuleAdapter.poll();
return workCount;
}
private void checkServiceHeartbeats(final long nowMs)
{
final long heartbeatThreshold = nowMs - serviceHeartbeatTimeoutMs;
if (null == dynamicJoin)
{
for (final Counter serviceHeartbeat : serviceHeartbeats)
{
final long heartbeat = serviceHeartbeat.get();
if (heartbeat < heartbeatThreshold)
{
ctx.countedErrorHandler().onError(new TimeoutException("no heartbeat from service: " + heartbeat));
ctx.terminationHook().run();
}
}
}
}
private int checkControlToggle(final long nowMs)
{
switch (ClusterControl.ToggleState.get(controlToggle))
{
case SUSPEND:
if (ConsensusModule.State.ACTIVE == state && appendAction(ClusterAction.SUSPEND, nowMs))
{
state(ConsensusModule.State.SUSPENDED);
ClusterControl.ToggleState.reset(controlToggle);
}
break;
case RESUME:
if (ConsensusModule.State.SUSPENDED == state && appendAction(ClusterAction.RESUME, nowMs))
{
state(ConsensusModule.State.ACTIVE);
ClusterControl.ToggleState.reset(controlToggle);
}
break;
case SNAPSHOT:
if (ConsensusModule.State.ACTIVE == state && appendAction(ClusterAction.SNAPSHOT, nowMs))
{
expectedAckPosition = logPosition();
state(ConsensusModule.State.SNAPSHOT);
}
break;
case SHUTDOWN:
if (ConsensusModule.State.ACTIVE == state && appendAction(ClusterAction.SNAPSHOT, nowMs))
{
final long position = logPosition();
clusterTermination = new ClusterTermination(
memberStatusPublisher,
cachedTimeMs + TimeUnit.NANOSECONDS.toMillis(ctx.terminationTimeoutNs()));
clusterTermination.terminationPosition(clusterMembers, thisMember, position);
terminationPosition = position;
expectedAckPosition = position;
state(ConsensusModule.State.SNAPSHOT);
}
break;
case ABORT:
if (ConsensusModule.State.ACTIVE == state)
{
final long position = logPosition();
clusterTermination = new ClusterTermination(
memberStatusPublisher,
cachedTimeMs + TimeUnit.NANOSECONDS.toMillis(ctx.terminationTimeoutNs()));
clusterTermination.terminationPosition(clusterMembers, thisMember, position);
terminationPosition = position;
expectedAckPosition = position;
serviceProxy.terminationPosition(terminationPosition);
state(ConsensusModule.State.TERMINATING);
}
break;
default:
return 0;
}
return 1;
}
private boolean appendAction(final ClusterAction action, final long nowMs)
{
final int length = DataHeaderFlyweight.HEADER_LENGTH +
MessageHeaderEncoder.ENCODED_LENGTH + ClusterActionRequestEncoder.BLOCK_LENGTH;
final long position = logPublisher.position() + BitUtil.align(length, FrameDescriptor.FRAME_ALIGNMENT);
return logPublisher.appendClusterAction(leadershipTermId, position, nowMs, action);
}
private int processPendingSessions(final ArrayList<ClusterSession> pendingSessions, final long nowMs)
{
int workCount = 0;
for (int lastIndex = pendingSessions.size() - 1, i = lastIndex; i >= 0; i--)
{
final ClusterSession session = pendingSessions.get(i);
if (session.state() == INIT || session.state() == CONNECTED)
{
if (session.isResponsePublicationConnected())
{
session.state(CONNECTED);
authenticator.onConnectedSession(sessionProxy.session(session), nowMs);
}
}
if (session.state() == CHALLENGED)
{
if (session.isResponsePublicationConnected())
{
authenticator.onChallengedSession(sessionProxy.session(session), nowMs);
}
}
if (session.state() == AUTHENTICATED)
{
ArrayListUtil.fastUnorderedRemove(pendingSessions, i, lastIndex--);
session.timeOfLastActivityMs(nowMs);
sessionByIdMap.put(session.id(), session);
appendSessionOpen(session, nowMs);
workCount += 1;
}
else if (session.state() == REJECTED)
{
ArrayListUtil.fastUnorderedRemove(pendingSessions, i, lastIndex--);
rejectedSessions.add(session);
}
else if (nowMs > (session.timeOfLastActivityMs() + sessionTimeoutMs))
{
ArrayListUtil.fastUnorderedRemove(pendingSessions, i, lastIndex--);
session.close();
ctx.timedOutClientCounter().incrementOrdered();
}
}
return workCount;
}
private int processRejectedSessions(final ArrayList<ClusterSession> rejectedSessions, final long nowMs)
{
int workCount = 0;
for (int lastIndex = rejectedSessions.size() - 1, i = lastIndex; i >= 0; i--)
{
final ClusterSession session = rejectedSessions.get(i);
final String detail = session.responseDetail();
final EventCode eventCode = session.eventCode();
if (egressPublisher.sendEvent(session, leadershipTermId, leaderMember.id(), eventCode, detail) ||
nowMs > (session.timeOfLastActivityMs() + sessionTimeoutMs))
{
ArrayListUtil.fastUnorderedRemove(rejectedSessions, i, lastIndex--);
session.close();
workCount++;
}
}
return workCount;
}
private int processRedirectSessions(final ArrayList<ClusterSession> redirectSessions, final long nowMs)
{
int workCount = 0;
for (int lastIndex = redirectSessions.size() - 1, i = lastIndex; i >= 0; i--)
{
final ClusterSession session = redirectSessions.get(i);
final EventCode eventCode = EventCode.REDIRECT;
final int id = leaderMember.id();
if (egressPublisher.sendEvent(session, leadershipTermId, id, eventCode, clientFacingEndpoints) ||
nowMs > (session.timeOfLastActivityMs() + sessionTimeoutMs))
{
ArrayListUtil.fastUnorderedRemove(redirectSessions, i, lastIndex--);
session.close();
workCount++;
}
}
return workCount;
}
private int processPassiveMembers(final ClusterMember[] passiveMembers)
{
int workCount = 0;
for (int i = 0, length = passiveMembers.length; i < length; i++)
{
final ClusterMember member = passiveMembers[i];
if (member.correlationId() != Aeron.NULL_VALUE)
{
if (memberStatusPublisher.clusterMemberChange(
member.publication(),
member.correlationId(),
leaderMember.id(),
ClusterMember.encodeAsString(clusterMembers),
ClusterMember.encodeAsString(passiveMembers)))
{
member.correlationId(Aeron.NULL_VALUE);
workCount++;
}
}
else if (member.hasRequestedJoin() && member.logPosition() == logPublisher.position())
{
final ClusterMember[] newMembers = ClusterMember.addMember(clusterMembers, member);
if (logPublisher.appendMembershipChangeEvent(
this.leadershipTermId,
logPublisher.position(),
clusterTimeMs,
thisMember.id(),
newMembers.length,
ChangeType.JOIN,
member.id(),
ClusterMember.encodeAsString(newMembers)))
{
timeOfLastLogUpdateMs = cachedTimeMs - leaderHeartbeatIntervalMs;
this.passiveMembers = ClusterMember.removeMember(this.passiveMembers, member.id());
this.clusterMembers = newMembers;
rankedPositions = new long[this.clusterMembers.length];
member.hasRequestedJoin(false);
workCount++;
break;
}
}
}
return workCount;
}
private int checkSessions(final Long2ObjectHashMap<ClusterSession> sessionByIdMap, final long nowMs)
{
int workCount = 0;
for (final Iterator<ClusterSession> i = sessionByIdMap.values().iterator(); i.hasNext(); )
{
final ClusterSession session = i.next();
if (nowMs > (session.timeOfLastActivityMs() + sessionTimeoutMs))
{
switch (session.state())
{
case OPEN:
if (session.isResponsePublicationConnected())
{
egressPublisher.sendEvent(
session, leadershipTermId, leaderMember.id(), EventCode.ERROR, SESSION_TIMEOUT_MSG);
}
session.close(CloseReason.TIMEOUT);
if (logPublisher.appendSessionClose(session, leadershipTermId, nowMs))
{
i.remove();
ctx.timedOutClientCounter().incrementOrdered();
}
break;
case CLOSED:
if (logPublisher.appendSessionClose(session, leadershipTermId, nowMs))
{
i.remove();
if (session.closeReason() == CloseReason.TIMEOUT)
{
ctx.timedOutClientCounter().incrementOrdered();
}
}
break;
default:
i.remove();
session.close();
}
workCount += 1;
}
else if (session.state() == CONNECTED)
{
appendSessionOpen(session, nowMs);
workCount += 1;
}
else if (session.hasNewLeaderEventPending())
{
sendNewLeaderEvent(session);
workCount += 1;
}
}
return workCount;
}
private void sendNewLeaderEvent(final ClusterSession session)
{
if (egressPublisher.newLeader(session, leadershipTermId, leaderMember.id(), clientFacingEndpoints))
{
session.hasNewLeaderEventPending(false);
}
}
private void appendSessionOpen(final ClusterSession session, final long nowMs)
{
final long resultingPosition = logPublisher.appendSessionOpen(session, leadershipTermId, nowMs);
if (resultingPosition > 0)
{
session.open(resultingPosition);
}
}
private void createAppendPosition(final int logSessionId)
{
final CountersReader counters = aeron.countersReader();
final int recordingCounterId = awaitRecordingCounter(counters, logSessionId);
appendedPosition = new ReadableCounter(counters, recordingCounterId);
}
private void recoverFromSnapshot(final RecordingLog.Snapshot snapshot, final AeronArchive archive)
{
clusterTimeMs(snapshot.timestamp);
expectedAckPosition = snapshot.logPosition;
leadershipTermId = snapshot.leadershipTermId;
final String channel = ctx.replayChannel();
final int streamId = ctx.replayStreamId();
final int sessionId = (int)archive.startReplay(snapshot.recordingId, 0, NULL_LENGTH, channel, streamId);
final String replaySubscriptionChannel = ChannelUri.addSessionId(channel, sessionId);
try (Subscription subscription = aeron.addSubscription(replaySubscriptionChannel, streamId))
{
final Image image = awaitImage(sessionId, subscription);
final ConsensusModuleSnapshotLoader snapshotLoader = new ConsensusModuleSnapshotLoader(image, this);
while (true)
{
final int fragments = snapshotLoader.poll();
if (fragments == 0)
{
if (snapshotLoader.isDone())
{
break;
}
if (image.isClosed())
{
throw new ClusterException("snapshot ended unexpectedly");
}
}
idle(fragments);
}
}
}
private Image awaitImage(final int sessionId, final Subscription subscription)
{
idleStrategy.reset();
Image image;
while ((image = subscription.imageBySessionId(sessionId)) == null)
{
idle();
}
return image;
}
private Counter addRecoveryStateCounter(final RecordingLog.RecoveryPlan plan)
{
final int snapshotsCount = plan.snapshots.size();
if (snapshotsCount > 0)
{
final long[] serviceSnapshotRecordingIds = new long[snapshotsCount - 1];
final RecordingLog.Snapshot snapshot = plan.snapshots.get(0);
for (int i = 1; i < snapshotsCount; i++)
{
final RecordingLog.Snapshot serviceSnapshot = plan.snapshots.get(i);
serviceSnapshotRecordingIds[serviceSnapshot.serviceId] = serviceSnapshot.recordingId;
}
return RecoveryState.allocate(
aeron,
tempBuffer,
snapshot.leadershipTermId,
snapshot.logPosition,
snapshot.timestamp,
plan.hasReplay(),
serviceSnapshotRecordingIds);
}
return RecoveryState.allocate(aeron, tempBuffer, leadershipTermId, 0, 0, plan.hasReplay());
}
private DynamicJoin requiresDynamicJoin()
{
if (recoveryPlan.snapshots.isEmpty() &&
0 == clusterMembers.length &&
null != ctx.clusterMembersStatusEndpoints())
{
return new DynamicJoin(
ctx.clusterMembersStatusEndpoints(),
archive,
memberStatusAdapter,
memberStatusPublisher,
ctx,
this);
}
return null;
}
private void awaitServiceAcks(final long logPosition)
{
while (!ServiceAck.hasReachedPosition(logPosition, serviceAckId, serviceAcks))
{
idle(consensusModuleAdapter.poll());
}
++serviceAckId;
}
private long logPosition()
{
return null != logAdapter ? logAdapter.position() : logPublisher.position();
}
private void validateServiceAck(final long logPosition, final long ackId, final int serviceId)
{
if (logPosition != expectedAckPosition || ackId != serviceAckId)
{
throw new ClusterException("invalid service ACK" +
" state " + state +
": serviceId=" + serviceId +
", logPosition=" + logPosition + " expected " + expectedAckPosition +
", ackId=" + ackId + " expected " + serviceAckId);
}
}
private void updateClientFacingEndpoints(final ClusterMember[] members)
{
final StringBuilder builder = new StringBuilder(100);
for (int i = 0, length = members.length; i < length; i++)
{
if (0 != i)
{
builder.append(',');
}
final ClusterMember member = members[i];
builder.append(member.id()).append('=').append(member.clientFacingEndpoint());
}
clientFacingEndpoints = builder.toString();
}
private void handleMemberRemovals(final long commitPosition)
{
ClusterMember[] newClusterMembers = clusterMembers;
for (final ClusterMember member : clusterMembers)
{
if (member.hasRequestedRemove() && member.removalPosition() <= commitPosition)
{
if (member == thisMember)
{
expectedAckPosition = commitPosition;
state(ConsensusModule.State.LEAVING);
}
newClusterMembers = ClusterMember.removeMember(newClusterMembers, member.id());
clusterMemberByIdMap.remove(member.id());
clusterMemberByIdMap.compact();
CloseHelper.close(member.publication());
member.publication(null);
logPublisher.removePassiveFollower(member.logEndpoint());
pendingMemberRemovals--;
}
}
clusterMembers = newClusterMembers;
rankedPositions = new long[clusterMembers.length];
}
private int updateMemberPosition(final long nowMs)
{
int workCount = 0;
final long appendedPosition = this.appendedPosition.get();
if (Cluster.Role.LEADER == role)
{
thisMember.logPosition(appendedPosition).timeOfLastAppendPositionMs(nowMs);
final long quorumPosition = ClusterMember.quorumPosition(clusterMembers, rankedPositions);
if (commitPosition.proposeMaxOrdered(Math.min(quorumPosition, appendedPosition)) ||
nowMs >= (timeOfLastLogUpdateMs + leaderHeartbeatIntervalMs))
{
final long commitPosition = this.commitPosition.getWeak();
for (final ClusterMember member : clusterMembers)
{
if (member != thisMember)
{
final Publication publication = member.publication();
memberStatusPublisher.commitPosition(publication, leadershipTermId, commitPosition, memberId);
}
}
timeOfLastLogUpdateMs = nowMs;
if (pendingMemberRemovals > 0)
{
handleMemberRemovals(commitPosition);
}
workCount += 1;
}
}
else
{
final Publication publication = leaderMember.publication();
if ((appendedPosition != lastAppendedPosition ||
nowMs >= (timeOfLastAppendPosition + leaderHeartbeatIntervalMs)) &&
memberStatusPublisher.appendedPosition(publication, leadershipTermId, appendedPosition, memberId))
{
lastAppendedPosition = appendedPosition;
timeOfLastAppendPosition = nowMs;
workCount += 1;
}
commitPosition.proposeMaxOrdered(Math.min(logAdapter.position(), appendedPosition));
if (nowMs >= (timeOfLastLogUpdateMs + leaderHeartbeatTimeoutMs))
{
ctx.countedErrorHandler().onError(new ClusterException("heartbeat timeout from leader"));
enterElection(nowMs);
workCount += 1;
}
}
return workCount;
}
private void enterElection(final long nowMs)
{
ingressAdapter.close();
commitPosition.proposeMaxOrdered(followerCommitPosition);
election = new Election(
false,
leadershipTermId,
commitPosition.getWeak(),
clusterMembers,
clusterMemberByIdMap,
thisMember,
memberStatusAdapter,
memberStatusPublisher,
ctx,
this);
election.doWork(nowMs);
serviceProxy.electionStartEvent(commitPosition.getWeak());
}
private void idle()
{
checkInterruptedStatus();
aeronClientInvoker.invoke();
idleStrategy.idle();
}
private void idle(final int workCount)
{
checkInterruptedStatus();
aeronClientInvoker.invoke();
idleStrategy.idle(workCount);
}
private static void checkInterruptedStatus()
{
if (Thread.currentThread().isInterrupted())
{
throw new TimeoutException("unexpected interrupt");
}
}
private void takeSnapshot(final long timestampMs, final long logPosition)
{
try (Publication publication = aeron.addExclusivePublication(ctx.snapshotChannel(), ctx.snapshotStreamId()))
{
final String channel = ChannelUri.addSessionId(ctx.snapshotChannel(), publication.sessionId());
final long subscriptionId = archive.startRecording(channel, ctx.snapshotStreamId(), LOCAL);
try
{
final CountersReader counters = aeron.countersReader();
final int counterId = awaitRecordingCounter(counters, publication.sessionId());
final long recordingId = RecordingPos.getRecordingId(counters, counterId);
final long termBaseLogPosition = recordingLog.getTermEntry(leadershipTermId).termBaseLogPosition;
snapshotState(publication, logPosition, leadershipTermId);
awaitRecordingComplete(recordingId, publication.position(), counters, counterId);
for (int serviceId = serviceAcks.length - 1; serviceId >= 0; serviceId--)
{
final long snapshotId = serviceAcks[serviceId].relevantId();
recordingLog.appendSnapshot(
snapshotId, leadershipTermId, termBaseLogPosition, logPosition, timestampMs, serviceId);
}
recordingLog.appendSnapshot(
recordingId, leadershipTermId, termBaseLogPosition, logPosition, timestampMs, SERVICE_ID);
recordingLog.force();
}
finally
{
archive.stopRecording(subscriptionId);
}
ctx.snapshotCounter().incrementOrdered();
}
}
private void awaitRecordingComplete(
final long recordingId, final long position, final CountersReader counters, final int counterId)
{
idleStrategy.reset();
do
{
idle();
if (!RecordingPos.isActive(counters, counterId, recordingId))
{
throw new ClusterException("recording has stopped unexpectedly: " + recordingId);
}
}
while (counters.getCounterValue(counterId) < position);
}
private int awaitRecordingCounter(final CountersReader counters, final int sessionId)
{
idleStrategy.reset();
int counterId = RecordingPos.findCounterIdBySession(counters, sessionId);
while (CountersReader.NULL_COUNTER_ID == counterId)
{
idle();
counterId = RecordingPos.findCounterIdBySession(counters, sessionId);
}
return counterId;
}
private void snapshotState(final Publication publication, final long logPosition, final long leadershipTermId)
{
final ConsensusModuleSnapshotTaker snapshotTaker = new ConsensusModuleSnapshotTaker(
publication, idleStrategy, aeronClientInvoker);
snapshotTaker.markBegin(SNAPSHOT_TYPE_ID, logPosition, leadershipTermId, 0);
for (final ClusterSession session : sessionByIdMap.values())
{
if (session.state() == OPEN || session.state() == CLOSED)
{
snapshotTaker.snapshotSession(session);
}
}
aeronClientInvoker.invoke();
timerService.snapshot(snapshotTaker);
snapshotTaker.consensusModuleState(nextSessionId);
snapshotTaker.clusterMembers(memberId, highMemberId, clusterMembers);
snapshotTaker.markEnd(SNAPSHOT_TYPE_ID, logPosition, leadershipTermId, 0);
}
private Publication createLogPublication(
final ChannelUri channelUri, final RecordingLog.RecoveryPlan plan, final long position)
{
channelUri.put(TAGS_PARAM_NAME, ConsensusModule.Configuration.LOG_PUBLICATION_TAGS);
if (!plan.logs.isEmpty())
{
final RecordingLog.Log log = plan.logs.get(0);
logInitialTermId = log.initialTermId;
logTermBufferLength = log.termBufferLength;
logMtuLength = log.mtuLength;
}
if (NULL_VALUE != logInitialTermId)
{
channelUri.initialPosition(position, logInitialTermId, logTermBufferLength);
channelUri.put(MTU_LENGTH_PARAM_NAME, Integer.toString(logMtuLength));
}
final Publication publication = aeron.addExclusivePublication(channelUri.toString(), ctx.logStreamId());
if (!channelUri.containsKey(ENDPOINT_PARAM_NAME) && UDP_MEDIA.equals(channelUri.media()))
{
final ChannelUriStringBuilder builder = new ChannelUriStringBuilder().media(UDP_MEDIA);
for (final ClusterMember member : clusterMembers)
{
if (member != thisMember)
{
publication.addDestination(builder.endpoint(member.logEndpoint()).build());
}
}
for (final ClusterMember member : passiveMembers)
{
publication.addDestination(builder.endpoint(member.logEndpoint()).build());
}
}
return publication;
}
private void startLogRecording(final String channel, final SourceLocation sourceLocation)
{
lastRecordingId = recordingLog.findLastTermRecordingId();
if (RecordingPos.NULL_RECORDING_ID == lastRecordingId)
{
archive.startRecording(channel, ctx.logStreamId(), sourceLocation);
}
else
{
archive.extendRecording(lastRecordingId, channel, ctx.logStreamId(), sourceLocation);
}
logRecordingChannel = channel;
}
private void clusterMemberJoined(final int memberId, final ClusterMember[] newMembers)
{
highMemberId = Math.max(highMemberId, memberId);
final ClusterMember eventMember = ClusterMember.findMember(newMembers, memberId);
this.clusterMembers = ClusterMember.addMember(this.clusterMembers, eventMember);
clusterMemberByIdMap.put(memberId, eventMember);
rankedPositions = new long[this.clusterMembers.length];
}
private void clusterMemberQuit(final int memberId)
{
clusterMembers = ClusterMember.removeMember(clusterMembers, memberId);
clusterMemberByIdMap.remove(memberId);
rankedPositions = new long[clusterMembers.length];
}
private void closeExistingLog()
{
logPublisher.disconnect();
CloseHelper.close(logAdapter);
logAdapter = null;
}
private void cancelMissedTimers()
{
for (final LongHashSet.LongIterator iterator = missedTimersSet.iterator(); iterator.hasNext(); )
{
if (timerService.cancelTimer(iterator.nextValue()))
{
iterator.remove();
}
}
}
private void onUnavailableIngressImage(final Image image)
{
ingressAdapter.freeSessionBuffer(image.sessionId());
}
private void clusterTimeMs(final long nowMs)
{
if (NULL_VALUE == clusterTimeMs)
{
timerService.resetStartTime(nowMs);
}
clusterTimeMs = nowMs;
}
private ClusterMember determineMemberAndCheckEndpoints(final ClusterMember[] clusterMembers)
{
final int memberId = ctx.clusterMemberId();
ClusterMember member = NULL_VALUE != memberId ? ClusterMember.findMember(clusterMembers, memberId) : null;
if ((null == clusterMembers || 0 == clusterMembers.length) && null == member)
{
member = ClusterMember.parseEndpoints(NULL_VALUE, ctx.memberEndpoints());
}
else
{
if (null == member)
{
throw new ClusterException("memberId=" + memberId + " not found in clusterMembers");
}
if (!ctx.memberEndpoints().equals(""))
{
ClusterMember.validateMemberEndpoints(member, ctx.memberEndpoints());
}
}
return member;
}
}
| aeron-cluster/src/main/java/io/aeron/cluster/ConsensusModuleAgent.java | /*
* Copyright 2014-2019 Real Logic Ltd.
*
* 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.aeron.cluster;
import io.aeron.*;
import io.aeron.archive.client.AeronArchive;
import io.aeron.archive.codecs.SourceLocation;
import io.aeron.archive.status.RecordingPos;
import io.aeron.cluster.client.AeronCluster;
import io.aeron.cluster.client.ClusterException;
import io.aeron.cluster.codecs.*;
import io.aeron.cluster.service.Cluster;
import io.aeron.cluster.service.ClusterMarkFile;
import io.aeron.cluster.service.RecoveryState;
import io.aeron.exceptions.TimeoutException;
import io.aeron.logbuffer.ControlledFragmentHandler;
import io.aeron.logbuffer.FrameDescriptor;
import io.aeron.logbuffer.Header;
import io.aeron.protocol.DataHeaderFlyweight;
import io.aeron.security.Authenticator;
import io.aeron.status.ReadableCounter;
import org.agrona.*;
import org.agrona.collections.ArrayListUtil;
import org.agrona.collections.Int2ObjectHashMap;
import org.agrona.collections.Long2ObjectHashMap;
import org.agrona.collections.LongHashSet;
import org.agrona.concurrent.Agent;
import org.agrona.concurrent.AgentInvoker;
import org.agrona.concurrent.EpochClock;
import org.agrona.concurrent.IdleStrategy;
import org.agrona.concurrent.status.CountersReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.TimeUnit;
import static io.aeron.Aeron.NULL_VALUE;
import static io.aeron.ChannelUri.SPY_QUALIFIER;
import static io.aeron.CommonContext.*;
import static io.aeron.archive.client.AeronArchive.NULL_LENGTH;
import static io.aeron.archive.client.AeronArchive.NULL_POSITION;
import static io.aeron.archive.codecs.SourceLocation.LOCAL;
import static io.aeron.cluster.ClusterSession.State.*;
import static io.aeron.cluster.ConsensusModule.Configuration.*;
class ConsensusModuleAgent implements Agent, MemberStatusListener
{
private final long sessionTimeoutMs;
private final long leaderHeartbeatIntervalMs;
private final long leaderHeartbeatTimeoutMs;
private final long serviceHeartbeatTimeoutMs;
private long nextSessionId = 1;
private long leadershipTermId = NULL_VALUE;
private long expectedAckPosition = 0;
private long serviceAckId = 0;
private long lastAppendedPosition = 0;
private long followerCommitPosition = 0;
private long terminationPosition = NULL_POSITION;
private long timeOfLastLogUpdateMs = 0;
private long timeOfLastAppendPosition = 0;
private long cachedTimeMs;
private long clusterTimeMs = NULL_VALUE;
private long lastRecordingId = RecordingPos.NULL_RECORDING_ID;
private int logInitialTermId = NULL_VALUE;
private int logTermBufferLength = NULL_VALUE;
private int logMtuLength = NULL_VALUE;
private int memberId;
private int highMemberId;
private int pendingMemberRemovals = 0;
private ReadableCounter appendedPosition;
private final Counter commitPosition;
private ConsensusModule.State state = ConsensusModule.State.INIT;
private Cluster.Role role;
private ClusterMember[] clusterMembers;
private ClusterMember[] passiveMembers = ClusterMember.EMPTY_CLUSTER_MEMBER_ARRAY;
private ClusterMember leaderMember;
private ClusterMember thisMember;
private long[] rankedPositions;
private final ServiceAck[] serviceAcks;
private final Counter clusterRoleCounter;
private final ClusterMarkFile markFile;
private final AgentInvoker aeronClientInvoker;
private final EpochClock epochClock;
private final Counter moduleState;
private final Counter controlToggle;
private final TimerService timerService;
private final ConsensusModuleAdapter consensusModuleAdapter;
private final ServiceProxy serviceProxy;
private final IngressAdapter ingressAdapter;
private final EgressPublisher egressPublisher;
private final LogPublisher logPublisher;
private LogAdapter logAdapter;
private final MemberStatusAdapter memberStatusAdapter;
private final MemberStatusPublisher memberStatusPublisher = new MemberStatusPublisher();
private final Long2ObjectHashMap<ClusterSession> sessionByIdMap = new Long2ObjectHashMap<>();
private final ArrayList<ClusterSession> pendingSessions = new ArrayList<>();
private final ArrayList<ClusterSession> rejectedSessions = new ArrayList<>();
private final ArrayList<ClusterSession> redirectSessions = new ArrayList<>();
private final Int2ObjectHashMap<ClusterMember> clusterMemberByIdMap = new Int2ObjectHashMap<>();
private final LongHashSet missedTimersSet = new LongHashSet();
private final Authenticator authenticator;
private final ClusterSessionProxy sessionProxy;
private final Aeron aeron;
private AeronArchive archive;
private final ConsensusModule.Context ctx;
private final MutableDirectBuffer tempBuffer;
private final Counter[] serviceHeartbeats;
private final IdleStrategy idleStrategy;
private final RecordingLog recordingLog;
private final ArrayList<RecordingLog.Snapshot> dynamicJoinSnapshots = new ArrayList<>();
private RecordingLog.RecoveryPlan recoveryPlan;
private Election election;
private DynamicJoin dynamicJoin;
private ClusterTermination clusterTermination;
private String logRecordingChannel;
private String liveLogDestination;
private String replayLogDestination;
private String clientFacingEndpoints;
ConsensusModuleAgent(final ConsensusModule.Context ctx)
{
this.ctx = ctx;
this.aeron = ctx.aeron();
this.epochClock = ctx.epochClock();
this.sessionTimeoutMs = TimeUnit.NANOSECONDS.toMillis(ctx.sessionTimeoutNs());
this.leaderHeartbeatIntervalMs = TimeUnit.NANOSECONDS.toMillis(ctx.leaderHeartbeatIntervalNs());
this.leaderHeartbeatTimeoutMs = TimeUnit.NANOSECONDS.toMillis(ctx.leaderHeartbeatTimeoutNs());
this.serviceHeartbeatTimeoutMs = TimeUnit.NANOSECONDS.toMillis(ctx.serviceHeartbeatTimeoutNs());
this.egressPublisher = ctx.egressPublisher();
this.moduleState = ctx.moduleStateCounter();
this.commitPosition = ctx.commitPositionCounter();
this.controlToggle = ctx.controlToggleCounter();
this.logPublisher = ctx.logPublisher();
this.idleStrategy = ctx.idleStrategy();
this.timerService = new TimerService(this);
this.clusterMembers = ClusterMember.parse(ctx.clusterMembers());
this.sessionProxy = new ClusterSessionProxy(egressPublisher);
this.memberId = ctx.clusterMemberId();
this.clusterRoleCounter = ctx.clusterNodeCounter();
this.markFile = ctx.clusterMarkFile();
this.recordingLog = ctx.recordingLog();
this.tempBuffer = ctx.tempBuffer();
this.serviceHeartbeats = ctx.serviceHeartbeatCounters();
this.serviceAcks = ServiceAck.newArray(ctx.serviceCount());
this.highMemberId = ClusterMember.highMemberId(clusterMembers);
aeronClientInvoker = aeron.conductorAgentInvoker();
aeronClientInvoker.invoke();
rankedPositions = new long[ClusterMember.quorumThreshold(clusterMembers.length)];
role(Cluster.Role.FOLLOWER);
ClusterMember.addClusterMemberIds(clusterMembers, clusterMemberByIdMap);
thisMember = determineMemberAndCheckEndpoints(clusterMembers);
leaderMember = thisMember;
final ChannelUri memberStatusUri = ChannelUri.parse(ctx.memberStatusChannel());
memberStatusUri.put(ENDPOINT_PARAM_NAME, thisMember.memberFacingEndpoint());
final int statusStreamId = ctx.memberStatusStreamId();
memberStatusAdapter = new MemberStatusAdapter(
aeron.addSubscription(memberStatusUri.toString(), statusStreamId), this);
ClusterMember.addMemberStatusPublications(clusterMembers, thisMember, memberStatusUri, statusStreamId, aeron);
ingressAdapter = new IngressAdapter(this, ctx.invalidRequestCounter());
consensusModuleAdapter = new ConsensusModuleAdapter(
aeron.addSubscription(ctx.serviceControlChannel(), ctx.consensusModuleStreamId()), this);
serviceProxy = new ServiceProxy(aeron.addPublication(ctx.serviceControlChannel(), ctx.serviceStreamId()));
authenticator = ctx.authenticatorSupplier().get();
}
public void onClose()
{
if (!ctx.ownsAeronClient())
{
for (final ClusterSession session : sessionByIdMap.values())
{
session.close();
}
CloseHelper.close(memberStatusAdapter);
ClusterMember.closeMemberPublications(clusterMembers);
logPublisher.disconnect();
CloseHelper.close(ingressAdapter);
CloseHelper.close(serviceProxy);
CloseHelper.close(consensusModuleAdapter);
}
CloseHelper.close(archive);
ctx.close();
}
public void onStart()
{
final ChannelUri archiveUri = ChannelUri.parse(ctx.archiveContext().controlRequestChannel());
ClusterMember.checkArchiveEndpoint(thisMember, archiveUri);
archiveUri.put(ENDPOINT_PARAM_NAME, thisMember.archiveEndpoint());
ctx.archiveContext().controlRequestChannel(archiveUri.toString());
archive = AeronArchive.connect(ctx.archiveContext().clone());
recoveryPlan = recordingLog.createRecoveryPlan(archive, ctx.serviceCount());
if (null == (dynamicJoin = requiresDynamicJoin()))
{
try (Counter ignore = addRecoveryStateCounter(recoveryPlan))
{
if (!recoveryPlan.snapshots.isEmpty())
{
recoverFromSnapshot(recoveryPlan.snapshots.get(0), archive);
}
awaitServiceAcks(expectedAckPosition);
}
if (ConsensusModule.State.SUSPENDED != state)
{
state(ConsensusModule.State.ACTIVE);
}
timeOfLastLogUpdateMs = cachedTimeMs = epochClock.time();
timeOfLastAppendPosition = cachedTimeMs;
leadershipTermId = recoveryPlan.lastLeadershipTermId;
election = new Election(
true,
leadershipTermId,
recoveryPlan.appendedLogPosition,
clusterMembers,
clusterMemberByIdMap,
thisMember,
memberStatusAdapter,
memberStatusPublisher,
ctx,
this);
}
}
public int doWork()
{
int workCount = 0;
final long nowMs = epochClock.time();
if (cachedTimeMs != nowMs)
{
cachedTimeMs = nowMs;
if (Cluster.Role.LEADER == role)
{
clusterTimeMs(nowMs);
}
workCount += slowTickWork(nowMs);
}
if (null != dynamicJoin)
{
workCount += dynamicJoin.doWork(nowMs);
}
else if (null != election)
{
workCount += election.doWork(nowMs);
}
else
{
workCount += consensusWork(nowMs);
}
return workCount;
}
public String roleName()
{
return "consensus-module";
}
public void onSessionConnect(
final long correlationId,
final int responseStreamId,
final int version,
final String responseChannel,
final byte[] encodedCredentials)
{
final long clusterSessionId = Cluster.Role.LEADER == role ? nextSessionId++ : NULL_VALUE;
final ClusterSession session = new ClusterSession(clusterSessionId, responseStreamId, responseChannel);
session.lastActivity(cachedTimeMs, correlationId);
session.connect(aeron);
if (Cluster.Role.LEADER != role)
{
redirectSessions.add(session);
}
else
{
if (AeronCluster.Configuration.MAJOR_VERSION != SemanticVersion.major(version))
{
final String detail = SESSION_INVALID_VERSION_MSG + " " + SemanticVersion.toString(version) +
", cluster is " + SemanticVersion.toString(AeronCluster.Configuration.SEMANTIC_VERSION);
session.reject(EventCode.ERROR, detail);
rejectedSessions.add(session);
}
else if (pendingSessions.size() + sessionByIdMap.size() >= ctx.maxConcurrentSessions())
{
session.reject(EventCode.ERROR, SESSION_LIMIT_MSG);
rejectedSessions.add(session);
}
else
{
authenticator.onConnectRequest(session.id(), encodedCredentials, clusterTimeMs);
pendingSessions.add(session);
}
}
}
public void onSessionClose(final long clusterSessionId)
{
final ClusterSession session = sessionByIdMap.get(clusterSessionId);
if (null != session && Cluster.Role.LEADER == role)
{
session.close(CloseReason.CLIENT_ACTION);
if (logPublisher.appendSessionClose(session, leadershipTermId, clusterTimeMs))
{
sessionByIdMap.remove(clusterSessionId);
}
}
}
public ControlledFragmentAssembler.Action onIngressMessage(
final long leadershipTermId,
final long clusterSessionId,
final DirectBuffer buffer,
final int offset,
final int length)
{
if (leadershipTermId != this.leadershipTermId || Cluster.Role.LEADER != role)
{
return ControlledFragmentHandler.Action.CONTINUE;
}
final ClusterSession session = sessionByIdMap.get(clusterSessionId);
if (null == session || session.state() == CLOSED)
{
return ControlledFragmentHandler.Action.CONTINUE;
}
if (session.state() == OPEN &&
logPublisher.appendMessage(leadershipTermId, clusterSessionId, clusterTimeMs, buffer, offset, length))
{
session.timeOfLastActivityMs(clusterTimeMs);
return ControlledFragmentHandler.Action.CONTINUE;
}
return ControlledFragmentHandler.Action.ABORT;
}
public void onSessionKeepAlive(final long clusterSessionId, final long leadershipTermId)
{
if (Cluster.Role.LEADER == role && leadershipTermId == this.leadershipTermId)
{
final ClusterSession session = sessionByIdMap.get(clusterSessionId);
if (null != session && session.state() == OPEN)
{
session.timeOfLastActivityMs(clusterTimeMs);
}
}
}
public void onChallengeResponse(
final long correlationId, final long clusterSessionId, final byte[] encodedCredentials)
{
if (Cluster.Role.LEADER == role)
{
for (int lastIndex = pendingSessions.size() - 1, i = lastIndex; i >= 0; i--)
{
final ClusterSession session = pendingSessions.get(i);
if (session.id() == clusterSessionId && session.state() == CHALLENGED)
{
session.lastActivity(clusterTimeMs, correlationId);
authenticator.onChallengeResponse(clusterSessionId, encodedCredentials, clusterTimeMs);
break;
}
}
}
}
public boolean onTimerEvent(final long correlationId, final long nowMs)
{
return Cluster.Role.LEADER != role || logPublisher.appendTimer(correlationId, leadershipTermId, nowMs);
}
public void onCanvassPosition(final long logLeadershipTermId, final long logPosition, final int followerMemberId)
{
if (null != election)
{
election.onCanvassPosition(logLeadershipTermId, logPosition, followerMemberId);
}
else if (Cluster.Role.LEADER == role)
{
final ClusterMember follower = clusterMemberByIdMap.get(followerMemberId);
if (null != follower)
{
final long position = logLeadershipTermId == this.leadershipTermId ?
this.logPosition() :
recordingLog.getTermEntry(this.leadershipTermId).termBaseLogPosition;
memberStatusPublisher.newLeadershipTerm(
follower.publication(),
this.leadershipTermId,
position,
this.leadershipTermId,
this.logPosition(),
thisMember.id(),
logPublisher.sessionId());
}
}
}
public void onRequestVote(
final long logLeadershipTermId, final long logPosition, final long candidateTermId, final int candidateId)
{
if (null != election)
{
election.onRequestVote(logLeadershipTermId, logPosition, candidateTermId, candidateId);
}
else if (candidateTermId > this.leadershipTermId)
{
ctx.countedErrorHandler().onError(new ClusterException("unexpected vote request"));
enterElection(cachedTimeMs);
election.onRequestVote(logLeadershipTermId, logPosition, candidateTermId, candidateId);
}
}
public void onVote(
final long candidateTermId,
final long logLeadershipTermId,
final long logPosition,
final int candidateMemberId,
final int followerMemberId,
final boolean vote)
{
if (null != election)
{
election.onVote(
candidateTermId, logLeadershipTermId, logPosition, candidateMemberId, followerMemberId, vote);
}
}
public void onNewLeadershipTerm(
final long logLeadershipTermId,
final long logPosition,
final long leadershipTermId,
final long maxLogPosition,
final int leaderMemberId,
final int logSessionId)
{
if (null != election)
{
election.onNewLeadershipTerm(
logLeadershipTermId, logPosition, leadershipTermId, maxLogPosition, leaderMemberId, logSessionId);
}
else if (leadershipTermId > this.leadershipTermId)
{
ctx.countedErrorHandler().onError(new ClusterException("unexpected new leadership term"));
enterElection(cachedTimeMs);
}
}
public void onAppendedPosition(final long leadershipTermId, final long logPosition, final int followerMemberId)
{
if (null != election)
{
election.onAppendedPosition(leadershipTermId, logPosition, followerMemberId);
}
else if (Cluster.Role.LEADER == role && leadershipTermId == this.leadershipTermId)
{
final ClusterMember follower = clusterMemberByIdMap.get(followerMemberId);
if (null != follower)
{
follower
.logPosition(logPosition)
.timeOfLastAppendPositionMs(cachedTimeMs);
checkCatchupStop(follower);
}
}
}
public void onCommitPosition(final long leadershipTermId, final long logPosition, final int leaderMemberId)
{
if (null != election)
{
election.onCommitPosition(leadershipTermId, logPosition, leaderMemberId);
}
else if (Cluster.Role.FOLLOWER == role && leadershipTermId == this.leadershipTermId)
{
timeOfLastLogUpdateMs = cachedTimeMs;
followerCommitPosition = logPosition;
}
else if (leadershipTermId > this.leadershipTermId)
{
ctx.countedErrorHandler().onError(new ClusterException("unexpected commit position from new leader"));
enterElection(cachedTimeMs);
}
}
public void onCatchupPosition(final long leadershipTermId, final long logPosition, final int followerMemberId)
{
if (Cluster.Role.LEADER == role && leadershipTermId == this.leadershipTermId)
{
final ClusterMember follower = clusterMemberByIdMap.get(followerMemberId);
if (null != follower)
{
final String replayChannel = new ChannelUriStringBuilder()
.media(CommonContext.UDP_MEDIA)
.endpoint(follower.transferEndpoint())
.isSessionIdTagged(true)
.sessionId(ConsensusModule.Configuration.LOG_PUBLICATION_SESSION_ID_TAG)
.build();
if (follower.catchupReplaySessionId() == Aeron.NULL_VALUE)
{
follower.catchupReplaySessionId(archive.startReplay(
logRecordingId(), logPosition, Long.MAX_VALUE, replayChannel, ctx.logStreamId()));
}
}
}
}
public void onStopCatchup(final long leadershipTermId, final long logPosition, final int followerMemberId)
{
if (null != logAdapter && null != replayLogDestination && followerMemberId == memberId)
{
logAdapter.removeDestination(replayLogDestination);
replayLogDestination = null;
}
}
public void onAddPassiveMember(final long correlationId, final String memberEndpoints)
{
if (null == election && Cluster.Role.LEADER == role)
{
if (ClusterMember.isNotDuplicateEndpoints(passiveMembers, memberEndpoints))
{
final ClusterMember newMember = ClusterMember.parseEndpoints(++highMemberId, memberEndpoints);
newMember.correlationId(correlationId);
passiveMembers = ClusterMember.addMember(passiveMembers, newMember);
clusterMemberByIdMap.put(newMember.id(), newMember);
final ChannelUri memberStatusUri = ChannelUri.parse(ctx.memberStatusChannel());
ClusterMember.addMemberStatusPublication(
newMember, memberStatusUri, ctx.memberStatusStreamId(), aeron);
logPublisher.addPassiveFollower(newMember.logEndpoint());
}
}
else if (null == election && Cluster.Role.FOLLOWER == role)
{
// redirect add to leader. Leader will respond
memberStatusPublisher.addPassiveMember(leaderMember.publication(), correlationId, memberEndpoints);
}
}
public void onClusterMembersChange(
final long correlationId, final int leaderMemberId, final String activeMembers, final String passiveMembers)
{
if (null != dynamicJoin)
{
dynamicJoin.onClusterMembersChange(correlationId, leaderMemberId, activeMembers, passiveMembers);
}
}
public void onSnapshotRecordingQuery(final long correlationId, final int requestMemberId)
{
if (null == election && Cluster.Role.LEADER == role)
{
final ClusterMember requester = clusterMemberByIdMap.get(requestMemberId);
if (null != requester)
{
final RecordingLog.RecoveryPlan currentRecoveryPlan =
recordingLog.createRecoveryPlan(archive, ctx.serviceCount());
memberStatusPublisher.snapshotRecording(
requester.publication(),
correlationId,
currentRecoveryPlan,
ClusterMember.encodeAsString(clusterMembers));
}
}
}
public void onSnapshotRecordings(final long correlationId, final SnapshotRecordingsDecoder decoder)
{
if (null != dynamicJoin)
{
dynamicJoin.onSnapshotRecordings(correlationId, decoder);
}
}
@SuppressWarnings("unused")
public void onJoinCluster(final long leadershipTermId, final int memberId)
{
final ClusterMember member = clusterMemberByIdMap.get(memberId);
if (null == election && Cluster.Role.LEADER == role && null != member && !member.hasRequestedJoin())
{
if (null == member.publication())
{
final ChannelUri memberStatusUri = ChannelUri.parse(ctx.memberStatusChannel());
ClusterMember.addMemberStatusPublication(member, memberStatusUri, ctx.memberStatusStreamId(), aeron);
logPublisher.addPassiveFollower(member.logEndpoint());
}
member.hasRequestedJoin(true);
}
}
public void onTerminationPosition(final long logPosition)
{
if (Cluster.Role.FOLLOWER == role)
{
terminationPosition = logPosition;
}
}
public void onTerminationAck(final long logPosition, final int memberId)
{
if (Cluster.Role.LEADER == role && logPosition == terminationPosition)
{
final ClusterMember member = clusterMemberByIdMap.get(memberId);
if (null != member)
{
member.hasSentTerminationAck(true);
if (clusterTermination.canTerminate(clusterMembers, terminationPosition, cachedTimeMs))
{
recordingLog.commitLogPosition(leadershipTermId, logPosition);
state(ConsensusModule.State.CLOSED);
ctx.terminationHook().run();
}
}
}
}
void state(final ConsensusModule.State state)
{
this.state = state;
moduleState.set(state.code());
}
void role(final Cluster.Role role)
{
this.role = role;
clusterRoleCounter.setOrdered(role.code());
}
Cluster.Role role()
{
return role;
}
void prepareForNewLeadership(final long logPosition)
{
long recordingId = RecordingPos.NULL_RECORDING_ID;
if (null != appendedPosition)
{
recordingId = RecordingPos.getRecordingId(aeron.countersReader(), appendedPosition.counterId());
}
if (RecordingPos.NULL_RECORDING_ID == recordingId)
{
recordingId = recordingLog.findLastTermRecordingId();
if (RecordingPos.NULL_RECORDING_ID == recordingId)
{
return;
}
}
stopLogRecording();
long stopPosition;
idleStrategy.reset();
while (AeronArchive.NULL_POSITION == (stopPosition = archive.getStopPosition(recordingId)))
{
idle();
}
if (stopPosition > logPosition)
{
archive.truncateRecording(recordingId, logPosition);
}
if (NULL_VALUE == logInitialTermId)
{
final RecordingExtent recordingExtent = new RecordingExtent();
if (0 == archive.listRecording(recordingId, recordingExtent))
{
throw new ClusterException("recording not found id=" + recordingId);
}
logInitialTermId = recordingExtent.initialTermId;
logTermBufferLength = recordingExtent.termBufferLength;
logMtuLength = recordingExtent.mtuLength;
}
lastAppendedPosition = logPosition;
followerCommitPosition = logPosition;
lastRecordingId = recordingId;
commitPosition.setOrdered(logPosition);
clearSessionsAfter(logPosition);
}
void stopLogRecording()
{
if (null != logRecordingChannel)
{
archive.stopRecording(logRecordingChannel, ctx.logStreamId());
logRecordingChannel = null;
}
if (null != logAdapter && null != replayLogDestination)
{
logAdapter.removeDestination(replayLogDestination);
replayLogDestination = null;
}
if (null != logAdapter && null != liveLogDestination)
{
logAdapter.removeDestination(liveLogDestination);
liveLogDestination = null;
}
}
void appendedPositionCounter(final ReadableCounter appendedPositionCounter)
{
this.appendedPosition = appendedPositionCounter;
}
void clearSessionsAfter(final long logPosition)
{
for (final Iterator<ClusterSession> i = sessionByIdMap.values().iterator(); i.hasNext(); )
{
final ClusterSession session = i.next();
if (session.openedLogPosition() > logPosition)
{
i.remove();
session.close();
}
}
for (final ClusterSession session : pendingSessions)
{
session.close();
}
pendingSessions.clear();
}
void onServiceCloseSession(final long clusterSessionId)
{
final ClusterSession session = sessionByIdMap.get(clusterSessionId);
if (null != session)
{
if (session.isResponsePublicationConnected())
{
egressPublisher.sendEvent(
session, leadershipTermId, leaderMember.id(), EventCode.ERROR, SESSION_TERMINATED_MSG);
}
session.close(CloseReason.SERVICE_ACTION);
if (Cluster.Role.LEADER == role &&
logPublisher.appendSessionClose(session, leadershipTermId, clusterTimeMs))
{
sessionByIdMap.remove(clusterSessionId);
}
}
}
void onScheduleTimer(final long correlationId, final long deadlineMs)
{
timerService.scheduleTimer(correlationId, deadlineMs);
}
void onCancelTimer(final long correlationId)
{
timerService.cancelTimer(correlationId);
}
void onServiceAck(final long logPosition, final long ackId, final long relevantId, final int serviceId)
{
validateServiceAck(logPosition, ackId, serviceId);
serviceAcks[serviceId].logPosition(logPosition).ackId(ackId).relevantId(relevantId);
if (ServiceAck.hasReachedPosition(logPosition, serviceAckId, serviceAcks))
{
switch (state)
{
case SNAPSHOT:
++serviceAckId;
takeSnapshot(clusterTimeMs, logPosition);
if (NULL_POSITION == terminationPosition)
{
state(ConsensusModule.State.ACTIVE);
ClusterControl.ToggleState.reset(controlToggle);
for (final ClusterSession session : sessionByIdMap.values())
{
session.timeOfLastActivityMs(clusterTimeMs);
}
}
else
{
serviceProxy.terminationPosition(terminationPosition);
if (null != clusterTermination)
{
clusterTermination.deadlineMs(
cachedTimeMs + TimeUnit.NANOSECONDS.toMillis(ctx.terminationTimeoutNs()));
}
state(ConsensusModule.State.TERMINATING);
}
break;
case LEAVING:
recordingLog.commitLogPosition(leadershipTermId, logPosition);
state(ConsensusModule.State.CLOSED);
ctx.terminationHook().run();
break;
case TERMINATING:
final boolean canTerminate;
if (null == clusterTermination)
{
memberStatusPublisher.terminationAck(leaderMember.publication(), logPosition, memberId);
canTerminate = true;
}
else
{
clusterTermination.hasServiceTerminated(true);
canTerminate = clusterTermination.canTerminate(
clusterMembers, terminationPosition, cachedTimeMs);
}
if (canTerminate)
{
recordingLog.commitLogPosition(leadershipTermId, logPosition);
state(ConsensusModule.State.CLOSED);
ctx.terminationHook().run();
}
break;
}
}
}
public void onClusterMembersQuery(final long correlationId)
{
serviceProxy.clusterMembersResponse(
correlationId,
leaderMember.id(),
ClusterMember.encodeAsString(clusterMembers),
ClusterMember.encodeAsString(passiveMembers));
}
public void onRemoveMember(
@SuppressWarnings("unused") final long correlationId, final int memberId, final boolean isPassive)
{
final ClusterMember member = clusterMemberByIdMap.get(memberId);
if (null == election && Cluster.Role.LEADER == role && null != member)
{
if (isPassive)
{
passiveMembers = ClusterMember.removeMember(passiveMembers, memberId);
member.publication().close();
member.publication(null);
logPublisher.removePassiveFollower(member.logEndpoint());
clusterMemberByIdMap.remove(memberId);
clusterMemberByIdMap.compact();
}
else
{
final ClusterMember[] newClusterMembers = ClusterMember.removeMember(clusterMembers, memberId);
final String newClusterMembersString = ClusterMember.encodeAsString(newClusterMembers);
final long position = logPublisher.calculatePositionForMembershipChangeEvent(newClusterMembersString);
if (logPublisher.appendMembershipChangeEvent(
leadershipTermId,
position,
clusterTimeMs,
thisMember.id(),
clusterMembers.length,
ChangeType.QUIT,
memberId,
newClusterMembersString))
{
timeOfLastLogUpdateMs = cachedTimeMs - leaderHeartbeatIntervalMs;
member.removalPosition(logPublisher.position());
pendingMemberRemovals++;
}
}
}
}
@SuppressWarnings("unused")
void onReplaySessionMessage(
final long clusterSessionId,
final long timestamp,
final DirectBuffer buffer,
final int offset,
final int length,
final Header header)
{
clusterTimeMs(timestamp);
sessionByIdMap.get(clusterSessionId).timeOfLastActivityMs(timestamp);
}
void onReplayTimerEvent(final long correlationId, final long timestamp)
{
clusterTimeMs(timestamp);
if (!timerService.cancelTimer(correlationId))
{
missedTimersSet.add(correlationId);
}
}
void onReplaySessionOpen(
final long logPosition,
final long correlationId,
final long clusterSessionId,
final long timestamp,
final int responseStreamId,
final String responseChannel)
{
clusterTimeMs(timestamp);
final ClusterSession session = new ClusterSession(clusterSessionId, responseStreamId, responseChannel);
session.open(logPosition);
session.lastActivity(timestamp, correlationId);
sessionByIdMap.put(clusterSessionId, session);
if (clusterSessionId >= nextSessionId)
{
nextSessionId = clusterSessionId + 1;
}
}
void onLoadSession(
final long clusterSessionId,
final long correlationId,
final long openedPosition,
final long timeOfLastActivity,
final CloseReason closeReason,
final int responseStreamId,
final String responseChannel)
{
sessionByIdMap.put(clusterSessionId, new ClusterSession(
clusterSessionId,
correlationId,
openedPosition,
timeOfLastActivity,
responseStreamId,
responseChannel,
closeReason));
if (clusterSessionId >= nextSessionId)
{
nextSessionId = clusterSessionId + 1;
}
}
void onReplaySessionClose(final long clusterSessionId, final long timestamp, final CloseReason closeReason)
{
clusterTimeMs(timestamp);
sessionByIdMap.remove(clusterSessionId).close(closeReason);
}
@SuppressWarnings("unused")
void onReplayClusterAction(
final long leadershipTermId, final long logPosition, final long timestamp, final ClusterAction action)
{
clusterTimeMs(timestamp);
switch (action)
{
case SUSPEND:
state(ConsensusModule.State.SUSPENDED);
break;
case RESUME:
state(ConsensusModule.State.ACTIVE);
break;
case SNAPSHOT:
expectedAckPosition = logPosition;
state(ConsensusModule.State.SNAPSHOT);
break;
}
}
@SuppressWarnings("unused")
void onReplayNewLeadershipTermEvent(
final long leadershipTermId,
final long logPosition,
final long timestamp,
final int leaderMemberId,
final int logSessionId)
{
clusterTimeMs(timestamp);
this.leadershipTermId = leadershipTermId;
if (null != election && null != appendedPosition)
{
final long recordingId = RecordingPos.getRecordingId(aeron.countersReader(), appendedPosition.counterId());
election.onReplayNewLeadershipTermEvent(recordingId, leadershipTermId, logPosition, cachedTimeMs);
}
}
@SuppressWarnings("unused")
void onMembershipClusterChange(
final long leadershipTermId,
final long logPosition,
final long timestamp,
final int leaderMemberId,
final int clusterSize,
final ChangeType changeType,
final int memberId,
final String clusterMembers)
{
clusterTimeMs(timestamp);
this.leadershipTermId = leadershipTermId;
final ClusterMember[] newMembers = ClusterMember.parse(clusterMembers);
if (ChangeType.JOIN == changeType)
{
if (memberId == this.memberId)
{
this.clusterMembers = newMembers;
clusterMemberByIdMap.clear();
clusterMemberByIdMap.compact();
ClusterMember.addClusterMemberIds(newMembers, clusterMemberByIdMap);
thisMember = ClusterMember.findMember(this.clusterMembers, memberId);
leaderMember = ClusterMember.findMember(this.clusterMembers, leaderMemberId);
ClusterMember.addMemberStatusPublications(
newMembers,
thisMember,
ChannelUri.parse(ctx.memberStatusChannel()),
ctx.memberStatusStreamId(),
aeron);
}
else
{
clusterMemberJoined(memberId, newMembers);
}
}
else if (ChangeType.QUIT == changeType)
{
if (memberId == this.memberId)
{
expectedAckPosition = logPosition;
state(ConsensusModule.State.LEAVING);
}
else
{
final boolean hasCurrentLeaderSteppedDown = leaderMemberId == memberId;
clusterMemberQuit(memberId);
if (hasCurrentLeaderSteppedDown)
{
enterElection(cachedTimeMs);
}
}
}
}
void onReloadState(final long nextSessionId)
{
this.nextSessionId = nextSessionId;
}
void onReloadClusterMembers(final int memberId, final int highMemberId, final String members)
{
if (ctx.clusterMembersIgnoreSnapshot() || null != dynamicJoin)
{
return;
}
// TODO: this must be superset of any configured cluster members, unless being overridden
final ClusterMember[] snapshotClusterMembers = ClusterMember.parse(members);
if (Aeron.NULL_VALUE == this.memberId)
{
this.memberId = memberId;
ctx.clusterMarkFile().memberId(memberId);
}
if (ClusterMember.EMPTY_CLUSTER_MEMBER_ARRAY == this.clusterMembers)
{
clusterMembers = snapshotClusterMembers;
this.highMemberId = Math.max(ClusterMember.highMemberId(clusterMembers), highMemberId);
rankedPositions = new long[ClusterMember.quorumThreshold(clusterMembers.length)];
thisMember = clusterMemberByIdMap.get(this.memberId);
final ChannelUri memberStatusUri = ChannelUri.parse(ctx.memberStatusChannel());
memberStatusUri.put(ENDPOINT_PARAM_NAME, thisMember.memberFacingEndpoint());
ClusterMember.addMemberStatusPublications(
clusterMembers, thisMember, memberStatusUri, ctx.memberStatusStreamId(), aeron);
}
}
Publication addNewLogPublication()
{
closeExistingLog();
final ChannelUri channelUri = ChannelUri.parse(ctx.logChannel());
final Publication publication = createLogPublication(channelUri, recoveryPlan, election.logPosition());
logPublisher.connect(publication);
return publication;
}
void becomeLeader(final long leadershipTermId, final long logPosition, final int logSessionId)
{
this.leadershipTermId = leadershipTermId;
final ChannelUri channelUri = ChannelUri.parse(ctx.logChannel());
channelUri.put(CommonContext.SESSION_ID_PARAM_NAME, Integer.toString(logSessionId));
startLogRecording(channelUri.toString(), SourceLocation.LOCAL);
createAppendPosition(logSessionId);
awaitServicesReady(channelUri, logSessionId, logPosition);
for (final ClusterSession session : sessionByIdMap.values())
{
if (session.state() != CLOSED)
{
session.connect(aeron);
}
}
final long nowMs = epochClock.time();
for (final ClusterSession session : sessionByIdMap.values())
{
if (session.state() != CLOSED)
{
session.timeOfLastActivityMs(nowMs);
session.hasNewLeaderEventPending(true);
}
}
}
void followerCommitPosition(final long position)
{
followerCommitPosition = position;
}
void updateMemberDetails(final Election election)
{
leaderMember = election.leader();
sessionProxy.leaderMemberId(leaderMember.id()).leadershipTermId(leadershipTermId);
for (final ClusterMember clusterMember : clusterMembers)
{
clusterMember.isLeader(clusterMember.id() == leaderMember.id());
}
updateClientFacingEndpoints(clusterMembers);
}
void liveLogDestination(final String liveLogDestination)
{
this.liveLogDestination = liveLogDestination;
}
void replayLogDestination(final String replayLogDestination)
{
this.replayLogDestination = replayLogDestination;
}
Subscription createAndRecordLogSubscriptionAsFollower(final String logChannel)
{
closeExistingLog();
final Subscription subscription = aeron.addSubscription(logChannel, ctx.logStreamId());
startLogRecording(logChannel, SourceLocation.REMOTE);
return subscription;
}
void appendDynamicJoinTermAndSnapshots()
{
if (!dynamicJoinSnapshots.isEmpty())
{
final long logRecordingId = logRecordingId();
final RecordingLog.Snapshot lastSnapshot = dynamicJoinSnapshots.get(dynamicJoinSnapshots.size() - 1);
recordingLog.appendTerm(
logRecordingId,
lastSnapshot.leadershipTermId,
lastSnapshot.termBaseLogPosition,
lastSnapshot.timestamp);
for (int i = dynamicJoinSnapshots.size() - 1; i >= 0; i--)
{
final RecordingLog.Snapshot snapshot = dynamicJoinSnapshots.get(i);
recordingLog.appendSnapshot(
snapshot.recordingId,
snapshot.leadershipTermId,
snapshot.termBaseLogPosition,
snapshot.logPosition,
snapshot.timestamp,
snapshot.serviceId);
}
dynamicJoinSnapshots.clear();
}
}
boolean pollImageAndLogAdapter(final Subscription subscription, final int logSessionId)
{
boolean result = false;
if (null == logAdapter)
{
final Image image = subscription.imageBySessionId(logSessionId);
if (null != image)
{
logAdapter = new LogAdapter(image, this);
lastAppendedPosition = 0;
createAppendPosition(logSessionId);
appendDynamicJoinTermAndSnapshots();
result = true;
}
}
else
{
result = true;
}
return result;
}
void awaitImageAndCreateFollowerLogAdapter(final Subscription subscription, final int logSessionId)
{
leadershipTermId = election.leadershipTermId();
idleStrategy.reset();
while (!pollImageAndLogAdapter(subscription, logSessionId))
{
idle();
}
}
void awaitServicesReady(final ChannelUri logChannelUri, final int logSessionId, final long logPosition)
{
final String channel = Cluster.Role.LEADER == role && UDP_MEDIA.equals(logChannelUri.media()) ?
logChannelUri.prefix(SPY_QUALIFIER).toString() : logChannelUri.toString();
serviceProxy.joinLog(
leadershipTermId, logPosition, Long.MAX_VALUE, memberId, logSessionId, ctx.logStreamId(), channel);
expectedAckPosition = logPosition;
awaitServiceAcks(logPosition);
}
LogReplay newLogReplay(final long electionCommitPosition)
{
final RecordingLog.RecoveryPlan plan = recoveryPlan;
LogReplay logReplay = null;
if (!plan.logs.isEmpty())
{
final RecordingLog.Log log = plan.logs.get(0);
final long startPosition = log.startPosition;
final long stopPosition = Math.min(log.stopPosition, electionCommitPosition);
leadershipTermId = log.leadershipTermId;
if (log.logPosition < 0)
{
recordingLog.commitLogPosition(leadershipTermId, stopPosition);
}
if (plan.hasReplay())
{
logReplay = new LogReplay(
archive,
log.recordingId,
startPosition,
stopPosition,
leadershipTermId,
log.sessionId,
this,
ctx);
}
}
return logReplay;
}
void awaitServicesReadyForReplay(
final String channel,
final int streamId,
final int logSessionId,
final long leadershipTermId,
final long logPosition,
final long maxLogPosition)
{
serviceProxy.joinLog(leadershipTermId, logPosition, maxLogPosition, memberId, logSessionId, streamId, channel);
expectedAckPosition = logPosition;
awaitServiceAcks(logPosition);
}
void awaitServicesReplayComplete(final long stopPosition)
{
expectedAckPosition = stopPosition;
awaitServiceAcks(stopPosition);
while (0 != timerService.poll(clusterTimeMs) ||
(timerService.currentTickTimeMs() < clusterTimeMs && timerService.timerCount() > 0))
{
idle();
}
}
void replayLogPoll(final LogAdapter logAdapter, final long stopPosition)
{
final int workCount = logAdapter.poll(stopPosition);
if (0 == workCount)
{
if (logAdapter.isImageClosed() && logAdapter.position() != stopPosition)
{
throw new ClusterException("unexpected close of image when replaying log");
}
}
commitPosition.setOrdered(logAdapter.position());
consensusModuleAdapter.poll();
cancelMissedTimers();
}
long logRecordingId()
{
if (!recoveryPlan.logs.isEmpty())
{
return recoveryPlan.logs.get(0).recordingId;
}
return RecordingPos.getRecordingId(aeron.countersReader(), appendedPosition.counterId());
}
long logStopPosition(final long leadershipTermId)
{
if (NULL_VALUE == leadershipTermId)
{
return 0;
}
return recordingLog.getTermEntry(leadershipTermId).logPosition;
}
void truncateLogEntry(final long leadershipTermId, final long logPosition)
{
archive.truncateRecording(logRecordingId(), logPosition);
recordingLog.commitLogPosition(leadershipTermId, logPosition);
}
public void checkCatchupStop(final ClusterMember member)
{
if (null != member && Aeron.NULL_VALUE != member.catchupReplaySessionId())
{
if (member.logPosition() >= logPublisher.position())
{
archive.stopReplay(member.catchupReplaySessionId());
if (memberStatusPublisher.stopCatchup(
member.publication(), leadershipTermId, logPublisher.position(), member.id()))
{
member.catchupReplaySessionId(Aeron.NULL_VALUE);
}
}
}
}
boolean electionComplete(final long nowMs)
{
boolean result = false;
if (Cluster.Role.LEADER == role)
{
if (logPublisher.appendNewLeadershipTermEvent(
leadershipTermId, election.logPosition(), nowMs, memberId, logPublisher.sessionId()))
{
timeOfLastLogUpdateMs = cachedTimeMs - leaderHeartbeatIntervalMs;
election = null;
result = true;
}
}
else
{
timeOfLastLogUpdateMs = cachedTimeMs;
timeOfLastAppendPosition = cachedTimeMs;
election = null;
result = true;
}
if (!ctx.ingressChannel().contains(ENDPOINT_PARAM_NAME))
{
final ChannelUri ingressUri = ChannelUri.parse(ctx.ingressChannel());
ingressUri.put(ENDPOINT_PARAM_NAME, thisMember.clientFacingEndpoint());
ingressAdapter.connect(aeron.addSubscription(
ingressUri.toString(), ctx.ingressStreamId(), null, this::onUnavailableIngressImage));
}
else if (Cluster.Role.LEADER == role)
{
ingressAdapter.connect(aeron.addSubscription(
ctx.ingressChannel(), ctx.ingressStreamId(), null, this::onUnavailableIngressImage));
}
cancelMissedTimers();
if (missedTimersSet.capacity() > LongHashSet.DEFAULT_INITIAL_CAPACITY)
{
missedTimersSet.compact();
}
return result;
}
boolean dynamicJoinComplete()
{
if (0 == clusterMembers.length)
{
clusterMembers = dynamicJoin.clusterMembers();
ClusterMember.addClusterMemberIds(clusterMembers, clusterMemberByIdMap);
leaderMember = dynamicJoin.leader();
final ChannelUri memberStatusUri = ChannelUri.parse(ctx.memberStatusChannel());
ClusterMember.addMemberStatusPublications(
clusterMembers, thisMember, memberStatusUri, ctx.memberStatusStreamId(), aeron);
}
if (NULL_VALUE == memberId)
{
memberId = dynamicJoin.memberId();
ctx.clusterMarkFile().memberId(memberId);
thisMember.id(dynamicJoin.memberId());
}
election = new Election(
true,
leadershipTermId,
recoveryPlan.appendedLogPosition,
clusterMembers,
clusterMemberByIdMap,
thisMember,
memberStatusAdapter,
memberStatusPublisher,
ctx,
this);
dynamicJoin = null;
return true;
}
void catchupLogPoll(final Subscription subscription, final int logSessionId, final long stopPosition)
{
if (pollImageAndLogAdapter(subscription, logSessionId))
{
final Image image = logAdapter.image();
if (logAdapter.poll(stopPosition) == 0 && image.isClosed())
{
throw new ClusterException("unexpected close of image when replaying log");
}
final long appendedPosition = this.appendedPosition.get();
if (appendedPosition != lastAppendedPosition)
{
final Publication publication = election.leader().publication();
if (memberStatusPublisher.appendedPosition(publication, leadershipTermId, appendedPosition, memberId))
{
lastAppendedPosition = appendedPosition;
timeOfLastAppendPosition = cachedTimeMs;
}
}
commitPosition.setOrdered(Math.min(image.position(), appendedPosition));
consensusModuleAdapter.poll();
cancelMissedTimers();
}
}
boolean hasAppendReachedPosition(final Subscription subscription, final int logSessionId, final long position)
{
return pollImageAndLogAdapter(subscription, logSessionId) && appendedPosition.get() >= position;
}
boolean hasAppendReachedLivePosition(final Subscription subscription, final int logSessionId, final long position)
{
boolean result = false;
if (pollImageAndLogAdapter(subscription, logSessionId))
{
final long appendPosition = appendedPosition.get();
final long window = logAdapter.image().termBufferLength() * 2L;
result = appendPosition >= (position - window);
}
return result;
}
void stopAllCatchups()
{
for (final ClusterMember member : clusterMembers)
{
if (member.catchupReplaySessionId() != Aeron.NULL_VALUE)
{
try
{
archive.stopReplay(member.catchupReplaySessionId());
}
catch (final Exception ex)
{
ctx.countedErrorHandler().onError(ex);
}
member.catchupReplaySessionId(Aeron.NULL_VALUE);
}
}
}
void retrievedSnapshot(final long localRecordingId, final RecordingLog.Snapshot leaderSnapshot)
{
dynamicJoinSnapshots.add(new RecordingLog.Snapshot(
localRecordingId,
leaderSnapshot.leadershipTermId,
leaderSnapshot.termBaseLogPosition,
leaderSnapshot.logPosition,
leaderSnapshot.timestamp,
leaderSnapshot.serviceId));
}
Counter loadSnapshotsFromDynamicJoin()
{
recoveryPlan = RecordingLog.createRecoveryPlan(dynamicJoinSnapshots);
final Counter recoveryStateCounter = addRecoveryStateCounter(recoveryPlan);
if (!recoveryPlan.snapshots.isEmpty())
{
recoverFromSnapshot(recoveryPlan.snapshots.get(0), archive);
}
return recoveryStateCounter;
}
boolean pollForEndOfSnapshotLoad(final Counter recoveryStateCounter)
{
consensusModuleAdapter.poll();
if (ServiceAck.hasReachedPosition(expectedAckPosition, serviceAckId, serviceAcks))
{
++serviceAckId;
recoveryStateCounter.close();
if (ConsensusModule.State.SUSPENDED != state)
{
state(ConsensusModule.State.ACTIVE);
}
timeOfLastLogUpdateMs = cachedTimeMs = epochClock.time();
leadershipTermId = recoveryPlan.lastLeadershipTermId;
return true;
}
return false;
}
private int slowTickWork(final long nowMs)
{
int workCount = 0;
markFile.updateActivityTimestamp(nowMs);
checkServiceHeartbeats(nowMs);
workCount += aeronClientInvoker.invoke();
workCount += processRedirectSessions(redirectSessions, nowMs);
workCount += processRejectedSessions(rejectedSessions, nowMs);
if (Cluster.Role.LEADER == role && null == election)
{
workCount += checkControlToggle(nowMs);
if (ConsensusModule.State.ACTIVE == state)
{
workCount += processPendingSessions(pendingSessions, nowMs);
workCount += checkSessions(sessionByIdMap, nowMs);
workCount += processPassiveMembers(passiveMembers);
if (!ClusterMember.hasActiveQuorum(clusterMembers, nowMs, leaderHeartbeatTimeoutMs))
{
ctx.countedErrorHandler().onError(new ClusterException("lost connection to quorum of followers"));
enterElection(nowMs);
workCount += 1;
}
}
else if (ConsensusModule.State.TERMINATING == state)
{
if (clusterTermination.canTerminate(clusterMembers, terminationPosition, cachedTimeMs))
{
recordingLog.commitLogPosition(leadershipTermId, terminationPosition);
state(ConsensusModule.State.CLOSED);
ctx.terminationHook().run();
}
}
}
else
{
cancelMissedTimers();
}
if (null != archive)
{
archive.checkForErrorResponse();
}
return workCount;
}
private int consensusWork(final long nowMs)
{
int workCount = 0;
if (Cluster.Role.LEADER == role && ConsensusModule.State.ACTIVE == state)
{
workCount += ingressAdapter.poll();
workCount += timerService.poll(nowMs);
}
else if (Cluster.Role.FOLLOWER == role &&
(ConsensusModule.State.ACTIVE == state || ConsensusModule.State.SUSPENDED == state))
{
workCount += ingressAdapter.poll();
final int count = logAdapter.poll(followerCommitPosition);
if (0 == count && logAdapter.isImageClosed())
{
ctx.countedErrorHandler().onError(new ClusterException("lost connection to leader"));
enterElection(nowMs);
return 1;
}
workCount += count;
if (NULL_POSITION != terminationPosition)
{
if (logAdapter.position() >= terminationPosition && ConsensusModule.State.SNAPSHOT != state)
{
serviceProxy.terminationPosition(terminationPosition);
expectedAckPosition = terminationPosition;
state(ConsensusModule.State.TERMINATING);
}
}
}
workCount += memberStatusAdapter.poll();
workCount += updateMemberPosition(nowMs);
workCount += consensusModuleAdapter.poll();
return workCount;
}
private void checkServiceHeartbeats(final long nowMs)
{
final long heartbeatThreshold = nowMs - serviceHeartbeatTimeoutMs;
if (null == dynamicJoin)
{
for (final Counter serviceHeartbeat : serviceHeartbeats)
{
final long heartbeat = serviceHeartbeat.get();
if (heartbeat < heartbeatThreshold)
{
ctx.countedErrorHandler().onError(new TimeoutException("no heartbeat from service: " + heartbeat));
ctx.terminationHook().run();
}
}
}
}
private int checkControlToggle(final long nowMs)
{
switch (ClusterControl.ToggleState.get(controlToggle))
{
case SUSPEND:
if (ConsensusModule.State.ACTIVE == state && appendAction(ClusterAction.SUSPEND, nowMs))
{
state(ConsensusModule.State.SUSPENDED);
ClusterControl.ToggleState.reset(controlToggle);
}
break;
case RESUME:
if (ConsensusModule.State.SUSPENDED == state && appendAction(ClusterAction.RESUME, nowMs))
{
state(ConsensusModule.State.ACTIVE);
ClusterControl.ToggleState.reset(controlToggle);
}
break;
case SNAPSHOT:
if (ConsensusModule.State.ACTIVE == state && appendAction(ClusterAction.SNAPSHOT, nowMs))
{
expectedAckPosition = logPosition();
state(ConsensusModule.State.SNAPSHOT);
}
break;
case SHUTDOWN:
if (ConsensusModule.State.ACTIVE == state && appendAction(ClusterAction.SNAPSHOT, nowMs))
{
final long position = logPosition();
clusterTermination = new ClusterTermination(
memberStatusPublisher,
cachedTimeMs + TimeUnit.NANOSECONDS.toMillis(ctx.terminationTimeoutNs()));
clusterTermination.terminationPosition(clusterMembers, thisMember, position);
terminationPosition = position;
expectedAckPosition = position;
state(ConsensusModule.State.SNAPSHOT);
}
break;
case ABORT:
if (ConsensusModule.State.ACTIVE == state)
{
final long position = logPosition();
clusterTermination = new ClusterTermination(
memberStatusPublisher,
cachedTimeMs + TimeUnit.NANOSECONDS.toMillis(ctx.terminationTimeoutNs()));
clusterTermination.terminationPosition(clusterMembers, thisMember, position);
terminationPosition = position;
expectedAckPosition = position;
serviceProxy.terminationPosition(terminationPosition);
state(ConsensusModule.State.TERMINATING);
}
break;
default:
return 0;
}
return 1;
}
private boolean appendAction(final ClusterAction action, final long nowMs)
{
final int length = DataHeaderFlyweight.HEADER_LENGTH +
MessageHeaderEncoder.ENCODED_LENGTH + ClusterActionRequestEncoder.BLOCK_LENGTH;
final long position = logPublisher.position() + BitUtil.align(length, FrameDescriptor.FRAME_ALIGNMENT);
return logPublisher.appendClusterAction(leadershipTermId, position, nowMs, action);
}
private int processPendingSessions(final ArrayList<ClusterSession> pendingSessions, final long nowMs)
{
int workCount = 0;
for (int lastIndex = pendingSessions.size() - 1, i = lastIndex; i >= 0; i--)
{
final ClusterSession session = pendingSessions.get(i);
if (session.state() == INIT || session.state() == CONNECTED)
{
if (session.isResponsePublicationConnected())
{
session.state(CONNECTED);
authenticator.onConnectedSession(sessionProxy.session(session), nowMs);
}
}
if (session.state() == CHALLENGED)
{
if (session.isResponsePublicationConnected())
{
authenticator.onChallengedSession(sessionProxy.session(session), nowMs);
}
}
if (session.state() == AUTHENTICATED)
{
ArrayListUtil.fastUnorderedRemove(pendingSessions, i, lastIndex--);
session.timeOfLastActivityMs(nowMs);
sessionByIdMap.put(session.id(), session);
appendSessionOpen(session, nowMs);
workCount += 1;
}
else if (session.state() == REJECTED)
{
ArrayListUtil.fastUnorderedRemove(pendingSessions, i, lastIndex--);
rejectedSessions.add(session);
}
else if (nowMs > (session.timeOfLastActivityMs() + sessionTimeoutMs))
{
ArrayListUtil.fastUnorderedRemove(pendingSessions, i, lastIndex--);
session.close();
ctx.timedOutClientCounter().incrementOrdered();
}
}
return workCount;
}
private int processRejectedSessions(final ArrayList<ClusterSession> rejectedSessions, final long nowMs)
{
int workCount = 0;
for (int lastIndex = rejectedSessions.size() - 1, i = lastIndex; i >= 0; i--)
{
final ClusterSession session = rejectedSessions.get(i);
final String detail = session.responseDetail();
final EventCode eventCode = session.eventCode();
if (egressPublisher.sendEvent(session, leadershipTermId, leaderMember.id(), eventCode, detail) ||
nowMs > (session.timeOfLastActivityMs() + sessionTimeoutMs))
{
ArrayListUtil.fastUnorderedRemove(rejectedSessions, i, lastIndex--);
session.close();
workCount++;
}
}
return workCount;
}
private int processRedirectSessions(final ArrayList<ClusterSession> redirectSessions, final long nowMs)
{
int workCount = 0;
for (int lastIndex = redirectSessions.size() - 1, i = lastIndex; i >= 0; i--)
{
final ClusterSession session = redirectSessions.get(i);
final EventCode eventCode = EventCode.REDIRECT;
final int id = leaderMember.id();
if (egressPublisher.sendEvent(session, leadershipTermId, id, eventCode, clientFacingEndpoints) ||
nowMs > (session.timeOfLastActivityMs() + sessionTimeoutMs))
{
ArrayListUtil.fastUnorderedRemove(redirectSessions, i, lastIndex--);
session.close();
workCount++;
}
}
return workCount;
}
private int processPassiveMembers(final ClusterMember[] passiveMembers)
{
int workCount = 0;
for (int i = 0, length = passiveMembers.length; i < length; i++)
{
final ClusterMember member = passiveMembers[i];
if (member.correlationId() != Aeron.NULL_VALUE)
{
if (memberStatusPublisher.clusterMemberChange(
member.publication(),
member.correlationId(),
leaderMember.id(),
ClusterMember.encodeAsString(clusterMembers),
ClusterMember.encodeAsString(passiveMembers)))
{
member.correlationId(Aeron.NULL_VALUE);
workCount++;
}
}
else if (member.hasRequestedJoin() && member.logPosition() == logPublisher.position())
{
final ClusterMember[] newMembers = ClusterMember.addMember(clusterMembers, member);
if (logPublisher.appendMembershipChangeEvent(
this.leadershipTermId,
logPublisher.position(),
clusterTimeMs,
thisMember.id(),
newMembers.length,
ChangeType.JOIN,
member.id(),
ClusterMember.encodeAsString(newMembers)))
{
timeOfLastLogUpdateMs = cachedTimeMs - leaderHeartbeatIntervalMs;
this.passiveMembers = ClusterMember.removeMember(this.passiveMembers, member.id());
this.clusterMembers = newMembers;
rankedPositions = new long[this.clusterMembers.length];
member.hasRequestedJoin(false);
workCount++;
break;
}
}
}
return workCount;
}
private int checkSessions(final Long2ObjectHashMap<ClusterSession> sessionByIdMap, final long nowMs)
{
int workCount = 0;
for (final Iterator<ClusterSession> i = sessionByIdMap.values().iterator(); i.hasNext(); )
{
final ClusterSession session = i.next();
if (nowMs > (session.timeOfLastActivityMs() + sessionTimeoutMs))
{
switch (session.state())
{
case OPEN:
if (session.isResponsePublicationConnected())
{
egressPublisher.sendEvent(
session, leadershipTermId, leaderMember.id(), EventCode.ERROR, SESSION_TIMEOUT_MSG);
}
session.close(CloseReason.TIMEOUT);
if (logPublisher.appendSessionClose(session, leadershipTermId, nowMs))
{
i.remove();
ctx.timedOutClientCounter().incrementOrdered();
}
break;
case CLOSED:
if (logPublisher.appendSessionClose(session, leadershipTermId, nowMs))
{
i.remove();
if (session.closeReason() == CloseReason.TIMEOUT)
{
ctx.timedOutClientCounter().incrementOrdered();
}
}
break;
default:
i.remove();
session.close();
}
workCount += 1;
}
else if (session.state() == CONNECTED)
{
appendSessionOpen(session, nowMs);
workCount += 1;
}
else if (session.hasNewLeaderEventPending())
{
sendNewLeaderEvent(session);
workCount += 1;
}
}
return workCount;
}
private void sendNewLeaderEvent(final ClusterSession session)
{
if (egressPublisher.newLeader(session, leadershipTermId, leaderMember.id(), clientFacingEndpoints))
{
session.hasNewLeaderEventPending(false);
}
}
private void appendSessionOpen(final ClusterSession session, final long nowMs)
{
final long resultingPosition = logPublisher.appendSessionOpen(session, leadershipTermId, nowMs);
if (resultingPosition > 0)
{
session.open(resultingPosition);
}
}
private void createAppendPosition(final int logSessionId)
{
final CountersReader counters = aeron.countersReader();
final int recordingCounterId = awaitRecordingCounter(counters, logSessionId);
appendedPosition = new ReadableCounter(counters, recordingCounterId);
}
private void recoverFromSnapshot(final RecordingLog.Snapshot snapshot, final AeronArchive archive)
{
clusterTimeMs(snapshot.timestamp);
expectedAckPosition = snapshot.logPosition;
leadershipTermId = snapshot.leadershipTermId;
final String channel = ctx.replayChannel();
final int streamId = ctx.replayStreamId();
final int sessionId = (int)archive.startReplay(snapshot.recordingId, 0, NULL_LENGTH, channel, streamId);
final String replaySubscriptionChannel = ChannelUri.addSessionId(channel, sessionId);
try (Subscription subscription = aeron.addSubscription(replaySubscriptionChannel, streamId))
{
final Image image = awaitImage(sessionId, subscription);
final ConsensusModuleSnapshotLoader snapshotLoader = new ConsensusModuleSnapshotLoader(image, this);
while (true)
{
final int fragments = snapshotLoader.poll();
if (fragments == 0)
{
if (snapshotLoader.isDone())
{
break;
}
if (image.isClosed())
{
throw new ClusterException("snapshot ended unexpectedly");
}
}
idle(fragments);
}
}
}
private Image awaitImage(final int sessionId, final Subscription subscription)
{
idleStrategy.reset();
Image image;
while ((image = subscription.imageBySessionId(sessionId)) == null)
{
idle();
}
return image;
}
private Counter addRecoveryStateCounter(final RecordingLog.RecoveryPlan plan)
{
final int snapshotsCount = plan.snapshots.size();
if (snapshotsCount > 0)
{
final long[] serviceSnapshotRecordingIds = new long[snapshotsCount - 1];
final RecordingLog.Snapshot snapshot = plan.snapshots.get(0);
for (int i = 1; i < snapshotsCount; i++)
{
final RecordingLog.Snapshot serviceSnapshot = plan.snapshots.get(i);
serviceSnapshotRecordingIds[serviceSnapshot.serviceId] = serviceSnapshot.recordingId;
}
return RecoveryState.allocate(
aeron,
tempBuffer,
snapshot.leadershipTermId,
snapshot.logPosition,
snapshot.timestamp,
plan.hasReplay(),
serviceSnapshotRecordingIds);
}
return RecoveryState.allocate(aeron, tempBuffer, leadershipTermId, 0, 0, plan.hasReplay());
}
private DynamicJoin requiresDynamicJoin()
{
if (recoveryPlan.snapshots.isEmpty() &&
0 == clusterMembers.length &&
null != ctx.clusterMembersStatusEndpoints())
{
return new DynamicJoin(
ctx.clusterMembersStatusEndpoints(),
archive,
memberStatusAdapter,
memberStatusPublisher,
ctx,
this);
}
return null;
}
private void awaitServiceAcks(final long logPosition)
{
while (!ServiceAck.hasReachedPosition(logPosition, serviceAckId, serviceAcks))
{
idle(consensusModuleAdapter.poll());
}
++serviceAckId;
}
private long logPosition()
{
return null != logAdapter ? logAdapter.position() : logPublisher.position();
}
private void validateServiceAck(final long logPosition, final long ackId, final int serviceId)
{
if (logPosition != expectedAckPosition || ackId != serviceAckId)
{
throw new ClusterException("invalid service ACK" +
" state " + state +
": serviceId=" + serviceId +
", logPosition=" + logPosition + " expected " + expectedAckPosition +
", ackId=" + ackId + " expected " + serviceAckId);
}
}
private void updateClientFacingEndpoints(final ClusterMember[] members)
{
final StringBuilder builder = new StringBuilder(100);
for (int i = 0, length = members.length; i < length; i++)
{
if (0 != i)
{
builder.append(',');
}
final ClusterMember member = members[i];
builder.append(member.id()).append('=').append(member.clientFacingEndpoint());
}
clientFacingEndpoints = builder.toString();
}
private void handleMemberRemovals(final long commitPosition)
{
ClusterMember[] newClusterMembers = clusterMembers;
for (final ClusterMember member : clusterMembers)
{
if (member.hasRequestedRemove() && member.removalPosition() <= commitPosition)
{
if (member == thisMember)
{
expectedAckPosition = commitPosition;
state(ConsensusModule.State.LEAVING);
}
newClusterMembers = ClusterMember.removeMember(newClusterMembers, member.id());
clusterMemberByIdMap.remove(member.id());
clusterMemberByIdMap.compact();
CloseHelper.close(member.publication());
member.publication(null);
logPublisher.removePassiveFollower(member.logEndpoint());
pendingMemberRemovals--;
}
}
clusterMembers = newClusterMembers;
rankedPositions = new long[clusterMembers.length];
}
private int updateMemberPosition(final long nowMs)
{
int workCount = 0;
final long appendedPosition = this.appendedPosition.get();
if (Cluster.Role.LEADER == role)
{
thisMember.logPosition(appendedPosition).timeOfLastAppendPositionMs(nowMs);
final long quorumPosition = ClusterMember.quorumPosition(clusterMembers, rankedPositions);
if (commitPosition.proposeMaxOrdered(Math.min(quorumPosition, appendedPosition)) ||
nowMs >= (timeOfLastLogUpdateMs + leaderHeartbeatIntervalMs))
{
final long commitPosition = this.commitPosition.getWeak();
for (final ClusterMember member : clusterMembers)
{
if (member != thisMember)
{
final Publication publication = member.publication();
memberStatusPublisher.commitPosition(publication, leadershipTermId, commitPosition, memberId);
}
}
timeOfLastLogUpdateMs = nowMs;
if (pendingMemberRemovals > 0)
{
handleMemberRemovals(commitPosition);
}
workCount += 1;
}
}
else
{
final Publication publication = leaderMember.publication();
if ((appendedPosition != lastAppendedPosition ||
nowMs >= (timeOfLastAppendPosition + leaderHeartbeatIntervalMs)) &&
memberStatusPublisher.appendedPosition(publication, leadershipTermId, appendedPosition, memberId))
{
lastAppendedPosition = appendedPosition;
timeOfLastAppendPosition = nowMs;
workCount += 1;
}
commitPosition.proposeMaxOrdered(Math.min(logAdapter.position(), appendedPosition));
if (nowMs >= (timeOfLastLogUpdateMs + leaderHeartbeatTimeoutMs))
{
ctx.countedErrorHandler().onError(new ClusterException("heartbeat timeout from leader"));
enterElection(nowMs);
workCount += 1;
}
}
return workCount;
}
private void enterElection(final long nowMs)
{
ingressAdapter.close();
commitPosition.proposeMaxOrdered(followerCommitPosition);
election = new Election(
false,
leadershipTermId,
commitPosition.getWeak(),
clusterMembers,
clusterMemberByIdMap,
thisMember,
memberStatusAdapter,
memberStatusPublisher,
ctx,
this);
election.doWork(nowMs);
serviceProxy.electionStartEvent(commitPosition.getWeak());
}
private void idle()
{
checkInterruptedStatus();
aeronClientInvoker.invoke();
idleStrategy.idle();
}
private void idle(final int workCount)
{
checkInterruptedStatus();
aeronClientInvoker.invoke();
idleStrategy.idle(workCount);
}
private static void checkInterruptedStatus()
{
if (Thread.currentThread().isInterrupted())
{
throw new TimeoutException("unexpected interrupt");
}
}
private void takeSnapshot(final long timestampMs, final long logPosition)
{
try (Publication publication = aeron.addExclusivePublication(ctx.snapshotChannel(), ctx.snapshotStreamId()))
{
final String channel = ChannelUri.addSessionId(ctx.snapshotChannel(), publication.sessionId());
final long subscriptionId = archive.startRecording(channel, ctx.snapshotStreamId(), LOCAL);
try
{
final CountersReader counters = aeron.countersReader();
final int counterId = awaitRecordingCounter(counters, publication.sessionId());
final long recordingId = RecordingPos.getRecordingId(counters, counterId);
final long termBaseLogPosition = recordingLog.getTermEntry(leadershipTermId).termBaseLogPosition;
snapshotState(publication, logPosition, leadershipTermId);
awaitRecordingComplete(recordingId, publication.position(), counters, counterId);
for (int serviceId = serviceAcks.length - 1; serviceId >= 0; serviceId--)
{
final long snapshotId = serviceAcks[serviceId].relevantId();
recordingLog.appendSnapshot(
snapshotId, leadershipTermId, termBaseLogPosition, logPosition, timestampMs, serviceId);
}
recordingLog.appendSnapshot(
recordingId, leadershipTermId, termBaseLogPosition, logPosition, timestampMs, SERVICE_ID);
recordingLog.force();
}
finally
{
archive.stopRecording(subscriptionId);
}
ctx.snapshotCounter().incrementOrdered();
}
}
private void awaitRecordingComplete(
final long recordingId, final long position, final CountersReader counters, final int counterId)
{
idleStrategy.reset();
do
{
idle();
if (!RecordingPos.isActive(counters, counterId, recordingId))
{
throw new ClusterException("recording has stopped unexpectedly: " + recordingId);
}
}
while (counters.getCounterValue(counterId) < position);
}
private int awaitRecordingCounter(final CountersReader counters, final int sessionId)
{
idleStrategy.reset();
int counterId = RecordingPos.findCounterIdBySession(counters, sessionId);
while (CountersReader.NULL_COUNTER_ID == counterId)
{
idle();
counterId = RecordingPos.findCounterIdBySession(counters, sessionId);
}
return counterId;
}
private void snapshotState(final Publication publication, final long logPosition, final long leadershipTermId)
{
final ConsensusModuleSnapshotTaker snapshotTaker = new ConsensusModuleSnapshotTaker(
publication, idleStrategy, aeronClientInvoker);
snapshotTaker.markBegin(SNAPSHOT_TYPE_ID, logPosition, leadershipTermId, 0);
for (final ClusterSession session : sessionByIdMap.values())
{
if (session.state() == OPEN || session.state() == CLOSED)
{
snapshotTaker.snapshotSession(session);
}
}
aeronClientInvoker.invoke();
timerService.snapshot(snapshotTaker);
snapshotTaker.consensusModuleState(nextSessionId);
snapshotTaker.clusterMembers(memberId, highMemberId, clusterMembers);
snapshotTaker.markEnd(SNAPSHOT_TYPE_ID, logPosition, leadershipTermId, 0);
}
private Publication createLogPublication(
final ChannelUri channelUri, final RecordingLog.RecoveryPlan plan, final long position)
{
channelUri.put(TAGS_PARAM_NAME, ConsensusModule.Configuration.LOG_PUBLICATION_TAGS);
if (!plan.logs.isEmpty())
{
final RecordingLog.Log log = plan.logs.get(0);
logInitialTermId = log.initialTermId;
logTermBufferLength = log.termBufferLength;
logMtuLength = log.mtuLength;
}
if (NULL_VALUE != logInitialTermId)
{
channelUri.initialPosition(position, logInitialTermId, logTermBufferLength);
channelUri.put(MTU_LENGTH_PARAM_NAME, Integer.toString(logMtuLength));
}
final Publication publication = aeron.addExclusivePublication(channelUri.toString(), ctx.logStreamId());
if (!channelUri.containsKey(ENDPOINT_PARAM_NAME) && UDP_MEDIA.equals(channelUri.media()))
{
final ChannelUriStringBuilder builder = new ChannelUriStringBuilder().media(UDP_MEDIA);
for (final ClusterMember member : clusterMembers)
{
if (member != thisMember)
{
publication.addDestination(builder.endpoint(member.logEndpoint()).build());
}
}
for (final ClusterMember member : passiveMembers)
{
publication.addDestination(builder.endpoint(member.logEndpoint()).build());
}
}
return publication;
}
private void startLogRecording(final String channel, final SourceLocation sourceLocation)
{
lastRecordingId = recordingLog.findLastTermRecordingId();
if (RecordingPos.NULL_RECORDING_ID == lastRecordingId)
{
archive.startRecording(channel, ctx.logStreamId(), sourceLocation);
}
else
{
archive.extendRecording(lastRecordingId, channel, ctx.logStreamId(), sourceLocation);
}
logRecordingChannel = channel;
}
private void clusterMemberJoined(final int memberId, final ClusterMember[] newMembers)
{
highMemberId = Math.max(highMemberId, memberId);
final ClusterMember eventMember = ClusterMember.findMember(newMembers, memberId);
this.clusterMembers = ClusterMember.addMember(this.clusterMembers, eventMember);
clusterMemberByIdMap.put(memberId, eventMember);
rankedPositions = new long[this.clusterMembers.length];
}
private void clusterMemberQuit(final int memberId)
{
clusterMembers = ClusterMember.removeMember(clusterMembers, memberId);
clusterMemberByIdMap.remove(memberId);
rankedPositions = new long[clusterMembers.length];
}
private void closeExistingLog()
{
logPublisher.disconnect();
CloseHelper.close(logAdapter);
logAdapter = null;
}
private void cancelMissedTimers()
{
final LongHashSet.LongIterator timerIdIterator = missedTimersSet.iterator();
while (timerIdIterator.hasNext())
{
final long missedTimerId = timerIdIterator.nextValue();
if (timerService.cancelTimer(missedTimerId))
{
timerIdIterator.remove();
}
}
}
private void onUnavailableIngressImage(final Image image)
{
ingressAdapter.freeSessionBuffer(image.sessionId());
}
private void clusterTimeMs(final long nowMs)
{
if (NULL_VALUE == clusterTimeMs)
{
timerService.resetStartTime(nowMs);
}
clusterTimeMs = nowMs;
}
private ClusterMember determineMemberAndCheckEndpoints(final ClusterMember[] clusterMembers)
{
final int memberId = ctx.clusterMemberId();
ClusterMember member = NULL_VALUE != memberId ? ClusterMember.findMember(clusterMembers, memberId) : null;
if ((null == clusterMembers || 0 == clusterMembers.length) && null == member)
{
member = ClusterMember.parseEndpoints(NULL_VALUE, ctx.memberEndpoints());
}
else
{
if (null == member)
{
throw new ClusterException("memberId=" + memberId + " not found in clusterMembers");
}
if (!ctx.memberEndpoints().equals(""))
{
ClusterMember.validateMemberEndpoints(member, ctx.memberEndpoints());
}
}
return member;
}
}
| [Java] Code formatting.
| aeron-cluster/src/main/java/io/aeron/cluster/ConsensusModuleAgent.java | [Java] Code formatting. | <ide><path>eron-cluster/src/main/java/io/aeron/cluster/ConsensusModuleAgent.java
<ide>
<ide> private void cancelMissedTimers()
<ide> {
<del> final LongHashSet.LongIterator timerIdIterator = missedTimersSet.iterator();
<del> while (timerIdIterator.hasNext())
<del> {
<del> final long missedTimerId = timerIdIterator.nextValue();
<del> if (timerService.cancelTimer(missedTimerId))
<del> {
<del> timerIdIterator.remove();
<add> for (final LongHashSet.LongIterator iterator = missedTimersSet.iterator(); iterator.hasNext(); )
<add> {
<add> if (timerService.cancelTimer(iterator.nextValue()))
<add> {
<add> iterator.remove();
<ide> }
<ide> }
<ide> } |
|
Java | lgpl-2.1 | ab5b95a6c9503346c5611e64aa4066cd798895d3 | 0 | pbondoer/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This 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 software 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 software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package com.xpn.xwiki.web;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.model.reference.LocalDocumentReference;
import org.xwiki.resource.internal.entity.EntityResourceActionLister;
import org.xwiki.test.annotation.BeforeComponent;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.test.MockitoOldcoreRule;
import com.xpn.xwiki.test.reference.ReferenceComponentList;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Validate {@link XWikiServletURLFactory}.
*
* @version $Id$
*/
@ReferenceComponentList
public class XWikiServletURLFactoryTest
{
private static final String MAIN_WIKI_NAME = "xwiki";
@Rule
public MockitoOldcoreRule oldcore = new MockitoOldcoreRule();
private XWikiServletURLFactory urlFactory;
/**
* Flag indicating if the request is secure. A request is secure if either its URL uses the HTTPS scheme or the
* receiving web application is behind a secure reverse proxy (e.g. the request was send to the reverse proxy
* through HTTPS).
* <p>
* Tests can set this flag to control the value returned by {@link XWikiRequest#isSecure()}.
*/
private boolean secure;
/**
* The map of HTTP headers.
* <p>
* Tests can add values to this map to control the value returned by {@link XWikiRequest#getHeader(String)}.
*/
private final Map<String, String> httpHeaders = new HashMap<>();
@BeforeComponent
public void beforeComponent() throws Exception
{
EntityResourceActionLister actionLister =
this.oldcore.getMocker().registerMockComponent(EntityResourceActionLister.class);
when(actionLister.listActions()).thenReturn(Arrays.asList("view"));
}
@Before
public void before() throws Exception
{
doReturn("DefaultSpace").when(this.oldcore.getSpyXWiki()).getDefaultSpace(any(XWikiContext.class));
// Request
XWikiRequest mockXWikiRequest = mock(XWikiRequest.class);
when(mockXWikiRequest.getScheme()).thenReturn("http");
when(mockXWikiRequest.isSecure()).then(new Answer<Boolean>()
{
@Override
public Boolean answer(InvocationOnMock invocation) throws Throwable
{
return secure;
}
});
when(mockXWikiRequest.getServletPath()).thenReturn("");
when(mockXWikiRequest.getContextPath()).thenReturn("/xwiki");
when(mockXWikiRequest.getHeader(anyString())).then(new Answer<String>()
{
@Override
public String answer(InvocationOnMock invocation) throws Throwable
{
return httpHeaders.get(invocation.getArgumentAt(0, String.class));
}
});
this.oldcore.getXWikiContext().setRequest(mockXWikiRequest);
// Response
XWikiResponse xwikiResponse = mock(XWikiResponse.class);
when(xwikiResponse.encodeURL(anyString())).then(new Answer<String>()
{
@Override
public String answer(InvocationOnMock invocation) throws Throwable
{
return invocation.getArgumentAt(0, String.class);
}
});
this.oldcore.getXWikiContext().setResponse(xwikiResponse);
// Create sub-wikis.
createWiki("wiki1");
createWiki("wiki2");
this.oldcore.getXWikiContext().setURL(new URL("http://127.0.0.1/xwiki/view/InitialSpace/InitialPage"));
this.urlFactory = new XWikiServletURLFactory();
this.urlFactory.init(this.oldcore.getXWikiContext());
}
/**
* Creates a new sub-wiki with the given name.
*
* @param wikiName the wiki name
* @throws Exception if creating the wiki fails
*/
private void createWiki(String wikiName) throws Exception
{
String wikiDocName = "XWikiServer" + wikiName.substring(0, 1).toUpperCase() + wikiName.substring(1);
XWikiDocument wikiDoc = this.oldcore.getSpyXWiki()
.getDocument(new DocumentReference(MAIN_WIKI_NAME, "XWiki", wikiDocName), this.oldcore.getXWikiContext());
BaseObject wikiObj =
wikiDoc.newXObject(new LocalDocumentReference("XWiki", "XWikiServerClass"), this.oldcore.getXWikiContext());
wikiObj.setStringValue("server", wikiName + "server");
this.oldcore.getSpyXWiki().saveDocument(wikiDoc, this.oldcore.getXWikiContext());
}
// Tests
@Test
public void createURLOnMainWiki() throws MalformedURLException
{
URL url = this.urlFactory.createURL("Space", "Page", "view", "param1=1", "anchor", "xwiki",
this.oldcore.getXWikiContext());
assertEquals(new URL("http://127.0.0.1/xwiki/bin/view/Space/Page?param1=1#anchor"), url);
}
@Test
public void createURLOnSubWiki() throws MalformedURLException
{
URL url = this.urlFactory.createURL("Space", "Page", "view", "param1=1", "anchor", "wiki1",
this.oldcore.getXWikiContext());
assertEquals(new URL("http://127.0.0.1/xwiki/wiki/wiki1server/view/Space/Page?param1=1#anchor"), url);
}
@Test
public void createURLOnSubWikiInVirtualMode() throws MalformedURLException
{
this.oldcore.getMockXWikiCfg().setProperty("xwiki.virtual", "1");
URL url = this.urlFactory.createURL("Space", "Page", "view", "param1=1", "anchor", "wiki1",
this.oldcore.getXWikiContext());
assertEquals(new URL("http://127.0.0.1/xwiki/wiki/wiki1server/view/Space/Page?param1=1#anchor"), url);
}
@Test
public void createURLOnMainWikiInPathMode() throws MalformedURLException
{
this.oldcore.getMockXWikiCfg().setProperty("xwiki.virtual.usepath", "1");
URL url = this.urlFactory.createURL("Space", "Page", "view", "param1=1", "anchor", "xwiki",
this.oldcore.getXWikiContext());
assertEquals(new URL("http://127.0.0.1/xwiki/bin/view/Space/Page?param1=1#anchor"), url);
}
@Test
public void createURLOnSubWikiInPathMode() throws MalformedURLException
{
this.oldcore.getMockXWikiCfg().setProperty("xwiki.virtual.usepath", "1");
URL url = this.urlFactory.createURL("Space", "Page", "view", "param1=1", "anchor", "wiki1",
this.oldcore.getXWikiContext());
assertEquals(new URL("http://127.0.0.1/xwiki/wiki/wiki1server/view/Space/Page?param1=1#anchor"), url);
}
@Test
public void createURLOnSubWikiInVirtualModeInPathMode() throws MalformedURLException
{
this.oldcore.getMockXWikiCfg().setProperty("xwiki.virtual", "1");
this.oldcore.getMockXWikiCfg().setProperty("xwiki.virtual.usepath", "1");
secure = true;
// Change the context URL to include a port number and to use HTTPS.
this.oldcore.getXWikiContext().setURL(new URL("https://localhost:8080/xwiki/view/Main/"));
// Reinitialize the URL factory to take into account the new context URL.
urlFactory.init(this.oldcore.getXWikiContext());
URL url = this.urlFactory.createURL("Space", "Page", "view", "param1=1", "anchor", "wiki1",
this.oldcore.getXWikiContext());
assertEquals(new URL("https://localhost:8080/xwiki/wiki/wiki1server/view/Space/Page?param1=1#anchor"), url);
assertEquals("/xwiki/wiki/wiki1server/view/Space/Page?param1=1#anchor",
urlFactory.getURL(url, this.oldcore.getXWikiContext()));
}
@Test
public void createURLOnMainWikiInDomainMode() throws MalformedURLException
{
this.oldcore.getMockXWikiCfg().setProperty("xwiki.virtual.usepath", "0");
URL url = this.urlFactory.createURL("Space", "Page", "view", "param1=1", "anchor", "xwiki",
this.oldcore.getXWikiContext());
assertEquals(new URL("http://127.0.0.1/xwiki/bin/view/Space/Page?param1=1#anchor"), url);
}
@Test
public void createURLOnSubWikiInDomainMode() throws MalformedURLException
{
this.oldcore.getMockXWikiCfg().setProperty("xwiki.virtual.usepath", "0");
URL url = this.urlFactory.createURL("Space", "Page", "view", "param1=1", "anchor", "wiki1",
this.oldcore.getXWikiContext());
assertEquals(new URL("http://wiki1server/xwiki/bin/view/Space/Page?param1=1#anchor"), url);
}
@Test
public void createURLOnSubWikiInVirtualModeInDomainMode() throws MalformedURLException
{
this.oldcore.getMockXWikiCfg().setProperty("xwiki.virtual", "1");
this.oldcore.getMockXWikiCfg().setProperty("xwiki.virtual.usepath", "0");
URL url = this.urlFactory.createURL("Space", "Page", "view", "param1=1", "anchor", "wiki1",
this.oldcore.getXWikiContext());
assertEquals(new URL("http://wiki1server/xwiki/bin/view/Space/Page?param1=1#anchor"), url);
}
/**
* Checks the URLs created on the main wiki when XWiki is behind a reverse proxy.
*
* @throws MalformedURLException shouldn't happen
*/
@Test
public void createURLOnMainWikiInDomainModeInReverseProxyMode() throws MalformedURLException
{
secure = true;
httpHeaders.put("x-forwarded-host", "www.xwiki.org");
// Reinitialize the URL factory to take into account the new security level and HTTP headers.
urlFactory.init(this.oldcore.getXWikiContext());
this.oldcore.getMockXWikiCfg().setProperty("xwiki.virtual.usepath", "0");
URL url = urlFactory.createURL("Space", "Page", "view", "param1=1", "anchor", "xwiki",
this.oldcore.getXWikiContext());
assertEquals(new URL("https://www.xwiki.org/xwiki/bin/view/Space/Page?param1=1#anchor"), url);
assertEquals("/xwiki/bin/view/Space/Page?param1=1#anchor",
urlFactory.getURL(url, this.oldcore.getXWikiContext()));
}
@Test
public void createURLOnSubWikiInDomainModeInReverseProxyMode() throws MalformedURLException
{
httpHeaders.put("x-forwarded-host", "www.xwiki.org");
// Reinitialize the URL factory to take into account the new HTTP headers.
urlFactory.init(this.oldcore.getXWikiContext());
this.oldcore.getMockXWikiCfg().setProperty("xwiki.virtual.usepath", "0");
URL url = urlFactory.createURL("Space", "Page", "view", "param1=1", "anchor", "wiki1",
this.oldcore.getXWikiContext());
assertEquals(new URL("http://wiki1server/xwiki/bin/view/Space/Page?param1=1#anchor"), url);
// The URL remains absolute in this case.
assertEquals("http://wiki1server/xwiki/bin/view/Space/Page?param1=1#anchor",
urlFactory.getURL(url, this.oldcore.getXWikiContext()));
}
@Test
public void createURLOnSubWikiInVirtualModeInDomainModeInReverseProxyMode() throws MalformedURLException
{
secure = true;
httpHeaders.put("x-forwarded-host", "www.xwiki.org");
// Reinitialize the URL factory to take into account the new security level and HTTP headers.
urlFactory.init(this.oldcore.getXWikiContext());
this.oldcore.getMockXWikiCfg().setProperty("xwiki.virtual", "1");
this.oldcore.getMockXWikiCfg().setProperty("xwiki.virtual.usepath", "0");
URL url = urlFactory.createURL("Space", "Page", "view", "param1=1", "anchor", "wiki1",
this.oldcore.getXWikiContext());
assertEquals(new URL("https://wiki1server/xwiki/bin/view/Space/Page?param1=1#anchor"), url);
// The URL remains absolute in this case.
assertEquals("https://wiki1server/xwiki/bin/view/Space/Page?param1=1#anchor",
urlFactory.getURL(url, this.oldcore.getXWikiContext()));
}
@Test
public void createURLOnMainWikiInPathModeInReverseProxyMode() throws MalformedURLException
{
httpHeaders.put("x-forwarded-host", "www.xwiki.org");
// Reinitialize the URL factory to take into account the new HTTP headers.
urlFactory.init(this.oldcore.getXWikiContext());
this.oldcore.getMockXWikiCfg().setProperty("xwiki.virtual.usepath", "1");
URL url = urlFactory.createURL("Space", "Page", "view", "param1=1", "anchor", "xwiki",
this.oldcore.getXWikiContext());
assertEquals(new URL("http://www.xwiki.org/xwiki/bin/view/Space/Page?param1=1#anchor"), url);
assertEquals("/xwiki/bin/view/Space/Page?param1=1#anchor",
urlFactory.getURL(url, this.oldcore.getXWikiContext()));
}
@Test
public void createURLOnSubWikiInPathModeInReverseProxyMode() throws MalformedURLException
{
secure = true;
httpHeaders.put("x-forwarded-host", "www.xwiki.org");
// Reinitialize the URL factory to take into account the new security level and HTTP headers.
urlFactory.init(this.oldcore.getXWikiContext());
this.oldcore.getMockXWikiCfg().setProperty("xwiki.virtual.usepath", "1");
URL url = urlFactory.createURL("Space", "Page", "view", "param1=1", "anchor", "wiki1",
this.oldcore.getXWikiContext());
assertEquals(new URL("https://www.xwiki.org/xwiki/wiki/wiki1server/view/Space/Page?param1=1#anchor"), url);
assertEquals("/xwiki/wiki/wiki1server/view/Space/Page?param1=1#anchor",
urlFactory.getURL(url, this.oldcore.getXWikiContext()));
}
@Test
public void createURLOnSubWikiInVirtualModeInPathModeInReverseProxyMode() throws MalformedURLException
{
httpHeaders.put("x-forwarded-host", "www.xwiki.org:8080");
// Reinitialize the URL factory to take into account the new HTTP headers.
urlFactory.init(this.oldcore.getXWikiContext());
this.oldcore.getMockXWikiCfg().setProperty("xwiki.virtual", "1");
this.oldcore.getMockXWikiCfg().setProperty("xwiki.virtual.usepath", "1");
URL url = urlFactory.createURL("Space", "Page", "view", "param1=1", "anchor", "wiki1",
this.oldcore.getXWikiContext());
assertEquals(new URL("http://www.xwiki.org:8080/xwiki/wiki/wiki1server/view/Space/Page?param1=1#anchor"), url);
assertEquals("/xwiki/wiki/wiki1server/view/Space/Page?param1=1#anchor",
urlFactory.getURL(url, this.oldcore.getXWikiContext()));
}
/**
* Tests how URLs are serialized when the request wiki (taken from the request URL) and the context wiki (explicitly
* set from code on the XWiki context) are different.
*/
@Test
public void getURLWhenRequestWikiAndContextWikiAreDifferent() throws MalformedURLException
{
this.oldcore.getXWikiContext().setURL(new URL("http://wiki1server/xwiki/view/InitialSpace/InitialPage"));
// Reinitialize the URL factory to take into account the new request URL.
urlFactory.init(this.oldcore.getXWikiContext());
this.oldcore.getXWikiContext().setWikiId("wiki2");
String url =
urlFactory.getURL(new URL("http://wiki1server/xwiki/bin/view/Space/Page"), this.oldcore.getXWikiContext());
assertEquals("/xwiki/bin/view/Space/Page", url);
url =
urlFactory.getURL(new URL("http://wiki2server/xwiki/bin/view/Space/Page"), this.oldcore.getXWikiContext());
assertEquals("http://wiki2server/xwiki/bin/view/Space/Page", url);
}
/** When the URL contains only the hostname, without a path, / is returned instead of the empty string. */
@Test
public void getURLWithEmptyPathReturnsSlash() throws MalformedURLException
{
this.oldcore.getXWikiContext().setURL(new URL("http://wiki1server/xwiki/view/InitialSpace/InitialPage"));
// Reinitialize the URL factory to take into account the new request URL.
this.urlFactory.init(this.oldcore.getXWikiContext());
String url = this.urlFactory.getURL(new URL("http://wiki1server/"), this.oldcore.getXWikiContext());
assertEquals("/", url);
}
/**
* When getServerURL is called on a resource from the main wiki, the user is in a subwiki, and xwiki.home is set,
* xwiki.home should be returned. see: XWIKI-5981
*/
@Test
public void getServerURLFromVirtualWithXWikiDotHomeEnabled() throws MalformedURLException
{
this.oldcore.getXWikiContext()
.setURL(new URL("http://virtual1.mywiki.tld/xwiki/view/InitialSpace/InitialPage"));
this.oldcore.getXWikiContext().setWikiId("subwiki");
// This is called by XWiki#getXWiki() and is set to whatever the user asks for.
// The test sets it to "xwiki" which is wrong for this test.
this.oldcore.getXWikiContext().setOriginalWikiId("subwiki");
this.oldcore.getMockXWikiCfg().setProperty("xwiki.home", "http://mainwiki.mywiki.tld/");
this.oldcore.getMockXWikiCfg().setProperty("xwiki.virtual", "1");
urlFactory.init(this.oldcore.getXWikiContext());
assertEquals("http://mainwiki.mywiki.tld/",
urlFactory.getServerURL("xwiki", this.oldcore.getXWikiContext()).toString());
}
/**
* Proves that from a virtual wiki, URLs generated to point to the main wiki will use xwiki.home. see: XWIKI-5981
*/
@Test
public void createURLWhenWikiDotHomeParameterFromVirtualWiki() throws MalformedURLException
{
this.oldcore.getXWikiContext()
.setURL(new URL("http://virtual1.mywiki.tld/xwiki/view/InitialSpace/InitialPage"));
this.oldcore.getXWikiContext().setWikiId("subwiki");
// This is called by XWiki#getXWiki() and is set to whatever the user asks for.
// The test sets it to "xwiki" which is wrong for this test.
this.oldcore.getXWikiContext().setOriginalWikiId("subwiki");
this.oldcore.getMockXWikiCfg().setProperty("xwiki.home", "http://mainwiki.mywiki.tld/");
this.oldcore.getMockXWikiCfg().setProperty("xwiki.virtual", "1");
// Reinitialize the URL factory to take into account the new request URL.
urlFactory.init(this.oldcore.getXWikiContext());
// No wiki passed, assume same wiki. we should expect it to return http://virtual1.mywiki.tld/
URL url =
urlFactory.createURL("Space", "Page", "view", "param1=1", "anchor", null, this.oldcore.getXWikiContext());
assertEquals(new URL("http://virtual1.mywiki.tld/xwiki/bin/view/Space/Page?param1=1#anchor"), url);
// We are already in virtual1 so it should be a relative reference.
assertEquals("/xwiki/bin/view/Space/Page?param1=1#anchor",
urlFactory.getURL(url, this.oldcore.getXWikiContext()));
// Pass "xwiki" as the wiki, expect it to return the main wiki as set in the xwiki.home parameter.
url = urlFactory.createURL("Space", "Page", "view", "param1=1", "anchor", "xwiki",
this.oldcore.getXWikiContext());
assertEquals(new URL("http://mainwiki.mywiki.tld/xwiki/bin/view/Space/Page?param1=1#anchor"), url);
assertEquals("http://mainwiki.mywiki.tld/xwiki/bin/view/Space/Page?param1=1#anchor",
urlFactory.getURL(url, this.oldcore.getXWikiContext()));
}
/**
* When getServerURL is called on a resource from the main wiki, the user is in the main wiki, and xwiki.home is
* set, xwiki.home should be returned. see: XWIKI-5981
*/
@Test
public void getServerURLNonVirtualModeWithXWikiDotHomeEnabled() throws MalformedURLException
{
this.oldcore.getXWikiContext().setURL(new URL("http://127.0.0.1:8080/xwiki/view/InitialSpace/InitialPage"));
this.oldcore.getMockXWikiCfg().setProperty("xwiki.home", "http://mainwiki.mywiki.tld/");
urlFactory.init(this.oldcore.getXWikiContext());
// TODO: Fix getServerURL() so that is is consistent about returning a trailing / or not.
assertEquals("http://mainwiki.mywiki.tld",
urlFactory.getServerURL("xwiki", this.oldcore.getXWikiContext()).toString());
assertEquals("http://mainwiki.mywiki.tld",
urlFactory.getServerURL(null, this.oldcore.getXWikiContext()).toString());
}
/**
* Proves that in a single wiki instance, URLs are always generated using xwiki.home if present. see: XWIKI-5981
*/
@Test
public void createURLWhenXWikiDotHomeParameterNonVirtualMode() throws MalformedURLException
{
// Some proxies will modify the host field without adding a x-forwarded-host field,
// Using xwiki.home we should be able to make it work anyway.
this.oldcore.getXWikiContext().setURL(new URL("http://localhost:8080/xwiki/view/InitialSpace/InitialPage"));
this.oldcore.getMockXWikiCfg().setProperty("xwiki.home", "http://mainwiki.mywiki.tld/");
// Reinitialize the URL factory to take into account the new request URL.
urlFactory.init(this.oldcore.getXWikiContext());
// No wiki passed, assume main wiki. we should expect it to return mainwiki.mywiki.tld and not
// xwiki.mywiki.tld.
URL url =
urlFactory.createURL("Space", "Page", "view", "param1=1", "anchor", null, this.oldcore.getXWikiContext());
assertEquals(new URL("http://mainwiki.mywiki.tld/xwiki/bin/view/Space/Page?param1=1#anchor"), url);
assertEquals("/xwiki/bin/view/Space/Page?param1=1#anchor",
urlFactory.getURL(url, this.oldcore.getXWikiContext()));
// Pass "xwiki" as the wiki, expect same result.
url = urlFactory.createURL("Space", "Page", "view", "param1=1", "anchor", "xwiki",
this.oldcore.getXWikiContext());
assertEquals(new URL("http://mainwiki.mywiki.tld/xwiki/bin/view/Space/Page?param1=1#anchor"), url);
assertEquals("/xwiki/bin/view/Space/Page?param1=1#anchor",
urlFactory.getURL(url, this.oldcore.getXWikiContext()));
}
/**
* Verify that jsessionid is removed from URL.
*/
@Test
public void normalizeURL() throws Exception
{
assertEquals(new URL("http://www.xwiki.org/xwiki/bin/view/Blog/Bug+Fixing+Day+35?language=en"),
XWikiServletURLFactory.normalizeURL("http://www.xwiki.org/xwiki/bin/view/Blog/Bug+Fixing+Day+35"
+ ";jsessionid=0AF95AFB8997826B936C0397DF6A0C7F?language=en", this.oldcore.getXWikiContext()));
}
@Test
public void createURLWithNestedSpaces() throws Exception
{
URL url = this.urlFactory.createURL("Space1.Space2", "Page", this.oldcore.getXWikiContext());
assertEquals(new URL("http://127.0.0.1/xwiki/bin/view/Space1/Space2/Page"), url);
}
@Test
public void createAttachmentURLWhenViewRevAndRevSpecifiedAndIsNotContextDoc() throws Exception
{
XWikiContext xwikiContext = this.oldcore.getXWikiContext();
xwikiContext.put("rev", "1.0");
xwikiContext.setAction("viewrev");
xwikiContext.setDoc(new XWikiDocument(new DocumentReference("currentwiki", "currentspace", "currentpage")));
URL url = this.urlFactory.createAttachmentURL("file", "space", "page", "viewrev", null, xwikiContext);
assertEquals(new URL("http://127.0.0.1/xwiki/bin/viewrev/space/page/file"), url);
}
@Test
public void createAttachmentURLWhenViewRevAndRevSpecifiedAndIsContextDocAndAttachmentDoesntExist()
throws Exception
{
XWikiContext xwikiContext = this.oldcore.getXWikiContext();
xwikiContext.put("rev", "1.0");
xwikiContext.setAction("viewrev");
XWikiDocument document = new XWikiDocument(new DocumentReference("currentwiki", "currentspace", "currentpage"));
this.oldcore.getSpyXWiki().saveDocument(document, this.oldcore.getXWikiContext());
xwikiContext.setDoc(document);
xwikiContext.setWikiId("currentwiki");
URL url =
this.urlFactory.createAttachmentURL("file", "currentspace", "currentpage", "viewrev", null, xwikiContext);
assertEquals(new URL("http://127.0.0.1/xwiki/bin/viewattachrev/currentspace/currentpage/file"), url);
}
@Test
public void createURLWhenShowViewActionFalse() throws Exception
{
doReturn(false).when(this.oldcore.getSpyXWiki()).showViewAction(any(XWikiContext.class));
URL url = this.urlFactory.createURL("Space", "Page", "view", this.oldcore.getXWikiContext());
assertEquals(new URL("http://127.0.0.1/xwiki/bin/Space/Page"), url);
}
@Test
public void createURLWhenShowViewActionFalseAndSpaceIsNamedAfterAnAction() throws Exception
{
doReturn(false).when(this.oldcore.getSpyXWiki()).showViewAction(any(XWikiContext.class));
URL url = this.urlFactory.createURL("view.space2", "page", "view", this.oldcore.getXWikiContext());
assertEquals(new URL("http://127.0.0.1/xwiki/bin/view/view/space2/page"), url);
}
@Test
public void createResourceURL() throws Exception
{
// Verify that the URL factory encodes each path segment.
URL url = this.urlFactory.createResourceURL("o;ne/t?w&o/t=hr#e e", false, this.oldcore.getXWikiContext());
assertEquals(new URL("http://127.0.0.1/xwiki/resources/o;ne/t%3Fw&o/t=hr%23e%20e"), url);
}
@Test
public void createURLWhenCharactersNeedToBeEncoded() throws Exception
{
// Note: The query string is not encoded, and used as is. It's the responsibility of the caller to
// url-encode it.
// See XWikiServletURLFactory#encodeWithinPath() and XWikiServletURLFactory#encodeWithinQuery() for explanations
// Note: We also verify that the single quote is encoded since otherwise that could cause problems in HTML when
// the returned URL is used in the HREF attribute of a A tag (when using single quote delimiters).
URL url = this.urlFactory.createURL("a b.c+d'", "e f", "view", "g=h+i", "j k+l", this.oldcore.getXWikiContext());
assertEquals("http://127.0.0.1/xwiki/bin/view/a%20b/c%2Bd%27/e%20f?g=h+i#j+k%2Bl", url.toString());
}
}
| xwiki-platform-core/xwiki-platform-oldcore/src/test/java/com/xpn/xwiki/web/XWikiServletURLFactoryTest.java | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This 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 software 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 software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package com.xpn.xwiki.web;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.model.reference.LocalDocumentReference;
import org.xwiki.resource.internal.entity.EntityResourceActionLister;
import org.xwiki.test.annotation.BeforeComponent;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.test.MockitoOldcoreRule;
import com.xpn.xwiki.test.reference.ReferenceComponentList;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Validate {@link XWikiServletURLFactory}.
*
* @version $Id$
*/
@ReferenceComponentList
public class XWikiServletURLFactoryTest
{
private static final String MAIN_WIKI_NAME = "xwiki";
@Rule
public MockitoOldcoreRule oldcore = new MockitoOldcoreRule();
private XWikiServletURLFactory urlFactory;
/**
* Flag indicating if the request is secure. A request is secure if either its URL uses the HTTPS scheme or the
* receiving web application is behind a secure reverse proxy (e.g. the request was send to the reverse proxy
* through HTTPS).
* <p>
* Tests can set this flag to control the value returned by {@link XWikiRequest#isSecure()}.
*/
private boolean secure;
/**
* The map of HTTP headers.
* <p>
* Tests can add values to this map to control the value returned by {@link XWikiRequest#getHeader(String)}.
*/
private final Map<String, String> httpHeaders = new HashMap<>();
@BeforeComponent
public void beforeComponent() throws Exception
{
EntityResourceActionLister actionLister =
this.oldcore.getMocker().registerMockComponent(EntityResourceActionLister.class);
when(actionLister.listActions()).thenReturn(Arrays.asList("view"));
}
@Before
public void before() throws Exception
{
doReturn("DefaultSpace").when(this.oldcore.getSpyXWiki()).getDefaultSpace(any(XWikiContext.class));
// Request
XWikiRequest mockXWikiRequest = mock(XWikiRequest.class);
when(mockXWikiRequest.getScheme()).thenReturn("http");
when(mockXWikiRequest.isSecure()).then(new Answer<Boolean>()
{
@Override
public Boolean answer(InvocationOnMock invocation) throws Throwable
{
return secure;
}
});
when(mockXWikiRequest.getServletPath()).thenReturn("");
when(mockXWikiRequest.getContextPath()).thenReturn("/xwiki");
when(mockXWikiRequest.getHeader(anyString())).then(new Answer<String>()
{
@Override
public String answer(InvocationOnMock invocation) throws Throwable
{
return httpHeaders.get(invocation.getArgumentAt(0, String.class));
}
});
this.oldcore.getXWikiContext().setRequest(mockXWikiRequest);
// Response
XWikiResponse xwikiResponse = mock(XWikiResponse.class);
when(xwikiResponse.encodeURL(anyString())).then(new Answer<String>()
{
@Override
public String answer(InvocationOnMock invocation) throws Throwable
{
return invocation.getArgumentAt(0, String.class);
}
});
this.oldcore.getXWikiContext().setResponse(xwikiResponse);
// Create sub-wikis.
createWiki("wiki1");
createWiki("wiki2");
this.oldcore.getXWikiContext().setURL(new URL("http://127.0.0.1/xwiki/view/InitialSpace/InitialPage"));
this.urlFactory = new XWikiServletURLFactory();
this.urlFactory.init(this.oldcore.getXWikiContext());
}
/**
* Creates a new sub-wiki with the given name.
*
* @param wikiName the wiki name
* @throws Exception if creating the wiki fails
*/
private void createWiki(String wikiName) throws Exception
{
String wikiDocName = "XWikiServer" + wikiName.substring(0, 1).toUpperCase() + wikiName.substring(1);
XWikiDocument wikiDoc = this.oldcore.getSpyXWiki()
.getDocument(new DocumentReference(MAIN_WIKI_NAME, "XWiki", wikiDocName), this.oldcore.getXWikiContext());
BaseObject wikiObj =
wikiDoc.newXObject(new LocalDocumentReference("XWiki", "XWikiServerClass"), this.oldcore.getXWikiContext());
wikiObj.setStringValue("server", wikiName + "server");
this.oldcore.getSpyXWiki().saveDocument(wikiDoc, this.oldcore.getXWikiContext());
}
// Tests
@Test
public void createURLOnMainWiki() throws MalformedURLException
{
URL url = this.urlFactory.createURL("Space", "Page", "view", "param1=1", "anchor", "xwiki",
this.oldcore.getXWikiContext());
assertEquals(new URL("http://127.0.0.1/xwiki/bin/view/Space/Page?param1=1#anchor"), url);
}
@Test
public void createURLOnSubWiki() throws MalformedURLException
{
URL url = this.urlFactory.createURL("Space", "Page", "view", "param1=1", "anchor", "wiki1",
this.oldcore.getXWikiContext());
assertEquals(new URL("http://127.0.0.1/xwiki/wiki/wiki1server/view/Space/Page?param1=1#anchor"), url);
}
@Test
public void createURLOnSubWikiInVirtualMode() throws MalformedURLException
{
this.oldcore.getMockXWikiCfg().setProperty("xwiki.virtual", "1");
URL url = this.urlFactory.createURL("Space", "Page", "view", "param1=1", "anchor", "wiki1",
this.oldcore.getXWikiContext());
assertEquals(new URL("http://127.0.0.1/xwiki/wiki/wiki1server/view/Space/Page?param1=1#anchor"), url);
}
@Test
public void createURLOnMainWikiInPathMode() throws MalformedURLException
{
this.oldcore.getMockXWikiCfg().setProperty("xwiki.virtual.usepath", "1");
URL url = this.urlFactory.createURL("Space", "Page", "view", "param1=1", "anchor", "xwiki",
this.oldcore.getXWikiContext());
assertEquals(new URL("http://127.0.0.1/xwiki/bin/view/Space/Page?param1=1#anchor"), url);
}
@Test
public void createURLOnSubWikiInPathMode() throws MalformedURLException
{
this.oldcore.getMockXWikiCfg().setProperty("xwiki.virtual.usepath", "1");
URL url = this.urlFactory.createURL("Space", "Page", "view", "param1=1", "anchor", "wiki1",
this.oldcore.getXWikiContext());
assertEquals(new URL("http://127.0.0.1/xwiki/wiki/wiki1server/view/Space/Page?param1=1#anchor"), url);
}
@Test
public void createURLOnSubWikiInVirtualModeInPathMode() throws MalformedURLException
{
this.oldcore.getMockXWikiCfg().setProperty("xwiki.virtual", "1");
this.oldcore.getMockXWikiCfg().setProperty("xwiki.virtual.usepath", "1");
secure = true;
// Change the context URL to include a port number and to use HTTPS.
this.oldcore.getXWikiContext().setURL(new URL("https://localhost:8080/xwiki/view/Main/"));
// Reinitialize the URL factory to take into account the new context URL.
urlFactory.init(this.oldcore.getXWikiContext());
URL url = this.urlFactory.createURL("Space", "Page", "view", "param1=1", "anchor", "wiki1",
this.oldcore.getXWikiContext());
assertEquals(new URL("https://localhost:8080/xwiki/wiki/wiki1server/view/Space/Page?param1=1#anchor"), url);
assertEquals("/xwiki/wiki/wiki1server/view/Space/Page?param1=1#anchor",
urlFactory.getURL(url, this.oldcore.getXWikiContext()));
}
@Test
public void createURLOnMainWikiInDomainMode() throws MalformedURLException
{
this.oldcore.getMockXWikiCfg().setProperty("xwiki.virtual.usepath", "0");
URL url = this.urlFactory.createURL("Space", "Page", "view", "param1=1", "anchor", "xwiki",
this.oldcore.getXWikiContext());
assertEquals(new URL("http://127.0.0.1/xwiki/bin/view/Space/Page?param1=1#anchor"), url);
}
@Test
public void createURLOnSubWikiInDomainMode() throws MalformedURLException
{
this.oldcore.getMockXWikiCfg().setProperty("xwiki.virtual.usepath", "0");
URL url = this.urlFactory.createURL("Space", "Page", "view", "param1=1", "anchor", "wiki1",
this.oldcore.getXWikiContext());
assertEquals(new URL("http://wiki1server/xwiki/bin/view/Space/Page?param1=1#anchor"), url);
}
@Test
public void createURLOnSubWikiInVirtualModeInDomainMode() throws MalformedURLException
{
this.oldcore.getMockXWikiCfg().setProperty("xwiki.virtual", "1");
this.oldcore.getMockXWikiCfg().setProperty("xwiki.virtual.usepath", "0");
URL url = this.urlFactory.createURL("Space", "Page", "view", "param1=1", "anchor", "wiki1",
this.oldcore.getXWikiContext());
assertEquals(new URL("http://wiki1server/xwiki/bin/view/Space/Page?param1=1#anchor"), url);
}
/**
* Checks the URLs created on the main wiki when XWiki is behind a reverse proxy.
*
* @throws MalformedURLException shouldn't happen
*/
@Test
public void createURLOnMainWikiInDomainModeInReverseProxyMode() throws MalformedURLException
{
secure = true;
httpHeaders.put("x-forwarded-host", "www.xwiki.org");
// Reinitialize the URL factory to take into account the new security level and HTTP headers.
urlFactory.init(this.oldcore.getXWikiContext());
this.oldcore.getMockXWikiCfg().setProperty("xwiki.virtual.usepath", "0");
URL url = urlFactory.createURL("Space", "Page", "view", "param1=1", "anchor", "xwiki",
this.oldcore.getXWikiContext());
assertEquals(new URL("https://www.xwiki.org/xwiki/bin/view/Space/Page?param1=1#anchor"), url);
assertEquals("/xwiki/bin/view/Space/Page?param1=1#anchor",
urlFactory.getURL(url, this.oldcore.getXWikiContext()));
}
@Test
public void createURLOnSubWikiInDomainModeInReverseProxyMode() throws MalformedURLException
{
httpHeaders.put("x-forwarded-host", "www.xwiki.org");
// Reinitialize the URL factory to take into account the new HTTP headers.
urlFactory.init(this.oldcore.getXWikiContext());
this.oldcore.getMockXWikiCfg().setProperty("xwiki.virtual.usepath", "0");
URL url = urlFactory.createURL("Space", "Page", "view", "param1=1", "anchor", "wiki1",
this.oldcore.getXWikiContext());
assertEquals(new URL("http://wiki1server/xwiki/bin/view/Space/Page?param1=1#anchor"), url);
// The URL remains absolute in this case.
assertEquals("http://wiki1server/xwiki/bin/view/Space/Page?param1=1#anchor",
urlFactory.getURL(url, this.oldcore.getXWikiContext()));
}
@Test
public void createURLOnSubWikiInVirtualModeInDomainModeInReverseProxyMode() throws MalformedURLException
{
secure = true;
httpHeaders.put("x-forwarded-host", "www.xwiki.org");
// Reinitialize the URL factory to take into account the new security level and HTTP headers.
urlFactory.init(this.oldcore.getXWikiContext());
this.oldcore.getMockXWikiCfg().setProperty("xwiki.virtual", "1");
this.oldcore.getMockXWikiCfg().setProperty("xwiki.virtual.usepath", "0");
URL url = urlFactory.createURL("Space", "Page", "view", "param1=1", "anchor", "wiki1",
this.oldcore.getXWikiContext());
assertEquals(new URL("https://wiki1server/xwiki/bin/view/Space/Page?param1=1#anchor"), url);
// The URL remains absolute in this case.
assertEquals("https://wiki1server/xwiki/bin/view/Space/Page?param1=1#anchor",
urlFactory.getURL(url, this.oldcore.getXWikiContext()));
}
@Test
public void createURLOnMainWikiInPathModeInReverseProxyMode() throws MalformedURLException
{
httpHeaders.put("x-forwarded-host", "www.xwiki.org");
// Reinitialize the URL factory to take into account the new HTTP headers.
urlFactory.init(this.oldcore.getXWikiContext());
this.oldcore.getMockXWikiCfg().setProperty("xwiki.virtual.usepath", "1");
URL url = urlFactory.createURL("Space", "Page", "view", "param1=1", "anchor", "xwiki",
this.oldcore.getXWikiContext());
assertEquals(new URL("http://www.xwiki.org/xwiki/bin/view/Space/Page?param1=1#anchor"), url);
assertEquals("/xwiki/bin/view/Space/Page?param1=1#anchor",
urlFactory.getURL(url, this.oldcore.getXWikiContext()));
}
@Test
public void createURLOnSubWikiInPathModeInReverseProxyMode() throws MalformedURLException
{
secure = true;
httpHeaders.put("x-forwarded-host", "www.xwiki.org");
// Reinitialize the URL factory to take into account the new security level and HTTP headers.
urlFactory.init(this.oldcore.getXWikiContext());
this.oldcore.getMockXWikiCfg().setProperty("xwiki.virtual.usepath", "1");
URL url = urlFactory.createURL("Space", "Page", "view", "param1=1", "anchor", "wiki1",
this.oldcore.getXWikiContext());
assertEquals(new URL("https://www.xwiki.org/xwiki/wiki/wiki1server/view/Space/Page?param1=1#anchor"), url);
assertEquals("/xwiki/wiki/wiki1server/view/Space/Page?param1=1#anchor",
urlFactory.getURL(url, this.oldcore.getXWikiContext()));
}
@Test
public void createURLOnSubWikiInVirtualModeInPathModeInReverseProxyMode() throws MalformedURLException
{
httpHeaders.put("x-forwarded-host", "www.xwiki.org:8080");
// Reinitialize the URL factory to take into account the new HTTP headers.
urlFactory.init(this.oldcore.getXWikiContext());
this.oldcore.getMockXWikiCfg().setProperty("xwiki.virtual", "1");
this.oldcore.getMockXWikiCfg().setProperty("xwiki.virtual.usepath", "1");
URL url = urlFactory.createURL("Space", "Page", "view", "param1=1", "anchor", "wiki1",
this.oldcore.getXWikiContext());
assertEquals(new URL("http://www.xwiki.org:8080/xwiki/wiki/wiki1server/view/Space/Page?param1=1#anchor"), url);
assertEquals("/xwiki/wiki/wiki1server/view/Space/Page?param1=1#anchor",
urlFactory.getURL(url, this.oldcore.getXWikiContext()));
}
/**
* Tests how URLs are serialized when the request wiki (taken from the request URL) and the context wiki (explicitly
* set from code on the XWiki context) are different.
*/
@Test
public void getURLWhenRequestWikiAndContextWikiAreDifferent() throws MalformedURLException
{
this.oldcore.getXWikiContext().setURL(new URL("http://wiki1server/xwiki/view/InitialSpace/InitialPage"));
// Reinitialize the URL factory to take into account the new request URL.
urlFactory.init(this.oldcore.getXWikiContext());
this.oldcore.getXWikiContext().setWikiId("wiki2");
String url =
urlFactory.getURL(new URL("http://wiki1server/xwiki/bin/view/Space/Page"), this.oldcore.getXWikiContext());
assertEquals("/xwiki/bin/view/Space/Page", url);
url =
urlFactory.getURL(new URL("http://wiki2server/xwiki/bin/view/Space/Page"), this.oldcore.getXWikiContext());
assertEquals("http://wiki2server/xwiki/bin/view/Space/Page", url);
}
/** When the URL contains only the hostname, without a path, / is returned instead of the empty string. */
@Test
public void getURLWithEmptyPathReturnsSlash() throws MalformedURLException
{
this.oldcore.getXWikiContext().setURL(new URL("http://wiki1server/xwiki/view/InitialSpace/InitialPage"));
// Reinitialize the URL factory to take into account the new request URL.
this.urlFactory.init(this.oldcore.getXWikiContext());
String url = this.urlFactory.getURL(new URL("http://wiki1server/"), this.oldcore.getXWikiContext());
assertEquals("/", url);
}
/**
* When getServerURL is called on a resource from the main wiki, the user is in a subwiki, and xwiki.home is set,
* xwiki.home should be returned. see: XWIKI-5981
*/
@Test
public void getServerURLFromVirtualWithXWikiDotHomeEnabled() throws MalformedURLException
{
this.oldcore.getXWikiContext()
.setURL(new URL("http://virtual1.mywiki.tld/xwiki/view/InitialSpace/InitialPage"));
this.oldcore.getXWikiContext().setWikiId("subwiki");
// This is called by XWiki#getXWiki() and is set to whatever the user asks for.
// The test sets it to "xwiki" which is wrong for this test.
this.oldcore.getXWikiContext().setOriginalWikiId("subwiki");
this.oldcore.getMockXWikiCfg().setProperty("xwiki.home", "http://mainwiki.mywiki.tld/");
this.oldcore.getMockXWikiCfg().setProperty("xwiki.virtual", "1");
urlFactory.init(this.oldcore.getXWikiContext());
assertEquals("http://mainwiki.mywiki.tld/",
urlFactory.getServerURL("xwiki", this.oldcore.getXWikiContext()).toString());
}
/**
* Proves that from a virtual wiki, URLs generated to point to the main wiki will use xwiki.home. see: XWIKI-5981
*/
@Test
public void createURLWhenWikiDotHomeParameterFromVirtualWiki() throws MalformedURLException
{
this.oldcore.getXWikiContext()
.setURL(new URL("http://virtual1.mywiki.tld/xwiki/view/InitialSpace/InitialPage"));
this.oldcore.getXWikiContext().setWikiId("subwiki");
// This is called by XWiki#getXWiki() and is set to whatever the user asks for.
// The test sets it to "xwiki" which is wrong for this test.
this.oldcore.getXWikiContext().setOriginalWikiId("subwiki");
this.oldcore.getMockXWikiCfg().setProperty("xwiki.home", "http://mainwiki.mywiki.tld/");
this.oldcore.getMockXWikiCfg().setProperty("xwiki.virtual", "1");
// Reinitialize the URL factory to take into account the new request URL.
urlFactory.init(this.oldcore.getXWikiContext());
// No wiki passed, assume same wiki. we should expect it to return http://virtual1.mywiki.tld/
URL url =
urlFactory.createURL("Space", "Page", "view", "param1=1", "anchor", null, this.oldcore.getXWikiContext());
assertEquals(new URL("http://virtual1.mywiki.tld/xwiki/bin/view/Space/Page?param1=1#anchor"), url);
// We are already in virtual1 so it should be a relative reference.
assertEquals("/xwiki/bin/view/Space/Page?param1=1#anchor",
urlFactory.getURL(url, this.oldcore.getXWikiContext()));
// Pass "xwiki" as the wiki, expect it to return the main wiki as set in the xwiki.home parameter.
url = urlFactory.createURL("Space", "Page", "view", "param1=1", "anchor", "xwiki",
this.oldcore.getXWikiContext());
assertEquals(new URL("http://mainwiki.mywiki.tld/xwiki/bin/view/Space/Page?param1=1#anchor"), url);
assertEquals("http://mainwiki.mywiki.tld/xwiki/bin/view/Space/Page?param1=1#anchor",
urlFactory.getURL(url, this.oldcore.getXWikiContext()));
}
/**
* When getServerURL is called on a resource from the main wiki, the user is in the main wiki, and xwiki.home is
* set, xwiki.home should be returned. see: XWIKI-5981
*/
@Test
public void getServerURLNonVirtualModeWithXWikiDotHomeEnabled() throws MalformedURLException
{
this.oldcore.getXWikiContext().setURL(new URL("http://127.0.0.1:8080/xwiki/view/InitialSpace/InitialPage"));
this.oldcore.getMockXWikiCfg().setProperty("xwiki.home", "http://mainwiki.mywiki.tld/");
urlFactory.init(this.oldcore.getXWikiContext());
// TODO: Fix getServerURL() so that is is consistent about returning a trailing / or not.
assertEquals("http://mainwiki.mywiki.tld",
urlFactory.getServerURL("xwiki", this.oldcore.getXWikiContext()).toString());
assertEquals("http://mainwiki.mywiki.tld",
urlFactory.getServerURL(null, this.oldcore.getXWikiContext()).toString());
}
/**
* Proves that in a single wiki instance, URLs are always generated using xwiki.home if present. see: XWIKI-5981
*/
@Test
public void createURLWhenXWikiDotHomeParameterNonVirtualMode() throws MalformedURLException
{
// Some proxies will modify the host field without adding a x-forwarded-host field,
// Using xwiki.home we should be able to make it work anyway.
this.oldcore.getXWikiContext().setURL(new URL("http://localhost:8080/xwiki/view/InitialSpace/InitialPage"));
this.oldcore.getMockXWikiCfg().setProperty("xwiki.home", "http://mainwiki.mywiki.tld/");
// Reinitialize the URL factory to take into account the new request URL.
urlFactory.init(this.oldcore.getXWikiContext());
// No wiki passed, assume main wiki. we should expect it to return mainwiki.mywiki.tld and not
// xwiki.mywiki.tld.
URL url =
urlFactory.createURL("Space", "Page", "view", "param1=1", "anchor", null, this.oldcore.getXWikiContext());
assertEquals(new URL("http://mainwiki.mywiki.tld/xwiki/bin/view/Space/Page?param1=1#anchor"), url);
assertEquals("/xwiki/bin/view/Space/Page?param1=1#anchor",
urlFactory.getURL(url, this.oldcore.getXWikiContext()));
// Pass "xwiki" as the wiki, expect same result.
url = urlFactory.createURL("Space", "Page", "view", "param1=1", "anchor", "xwiki",
this.oldcore.getXWikiContext());
assertEquals(new URL("http://mainwiki.mywiki.tld/xwiki/bin/view/Space/Page?param1=1#anchor"), url);
assertEquals("/xwiki/bin/view/Space/Page?param1=1#anchor",
urlFactory.getURL(url, this.oldcore.getXWikiContext()));
}
/**
* Verify that jsessionid is removed from URL.
*/
@Test
public void normalizeURL() throws Exception
{
assertEquals(new URL("http://www.xwiki.org/xwiki/bin/view/Blog/Bug+Fixing+Day+35?language=en"),
XWikiServletURLFactory.normalizeURL("http://www.xwiki.org/xwiki/bin/view/Blog/Bug+Fixing+Day+35"
+ ";jsessionid=0AF95AFB8997826B936C0397DF6A0C7F?language=en", this.oldcore.getXWikiContext()));
}
@Test
public void createURLWithNestedSpaces() throws Exception
{
URL url = this.urlFactory.createURL("Space1.Space2", "Page", this.oldcore.getXWikiContext());
assertEquals(new URL("http://127.0.0.1/xwiki/bin/view/Space1/Space2/Page"), url);
}
@Test
public void createAttachmentURLWhenViewRevAndRevSpecifiedAndIsNotContextDoc() throws Exception
{
XWikiContext xwikiContext = this.oldcore.getXWikiContext();
xwikiContext.put("rev", "1.0");
xwikiContext.setAction("viewrev");
xwikiContext.setDoc(new XWikiDocument(new DocumentReference("currentwiki", "currentspace", "currentpage")));
URL url = this.urlFactory.createAttachmentURL("file", "space", "page", "viewrev", null, xwikiContext);
assertEquals(new URL("http://127.0.0.1/xwiki/bin/viewrev/space/page/file"), url);
}
@Test
public void createAttachmentURLWhenViewRevAndRevSpecifiedAndIsContextDocAndAttachmentDoesntExist()
throws Exception
{
XWikiContext xwikiContext = this.oldcore.getXWikiContext();
xwikiContext.put("rev", "1.0");
xwikiContext.setAction("viewrev");
XWikiDocument document = new XWikiDocument(new DocumentReference("currentwiki", "currentspace", "currentpage"));
this.oldcore.getSpyXWiki().saveDocument(document, this.oldcore.getXWikiContext());
xwikiContext.setDoc(document);
xwikiContext.setWikiId("currentwiki");
URL url =
this.urlFactory.createAttachmentURL("file", "currentspace", "currentpage", "viewrev", null, xwikiContext);
assertEquals(new URL("http://127.0.0.1/xwiki/bin/viewattachrev/currentspace/currentpage/file"), url);
}
@Test
public void createURLWhenShowViewActionFalse() throws Exception
{
doReturn(false).when(this.oldcore.getSpyXWiki()).showViewAction(any(XWikiContext.class));
URL url = this.urlFactory.createURL("Space", "Page", "view", this.oldcore.getXWikiContext());
assertEquals(new URL("http://127.0.0.1/xwiki/bin/Space/Page"), url);
}
@Test
public void createURLWhenShowViewActionFalseAndSpaceIsNamedAfterAnAction() throws Exception
{
doReturn(false).when(this.oldcore.getSpyXWiki()).showViewAction(any(XWikiContext.class));
URL url = this.urlFactory.createURL("view.space2", "page", "view", this.oldcore.getXWikiContext());
assertEquals(new URL("http://127.0.0.1/xwiki/bin/view/view/space2/page"), url);
}
@Test
public void createResourceURL() throws Exception
{
// Verify that the URL factory encodes each path segment.
URL url = this.urlFactory.createResourceURL("o;ne/t?w&o/t=hr#e e", false, this.oldcore.getXWikiContext());
assertEquals(new URL("http://127.0.0.1/xwiki/resources/o;ne/t%3Fw&o/t=hr%23e%20e"), url);
}
@Test
public void createURLWhenCharactersNeedToBeEncoded() throws Exception
{
// Note: The query string is not encoded, and used as is. It's the responsibility of the caller to
// url-encode it.
// See XWikiServletURLFactory#encodeWithinPath() and XWikiServletURLFactory#encodeWithinQuery() for explanations
URL url = this.urlFactory.createURL("a b.c+d", "e f", "view", "g=h+i", "j k+l", this.oldcore.getXWikiContext());
assertEquals("http://127.0.0.1/xwiki/bin/view/a%20b/c%2Bd/e%20f?g=h+i#j+k%2Bl", url.toString());
}
}
| XWIKI-13557: Wrong encoding when creating URLs
* Update test
| xwiki-platform-core/xwiki-platform-oldcore/src/test/java/com/xpn/xwiki/web/XWikiServletURLFactoryTest.java | XWIKI-13557: Wrong encoding when creating URLs * Update test | <ide><path>wiki-platform-core/xwiki-platform-oldcore/src/test/java/com/xpn/xwiki/web/XWikiServletURLFactoryTest.java
<ide> // Note: The query string is not encoded, and used as is. It's the responsibility of the caller to
<ide> // url-encode it.
<ide> // See XWikiServletURLFactory#encodeWithinPath() and XWikiServletURLFactory#encodeWithinQuery() for explanations
<del> URL url = this.urlFactory.createURL("a b.c+d", "e f", "view", "g=h+i", "j k+l", this.oldcore.getXWikiContext());
<del>
<del> assertEquals("http://127.0.0.1/xwiki/bin/view/a%20b/c%2Bd/e%20f?g=h+i#j+k%2Bl", url.toString());
<add> // Note: We also verify that the single quote is encoded since otherwise that could cause problems in HTML when
<add> // the returned URL is used in the HREF attribute of a A tag (when using single quote delimiters).
<add> URL url = this.urlFactory.createURL("a b.c+d'", "e f", "view", "g=h+i", "j k+l", this.oldcore.getXWikiContext());
<add>
<add> assertEquals("http://127.0.0.1/xwiki/bin/view/a%20b/c%2Bd%27/e%20f?g=h+i#j+k%2Bl", url.toString());
<ide> }
<ide> } |
|
Java | epl-1.0 | 2e3f81c9e8684fe1eb29e91574a18cd8ebb1d5a0 | 0 | opendaylight/yangtools,opendaylight/yangtools | /*
* Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.yangtools.yang.data.impl.codec;
import java.util.AbstractMap.SimpleImmutableEntry;
import org.opendaylight.yangtools.yang.common.QName;
public class ValueWithQName<V> extends SimpleImmutableEntry<QName, V> {
private static final long serialVersionUID = 1L;
public ValueWithQName(final QName qname, final V value) {
super(qname, value);
}
public QName getQName() {
return getKey();
}
}
| yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/codec/ValueWithQName.java | /*
* Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.yangtools.yang.data.impl.codec;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.util.AbstractMap.SimpleImmutableEntry;
import org.opendaylight.yangtools.yang.common.QName;
public class ValueWithQName<V> extends SimpleImmutableEntry<QName, V> {
private static final long serialVersionUID = 1L;
public ValueWithQName(final QName qname, final V value) {
super(qname, value);
}
@Deprecated(forRemoval = true)
@SuppressFBWarnings(value = "NM_CONFUSING", justification = "Legacy typo")
public QName getQname() {
return getKey();
}
public QName getQName() {
return getKey();
}
}
| Remove ValueWithQName.getQname()
This is mispelled method, remove it as we have a direct replacement.
Change-Id: I987b7bc056819d199a6963e131bd5f527d416345
Signed-off-by: Robert Varga <[email protected]>
| yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/codec/ValueWithQName.java | Remove ValueWithQName.getQname() | <ide><path>ang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/codec/ValueWithQName.java
<ide> */
<ide> package org.opendaylight.yangtools.yang.data.impl.codec;
<ide>
<del>import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
<ide> import java.util.AbstractMap.SimpleImmutableEntry;
<ide> import org.opendaylight.yangtools.yang.common.QName;
<ide>
<ide> super(qname, value);
<ide> }
<ide>
<del> @Deprecated(forRemoval = true)
<del> @SuppressFBWarnings(value = "NM_CONFUSING", justification = "Legacy typo")
<del> public QName getQname() {
<del> return getKey();
<del> }
<del>
<ide> public QName getQName() {
<ide> return getKey();
<ide> } |
|
Java | apache-2.0 | e47512e4b3cd8ea7fb242d8372e23de651cf0fb8 | 0 | cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x | /*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.mvc;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;
/**
* <p>Extension of <code>SimpleFormController</code> that supports "cancellation"
* of form processing. By default, this controller looks for a given parameter in the
* request, identified by the <code>cancelParamKey<code>. If this parameter is present,
* then the controller will return the configured <code>cancelView</code>, otherwise
* processing is passed back to the superclass.</p>
*
* <p><b><a name="workflow">Workflow
* (<a href="SimpleFormController.html#workflow">in addition to the superclass</a>):</b><br>
* <ol>
* <li>Call to {@link #processFormSubmission processFormSubmission} which calls
* {@link #isCancelRequest} to see if the incoming request is to cancel the
* current form entry. By default, {@link #isCancelRequest} returns <code>true</code>
* if the configured <code>cancelParamKey</code> exists in the request.
* This behavior can be overridden in subclasses.</li>
* <li>If {@link #isCancelRequest} returns <code>false</code>, then the controller
* will delegate all processing back to {@link SimpleFormController SimpleFormController},
* otherwise it will call the {@link #onCancel} version with all parameters.
* By default, that method will delegate to the {@link #onCancel} version with just
* the command object, which will in turn simply return the configured
* <code>cancelView</code>. This behavior can be overridden in subclasses.</li>
* </ol>
* </p>
*
* @author Rob Harrop
* @author Juergen Hoeller
* @author Erwin Bolwidt
* @since 1.2.3
* @see #setCancelParamKey
* @see #setCancelView
* @see #isCancelRequest(javax.servlet.http.HttpServletRequest)
* @see #onCancel(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, Object)
*/
public class CancellableFormController extends SimpleFormController {
/**
* Default parameter triggering the cancel action.
* Can be called even with validation errors on the form.
*/
private static final String PARAM_CANCEL = "_cancel";
private String cancelParamKey = PARAM_CANCEL;
private String cancelView;
/**
* Set the key of the request parameter used to identify a cancel request.
* Default is "_cancel".
* <p>The parameter is recognized both when sent as a plain parameter
* ("_cancel") or when triggered by an image button ("_cancel.x").
*/
public final void setCancelParamKey(String cancelParamKey) {
this.cancelParamKey = cancelParamKey;
}
/**
* Return the key of the request parameter used to identify a cancel request.
*/
public final String getCancelParamKey() {
return cancelParamKey;
}
/**
* Sets the name of the cancel view.
*/
public final void setCancelView(String cancelView) {
this.cancelView = cancelView;
}
/**
* Gets the name of the cancel view.
*/
public final String getCancelView() {
return cancelView;
}
/**
* Consider an explicit cancel request as a form submission too.
* @see #isCancelRequest(javax.servlet.http.HttpServletRequest)
*/
protected boolean isFormSubmission(HttpServletRequest request) {
return super.isFormSubmission(request) || isCancelRequest(request);
}
/**
* This implementation first checks to see if the incoming is a cancel request,
* through a call to {@link #isCancelRequest}. If so, control is passed to
* {@link #onCancel}; otherwise, control is passed up to
* {@link SimpleFormController#processFormSubmission}.
* @see #isCancelRequest
* @see #onCancel(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, Object)
* @see SimpleFormController#processFormSubmission
*/
protected ModelAndView processFormSubmission(
HttpServletRequest request, HttpServletResponse response, Object command, BindException errors)
throws Exception {
if (isCancelRequest(request)) {
return onCancel(request, response, command);
}
else {
return super.processFormSubmission(request, response, command, errors);
}
}
/**
* Determine whether the incoming request is a request to cancel the
* processing of the current form.
* <p>By default, this method returns <code>true</code> if a parameter
* matching the configured <code>cancelParamKey</code> is present in
* the request, otherwise it returns <code>false</code>. Subclasses may
* override this method to provide custom logic to detect a cancel request.
* <p>The parameter is recognized both when sent as a plain parameter
* ("_cancel") or when triggered by an image button ("_cancel.x").
* @param request current HTTP request
* @see #setCancelParamKey
* @see #PARAM_CANCEL
*/
protected boolean isCancelRequest(HttpServletRequest request) {
return WebUtils.hasSubmitParameter(request, getCancelParamKey());
}
/**
* Callback method for handling a cancel request. Called if {@link #isCancelRequest}
* returns <code>true</code>.
* <p>Default implementation delegates to <code>onCancel(Object)</code> to return
* the configured <code>cancelView</code>. Subclasses may override either of the two
* methods to build a custom {@link ModelAndView ModelAndView} that may contain model
* parameters used in the cancel view.
* <p>If you simply want to move the user to a new view and you don't want to add
* additional model parameters, use {@link #setCancelView(String)} rather than
* overriding an <code>onCancel</code> method.
* @param request current servlet request
* @param response current servlet response
* @param command form object with request parameters bound onto it
* @return the prepared model and view, or null
* @throws Exception in case of errors
* @see #isCancelRequest(javax.servlet.http.HttpServletRequest)
* @see #onCancel(Object)
* @see #setCancelView
*/
protected ModelAndView onCancel(HttpServletRequest request, HttpServletResponse response, Object command)
throws Exception {
return onCancel(command);
}
/**
* Simple <code>onCancel</code> version. Called by the default implementation
* of the <code>onCancel</code> version with all parameters.
* <p>Default implementation returns eturns the configured <code>cancelView</code>.
* Subclasses may override this method to build a custom {@link ModelAndView ModelAndView}
* that may contain model parameters used in the cancel view.
* <p>If you simply want to move the user to a new view and you don't want to add
* additional model parameters, use {@link #setCancelView(String)} rather than
* overriding an <code>onCancel</code> method.
* @param command form object with request parameters bound onto it
* @return the prepared model and view, or null
* @throws Exception in case of errors
* @see #onCancel(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, Object)
* @see #setCancelView
*/
protected ModelAndView onCancel(Object command) throws Exception {
return new ModelAndView(getCancelView());
}
}
| src/org/springframework/web/servlet/mvc/CancellableFormController.java | /*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.mvc;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;
/**
* <p>Extension of <code>SimpleFormController</code> that supports "cancellation"
* of form processing. By default, this controller looks for a given parameter in the
* request, identified by the <code>cancelParamKey<code>. If this parameter is present,
* then the controller will return the configured <code>cancelView</code>, otherwise
* processing is passed back to the superclass.</p>
*
* <p><b><a name="workflow">Workflow
* (<a href="SimpleFormController.html#workflow">in addition to the superclass</a>):</b><br>
* <ol>
* <li>Call to {@link #processFormSubmission processFormSubmission} which calls
* {@link #isCancelRequest} to see if the incoming request is to cancel the
* current form entry. By default, {@link #isCancelRequest} returns <code>true</code>
* if the configured <code>cancelParamKey</code> exists in the request.
* This behavior can be overridden in subclasses.</li>
* <li>If {@link #isCancelRequest} returns <code>false</code>, then the controller
* will delegate all processing back to {@link SimpleFormController SimpleFormController},
* otherwise it will call the {@link #onCancel} version with all parameters.
* By default, that method will delegate to the {@link #onCancel} version with just
* the command object, which will in turn simply return the configured
* <code>cancelView</code>. This behavior can be overridden in subclasses.</li>
* </ol>
* </p>
*
* @author Rob Harrop
* @author Juergen Hoeller
* @since 1.2.3
* @see #setCancelParamKey(String)
* @see #setCancelView(String)
* @see #isCancelRequest(javax.servlet.http.HttpServletRequest)
* @see #onCancel(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, Object)
*/
public class CancellableFormController extends SimpleFormController {
/**
* Default parameter triggering the cancel action.
* Can be called even with validation errors on the form.
*/
private static final String PARAM_CANCEL = "_cancel";
private String cancelParamKey = PARAM_CANCEL;
private String cancelView;
/**
* Set the key of the request parameter used to identify a cancel request.
* Default is "_cancel".
* <p>The parameter is recognized both when sent as a plain parameter
* ("_cancel") or when triggered by an image button ("_cancel.x").
*/
public final void setCancelParamKey(String cancelParamKey) {
this.cancelParamKey = cancelParamKey;
}
/**
* Return the key of the request parameter used to identify a cancel request.
*/
public final String getCancelParamKey() {
return cancelParamKey;
}
/**
* Sets the name of the cancel view.
*/
public final void setCancelView(String cancelView) {
this.cancelView = cancelView;
}
/**
* Gets the name of the cancel view.
*/
public final String getCancelView() {
return cancelView;
}
/**
* Consider an explicit cancel request as a form submission too.
* @see #isCancelRequest(javax.servlet.http.HttpServletRequest)
*/
protected boolean isFormSubmission(HttpServletRequest request) {
return super.isFormSubmission(request) || isCancelRequest(request);
}
/**
* This implementation first checks to see if the incoming is a cancel request,
* through a call to {@link #isCancelRequest}. If so, control is passed to
* {@link #onCancel}; otherwise, control is passed up to
* {@link SimpleFormController#processFormSubmission}.
* @see #isCancelRequest
* @see #onCancel(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, Object)
* @see SimpleFormController#processFormSubmission
*/
protected ModelAndView processFormSubmission(
HttpServletRequest request, HttpServletResponse response, Object command, BindException errors)
throws Exception {
if (isCancelRequest(request)) {
return onCancel(request, response, command);
}
else {
return super.processFormSubmission(request, response, command, errors);
}
}
/**
* Determine whether the incoming request is a request to cancel the
* processing of the current form.
* <p>By default, this method returns <code>true</code> if a parameter
* matching the configured <code>cancelParamKey</code> is present in
* the request, otherwise it returns <code>false</code>. Subclasses may
* override this method to provide custom logic to detect a cancel request.
* <p>The parameter is recognized both when sent as a plain parameter
* ("_cancel") or when triggered by an image button ("_cancel.x").
* @param request current HTTP request
* @see #setCancelParamKey
* @see #PARAM_CANCEL
*/
protected boolean isCancelRequest(HttpServletRequest request) {
return WebUtils.hasSubmitParameter(request, getCancelParamKey());
}
/**
* Callback method for handling a cancel request. Called if {@link #isCancelRequest}
* returns <code>true</code>.
* <p>Default implementation delegates to <code>onCancel(Object)</code> to return
* the configured <code>cancelView</code>. Subclasses may override either of the two
* methods to build a custom {@link ModelAndView ModelAndView} that may contain model
* parameters used in the cancel view.
* <p>If you simply want to move the user to a new view and you don't want to add
* additional model parameters, use {@link #setCancelView(String)} rather than
* overriding an <code>onCancel</code> method.
* @param request current servlet request
* @param response current servlet response
* @param command form object with request parameters bound onto it
* @return the prepared model and view, or null
* @throws Exception in case of errors
* @see #isCancelRequest(javax.servlet.http.HttpServletRequest)
* @see #onCancel(Object)
* @see #setCancelView
*/
protected ModelAndView onCancel(HttpServletRequest request, HttpServletResponse response, Object command)
throws Exception {
return onCancel(command);
}
/**
* Simple <code>onCancel</code> version. Called by the default implementation
* of the <code>onCancel</code> version with all parameters.
* <p>Default implementation returns eturns the configured <code>cancelView</code>.
* Subclasses may override this method to build a custom {@link ModelAndView ModelAndView}
* that may contain model parameters used in the cancel view.
* <p>If you simply want to move the user to a new view and you don't want to add
* additional model parameters, use {@link #setCancelView(String)} rather than
* overriding an <code>onCancel</code> method.
* @param command form object with request parameters bound onto it
* @return the prepared model and view, or null
* @throws Exception in case of errors
* @see #setCancelView
*/
protected ModelAndView onCancel(Object command) throws Exception {
return new ModelAndView(getCancelView());
}
}
| added further @author tag
git-svn-id: b619a0c99665f88f1afe72824344cefe9a1c8c90@7784 fd5a2b45-1f63-4059-99e9-3c7cb7fd75c8
| src/org/springframework/web/servlet/mvc/CancellableFormController.java | added further @author tag | <ide><path>rc/org/springframework/web/servlet/mvc/CancellableFormController.java
<ide> *
<ide> * @author Rob Harrop
<ide> * @author Juergen Hoeller
<add> * @author Erwin Bolwidt
<ide> * @since 1.2.3
<del> * @see #setCancelParamKey(String)
<del> * @see #setCancelView(String)
<add> * @see #setCancelParamKey
<add> * @see #setCancelView
<ide> * @see #isCancelRequest(javax.servlet.http.HttpServletRequest)
<ide> * @see #onCancel(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, Object)
<ide> */
<ide> * @param command form object with request parameters bound onto it
<ide> * @return the prepared model and view, or null
<ide> * @throws Exception in case of errors
<add> * @see #onCancel(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, Object)
<ide> * @see #setCancelView
<ide> */
<ide> protected ModelAndView onCancel(Object command) throws Exception { |
|
JavaScript | mit | a1f13cdf443ce2bb58cf41798fee549223bca46f | 0 | absolunet/kafe,absolunet/kafe | /* @echo header */
var Local = {};
Local.getPlaceholders = function(){
var $placeholders = $('[data-sitecore-placeholder]');
var _output = [];
$placeholders.each(function(i,v){
var _ph = {};
_ph.$element = $(this);
_ph.name = _ph.$element.data('sitecore-placeholder');
_ph.label = !!_ph.$element.data('sitecore-displayname') ? _ph.$element.data('sitecore-displayname') : _ph.name;
_ph.filter = ':not(code, .scEmptyPlaceholder, .clearer)';
_ph.$locator = $('<span class="sitecore-editor-toolbox-locator"></span>');
_ph.$field = $('<input id="sitecore-editor-toolbox-placeholder'+i+'" type="checkbox" checked="checked"/>');
_ph.$fieldLabel = $('<label for="sitecore-editor-toolbox-placeholder'+i+'">'+_ph.label+'</label>');
if(!!_ph.$element.data('sitecore-placeholder-opposite')){
_ph.opposite = _ph.$element.data('sitecore-placeholder-opposite');
}
_output.push(_ph);
});
$.each(_output, function(i,_currentPh){
if(!!_currentPh.opposite){
$.each(_output, function(i,_otherPh){
if(_currentPh.opposite == _otherPh.name){
_currentPh.opposite = {
$element:_otherPh.$element,
$field:_otherPh.$field
}
return false;
}
});
_currentPh.opposite = $.isPlainObject(_currentPh.opposite) ? _currentPh.opposite : null;
}
});
return _output;
}
/**
* ### Version <!-- @echo VERSION -->
* Additionnal methods for Sitecore
*
* @module <!-- @echo MODULE -->
* @class <!-- @echo NAME_FULL -->
*/
var sitecore = {};
K.env("sitecore-editor", $('html').data('sitecore-editor') === true);
/**
* Creates a toolbox for the Sitecore page editor. Allows the user to toggle unused placeholders to reflect a closer to reality result of the page.
*
* @method editorToolbox
* @param {Object} [options] Initial configurations.
* @param {String} [options.label='Editor Toolbox'] The label shown on the toolbox handle.
* @param {Function} [options.onUpdate] Callback that fires everytime the toolbox updates its component status.
* @example
* // Initializing placeholders for the toolbox using data attributes
* <section data-sitecore-placeholder="sidebar-left" data-sitecore-displayname="Left column" data-sitecore-placeholder-opposite="sidebar-right">
* <ul>
* <li>This is the optional left column</li>
* <li>data-sitecore-placeholder : *Required* The name of the placeholder defined in Sitecore, this attribute initiates the element has a placeholder for the toolbox.</li>
* <li>data-sitecore-displayname : The label identifying the placeholder within the toolbox, defaults to the value of 'data-sitecore-placeholder' if not set.</li>
* <li>data-sitecore-placeholder-opposite : The 'data-sitecore-placeholder' value of the opposite placeholder. Determines that the current placeholder should not be toggled if the opposite placeholder is active.</li>
* </ul>
* </section>
* @example
* // Initializing the toolbox
* <!-- @echo NAME_FULL -->.editorToolbox({
* label:"My Toolbox",
* onUpdate:function(data){
* console.log('There are ' + data.placeholders.filter(':visible').length + ' visible in the page');
* }
* });
*/
sitecore.editorToolbox = function(){
/*--- Options ---*/
var c = {};
var options = (arguments) ? arguments[0] : {};
c.label = !!options.label ? options.label : 'Editor Toolbox';
c.placeholders = {};
c.placeholders.label = !!options.placeholders.label ? options.placeholders.label : 'Placeholders'
c.placeholders.$elements = Local.getPlaceholders();
c.updateCallback = $.isFunction(options.onUpdate) ? options.onUpdate : function(){};
/*--- Config ---*/
var _showToolbox = false;
var _toolboxOpenClass = 'open';
var _callbackData = _getCallbackData();
/*--- Elements ---*/
var $editorToolbox = $('<div id="sitecore-editor-toolbox"></div>');
var $toolboxContent = $('<div class="content"></div>').appendTo($editorToolbox).hide();
var _toolboxHandle = {
$self:$('<a href="#" class="handle"></a>'),
$label:$('<span class="label">'+c.label+'</span>')
}
_toolboxHandle.$self.append(_toolboxHandle.$label).appendTo($editorToolbox);
/*--- Bindings ---*/
_toolboxHandle.$self.on('click', function(e){
e.preventDefault();
$toolboxContent.toggle();
$editorToolbox.toggleClass(_toolboxOpenClass);
if($editorToolbox.hasClass(_toolboxOpenClass)){
_updateToolbox();
}
});
$editorToolbox.on('mouseleave',function(e){
if($editorToolbox.hasClass(_toolboxOpenClass)){
_toolboxHandle.$self.trigger('click');
}
});
/*--- Functions ---*/
function _updateToolbox(){
/* Placeholders */
$.each(c.placeholders.$elements, function(i,_ph){
var _phIsEmpty = _ph.$element.children(_ph.filter).length === 0;
var _oppositeIsActive = _ph.opposite ? _ph.opposite.$field.is(':checked') : false;
var _phIsActive = _phIsEmpty && !_oppositeIsActive;
_ph.$field.prop('disabled', !_phIsActive);
});
c.updateCallback(_callbackData);
}
function _getCallbackData(){
/* Placeholders */
var _placeholders = [];
$.each(c.placeholders.$elements, function(i,_ph){
_placeholders.push(_ph.$element.get(0));
});
return {
placeholders:$(_placeholders)
};
}
/*--- Contents ---*/
/* Placeholders */
if(c.placeholders.$elements.length > 0){
var $scPlaceholders = $('<div class="toolbox-section placeholders"></div>').appendTo($toolboxContent);
var $pendingBox = $('<div style="display:none !important;"></div>').appendTo($editorToolbox);
$.each(c.placeholders.$elements, function(i,_ph){
var $currentItem = $('<div class="toolbox-item"></div>').appendTo($scPlaceholders);
_ph.$field.appendTo($currentItem).after(_ph.$fieldLabel)
.on('change', function(e, _isInit){
if(_ph.$field.is(':checked')){
_ph.$locator.replaceWith(_ph.$element);
}else{
_ph.$element.before(_ph.$locator).appendTo($pendingBox);
}
if(!_isInit){ _updateToolbox(); }
});
if(_ph.$element.children(_ph.filter).length === 0){
_ph.$field.prop('checked', false).trigger('change', true);
}
_showToolbox = true;
});
}
/*--- Initialization ---*/
if(_showToolbox){
$editorToolbox.prependTo('body').css({
'position':'fixed',
'top':'50%',
'left':'0',
'min-height':_toolboxHandle.$label.outerWidth()
}).css('margin-top','-'+($editorToolbox.outerHeight() / 2)+'px')
_toolboxHandle.$label.width($editorToolbox.outerHeight()).addClass('initialized');
_updateToolbox();
}
}
return sitecore;
/* @echo footer */ | src/kafe/cms/sitecore.js | /* @echo header */
var
_privateFunction = function () {
}
;
/**
* ### Version <!-- @echo VERSION -->
* Additionnal methods for Sitecore
*
* @module <!-- @echo MODULE -->
* @class <!-- @echo NAME_FULL -->
*/
var sitecore = {};
sitecore.publicFunction = function() {
};
return sitecore;
/* @echo footer */ | Module de boite à outils pour le page-editor de Sitecore
| src/kafe/cms/sitecore.js | Module de boite à outils pour le page-editor de Sitecore | <ide><path>rc/kafe/cms/sitecore.js
<ide> /* @echo header */
<ide>
<del> var
<del> _privateFunction = function () {
<add> var Local = {};
<ide>
<del> }
<del> ;
<add> Local.getPlaceholders = function(){
<add> var $placeholders = $('[data-sitecore-placeholder]');
<add> var _output = [];
<ide>
<add> $placeholders.each(function(i,v){
<add> var _ph = {};
<add> _ph.$element = $(this);
<add> _ph.name = _ph.$element.data('sitecore-placeholder');
<add> _ph.label = !!_ph.$element.data('sitecore-displayname') ? _ph.$element.data('sitecore-displayname') : _ph.name;
<add> _ph.filter = ':not(code, .scEmptyPlaceholder, .clearer)';
<add> _ph.$locator = $('<span class="sitecore-editor-toolbox-locator"></span>');
<add> _ph.$field = $('<input id="sitecore-editor-toolbox-placeholder'+i+'" type="checkbox" checked="checked"/>');
<add> _ph.$fieldLabel = $('<label for="sitecore-editor-toolbox-placeholder'+i+'">'+_ph.label+'</label>');
<add> if(!!_ph.$element.data('sitecore-placeholder-opposite')){
<add> _ph.opposite = _ph.$element.data('sitecore-placeholder-opposite');
<add> }
<add> _output.push(_ph);
<add> });
<add>
<add> $.each(_output, function(i,_currentPh){
<add> if(!!_currentPh.opposite){
<add> $.each(_output, function(i,_otherPh){
<add> if(_currentPh.opposite == _otherPh.name){
<add> _currentPh.opposite = {
<add> $element:_otherPh.$element,
<add> $field:_otherPh.$field
<add> }
<add> return false;
<add> }
<add> });
<add> _currentPh.opposite = $.isPlainObject(_currentPh.opposite) ? _currentPh.opposite : null;
<add> }
<add> });
<add>
<add> return _output;
<add> }
<ide>
<ide> /**
<ide> * ### Version <!-- @echo VERSION -->
<ide> * @class <!-- @echo NAME_FULL -->
<ide> */
<ide> var sitecore = {};
<add> K.env("sitecore-editor", $('html').data('sitecore-editor') === true);
<ide>
<add> /**
<add> * Creates a toolbox for the Sitecore page editor. Allows the user to toggle unused placeholders to reflect a closer to reality result of the page.
<add> *
<add> * @method editorToolbox
<add> * @param {Object} [options] Initial configurations.
<add> * @param {String} [options.label='Editor Toolbox'] The label shown on the toolbox handle.
<add> * @param {Function} [options.onUpdate] Callback that fires everytime the toolbox updates its component status.
<add> * @example
<add> * // Initializing placeholders for the toolbox using data attributes
<add> * <section data-sitecore-placeholder="sidebar-left" data-sitecore-displayname="Left column" data-sitecore-placeholder-opposite="sidebar-right">
<add> * <ul>
<add> * <li>This is the optional left column</li>
<add> * <li>data-sitecore-placeholder : *Required* The name of the placeholder defined in Sitecore, this attribute initiates the element has a placeholder for the toolbox.</li>
<add> * <li>data-sitecore-displayname : The label identifying the placeholder within the toolbox, defaults to the value of 'data-sitecore-placeholder' if not set.</li>
<add> * <li>data-sitecore-placeholder-opposite : The 'data-sitecore-placeholder' value of the opposite placeholder. Determines that the current placeholder should not be toggled if the opposite placeholder is active.</li>
<add> * </ul>
<add> * </section>
<add> * @example
<add> * // Initializing the toolbox
<add> * <!-- @echo NAME_FULL -->.editorToolbox({
<add> * label:"My Toolbox",
<add> * onUpdate:function(data){
<add> * console.log('There are ' + data.placeholders.filter(':visible').length + ' visible in the page');
<add> * }
<add> * });
<add> */
<add> sitecore.editorToolbox = function(){
<add> /*--- Options ---*/
<add> var c = {};
<add> var options = (arguments) ? arguments[0] : {};
<ide>
<add> c.label = !!options.label ? options.label : 'Editor Toolbox';
<add> c.placeholders = {};
<add> c.placeholders.label = !!options.placeholders.label ? options.placeholders.label : 'Placeholders'
<add> c.placeholders.$elements = Local.getPlaceholders();
<add> c.updateCallback = $.isFunction(options.onUpdate) ? options.onUpdate : function(){};
<ide>
<del> sitecore.publicFunction = function() {
<add> /*--- Config ---*/
<add> var _showToolbox = false;
<add> var _toolboxOpenClass = 'open';
<add> var _callbackData = _getCallbackData();
<ide>
<del> };
<add> /*--- Elements ---*/
<add> var $editorToolbox = $('<div id="sitecore-editor-toolbox"></div>');
<add> var $toolboxContent = $('<div class="content"></div>').appendTo($editorToolbox).hide();
<add> var _toolboxHandle = {
<add> $self:$('<a href="#" class="handle"></a>'),
<add> $label:$('<span class="label">'+c.label+'</span>')
<add> }
<add> _toolboxHandle.$self.append(_toolboxHandle.$label).appendTo($editorToolbox);
<add>
<add> /*--- Bindings ---*/
<add> _toolboxHandle.$self.on('click', function(e){
<add> e.preventDefault();
<add> $toolboxContent.toggle();
<add> $editorToolbox.toggleClass(_toolboxOpenClass);
<add> if($editorToolbox.hasClass(_toolboxOpenClass)){
<add> _updateToolbox();
<add> }
<add> });
<add>
<add> $editorToolbox.on('mouseleave',function(e){
<add> if($editorToolbox.hasClass(_toolboxOpenClass)){
<add> _toolboxHandle.$self.trigger('click');
<add> }
<add> });
<add>
<add> /*--- Functions ---*/
<add> function _updateToolbox(){
<add> /* Placeholders */
<add> $.each(c.placeholders.$elements, function(i,_ph){
<add> var _phIsEmpty = _ph.$element.children(_ph.filter).length === 0;
<add> var _oppositeIsActive = _ph.opposite ? _ph.opposite.$field.is(':checked') : false;
<add> var _phIsActive = _phIsEmpty && !_oppositeIsActive;
<add> _ph.$field.prop('disabled', !_phIsActive);
<add> });
<add> c.updateCallback(_callbackData);
<add> }
<add>
<add> function _getCallbackData(){
<add> /* Placeholders */
<add> var _placeholders = [];
<add> $.each(c.placeholders.$elements, function(i,_ph){
<add> _placeholders.push(_ph.$element.get(0));
<add> });
<add>
<add> return {
<add> placeholders:$(_placeholders)
<add> };
<add> }
<add>
<add> /*--- Contents ---*/
<add>
<add> /* Placeholders */
<add> if(c.placeholders.$elements.length > 0){
<add> var $scPlaceholders = $('<div class="toolbox-section placeholders"></div>').appendTo($toolboxContent);
<add> var $pendingBox = $('<div style="display:none !important;"></div>').appendTo($editorToolbox);
<add>
<add> $.each(c.placeholders.$elements, function(i,_ph){
<add> var $currentItem = $('<div class="toolbox-item"></div>').appendTo($scPlaceholders);
<add> _ph.$field.appendTo($currentItem).after(_ph.$fieldLabel)
<add> .on('change', function(e, _isInit){
<add> if(_ph.$field.is(':checked')){
<add> _ph.$locator.replaceWith(_ph.$element);
<add> }else{
<add> _ph.$element.before(_ph.$locator).appendTo($pendingBox);
<add> }
<add> if(!_isInit){ _updateToolbox(); }
<add> });
<add>
<add> if(_ph.$element.children(_ph.filter).length === 0){
<add> _ph.$field.prop('checked', false).trigger('change', true);
<add> }
<add>
<add> _showToolbox = true;
<add> });
<add> }
<add>
<add> /*--- Initialization ---*/
<add> if(_showToolbox){
<add> $editorToolbox.prependTo('body').css({
<add> 'position':'fixed',
<add> 'top':'50%',
<add> 'left':'0',
<add> 'min-height':_toolboxHandle.$label.outerWidth()
<add> }).css('margin-top','-'+($editorToolbox.outerHeight() / 2)+'px')
<add> _toolboxHandle.$label.width($editorToolbox.outerHeight()).addClass('initialized');
<add> _updateToolbox();
<add> }
<add> }
<ide>
<ide> return sitecore;
<ide> |
|
Java | apache-2.0 | cc06b02e0c1f368fc4c8d780c8e718a578d06576 | 0 | typesafehub/config,typesafehub/config | package com.typesafe.config;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* Allows an config property to be {@code null}.
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface Nullable {
}
| config/src/main/java/com/typesafe/config/Nullable.java | package com.typesafe.config;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface Nullable {
}
| Add a Javadoc comment to the Nullable annotation class. | config/src/main/java/com/typesafe/config/Nullable.java | Add a Javadoc comment to the Nullable annotation class. | <ide><path>onfig/src/main/java/com/typesafe/config/Nullable.java
<ide> import java.lang.annotation.Retention;
<ide> import java.lang.annotation.RetentionPolicy;
<ide>
<add>/**
<add> * Allows an config property to be {@code null}.
<add> */
<ide> @Documented
<ide> @Retention(RetentionPolicy.RUNTIME)
<ide> public @interface Nullable { |
|
JavaScript | mit | c2083af0905797c37a4fc7892ce795a56e2a453c | 0 | shanmugamss/three.js-modified,jpweeks/three.js,Aldrien-/three.js,googlecreativelab/three.js,colombod/three.js,jee7/three.js,RemusMar/three.js,Astrak/three.js,arodic/three.js,Ludobaka/three.js,mrdoob/three.js,pailhead/three.js,TristanVALCKE/three.js,Aldrien-/three.js,Amritesh/three.js,jeffgoku/three.js,daoshengmu/three.js,nhalloran/three.js,Samsung-Blue/three.js,mhoangvslev/data-visualizer,RemusMar/three.js,stanford-gfx/three.js,Astrak/three.js,googlecreativelab/three.js,TristanVALCKE/three.js,ngokevin/three-dev,fraguada/three.js,Mugen87/three.js,Ludobaka/three.js,Aldrien-/three.js,stanford-gfx/three.js,zhoushijie163/three.js,xundaokeji/three.js,sasha240100/three.js,jeffgoku/three.js,brianchirls/three.js,fernandojsg/three.js,opensim-org/three.js,opensim-org/three.js,jeffgoku/three.js,Samsy/three.js,ondys/three.js,RemusMar/three.js,framelab/three.js,ValtoLibraries/ThreeJS,fraguada/three.js,brianchirls/three.js,gero3/three.js,arodic/three.js,jayschwa/three.js,Samsung-Blue/three.js,carlosanunes/three.js,mese79/three.js,Aldrien-/three.js,Ludobaka/three.js,fyoudine/three.js,colombod/three.js,ValtoLibraries/ThreeJS,donmccurdy/three.js,fernandojsg/three.js,ValtoLibraries/ThreeJS,ValtoLibraries/ThreeJS,06wj/three.js,fanzhanggoogle/three.js,Liuer/three.js,carlosanunes/three.js,jayschwa/three.js,jee7/three.js,jayschwa/three.js,shanmugamss/three.js-modified,ngokevin/three-dev,Samsy/three.js,rfm1201/rfm.three.js,Liuer/three.js,amakaroff82/three.js,ondys/three.js,donmccurdy/three.js,WestLangley/three.js,sherousee/three.js,hsimpson/three.js,nhalloran/three.js,jeffgoku/three.js,Hectate/three.js,ondys/three.js,TristanVALCKE/three.js,sttz/three.js,xundaokeji/three.js,Aldrien-/three.js,julapy/three.js,sherousee/three.js,satori99/three.js,colombod/three.js,jeffgoku/three.js,greggman/three.js,gero3/three.js,fanzhanggoogle/three.js,sasha240100/three.js,Samsy/three.js,fanzhanggoogle/three.js,ondys/three.js,mese79/three.js,amakaroff82/three.js,sasha240100/three.js,googlecreativelab/three.js,Samsung-Blue/three.js,ngokevin/three-dev,arodic/three.js,jayschwa/three.js,brianchirls/three.js,Astrak/three.js,mhoangvslev/data-visualizer,ndebeiss/three.js,Hectate/three.js,jostschmithals/three.js,mese79/three.js,Samsung-Blue/three.js,SpinVR/three.js,ngokevin/three.js,spite/three.js,RemusMar/three.js,mese79/three.js,QingchaoHu/three.js,ndebeiss/three.js,hsimpson/three.js,mese79/three.js,shanmugamss/three.js-modified,Samsy/three.js,colombod/three.js,Hectate/three.js,sasha240100/three.js,matgr1/three.js,ngokevin/three-dev,arodic/three.js,julapy/three.js,jostschmithals/three.js,jostschmithals/three.js,jostschmithals/three.js,rfm1201/rfm.three.js,amakaroff82/three.js,jayschwa/three.js,ngokevin/three.js,shinate/three.js,mhoangvslev/data-visualizer,spite/three.js,fanzhanggoogle/three.js,googlecreativelab/three.js,pailhead/three.js,amakaroff82/three.js,TristanVALCKE/three.js,ngokevin/three.js,nhalloran/three.js,matgr1/three.js,mhoangvslev/data-visualizer,fraguada/three.js,satori99/three.js,sasha240100/three.js,sasha240100/three.js,ndebeiss/three.js,aardgoose/three.js,shanmugamss/three.js-modified,fraguada/three.js,ngokevin/three.js,ondys/three.js,rfm1201/rfm.three.js,daoshengmu/three.js,QingchaoHu/three.js,daoshengmu/three.js,carlosanunes/three.js,Samsung-Blue/three.js,brianchirls/three.js,carlosanunes/three.js,Astrak/three.js,Mugen87/three.js,Samsy/three.js,framelab/three.js,fraguada/three.js,Mugen87/three.js,mese79/three.js,shinate/three.js,Hectate/three.js,mrdoob/three.js,Amritesh/three.js,Amritesh/three.js,colombod/three.js,julapy/three.js,pailhead/three.js,shanmugamss/three.js-modified,mhoangvslev/data-visualizer,fanzhanggoogle/three.js,Hectate/three.js,kaisalmen/three.js,framelab/three.js,ndebeiss/three.js,daoshengmu/three.js,ngokevin/three.js,looeee/three.js,Ludobaka/three.js,arodic/three.js,spite/three.js,carlosanunes/three.js,nhalloran/three.js,mhoangvslev/data-visualizer,carlosanunes/three.js,spite/three.js,Ludobaka/three.js,amakaroff82/three.js,Itee/three.js,fraguada/three.js,Astrak/three.js,greggman/three.js,daoshengmu/three.js,fanzhanggoogle/three.js,satori99/three.js,spite/three.js,fernandojsg/three.js,ngokevin/three-dev,satori99/three.js,jostschmithals/three.js,sherousee/three.js,arodic/three.js,googlecreativelab/three.js,TristanVALCKE/three.js,Itee/three.js,matgr1/three.js,ValtoLibraries/ThreeJS,WestLangley/three.js,jee7/three.js,ndebeiss/three.js,zhoushijie163/three.js,ngokevin/three.js,matgr1/three.js,googlecreativelab/three.js,shanmugamss/three.js-modified,jpweeks/three.js,Aldrien-/three.js,ondys/three.js,aardgoose/three.js,nhalloran/three.js,xundaokeji/three.js,daoshengmu/three.js,xundaokeji/three.js,TristanVALCKE/three.js,06wj/three.js,ndebeiss/three.js,hsimpson/three.js,satori99/three.js,Samsung-Blue/three.js,ValtoLibraries/ThreeJS,cadenasgmbh/three.js,kaisalmen/three.js,shinate/three.js,nhalloran/three.js,Astrak/three.js,shinate/three.js,fyoudine/three.js,brianchirls/three.js,jayschwa/three.js,amakaroff82/three.js,jeffgoku/three.js,RemusMar/three.js,sttz/three.js,cadenasgmbh/three.js,Samsy/three.js,Hectate/three.js,matgr1/three.js,ngokevin/three-dev,jostschmithals/three.js,colombod/three.js,RemusMar/three.js,xundaokeji/three.js,makc/three.js.fork,spite/three.js,makc/three.js.fork,matgr1/three.js,Ludobaka/three.js,looeee/three.js,brianchirls/three.js,shinate/three.js,xundaokeji/three.js,shinate/three.js,satori99/three.js,SpinVR/three.js | import { EventDispatcher } from './EventDispatcher';
import { Face3 } from './Face3';
import { Matrix3 } from '../math/Matrix3';
import { Sphere } from '../math/Sphere';
import { Box3 } from '../math/Box3';
import { Vector3 } from '../math/Vector3';
import { Matrix4 } from '../math/Matrix4';
import { Vector2 } from '../math/Vector2';
import { Color } from '../math/Color';
import { Object3D } from './Object3D';
import { _Math } from '../math/Math';
/**
* @author mrdoob / http://mrdoob.com/
* @author kile / http://kile.stravaganza.org/
* @author alteredq / http://alteredqualia.com/
* @author mikael emtinger / http://gomo.se/
* @author zz85 / http://www.lab4games.net/zz85/blog
* @author bhouston / http://clara.io
*/
var count = 0;
function GeometryIdCount() { return count++; };
function Geometry() {
Object.defineProperty( this, 'id', { value: GeometryIdCount() } );
this.uuid = _Math.generateUUID();
this.name = '';
this.type = 'Geometry';
this.vertices = [];
this.colors = [];
this.faces = [];
this.faceVertexUvs = [[]];
this.morphTargets = [];
this.morphNormals = [];
this.skinWeights = [];
this.skinIndices = [];
this.lineDistances = [];
this.boundingBox = null;
this.boundingSphere = null;
// update flags
this.elementsNeedUpdate = false;
this.verticesNeedUpdate = false;
this.uvsNeedUpdate = false;
this.normalsNeedUpdate = false;
this.colorsNeedUpdate = false;
this.lineDistancesNeedUpdate = false;
this.groupsNeedUpdate = false;
}
Object.assign( Geometry.prototype, EventDispatcher.prototype, {
constructor: Geometry,
isGeometry: true,
applyMatrix: function ( matrix ) {
var normalMatrix = new Matrix3().getNormalMatrix( matrix );
for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
var vertex = this.vertices[ i ];
vertex.applyMatrix4( matrix );
}
for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
var face = this.faces[ i ];
face.normal.applyMatrix3( normalMatrix ).normalize();
for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
}
}
if ( this.boundingBox !== null ) {
this.computeBoundingBox();
}
if ( this.boundingSphere !== null ) {
this.computeBoundingSphere();
}
this.verticesNeedUpdate = true;
this.normalsNeedUpdate = true;
return this;
},
rotateX: function () {
// rotate geometry around world x-axis
var m1;
return function rotateX( angle ) {
if ( m1 === undefined ) m1 = new Matrix4();
m1.makeRotationX( angle );
this.applyMatrix( m1 );
return this;
};
}(),
rotateY: function () {
// rotate geometry around world y-axis
var m1;
return function rotateY( angle ) {
if ( m1 === undefined ) m1 = new Matrix4();
m1.makeRotationY( angle );
this.applyMatrix( m1 );
return this;
};
}(),
rotateZ: function () {
// rotate geometry around world z-axis
var m1;
return function rotateZ( angle ) {
if ( m1 === undefined ) m1 = new Matrix4();
m1.makeRotationZ( angle );
this.applyMatrix( m1 );
return this;
};
}(),
translate: function () {
// translate geometry
var m1;
return function translate( x, y, z ) {
if ( m1 === undefined ) m1 = new Matrix4();
m1.makeTranslation( x, y, z );
this.applyMatrix( m1 );
return this;
};
}(),
scale: function () {
// scale geometry
var m1;
return function scale( x, y, z ) {
if ( m1 === undefined ) m1 = new Matrix4();
m1.makeScale( x, y, z );
this.applyMatrix( m1 );
return this;
};
}(),
lookAt: function () {
var obj;
return function lookAt( vector ) {
if ( obj === undefined ) obj = new Object3D();
obj.lookAt( vector );
obj.updateMatrix();
this.applyMatrix( obj.matrix );
};
}(),
fromBufferGeometry: function ( geometry ) {
var scope = this;
var indices = geometry.index !== null ? geometry.index.array : undefined;
var attributes = geometry.attributes;
var positions = attributes.position.array;
var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
var colors = attributes.color !== undefined ? attributes.color.array : undefined;
var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = [];
var tempNormals = [];
var tempUVs = [];
var tempUVs2 = [];
for ( var i = 0, j = 0; i < positions.length; i += 3, j += 2 ) {
scope.vertices.push( new Vector3( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ) );
if ( normals !== undefined ) {
tempNormals.push( new Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) );
}
if ( colors !== undefined ) {
scope.colors.push( new Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) );
}
if ( uvs !== undefined ) {
tempUVs.push( new Vector2( uvs[ j ], uvs[ j + 1 ] ) );
}
if ( uvs2 !== undefined ) {
tempUVs2.push( new Vector2( uvs2[ j ], uvs2[ j + 1 ] ) );
}
}
function addFace( a, b, c, materialIndex ) {
var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : [];
var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : [];
var face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex );
scope.faces.push( face );
if ( uvs !== undefined ) {
scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] );
}
if ( uvs2 !== undefined ) {
scope.faceVertexUvs[ 1 ].push( [ tempUVs2[ a ].clone(), tempUVs2[ b ].clone(), tempUVs2[ c ].clone() ] );
}
}
if ( indices !== undefined ) {
var groups = geometry.groups;
if ( groups.length > 0 ) {
for ( var i = 0; i < groups.length; i ++ ) {
var group = groups[ i ];
var start = group.start;
var count = group.count;
for ( var j = start, jl = start + count; j < jl; j += 3 ) {
addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex );
}
}
} else {
for ( var i = 0; i < indices.length; i += 3 ) {
addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
}
}
} else {
for ( var i = 0; i < positions.length / 3; i += 3 ) {
addFace( i, i + 1, i + 2 );
}
}
this.computeFaceNormals();
if ( geometry.boundingBox !== null ) {
this.boundingBox = geometry.boundingBox.clone();
}
if ( geometry.boundingSphere !== null ) {
this.boundingSphere = geometry.boundingSphere.clone();
}
return this;
},
center: function () {
this.computeBoundingBox();
var offset = this.boundingBox.getCenter().negate();
this.translate( offset.x, offset.y, offset.z );
return offset;
},
normalize: function () {
this.computeBoundingSphere();
var center = this.boundingSphere.center;
var radius = this.boundingSphere.radius;
var s = radius === 0 ? 1 : 1.0 / radius;
var matrix = new Matrix4();
matrix.set(
s, 0, 0, - s * center.x,
0, s, 0, - s * center.y,
0, 0, s, - s * center.z,
0, 0, 0, 1
);
this.applyMatrix( matrix );
return this;
},
computeFaceNormals: function () {
var cb = new Vector3(), ab = new Vector3();
for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
var face = this.faces[ f ];
var vA = this.vertices[ face.a ];
var vB = this.vertices[ face.b ];
var vC = this.vertices[ face.c ];
cb.subVectors( vC, vB );
ab.subVectors( vA, vB );
cb.cross( ab );
cb.normalize();
face.normal.copy( cb );
}
},
computeVertexNormals: function ( areaWeighted ) {
if ( areaWeighted === undefined ) areaWeighted = true;
var v, vl, f, fl, face, vertices;
vertices = new Array( this.vertices.length );
for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
vertices[ v ] = new Vector3();
}
if ( areaWeighted ) {
// vertex normals weighted by triangle areas
// http://www.iquilezles.org/www/articles/normals/normals.htm
var vA, vB, vC;
var cb = new Vector3(), ab = new Vector3();
for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
face = this.faces[ f ];
vA = this.vertices[ face.a ];
vB = this.vertices[ face.b ];
vC = this.vertices[ face.c ];
cb.subVectors( vC, vB );
ab.subVectors( vA, vB );
cb.cross( ab );
vertices[ face.a ].add( cb );
vertices[ face.b ].add( cb );
vertices[ face.c ].add( cb );
}
} else {
this.computeFaceNormals();
for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
face = this.faces[ f ];
vertices[ face.a ].add( face.normal );
vertices[ face.b ].add( face.normal );
vertices[ face.c ].add( face.normal );
}
}
for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
vertices[ v ].normalize();
}
for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
face = this.faces[ f ];
var vertexNormals = face.vertexNormals;
if ( vertexNormals.length === 3 ) {
vertexNormals[ 0 ].copy( vertices[ face.a ] );
vertexNormals[ 1 ].copy( vertices[ face.b ] );
vertexNormals[ 2 ].copy( vertices[ face.c ] );
} else {
vertexNormals[ 0 ] = vertices[ face.a ].clone();
vertexNormals[ 1 ] = vertices[ face.b ].clone();
vertexNormals[ 2 ] = vertices[ face.c ].clone();
}
}
if ( this.faces.length > 0 ) {
this.normalsNeedUpdate = true;
}
},
computeFlatVertexNormals: function () {
var f, fl, face;
this.computeFaceNormals();
for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
face = this.faces[ f ];
var vertexNormals = face.vertexNormals;
if ( vertexNormals.length === 3 ) {
vertexNormals[ 0 ].copy( face.normal );
vertexNormals[ 1 ].copy( face.normal );
vertexNormals[ 2 ].copy( face.normal );
} else {
vertexNormals[ 0 ] = face.normal.clone();
vertexNormals[ 1 ] = face.normal.clone();
vertexNormals[ 2 ] = face.normal.clone();
}
}
if ( this.faces.length > 0 ) {
this.normalsNeedUpdate = true;
}
},
computeMorphNormals: function () {
var i, il, f, fl, face;
// save original normals
// - create temp variables on first access
// otherwise just copy (for faster repeated calls)
for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
face = this.faces[ f ];
if ( ! face.__originalFaceNormal ) {
face.__originalFaceNormal = face.normal.clone();
} else {
face.__originalFaceNormal.copy( face.normal );
}
if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
if ( ! face.__originalVertexNormals[ i ] ) {
face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
} else {
face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
}
}
}
// use temp geometry to compute face and vertex normals for each morph
var tmpGeo = new Geometry();
tmpGeo.faces = this.faces;
for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
// create on first access
if ( ! this.morphNormals[ i ] ) {
this.morphNormals[ i ] = {};
this.morphNormals[ i ].faceNormals = [];
this.morphNormals[ i ].vertexNormals = [];
var dstNormalsFace = this.morphNormals[ i ].faceNormals;
var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
var faceNormal, vertexNormals;
for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
faceNormal = new Vector3();
vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() };
dstNormalsFace.push( faceNormal );
dstNormalsVertex.push( vertexNormals );
}
}
var morphNormals = this.morphNormals[ i ];
// set vertices to morph target
tmpGeo.vertices = this.morphTargets[ i ].vertices;
// compute morph normals
tmpGeo.computeFaceNormals();
tmpGeo.computeVertexNormals();
// store morph normals
var faceNormal, vertexNormals;
for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
face = this.faces[ f ];
faceNormal = morphNormals.faceNormals[ f ];
vertexNormals = morphNormals.vertexNormals[ f ];
faceNormal.copy( face.normal );
vertexNormals.a.copy( face.vertexNormals[ 0 ] );
vertexNormals.b.copy( face.vertexNormals[ 1 ] );
vertexNormals.c.copy( face.vertexNormals[ 2 ] );
}
}
// restore original normals
for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
face = this.faces[ f ];
face.normal = face.__originalFaceNormal;
face.vertexNormals = face.__originalVertexNormals;
}
},
computeLineDistances: function () {
var d = 0;
var vertices = this.vertices;
for ( var i = 0, il = vertices.length; i < il; i ++ ) {
if ( i > 0 ) {
d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
}
this.lineDistances[ i ] = d;
}
},
computeBoundingBox: function () {
if ( this.boundingBox === null ) {
this.boundingBox = new Box3();
}
this.boundingBox.setFromPoints( this.vertices );
},
computeBoundingSphere: function () {
if ( this.boundingSphere === null ) {
this.boundingSphere = new Sphere();
}
this.boundingSphere.setFromPoints( this.vertices );
},
merge: function ( geometry, matrix, materialIndexOffset ) {
if ( ( geometry && geometry.isGeometry ) === false ) {
console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
return;
}
var normalMatrix,
vertexOffset = this.vertices.length,
vertices1 = this.vertices,
vertices2 = geometry.vertices,
faces1 = this.faces,
faces2 = geometry.faces,
uvs1 = this.faceVertexUvs[ 0 ],
uvs2 = geometry.faceVertexUvs[ 0 ],
colors1 = this.colors,
colors2 = geometry.colors;
if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
if ( matrix !== undefined ) {
normalMatrix = new Matrix3().getNormalMatrix( matrix );
}
// vertices
for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
var vertex = vertices2[ i ];
var vertexCopy = vertex.clone();
if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
vertices1.push( vertexCopy );
}
// colors
for ( var i = 0, il = colors2.length; i < il; i ++ ) {
colors1.push( colors2[ i ].clone() );
}
// faces
for ( i = 0, il = faces2.length; i < il; i ++ ) {
var face = faces2[ i ], faceCopy, normal, color,
faceVertexNormals = face.vertexNormals,
faceVertexColors = face.vertexColors;
faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
faceCopy.normal.copy( face.normal );
if ( normalMatrix !== undefined ) {
faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
}
for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
normal = faceVertexNormals[ j ].clone();
if ( normalMatrix !== undefined ) {
normal.applyMatrix3( normalMatrix ).normalize();
}
faceCopy.vertexNormals.push( normal );
}
faceCopy.color.copy( face.color );
for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
color = faceVertexColors[ j ];
faceCopy.vertexColors.push( color.clone() );
}
faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
faces1.push( faceCopy );
}
// uvs
for ( i = 0, il = uvs2.length; i < il; i ++ ) {
var uv = uvs2[ i ], uvCopy = [];
if ( uv === undefined ) {
continue;
}
for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
uvCopy.push( uv[ j ].clone() );
}
uvs1.push( uvCopy );
}
},
mergeMesh: function ( mesh ) {
if ( ( mesh && mesh.isMesh ) === false ) {
console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
return;
}
mesh.matrixAutoUpdate && mesh.updateMatrix();
this.merge( mesh.geometry, mesh.matrix );
},
/*
* Checks for duplicate vertices with hashmap.
* Duplicated vertices are removed
* and faces' vertices are updated.
*/
mergeVertices: function () {
var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
var unique = [], changes = [];
var v, key;
var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
var precision = Math.pow( 10, precisionPoints );
var i, il, face;
var indices, j, jl;
for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
v = this.vertices[ i ];
key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
if ( verticesMap[ key ] === undefined ) {
verticesMap[ key ] = i;
unique.push( this.vertices[ i ] );
changes[ i ] = unique.length - 1;
} else {
//console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
changes[ i ] = changes[ verticesMap[ key ] ];
}
}
// if faces are completely degenerate after merging vertices, we
// have to remove them from the geometry.
var faceIndicesToRemove = [];
for ( i = 0, il = this.faces.length; i < il; i ++ ) {
face = this.faces[ i ];
face.a = changes[ face.a ];
face.b = changes[ face.b ];
face.c = changes[ face.c ];
indices = [ face.a, face.b, face.c ];
// if any duplicate vertices are found in a Face3
// we have to remove the face as nothing can be saved
for ( var n = 0; n < 3; n ++ ) {
if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {
faceIndicesToRemove.push( i );
break;
}
}
}
for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
var idx = faceIndicesToRemove[ i ];
this.faces.splice( idx, 1 );
for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
this.faceVertexUvs[ j ].splice( idx, 1 );
}
}
// Use unique set of vertices
var diff = this.vertices.length - unique.length;
this.vertices = unique;
return diff;
},
sortFacesByMaterialIndex: function () {
var faces = this.faces;
var length = faces.length;
// tag faces
for ( var i = 0; i < length; i ++ ) {
faces[ i ]._id = i;
}
// sort faces
function materialIndexSort( a, b ) {
return a.materialIndex - b.materialIndex;
}
faces.sort( materialIndexSort );
// sort uvs
var uvs1 = this.faceVertexUvs[ 0 ];
var uvs2 = this.faceVertexUvs[ 1 ];
var newUvs1, newUvs2;
if ( uvs1 && uvs1.length === length ) newUvs1 = [];
if ( uvs2 && uvs2.length === length ) newUvs2 = [];
for ( var i = 0; i < length; i ++ ) {
var id = faces[ i ]._id;
if ( newUvs1 ) newUvs1.push( uvs1[ id ] );
if ( newUvs2 ) newUvs2.push( uvs2[ id ] );
}
if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1;
if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2;
},
toJSON: function () {
var data = {
metadata: {
version: 4.4,
type: 'Geometry',
generator: 'Geometry.toJSON'
}
};
// standard Geometry serialization
data.uuid = this.uuid;
data.type = this.type;
if ( this.name !== '' ) data.name = this.name;
if ( this.parameters !== undefined ) {
var parameters = this.parameters;
for ( var key in parameters ) {
if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
}
return data;
}
var vertices = [];
for ( var i = 0; i < this.vertices.length; i ++ ) {
var vertex = this.vertices[ i ];
vertices.push( vertex.x, vertex.y, vertex.z );
}
var faces = [];
var normals = [];
var normalsHash = {};
var colors = [];
var colorsHash = {};
var uvs = [];
var uvsHash = {};
for ( var i = 0; i < this.faces.length; i ++ ) {
var face = this.faces[ i ];
var hasMaterial = true;
var hasFaceUv = false; // deprecated
var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
var hasFaceNormal = face.normal.length() > 0;
var hasFaceVertexNormal = face.vertexNormals.length > 0;
var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
var hasFaceVertexColor = face.vertexColors.length > 0;
var faceType = 0;
faceType = setBit( faceType, 0, 0 ); // isQuad
faceType = setBit( faceType, 1, hasMaterial );
faceType = setBit( faceType, 2, hasFaceUv );
faceType = setBit( faceType, 3, hasFaceVertexUv );
faceType = setBit( faceType, 4, hasFaceNormal );
faceType = setBit( faceType, 5, hasFaceVertexNormal );
faceType = setBit( faceType, 6, hasFaceColor );
faceType = setBit( faceType, 7, hasFaceVertexColor );
faces.push( faceType );
faces.push( face.a, face.b, face.c );
faces.push( face.materialIndex );
if ( hasFaceVertexUv ) {
var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
faces.push(
getUvIndex( faceVertexUvs[ 0 ] ),
getUvIndex( faceVertexUvs[ 1 ] ),
getUvIndex( faceVertexUvs[ 2 ] )
);
}
if ( hasFaceNormal ) {
faces.push( getNormalIndex( face.normal ) );
}
if ( hasFaceVertexNormal ) {
var vertexNormals = face.vertexNormals;
faces.push(
getNormalIndex( vertexNormals[ 0 ] ),
getNormalIndex( vertexNormals[ 1 ] ),
getNormalIndex( vertexNormals[ 2 ] )
);
}
if ( hasFaceColor ) {
faces.push( getColorIndex( face.color ) );
}
if ( hasFaceVertexColor ) {
var vertexColors = face.vertexColors;
faces.push(
getColorIndex( vertexColors[ 0 ] ),
getColorIndex( vertexColors[ 1 ] ),
getColorIndex( vertexColors[ 2 ] )
);
}
}
function setBit( value, position, enabled ) {
return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) );
}
function getNormalIndex( normal ) {
var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
if ( normalsHash[ hash ] !== undefined ) {
return normalsHash[ hash ];
}
normalsHash[ hash ] = normals.length / 3;
normals.push( normal.x, normal.y, normal.z );
return normalsHash[ hash ];
}
function getColorIndex( color ) {
var hash = color.r.toString() + color.g.toString() + color.b.toString();
if ( colorsHash[ hash ] !== undefined ) {
return colorsHash[ hash ];
}
colorsHash[ hash ] = colors.length;
colors.push( color.getHex() );
return colorsHash[ hash ];
}
function getUvIndex( uv ) {
var hash = uv.x.toString() + uv.y.toString();
if ( uvsHash[ hash ] !== undefined ) {
return uvsHash[ hash ];
}
uvsHash[ hash ] = uvs.length / 2;
uvs.push( uv.x, uv.y );
return uvsHash[ hash ];
}
data.data = {};
data.data.vertices = vertices;
data.data.normals = normals;
if ( colors.length > 0 ) data.data.colors = colors;
if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility
data.data.faces = faces;
return data;
},
clone: function () {
/*
// Handle primitives
var parameters = this.parameters;
if ( parameters !== undefined ) {
var values = [];
for ( var key in parameters ) {
values.push( parameters[ key ] );
}
var geometry = Object.create( this.constructor.prototype );
this.constructor.apply( geometry, values );
return geometry;
}
return new this.constructor().copy( this );
*/
return new Geometry().copy( this );
},
copy: function ( source ) {
this.vertices = [];
this.faces = [];
this.faceVertexUvs = [ [] ];
this.colors = [];
var vertices = source.vertices;
for ( var i = 0, il = vertices.length; i < il; i ++ ) {
this.vertices.push( vertices[ i ].clone() );
}
var colors = source.colors;
for ( var i = 0, il = colors.length; i < il; i ++ ) {
this.colors.push( colors[ i ].clone() );
}
var faces = source.faces;
for ( var i = 0, il = faces.length; i < il; i ++ ) {
this.faces.push( faces[ i ].clone() );
}
for ( var i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) {
var faceVertexUvs = source.faceVertexUvs[ i ];
if ( this.faceVertexUvs[ i ] === undefined ) {
this.faceVertexUvs[ i ] = [];
}
for ( var j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
var uvs = faceVertexUvs[ j ], uvsCopy = [];
for ( var k = 0, kl = uvs.length; k < kl; k ++ ) {
var uv = uvs[ k ];
uvsCopy.push( uv.clone() );
}
this.faceVertexUvs[ i ].push( uvsCopy );
}
}
return this;
},
dispose: function () {
this.dispatchEvent( { type: 'dispose' } );
}
} );
export { GeometryIdCount, Geometry };
| src/core/Geometry.js | import { EventDispatcher } from './EventDispatcher';
import { Face3 } from './Face3';
import { Matrix3 } from '../math/Matrix3';
import { Sphere } from '../math/Sphere';
import { Box3 } from '../math/Box3';
import { Vector3 } from '../math/Vector3';
import { Matrix4 } from '../math/Matrix4';
import { Vector2 } from '../math/Vector2';
import { Color } from '../math/Color';
import { Object3D } from './Object3D';
import { _Math } from '../math/Math';
/**
* @author mrdoob / http://mrdoob.com/
* @author kile / http://kile.stravaganza.org/
* @author alteredq / http://alteredqualia.com/
* @author mikael emtinger / http://gomo.se/
* @author zz85 / http://www.lab4games.net/zz85/blog
* @author bhouston / http://clara.io
*/
var count = 0;
function GeometryIdCount() { return count++; };
function Geometry() {
Object.defineProperty( this, 'id', { value: GeometryIdCount() } );
this.uuid = _Math.generateUUID();
this.name = '';
this.type = 'Geometry';
this.vertices = [];
this.colors = [];
this.faces = [];
this.faceVertexUvs = [[]];
this.morphTargets = [];
this.morphNormals = [];
this.skinWeights = [];
this.skinIndices = [];
this.lineDistances = [];
this.boundingBox = null;
this.boundingSphere = null;
// update flags
this.elementsNeedUpdate = false;
this.verticesNeedUpdate = false;
this.uvsNeedUpdate = false;
this.normalsNeedUpdate = false;
this.colorsNeedUpdate = false;
this.lineDistancesNeedUpdate = false;
this.groupsNeedUpdate = false;
}
Geometry.prototype = {
constructor: Geometry,
isGeometry: true,
applyMatrix: function ( matrix ) {
var normalMatrix = new Matrix3().getNormalMatrix( matrix );
for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
var vertex = this.vertices[ i ];
vertex.applyMatrix4( matrix );
}
for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
var face = this.faces[ i ];
face.normal.applyMatrix3( normalMatrix ).normalize();
for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
}
}
if ( this.boundingBox !== null ) {
this.computeBoundingBox();
}
if ( this.boundingSphere !== null ) {
this.computeBoundingSphere();
}
this.verticesNeedUpdate = true;
this.normalsNeedUpdate = true;
return this;
},
rotateX: function () {
// rotate geometry around world x-axis
var m1;
return function rotateX( angle ) {
if ( m1 === undefined ) m1 = new Matrix4();
m1.makeRotationX( angle );
this.applyMatrix( m1 );
return this;
};
}(),
rotateY: function () {
// rotate geometry around world y-axis
var m1;
return function rotateY( angle ) {
if ( m1 === undefined ) m1 = new Matrix4();
m1.makeRotationY( angle );
this.applyMatrix( m1 );
return this;
};
}(),
rotateZ: function () {
// rotate geometry around world z-axis
var m1;
return function rotateZ( angle ) {
if ( m1 === undefined ) m1 = new Matrix4();
m1.makeRotationZ( angle );
this.applyMatrix( m1 );
return this;
};
}(),
translate: function () {
// translate geometry
var m1;
return function translate( x, y, z ) {
if ( m1 === undefined ) m1 = new Matrix4();
m1.makeTranslation( x, y, z );
this.applyMatrix( m1 );
return this;
};
}(),
scale: function () {
// scale geometry
var m1;
return function scale( x, y, z ) {
if ( m1 === undefined ) m1 = new Matrix4();
m1.makeScale( x, y, z );
this.applyMatrix( m1 );
return this;
};
}(),
lookAt: function () {
var obj;
return function lookAt( vector ) {
if ( obj === undefined ) obj = new Object3D();
obj.lookAt( vector );
obj.updateMatrix();
this.applyMatrix( obj.matrix );
};
}(),
fromBufferGeometry: function ( geometry ) {
var scope = this;
var indices = geometry.index !== null ? geometry.index.array : undefined;
var attributes = geometry.attributes;
var positions = attributes.position.array;
var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
var colors = attributes.color !== undefined ? attributes.color.array : undefined;
var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = [];
var tempNormals = [];
var tempUVs = [];
var tempUVs2 = [];
for ( var i = 0, j = 0; i < positions.length; i += 3, j += 2 ) {
scope.vertices.push( new Vector3( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ) );
if ( normals !== undefined ) {
tempNormals.push( new Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) );
}
if ( colors !== undefined ) {
scope.colors.push( new Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) );
}
if ( uvs !== undefined ) {
tempUVs.push( new Vector2( uvs[ j ], uvs[ j + 1 ] ) );
}
if ( uvs2 !== undefined ) {
tempUVs2.push( new Vector2( uvs2[ j ], uvs2[ j + 1 ] ) );
}
}
function addFace( a, b, c, materialIndex ) {
var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : [];
var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : [];
var face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex );
scope.faces.push( face );
if ( uvs !== undefined ) {
scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] );
}
if ( uvs2 !== undefined ) {
scope.faceVertexUvs[ 1 ].push( [ tempUVs2[ a ].clone(), tempUVs2[ b ].clone(), tempUVs2[ c ].clone() ] );
}
}
if ( indices !== undefined ) {
var groups = geometry.groups;
if ( groups.length > 0 ) {
for ( var i = 0; i < groups.length; i ++ ) {
var group = groups[ i ];
var start = group.start;
var count = group.count;
for ( var j = start, jl = start + count; j < jl; j += 3 ) {
addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex );
}
}
} else {
for ( var i = 0; i < indices.length; i += 3 ) {
addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
}
}
} else {
for ( var i = 0; i < positions.length / 3; i += 3 ) {
addFace( i, i + 1, i + 2 );
}
}
this.computeFaceNormals();
if ( geometry.boundingBox !== null ) {
this.boundingBox = geometry.boundingBox.clone();
}
if ( geometry.boundingSphere !== null ) {
this.boundingSphere = geometry.boundingSphere.clone();
}
return this;
},
center: function () {
this.computeBoundingBox();
var offset = this.boundingBox.getCenter().negate();
this.translate( offset.x, offset.y, offset.z );
return offset;
},
normalize: function () {
this.computeBoundingSphere();
var center = this.boundingSphere.center;
var radius = this.boundingSphere.radius;
var s = radius === 0 ? 1 : 1.0 / radius;
var matrix = new Matrix4();
matrix.set(
s, 0, 0, - s * center.x,
0, s, 0, - s * center.y,
0, 0, s, - s * center.z,
0, 0, 0, 1
);
this.applyMatrix( matrix );
return this;
},
computeFaceNormals: function () {
var cb = new Vector3(), ab = new Vector3();
for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
var face = this.faces[ f ];
var vA = this.vertices[ face.a ];
var vB = this.vertices[ face.b ];
var vC = this.vertices[ face.c ];
cb.subVectors( vC, vB );
ab.subVectors( vA, vB );
cb.cross( ab );
cb.normalize();
face.normal.copy( cb );
}
},
computeVertexNormals: function ( areaWeighted ) {
if ( areaWeighted === undefined ) areaWeighted = true;
var v, vl, f, fl, face, vertices;
vertices = new Array( this.vertices.length );
for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
vertices[ v ] = new Vector3();
}
if ( areaWeighted ) {
// vertex normals weighted by triangle areas
// http://www.iquilezles.org/www/articles/normals/normals.htm
var vA, vB, vC;
var cb = new Vector3(), ab = new Vector3();
for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
face = this.faces[ f ];
vA = this.vertices[ face.a ];
vB = this.vertices[ face.b ];
vC = this.vertices[ face.c ];
cb.subVectors( vC, vB );
ab.subVectors( vA, vB );
cb.cross( ab );
vertices[ face.a ].add( cb );
vertices[ face.b ].add( cb );
vertices[ face.c ].add( cb );
}
} else {
this.computeFaceNormals();
for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
face = this.faces[ f ];
vertices[ face.a ].add( face.normal );
vertices[ face.b ].add( face.normal );
vertices[ face.c ].add( face.normal );
}
}
for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
vertices[ v ].normalize();
}
for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
face = this.faces[ f ];
var vertexNormals = face.vertexNormals;
if ( vertexNormals.length === 3 ) {
vertexNormals[ 0 ].copy( vertices[ face.a ] );
vertexNormals[ 1 ].copy( vertices[ face.b ] );
vertexNormals[ 2 ].copy( vertices[ face.c ] );
} else {
vertexNormals[ 0 ] = vertices[ face.a ].clone();
vertexNormals[ 1 ] = vertices[ face.b ].clone();
vertexNormals[ 2 ] = vertices[ face.c ].clone();
}
}
if ( this.faces.length > 0 ) {
this.normalsNeedUpdate = true;
}
},
computeFlatVertexNormals: function () {
var f, fl, face;
this.computeFaceNormals();
for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
face = this.faces[ f ];
var vertexNormals = face.vertexNormals;
if ( vertexNormals.length === 3 ) {
vertexNormals[ 0 ].copy( face.normal );
vertexNormals[ 1 ].copy( face.normal );
vertexNormals[ 2 ].copy( face.normal );
} else {
vertexNormals[ 0 ] = face.normal.clone();
vertexNormals[ 1 ] = face.normal.clone();
vertexNormals[ 2 ] = face.normal.clone();
}
}
if ( this.faces.length > 0 ) {
this.normalsNeedUpdate = true;
}
},
computeMorphNormals: function () {
var i, il, f, fl, face;
// save original normals
// - create temp variables on first access
// otherwise just copy (for faster repeated calls)
for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
face = this.faces[ f ];
if ( ! face.__originalFaceNormal ) {
face.__originalFaceNormal = face.normal.clone();
} else {
face.__originalFaceNormal.copy( face.normal );
}
if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
if ( ! face.__originalVertexNormals[ i ] ) {
face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
} else {
face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
}
}
}
// use temp geometry to compute face and vertex normals for each morph
var tmpGeo = new Geometry();
tmpGeo.faces = this.faces;
for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
// create on first access
if ( ! this.morphNormals[ i ] ) {
this.morphNormals[ i ] = {};
this.morphNormals[ i ].faceNormals = [];
this.morphNormals[ i ].vertexNormals = [];
var dstNormalsFace = this.morphNormals[ i ].faceNormals;
var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
var faceNormal, vertexNormals;
for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
faceNormal = new Vector3();
vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() };
dstNormalsFace.push( faceNormal );
dstNormalsVertex.push( vertexNormals );
}
}
var morphNormals = this.morphNormals[ i ];
// set vertices to morph target
tmpGeo.vertices = this.morphTargets[ i ].vertices;
// compute morph normals
tmpGeo.computeFaceNormals();
tmpGeo.computeVertexNormals();
// store morph normals
var faceNormal, vertexNormals;
for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
face = this.faces[ f ];
faceNormal = morphNormals.faceNormals[ f ];
vertexNormals = morphNormals.vertexNormals[ f ];
faceNormal.copy( face.normal );
vertexNormals.a.copy( face.vertexNormals[ 0 ] );
vertexNormals.b.copy( face.vertexNormals[ 1 ] );
vertexNormals.c.copy( face.vertexNormals[ 2 ] );
}
}
// restore original normals
for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
face = this.faces[ f ];
face.normal = face.__originalFaceNormal;
face.vertexNormals = face.__originalVertexNormals;
}
},
computeLineDistances: function () {
var d = 0;
var vertices = this.vertices;
for ( var i = 0, il = vertices.length; i < il; i ++ ) {
if ( i > 0 ) {
d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
}
this.lineDistances[ i ] = d;
}
},
computeBoundingBox: function () {
if ( this.boundingBox === null ) {
this.boundingBox = new Box3();
}
this.boundingBox.setFromPoints( this.vertices );
},
computeBoundingSphere: function () {
if ( this.boundingSphere === null ) {
this.boundingSphere = new Sphere();
}
this.boundingSphere.setFromPoints( this.vertices );
},
merge: function ( geometry, matrix, materialIndexOffset ) {
if ( ( geometry && geometry.isGeometry ) === false ) {
console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
return;
}
var normalMatrix,
vertexOffset = this.vertices.length,
vertices1 = this.vertices,
vertices2 = geometry.vertices,
faces1 = this.faces,
faces2 = geometry.faces,
uvs1 = this.faceVertexUvs[ 0 ],
uvs2 = geometry.faceVertexUvs[ 0 ],
colors1 = this.colors,
colors2 = geometry.colors;
if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
if ( matrix !== undefined ) {
normalMatrix = new Matrix3().getNormalMatrix( matrix );
}
// vertices
for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
var vertex = vertices2[ i ];
var vertexCopy = vertex.clone();
if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
vertices1.push( vertexCopy );
}
// colors
for ( var i = 0, il = colors2.length; i < il; i ++ ) {
colors1.push( colors2[ i ].clone() );
}
// faces
for ( i = 0, il = faces2.length; i < il; i ++ ) {
var face = faces2[ i ], faceCopy, normal, color,
faceVertexNormals = face.vertexNormals,
faceVertexColors = face.vertexColors;
faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
faceCopy.normal.copy( face.normal );
if ( normalMatrix !== undefined ) {
faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
}
for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
normal = faceVertexNormals[ j ].clone();
if ( normalMatrix !== undefined ) {
normal.applyMatrix3( normalMatrix ).normalize();
}
faceCopy.vertexNormals.push( normal );
}
faceCopy.color.copy( face.color );
for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
color = faceVertexColors[ j ];
faceCopy.vertexColors.push( color.clone() );
}
faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
faces1.push( faceCopy );
}
// uvs
for ( i = 0, il = uvs2.length; i < il; i ++ ) {
var uv = uvs2[ i ], uvCopy = [];
if ( uv === undefined ) {
continue;
}
for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
uvCopy.push( uv[ j ].clone() );
}
uvs1.push( uvCopy );
}
},
mergeMesh: function ( mesh ) {
if ( ( mesh && mesh.isMesh ) === false ) {
console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
return;
}
mesh.matrixAutoUpdate && mesh.updateMatrix();
this.merge( mesh.geometry, mesh.matrix );
},
/*
* Checks for duplicate vertices with hashmap.
* Duplicated vertices are removed
* and faces' vertices are updated.
*/
mergeVertices: function () {
var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
var unique = [], changes = [];
var v, key;
var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
var precision = Math.pow( 10, precisionPoints );
var i, il, face;
var indices, j, jl;
for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
v = this.vertices[ i ];
key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
if ( verticesMap[ key ] === undefined ) {
verticesMap[ key ] = i;
unique.push( this.vertices[ i ] );
changes[ i ] = unique.length - 1;
} else {
//console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
changes[ i ] = changes[ verticesMap[ key ] ];
}
}
// if faces are completely degenerate after merging vertices, we
// have to remove them from the geometry.
var faceIndicesToRemove = [];
for ( i = 0, il = this.faces.length; i < il; i ++ ) {
face = this.faces[ i ];
face.a = changes[ face.a ];
face.b = changes[ face.b ];
face.c = changes[ face.c ];
indices = [ face.a, face.b, face.c ];
// if any duplicate vertices are found in a Face3
// we have to remove the face as nothing can be saved
for ( var n = 0; n < 3; n ++ ) {
if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {
faceIndicesToRemove.push( i );
break;
}
}
}
for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
var idx = faceIndicesToRemove[ i ];
this.faces.splice( idx, 1 );
for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
this.faceVertexUvs[ j ].splice( idx, 1 );
}
}
// Use unique set of vertices
var diff = this.vertices.length - unique.length;
this.vertices = unique;
return diff;
},
sortFacesByMaterialIndex: function () {
var faces = this.faces;
var length = faces.length;
// tag faces
for ( var i = 0; i < length; i ++ ) {
faces[ i ]._id = i;
}
// sort faces
function materialIndexSort( a, b ) {
return a.materialIndex - b.materialIndex;
}
faces.sort( materialIndexSort );
// sort uvs
var uvs1 = this.faceVertexUvs[ 0 ];
var uvs2 = this.faceVertexUvs[ 1 ];
var newUvs1, newUvs2;
if ( uvs1 && uvs1.length === length ) newUvs1 = [];
if ( uvs2 && uvs2.length === length ) newUvs2 = [];
for ( var i = 0; i < length; i ++ ) {
var id = faces[ i ]._id;
if ( newUvs1 ) newUvs1.push( uvs1[ id ] );
if ( newUvs2 ) newUvs2.push( uvs2[ id ] );
}
if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1;
if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2;
},
toJSON: function () {
var data = {
metadata: {
version: 4.4,
type: 'Geometry',
generator: 'Geometry.toJSON'
}
};
// standard Geometry serialization
data.uuid = this.uuid;
data.type = this.type;
if ( this.name !== '' ) data.name = this.name;
if ( this.parameters !== undefined ) {
var parameters = this.parameters;
for ( var key in parameters ) {
if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
}
return data;
}
var vertices = [];
for ( var i = 0; i < this.vertices.length; i ++ ) {
var vertex = this.vertices[ i ];
vertices.push( vertex.x, vertex.y, vertex.z );
}
var faces = [];
var normals = [];
var normalsHash = {};
var colors = [];
var colorsHash = {};
var uvs = [];
var uvsHash = {};
for ( var i = 0; i < this.faces.length; i ++ ) {
var face = this.faces[ i ];
var hasMaterial = true;
var hasFaceUv = false; // deprecated
var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
var hasFaceNormal = face.normal.length() > 0;
var hasFaceVertexNormal = face.vertexNormals.length > 0;
var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
var hasFaceVertexColor = face.vertexColors.length > 0;
var faceType = 0;
faceType = setBit( faceType, 0, 0 ); // isQuad
faceType = setBit( faceType, 1, hasMaterial );
faceType = setBit( faceType, 2, hasFaceUv );
faceType = setBit( faceType, 3, hasFaceVertexUv );
faceType = setBit( faceType, 4, hasFaceNormal );
faceType = setBit( faceType, 5, hasFaceVertexNormal );
faceType = setBit( faceType, 6, hasFaceColor );
faceType = setBit( faceType, 7, hasFaceVertexColor );
faces.push( faceType );
faces.push( face.a, face.b, face.c );
faces.push( face.materialIndex );
if ( hasFaceVertexUv ) {
var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
faces.push(
getUvIndex( faceVertexUvs[ 0 ] ),
getUvIndex( faceVertexUvs[ 1 ] ),
getUvIndex( faceVertexUvs[ 2 ] )
);
}
if ( hasFaceNormal ) {
faces.push( getNormalIndex( face.normal ) );
}
if ( hasFaceVertexNormal ) {
var vertexNormals = face.vertexNormals;
faces.push(
getNormalIndex( vertexNormals[ 0 ] ),
getNormalIndex( vertexNormals[ 1 ] ),
getNormalIndex( vertexNormals[ 2 ] )
);
}
if ( hasFaceColor ) {
faces.push( getColorIndex( face.color ) );
}
if ( hasFaceVertexColor ) {
var vertexColors = face.vertexColors;
faces.push(
getColorIndex( vertexColors[ 0 ] ),
getColorIndex( vertexColors[ 1 ] ),
getColorIndex( vertexColors[ 2 ] )
);
}
}
function setBit( value, position, enabled ) {
return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) );
}
function getNormalIndex( normal ) {
var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
if ( normalsHash[ hash ] !== undefined ) {
return normalsHash[ hash ];
}
normalsHash[ hash ] = normals.length / 3;
normals.push( normal.x, normal.y, normal.z );
return normalsHash[ hash ];
}
function getColorIndex( color ) {
var hash = color.r.toString() + color.g.toString() + color.b.toString();
if ( colorsHash[ hash ] !== undefined ) {
return colorsHash[ hash ];
}
colorsHash[ hash ] = colors.length;
colors.push( color.getHex() );
return colorsHash[ hash ];
}
function getUvIndex( uv ) {
var hash = uv.x.toString() + uv.y.toString();
if ( uvsHash[ hash ] !== undefined ) {
return uvsHash[ hash ];
}
uvsHash[ hash ] = uvs.length / 2;
uvs.push( uv.x, uv.y );
return uvsHash[ hash ];
}
data.data = {};
data.data.vertices = vertices;
data.data.normals = normals;
if ( colors.length > 0 ) data.data.colors = colors;
if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility
data.data.faces = faces;
return data;
},
clone: function () {
/*
// Handle primitives
var parameters = this.parameters;
if ( parameters !== undefined ) {
var values = [];
for ( var key in parameters ) {
values.push( parameters[ key ] );
}
var geometry = Object.create( this.constructor.prototype );
this.constructor.apply( geometry, values );
return geometry;
}
return new this.constructor().copy( this );
*/
return new Geometry().copy( this );
},
copy: function ( source ) {
this.vertices = [];
this.faces = [];
this.faceVertexUvs = [ [] ];
this.colors = [];
var vertices = source.vertices;
for ( var i = 0, il = vertices.length; i < il; i ++ ) {
this.vertices.push( vertices[ i ].clone() );
}
var colors = source.colors;
for ( var i = 0, il = colors.length; i < il; i ++ ) {
this.colors.push( colors[ i ].clone() );
}
var faces = source.faces;
for ( var i = 0, il = faces.length; i < il; i ++ ) {
this.faces.push( faces[ i ].clone() );
}
for ( var i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) {
var faceVertexUvs = source.faceVertexUvs[ i ];
if ( this.faceVertexUvs[ i ] === undefined ) {
this.faceVertexUvs[ i ] = [];
}
for ( var j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
var uvs = faceVertexUvs[ j ], uvsCopy = [];
for ( var k = 0, kl = uvs.length; k < kl; k ++ ) {
var uv = uvs[ k ];
uvsCopy.push( uv.clone() );
}
this.faceVertexUvs[ i ].push( uvsCopy );
}
}
return this;
},
dispose: function () {
this.dispatchEvent( { type: 'dispose' } );
}
};
Object.assign( Geometry.prototype, EventDispatcher.prototype );
export { GeometryIdCount, Geometry };
| Protect Geometry against the closure circular reference bug
| src/core/Geometry.js | Protect Geometry against the closure circular reference bug | <ide><path>rc/core/Geometry.js
<ide>
<ide> }
<ide>
<del>Geometry.prototype = {
<add>Object.assign( Geometry.prototype, EventDispatcher.prototype, {
<ide>
<ide> constructor: Geometry,
<ide>
<ide> }
<ide>
<ide> var normalMatrix,
<del> vertexOffset = this.vertices.length,
<del> vertices1 = this.vertices,
<del> vertices2 = geometry.vertices,
<del> faces1 = this.faces,
<del> faces2 = geometry.faces,
<del> uvs1 = this.faceVertexUvs[ 0 ],
<del> uvs2 = geometry.faceVertexUvs[ 0 ],
<del> colors1 = this.colors,
<del> colors2 = geometry.colors;
<add> vertexOffset = this.vertices.length,
<add> vertices1 = this.vertices,
<add> vertices2 = geometry.vertices,
<add> faces1 = this.faces,
<add> faces2 = geometry.faces,
<add> uvs1 = this.faceVertexUvs[ 0 ],
<add> uvs2 = geometry.faceVertexUvs[ 0 ],
<add> colors1 = this.colors,
<add> colors2 = geometry.colors;
<ide>
<ide> if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
<ide>
<ide> for ( i = 0, il = faces2.length; i < il; i ++ ) {
<ide>
<ide> var face = faces2[ i ], faceCopy, normal, color,
<del> faceVertexNormals = face.vertexNormals,
<del> faceVertexColors = face.vertexColors;
<add> faceVertexNormals = face.vertexNormals,
<add> faceVertexColors = face.vertexColors;
<ide>
<ide> faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
<ide> faceCopy.normal.copy( face.normal );
<ide> clone: function () {
<ide>
<ide> /*
<del> // Handle primitives
<del>
<del> var parameters = this.parameters;
<del>
<del> if ( parameters !== undefined ) {
<del>
<del> var values = [];
<del>
<del> for ( var key in parameters ) {
<del>
<del> values.push( parameters[ key ] );
<del>
<del> }
<del>
<del> var geometry = Object.create( this.constructor.prototype );
<del> this.constructor.apply( geometry, values );
<del> return geometry;
<del>
<del> }
<del>
<del> return new this.constructor().copy( this );
<del> */
<add> // Handle primitives
<add>
<add> var parameters = this.parameters;
<add>
<add> if ( parameters !== undefined ) {
<add>
<add> var values = [];
<add>
<add> for ( var key in parameters ) {
<add>
<add> values.push( parameters[ key ] );
<add>
<add> }
<add>
<add> var geometry = Object.create( this.constructor.prototype );
<add> this.constructor.apply( geometry, values );
<add> return geometry;
<add>
<add> }
<add>
<add> return new this.constructor().copy( this );
<add> */
<ide>
<ide> return new Geometry().copy( this );
<ide>
<ide>
<ide> }
<ide>
<del>};
<del>
<del>Object.assign( Geometry.prototype, EventDispatcher.prototype );
<add>} );
<add>
<ide>
<ide> export { GeometryIdCount, Geometry }; |
|
JavaScript | apache-2.0 | cbaad2c94f4bb2a8dc036a03b4d81a19bee8e7cc | 0 | apache/shindig,apache/shindig,apache/shindig,apparentlymart/shindig,apache/shindig,apache/shindig,apparentlymart/shindig,apparentlymart/shindig,apparentlymart/shindig | /*
* 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.
*/
/**
* @fileoverview Remote procedure call library for gadget-to-container,
* container-to-gadget, and gadget-to-gadget (thru container) communication.
*/
var gadgets = gadgets || {};
/**
* gadgets.rpc Transports
*
* All transports are stored in object gadgets.rpctx, and are provided
* to the core gadgets.rpc library by various build rules.
*
* Transports used by core gadgets.rpc code to actually pass messages.
* each transport implements the same interface exposing hooks that
* the core library calls at strategic points to set up and use
* the transport.
*
* The methods each transport must implement are:
* + getCode(): returns a string identifying the transport. For debugging.
* + isParentVerifiable(): indicates (via boolean) whether the method
* has the property that its relay URL verifies for certain the
* receiver's protocol://host:port.
* + init(processFn, readyFn): Performs any global initialization needed. Called
* before any other gadgets.rpc methods are invoked. processFn is
* the function in gadgets.rpc used to process an rpc packet. readyFn is
* a function that must be called when the transport is ready to send
* and receive messages bidirectionally. Returns
* true if successful, false otherwise.
* + setup(receiverId, token): Performs per-receiver initialization, if any.
* receiverId will be '..' for gadget-to-container. Returns true if
* successful, false otherwise.
* + call(targetId, from, rpc): Invoked to send an actual
* message to the given targetId, with the given serviceName, from
* the sender identified by 'from'. Payload is an rpc packet. Returns
* true if successful, false otherwise.
*/
/**
* @static
* @class Provides operations for making rpc calls.
* @name gadgets.rpc
*/
gadgets.rpc = function() {
// General constants.
var CALLBACK_NAME = '__cb';
var DEFAULT_NAME = '';
// Special service name for acknowledgements.
var ACK = '__ack';
// Timeout and number of setup attempts between each
// for when setAuthToken is called before the target it specifies exists.
var SETUP_FRAME_TIMEOUT = 500;
var SETUP_FRAME_MAX_TRIES = 10;
var services = {};
var relayUrl = {};
var useLegacyProtocol = {};
var authToken = {};
var callId = 0;
var callbacks = {};
var setup = {};
var sameDomain = {};
var params = {};
var receiverTx = {};
var earlyRpcQueue = {};
// isGadget =~ isChild for the purposes of rpc (used only in setup).
var isGadget = (window.top !== window.self);
// Fallback transport is simply a dummy impl that emits no errors
// and logs info on calls it receives, to avoid undesired side-effects
// from falling back to IFPC or some other transport.
var fallbackTransport = (function() {
function logFn(name) {
return function() {
gadgets.info("gadgets.rpc." + name + "(" +
gadgets.json.stringify(arguments) +
"): call ignored. [caller: " + document.location +
", isGadget: " + isGadget + "]");
}
}
return {
getCode: function() {
return "noop";
},
isParentVerifiable: function() {
return true; // Not really, but prevents transport assignment to IFPC.
},
init: logFn("init"),
setup: logFn("setup"),
call: logFn("call")
}
})();
// Load the authentication token for speaking to the container
// from the gadget's parameters, or default to '0' if not found.
if (gadgets.util) {
params = gadgets.util.getUrlParameters();
}
authToken['..'] = params.rpctoken || params.ifpctok || 0;
// Indicates whether to support early-message queueing, which is designed
// to ensure that all messages sent by gadgets.rpc.call, irrespective
// when they were made (before/after setAuthToken, before/after transport
// setup complete), are sent. Hiding behind a query param to allow opt-in
// for a time while this technique is proven.
var useEarlyQueueing = (params['rpc_earlyq'] === "1");
/*
* Return a transport representing the best available cross-domain
* message-passing mechanism available to the browser.
*
* Transports are selected on a cascading basis determined by browser
* capability and other checks. The order of preference is:
* 1. wpm: Uses window.postMessage standard.
* 2. dpm: Uses document.postMessage, similar to wpm but pre-standard.
* 3. nix: Uses IE-specific browser hacks.
* 4. rmr: Signals message passing using relay file's onresize handler.
* 5. fe: Uses FF2-specific window.frameElement hack.
* 6. ifpc: Sends messages via active load of a relay file.
*
* See each transport's commentary/documentation for details.
*/
function getTransport() {
return typeof window.postMessage === 'function' ? gadgets.rpctx.wpm :
typeof window.postMessage === 'object' ? gadgets.rpctx.wpm :
window.ActiveXObject ? gadgets.rpctx.nix :
navigator.userAgent.indexOf('WebKit') > 0 ? gadgets.rpctx.rmr :
navigator.product === 'Gecko' ? gadgets.rpctx.frameElement :
gadgets.rpctx.ifpc;
}
/**
* Function passed to, and called by, a transport indicating it's ready to
* send and receive messages.
*/
function transportReady(receiverId, readySuccess) {
var tx = transport;
if (!readySuccess) {
tx = fallbackTransport;
}
receiverTx[receiverId] = tx;
// If there are any early-queued messages, send them now directly through
// the needed transport. This queue will only have contents if
// useEarlyQueueing === true (see call method).
var earlyQueue = earlyRpcQueue[receiverId] || [];
for (var i = 0; i < earlyQueue.length; ++i) {
var rpc = earlyQueue[i];
// There was no auth/rpc token set before, so set it now.
rpc.t = gadgets.rpc.getAuthToken(receiverId);
tx.call(receiverId, rpc.f, rpc);
}
// Clear the queue so it won't be sent again.
earlyRpcQueue[receiverId] = [];
}
/**
* Helper function to process an RPC request
* @param {Object} rpc RPC request object
* @private
*/
function process(rpc) {
//
// RPC object contents:
// s: Service Name
// f: From
// c: The callback ID or 0 if none.
// a: The arguments for this RPC call.
// t: The authentication token.
//
if (rpc && typeof rpc.s === 'string' && typeof rpc.f === 'string' &&
rpc.a instanceof Array) {
// Validate auth token.
if (authToken[rpc.f]) {
// We don't do type coercion here because all entries in the authToken
// object are strings, as are all url params. See setAuthToken(...).
if (authToken[rpc.f] !== rpc.t) {
throw new Error("Invalid auth token. " +
authToken[rpc.f] + " vs " + rpc.t);
}
}
if (rpc.s === ACK) {
// Acknowledgement API, used to indicate a receiver is ready.
window.setTimeout(function() { transportReady(rpc.f, true); }, 0);
return;
}
// If there is a callback for this service, attach a callback function
// to the rpc context object for asynchronous rpc services.
//
// Synchronous rpc request handlers should simply ignore it and return a
// value as usual.
// Asynchronous rpc request handlers, on the other hand, should pass its
// result to this callback function and not return a value on exit.
//
// For example, the following rpc handler passes the first parameter back
// to its rpc client with a one-second delay.
//
// function asyncRpcHandler(param) {
// var me = this;
// setTimeout(function() {
// me.callback(param);
// }, 1000);
// }
if (rpc.c) {
rpc.callback = function(result) {
gadgets.rpc.call(rpc.f, CALLBACK_NAME, null, rpc.c, result);
};
}
// Call the requested RPC service.
var result = (services[rpc.s] ||
services[DEFAULT_NAME]).apply(rpc, rpc.a);
// If the rpc request handler returns a value, immediately pass it back
// to the callback. Otherwise, do nothing, assuming that the rpc handler
// will make an asynchronous call later.
if (rpc.c && typeof result !== 'undefined') {
gadgets.rpc.call(rpc.f, CALLBACK_NAME, null, rpc.c, result);
}
}
}
/**
* Helper method returning a canonicalized protocol://host[:port] for
* a given input URL, provided as a string. Used to compute convenient
* relay URLs and to determine whether a call is coming from the same
* domain as its receiver (bypassing the try/catch capability detection
* flow, thereby obviating Firebug and other tools reporting an exception).
*
* @param {string} url Base URL to canonicalize.
*/
function getOrigin(url) {
if (!url) {
return "";
}
url = url.toLowerCase();
if (url.indexOf("//") == 0) {
url = window.location.protocol + ":" + url;
}
if (url.indexOf("http://") != 0 &&
url.indexOf("https://") != 0) {
// Assumed to be schemaless. Default to current protocol.
url = window.location.protocol + "://" + url;
}
// At this point we guarantee that "://" is in the URL and defines
// current protocol. Skip past this to search for host:port.
var host = url.substring(url.indexOf("://") + 3);
// Find the first slash char, delimiting the host:port.
var slashPos = host.indexOf("/");
if (slashPos != -1) {
host = host.substring(0, slashPos);
}
var protocol = url.substring(0, url.indexOf("://"));
// Use port only if it's not default for the protocol.
var portStr = "";
var portPos = host.indexOf(":");
if (portPos != -1) {
var port = host.substring(portPos + 1);
host = host.substring(0, portPos);
if ((protocol === "http" && port !== "80") ||
(protocol === "https" && port !== "443")) {
portStr = ":" + port;
}
}
// Return <protocol>://<host>[<port>]
return protocol + "://" + host + portStr;
}
// Pick the most efficient RPC relay mechanism.
var transport = getTransport();
// Create the Default RPC handler.
services[DEFAULT_NAME] = function() {
gadgets.warn('Unknown RPC service: ' + this.s);
};
// Create a Special RPC handler for callbacks.
services[CALLBACK_NAME] = function(callbackId, result) {
var callback = callbacks[callbackId];
if (callback) {
delete callbacks[callbackId];
callback(result);
}
};
/**
* Conducts any frame-specific work necessary to setup
* the channel type chosen. This method is called when
* the container page first registers the gadget in the
* RPC mechanism. Gadgets, in turn, will complete the setup
* of the channel once they send their first messages.
*/
function setupFrame(frameId, token) {
if (setup[frameId] === true) {
return;
}
if (typeof setup[frameId] === 'undefined') {
setup[frameId] = 0;
}
var tgtFrame = document.getElementById(frameId);
if (frameId === '..' || tgtFrame != null) {
if (transport.setup(frameId, token) === true) {
setup[frameId] = true;
return;
}
}
if (setup[frameId] !== true && setup[frameId]++ < SETUP_FRAME_MAX_TRIES) {
// Try again in a bit, assuming that frame will soon exist.
window.setTimeout(function() { setupFrame(frameId, token) },
SETUP_FRAME_TIMEOUT);
} else {
// Fail: fall back.
transport = fallbackTransport;
setup[frameId] = true;
}
}
/**
* Attempts to make an rpc by calling the target's receive method directly.
* This works when gadgets are rendered on the same domain as their container,
* a potentially useful optimization for trusted content which keeps
* RPC behind a consistent interface.
* @param {String} target Module id of the rpc service provider
* @param {String} from Module id of the caller (this)
* @param {String} callbackId Id of the call
* @param {String} rpcData JSON-encoded RPC payload
* @return
*/
function callSameDomain(target, rpc) {
if (typeof sameDomain[target] === 'undefined') {
// Seed with a negative, typed value to avoid
// hitting this code path repeatedly.
sameDomain[target] = false;
var targetRelay = gadgets.rpc.getRelayUrl(target);
if (getOrigin(targetRelay) !== getOrigin(window.location.href)) {
// Not worth trying -- avoid the error and just return.
return false;
}
var targetEl = null;
if (target === '..') {
targetEl = parent;
} else {
targetEl = frames[target];
}
try {
// If this succeeds, then same-domain policy applied
sameDomain[target] = targetEl.gadgets.rpc.receiveSameDomain;
} catch (e) {
// Shouldn't happen due to origin check. Caught to emit
// more meaningful error to the caller.
gadgets.error("Same domain call failed: parent= incorrectly set.");
}
}
if (typeof sameDomain[target] === 'function') {
// Call target's receive method
sameDomain[target](rpc);
return true;
}
return false;
}
// gadgets.config might not be available, such as when serving container js.
if (isGadget && gadgets.config) {
/**
* Initializes gadget to container RPC params from the provided configuration.
*/
function init(config) {
var configRpc = config ? config.rpc : {};
var parentRelayUrl = configRpc.parentRelayUrl;
// Allow for wild card parent relay files as long as it's from a
// white listed domain. This is enforced by the rendering servlet.
if (parentRelayUrl.substring(0, 7) !== 'http://' &&
parentRelayUrl.substring(0, 8) !== 'https://' &&
parentRelayUrl.substring(0, 2) !== '//') {
// Relative path: we append to the parent.
// We're relying on the server validating the parent parameter in this
// case. Because of this, parent may only be passed in the query, not fragment.
if (params.parent !== "") {
// Otherwise, relayUrl['..'] will be null, signaling transport
// code to ignore rpc calls since they cannot work without a
// relay URL with host qualification.
parentRelayUrl = getOrigin(params.parent) + parentRelayUrl;
}
}
relayUrl['..'] = parentRelayUrl;
var useLegacy = !!configRpc.useLegacyProtocol;
useLegacyProtocol['..'] = useLegacy;
if (useLegacy) {
transport = gadgets.rpctx.ifpc;
transport.init(process, transportReady);
}
// Here, we add a hook for the transport to actively set up
// gadget -> container communication. Running here ensures
// that relayUri info will be available.
if (transport.setup('..') === false) {
transport = fallbackTransport;
}
}
var requiredConfig = {
parentRelayUrl : gadgets.config.NonEmptyStringValidator
};
gadgets.config.register("rpc", requiredConfig, init);
}
return /** @scope gadgets.rpc */ {
/**
* Registers an RPC service.
* @param {String} serviceName Service name to register.
* @param {Function} handler Service handler.
*
* @member gadgets.rpc
*/
register: function(serviceName, handler) {
if (serviceName === CALLBACK_NAME || serviceName === ACK) {
throw new Error("Cannot overwrite callback/ack service");
}
if (serviceName === DEFAULT_NAME) {
throw new Error("Cannot overwrite default service:"
+ " use registerDefault");
}
services[serviceName] = handler;
},
/**
* Unregisters an RPC service.
* @param {String} serviceName Service name to unregister.
*
* @member gadgets.rpc
*/
unregister: function(serviceName) {
if (serviceName === CALLBACK_NAME || serviceName === ACK) {
throw new Error("Cannot delete callback/ack service");
}
if (serviceName === DEFAULT_NAME) {
throw new Error("Cannot delete default service:"
+ " use unregisterDefault");
}
delete services[serviceName];
},
/**
* Registers a default service handler to processes all unknown
* RPC calls which raise an exception by default.
* @param {Function} handler Service handler.
*
* @member gadgets.rpc
*/
registerDefault: function(handler) {
services[DEFAULT_NAME] = handler;
},
/**
* Unregisters the default service handler. Future unknown RPC
* calls will fail silently.
*
* @member gadgets.rpc
*/
unregisterDefault: function() {
delete services[DEFAULT_NAME];
},
/**
* Forces all subsequent calls to be made by a transport
* method that allows the caller to verify the message receiver
* (by way of the parent parameter, through getRelayUrl(...)).
* At present this means IFPC or WPM.
*/
forceParentVerifiable: function() {
if (!transport.isParentVerifiable()) {
transport = gadgets.rpctx.ifpc;
}
},
/**
* Calls an RPC service.
* @param {String} targetId Module Id of the RPC service provider.
* Empty if calling the parent container.
* @param {String} serviceName Service name to call.
* @param {Function|null} callback Callback function (if any) to process
* the return value of the RPC request.
* @param {*} var_args Parameters for the RPC request.
*
* @member gadgets.rpc
*/
call: function(targetId, serviceName, callback, var_args) {
targetId = targetId || '..';
// Default to the container calling.
var from = '..';
if (targetId === '..') {
from = window.name;
}
++callId;
if (callback) {
callbacks[callId] = callback;
}
var rpc = {
s: serviceName,
f: from,
c: callback ? callId : 0,
a: Array.prototype.slice.call(arguments, 3),
t: authToken[targetId],
l: useLegacyProtocol[targetId]
};
// If target is on the same domain, call method directly
if (callSameDomain(targetId, rpc)) {
return;
}
// Attempt to make call via a cross-domain transport.
var channel = useEarlyQueueing ? receiverTx[targetId] : transport;
if (!channel) {
// Not set up yet. Enqueue the rpc for such time as it is.
if (!earlyRpcQueue[targetId]) {
earlyRpcQueue[targetId] = [ rpc ];
} else {
earlyRpcQueue[targetId].push(rpc);
}
return;
}
// If we are told to use the legacy format, then we must
// default to IFPC.
if (useLegacyProtocol[targetId]) {
channel = gadgets.rpctx.ifpc;
}
if (channel.call(targetId, from, rpc) === false) {
// Fall back to IFPC. This behavior may be removed as IFPC is as well.
transport = fallbackTransport;
transport.call(targetId, from, rpc);
}
},
/**
* Gets the relay URL of a target frame.
* @param {String} targetId Name of the target frame.
* @return {String|undefined} Relay URL of the target frame.
*
* @member gadgets.rpc
*/
getRelayUrl: function(targetId) {
var url = relayUrl[targetId];
// Some RPC methods (wpm, for one) are unhappy with schemeless URLs.
if (url && url.indexOf('//') == 0) {
url = document.location.protocol + url;
}
return url;
},
/**
* Sets the relay URL of a target frame.
* @param {String} targetId Name of the target frame.
* @param {String} url Full relay URL of the target frame.
* @param {Boolean} opt_useLegacy True if this relay needs the legacy IFPC
* wire format.
*
* @member gadgets.rpc
*/
setRelayUrl: function(targetId, url, opt_useLegacy) {
relayUrl[targetId] = url;
useLegacyProtocol[targetId] = !!opt_useLegacy;
},
/**
* Sets the auth token of a target frame.
* @param {String} targetId Name of the target frame.
* @param {String} token The authentication token to use for all
* calls to or from this target id.
*
* @member gadgets.rpc
*/
setAuthToken: function(targetId, token) {
token = token || "";
// Coerce token to a String, ensuring that all authToken values
// are strings. This ensures correct comparison with URL params
// in the process(rpc) method.
authToken[targetId] = String(token);
setupFrame(targetId, token);
},
/**
* Helper method to retrieve the authToken for a given gadget.
*/
getAuthToken: function(targetId) {
return authToken[targetId];
},
/**
* Gets the RPC relay mechanism.
* @return {String} RPC relay mechanism. See above for
* a list of supported types.
*
* @member gadgets.rpc
*/
getRelayChannel: function() {
return transport.getCode();
},
/**
* Receives and processes an RPC request. (Not to be used directly.)
* Only used by IFPC.
* @param {Array.<String>} fragment An RPC request fragment encoded as
* an array. The first 4 elements are target id, source id & call id,
* total packet number, packet id. The last element stores the actual
* JSON-encoded and URI escaped packet data.
*
* @member gadgets.rpc
*/
receive: function(fragment) {
if (fragment.length > 4) {
// TODO parse fragment[1..3] to merge multi-fragment messages
process(gadgets.json.parse(
decodeURIComponent(fragment[fragment.length - 1])));
}
},
/**
* Receives and processes an RPC request sent via the same domain.
* (Not to be used directly). Converts the inbound rpc object's
* Array into a local Array to pass the process() Array test.
* @param {Object} rpc RPC object containing all request params
*/
receiveSameDomain: function(rpc) {
// Pass through to local process method but converting to a local Array
rpc.a = Array.prototype.slice.call(rpc.a);
window.setTimeout(function() { process(rpc); }, 0);
},
/**
* Helper method to get the protocol://host:port of an input URL.
*/
getOrigin: getOrigin,
/**
* Internal-only method used to initialize gadgets.rpc.
*/
init: function() {
// Conduct any global setup necessary for the chosen transport.
// Do so after gadgets.rpc definition to allow transport to access
// gadgets.rpc methods.
if (transport.init(process, transportReady) === false) {
transport = fallbackTransport;
}
},
/** Exported constant, for use by transports only. */
ACK: ACK
};
}();
// Initialize library/transport.
gadgets.rpc.init();
| features/src/main/javascript/features/rpc/rpc.js | /*
* 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.
*/
/**
* @fileoverview Remote procedure call library for gadget-to-container,
* container-to-gadget, and gadget-to-gadget (thru container) communication.
*/
var gadgets = gadgets || {};
/**
* gadgets.rpc Transports
*
* All transports are stored in object gadgets.rpctx, and are provided
* to the core gadgets.rpc library by various build rules.
*
* Transports used by core gadgets.rpc code to actually pass messages.
* each transport implements the same interface exposing hooks that
* the core library calls at strategic points to set up and use
* the transport.
*
* The methods each transport must implement are:
* + getCode(): returns a string identifying the transport. For debugging.
* + isParentVerifiable(): indicates (via boolean) whether the method
* has the property that its relay URL verifies for certain the
* receiver's protocol://host:port.
* + init(processFn, readyFn): Performs any global initialization needed. Called
* before any other gadgets.rpc methods are invoked. processFn is
* the function in gadgets.rpc used to process an rpc packet. readyFn is
* a function that must be called when the transport is ready to send
* and receive messages bidirectionally. Returns
* true if successful, false otherwise.
* + setup(receiverId, token): Performs per-receiver initialization, if any.
* receiverId will be '..' for gadget-to-container. Returns true if
* successful, false otherwise.
* + call(targetId, from, rpc): Invoked to send an actual
* message to the given targetId, with the given serviceName, from
* the sender identified by 'from'. Payload is an rpc packet. Returns
* true if successful, false otherwise.
*/
/**
* @static
* @class Provides operations for making rpc calls.
* @name gadgets.rpc
*/
gadgets.rpc = function() {
// General constants.
var CALLBACK_NAME = '__cb';
var DEFAULT_NAME = '';
// Special service name for acknowledgements.
var ACK = '__ack';
// Timeout and number of setup attempts between each
// for when setAuthToken is called before the target it specifies exists.
var SETUP_FRAME_TIMEOUT = 500;
var SETUP_FRAME_MAX_TRIES = 10;
var services = {};
var relayUrl = {};
var useLegacyProtocol = {};
var authToken = {};
var callId = 0;
var callbacks = {};
var setup = {};
var sameDomain = {};
var params = {};
var receiverTx = {};
var earlyRpcQueue = {};
// isGadget =~ isChild for the purposes of rpc (used only in setup).
var isGadget = (window.top !== window.self);
var fallbackTransport = gadgets.rpctx.ifpc;
// Load the authentication token for speaking to the container
// from the gadget's parameters, or default to '0' if not found.
if (gadgets.util) {
params = gadgets.util.getUrlParameters();
}
authToken['..'] = params.rpctoken || params.ifpctok || 0;
// Indicates whether to support early-message queueing, which is designed
// to ensure that all messages sent by gadgets.rpc.call, irrespective
// when they were made (before/after setAuthToken, before/after transport
// setup complete), are sent. Hiding behind a query param to allow opt-in
// for a time while this technique is proven.
var useEarlyQueueing = (params['rpc_earlyq'] === "1");
/*
* Return a transport representing the best available cross-domain
* message-passing mechanism available to the browser.
*
* Transports are selected on a cascading basis determined by browser
* capability and other checks. The order of preference is:
* 1. wpm: Uses window.postMessage standard.
* 2. dpm: Uses document.postMessage, similar to wpm but pre-standard.
* 3. nix: Uses IE-specific browser hacks.
* 4. rmr: Signals message passing using relay file's onresize handler.
* 5. fe: Uses FF2-specific window.frameElement hack.
* 6. ifpc: Sends messages via active load of a relay file.
*
* See each transport's commentary/documentation for details.
*/
function getTransport() {
return typeof window.postMessage === 'function' ? gadgets.rpctx.wpm :
typeof window.postMessage === 'object' ? gadgets.rpctx.wpm :
window.ActiveXObject ? gadgets.rpctx.nix :
navigator.userAgent.indexOf('WebKit') > 0 ? gadgets.rpctx.rmr :
navigator.product === 'Gecko' ? gadgets.rpctx.frameElement :
gadgets.rpctx.ifpc;
}
/**
* Function passed to, and called by, a transport indicating it's ready to
* send and receive messages.
*/
function transportReady(receiverId, readySuccess) {
var tx = transport;
if (!readySuccess) {
tx = fallbackTransport;
}
receiverTx[receiverId] = tx;
// If there are any early-queued messages, send them now directly through
// the needed transport. This queue will only have contents if
// useEarlyQueueing === true (see call method).
var earlyQueue = earlyRpcQueue[receiverId] || [];
for (var i = 0; i < earlyQueue.length; ++i) {
var rpc = earlyQueue[i];
// There was no auth/rpc token set before, so set it now.
rpc.t = gadgets.rpc.getAuthToken(receiverId);
tx.call(receiverId, rpc.f, rpc);
}
// Clear the queue so it won't be sent again.
earlyRpcQueue[receiverId] = [];
}
/**
* Helper function to process an RPC request
* @param {Object} rpc RPC request object
* @private
*/
function process(rpc) {
//
// RPC object contents:
// s: Service Name
// f: From
// c: The callback ID or 0 if none.
// a: The arguments for this RPC call.
// t: The authentication token.
//
if (rpc && typeof rpc.s === 'string' && typeof rpc.f === 'string' &&
rpc.a instanceof Array) {
// Validate auth token.
if (authToken[rpc.f]) {
// We don't do type coercion here because all entries in the authToken
// object are strings, as are all url params. See setAuthToken(...).
if (authToken[rpc.f] !== rpc.t) {
throw new Error("Invalid auth token. " +
authToken[rpc.f] + " vs " + rpc.t);
}
}
if (rpc.s === ACK) {
// Acknowledgement API, used to indicate a receiver is ready.
window.setTimeout(function() { transportReady(rpc.f, true); }, 0);
return;
}
// If there is a callback for this service, attach a callback function
// to the rpc context object for asynchronous rpc services.
//
// Synchronous rpc request handlers should simply ignore it and return a
// value as usual.
// Asynchronous rpc request handlers, on the other hand, should pass its
// result to this callback function and not return a value on exit.
//
// For example, the following rpc handler passes the first parameter back
// to its rpc client with a one-second delay.
//
// function asyncRpcHandler(param) {
// var me = this;
// setTimeout(function() {
// me.callback(param);
// }, 1000);
// }
if (rpc.c) {
rpc.callback = function(result) {
gadgets.rpc.call(rpc.f, CALLBACK_NAME, null, rpc.c, result);
};
}
// Call the requested RPC service.
var result = (services[rpc.s] ||
services[DEFAULT_NAME]).apply(rpc, rpc.a);
// If the rpc request handler returns a value, immediately pass it back
// to the callback. Otherwise, do nothing, assuming that the rpc handler
// will make an asynchronous call later.
if (rpc.c && typeof result !== 'undefined') {
gadgets.rpc.call(rpc.f, CALLBACK_NAME, null, rpc.c, result);
}
}
}
/**
* Helper method returning a canonicalized protocol://host[:port] for
* a given input URL, provided as a string. Used to compute convenient
* relay URLs and to determine whether a call is coming from the same
* domain as its receiver (bypassing the try/catch capability detection
* flow, thereby obviating Firebug and other tools reporting an exception).
*
* @param {string} url Base URL to canonicalize.
*/
function getOrigin(url) {
if (!url) {
return "";
}
url = url.toLowerCase();
if (url.indexOf("//") == 0) {
url = window.location.protocol + ":" + url;
}
if (url.indexOf("http://") != 0 &&
url.indexOf("https://") != 0) {
// Assumed to be schemaless. Default to current protocol.
url = window.location.protocol + "://" + url;
}
// At this point we guarantee that "://" is in the URL and defines
// current protocol. Skip past this to search for host:port.
var host = url.substring(url.indexOf("://") + 3);
// Find the first slash char, delimiting the host:port.
var slashPos = host.indexOf("/");
if (slashPos != -1) {
host = host.substring(0, slashPos);
}
var protocol = url.substring(0, url.indexOf("://"));
// Use port only if it's not default for the protocol.
var portStr = "";
var portPos = host.indexOf(":");
if (portPos != -1) {
var port = host.substring(portPos + 1);
host = host.substring(0, portPos);
if ((protocol === "http" && port !== "80") ||
(protocol === "https" && port !== "443")) {
portStr = ":" + port;
}
}
// Return <protocol>://<host>[<port>]
return protocol + "://" + host + portStr;
}
// Pick the most efficient RPC relay mechanism.
var transport = getTransport();
// Create the Default RPC handler.
services[DEFAULT_NAME] = function() {
gadgets.warn('Unknown RPC service: ' + this.s);
};
// Create a Special RPC handler for callbacks.
services[CALLBACK_NAME] = function(callbackId, result) {
var callback = callbacks[callbackId];
if (callback) {
delete callbacks[callbackId];
callback(result);
}
};
/**
* Conducts any frame-specific work necessary to setup
* the channel type chosen. This method is called when
* the container page first registers the gadget in the
* RPC mechanism. Gadgets, in turn, will complete the setup
* of the channel once they send their first messages.
*/
function setupFrame(frameId, token) {
if (setup[frameId] === true) {
return;
}
if (typeof setup[frameId] === 'undefined') {
setup[frameId] = 0;
}
var tgtFrame = document.getElementById(frameId);
if (frameId === '..' || tgtFrame != null) {
if (transport.setup(frameId, token) === true) {
setup[frameId] = true;
return;
}
}
if (setup[frameId] !== true && setup[frameId]++ < SETUP_FRAME_MAX_TRIES) {
// Try again in a bit, assuming that frame will soon exist.
window.setTimeout(function() { setupFrame(frameId, token) },
SETUP_FRAME_TIMEOUT);
} else {
// Fail: fall back.
transport = fallbackTransport;
setup[frameId] = true;
}
}
/**
* Attempts to make an rpc by calling the target's receive method directly.
* This works when gadgets are rendered on the same domain as their container,
* a potentially useful optimization for trusted content which keeps
* RPC behind a consistent interface.
* @param {String} target Module id of the rpc service provider
* @param {String} from Module id of the caller (this)
* @param {String} callbackId Id of the call
* @param {String} rpcData JSON-encoded RPC payload
* @return
*/
function callSameDomain(target, rpc) {
if (typeof sameDomain[target] === 'undefined') {
// Seed with a negative, typed value to avoid
// hitting this code path repeatedly.
sameDomain[target] = false;
var targetRelay = gadgets.rpc.getRelayUrl(target);
if (getOrigin(targetRelay) !== getOrigin(window.location.href)) {
// Not worth trying -- avoid the error and just return.
return false;
}
var targetEl = null;
if (target === '..') {
targetEl = parent;
} else {
targetEl = frames[target];
}
try {
// If this succeeds, then same-domain policy applied
sameDomain[target] = targetEl.gadgets.rpc.receiveSameDomain;
} catch (e) {
// Shouldn't happen due to origin check. Caught to emit
// more meaningful error to the caller.
gadgets.error("Same domain call failed: parent= incorrectly set.");
}
}
if (typeof sameDomain[target] === 'function') {
// Call target's receive method
sameDomain[target](rpc);
return true;
}
return false;
}
// gadgets.config might not be available, such as when serving container js.
if (isGadget && gadgets.config) {
/**
* Initializes gadget to container RPC params from the provided configuration.
*/
function init(config) {
var configRpc = config ? config.rpc : {};
var parentRelayUrl = configRpc.parentRelayUrl;
// Allow for wild card parent relay files as long as it's from a
// white listed domain. This is enforced by the rendering servlet.
if (parentRelayUrl.substring(0, 7) !== 'http://' &&
parentRelayUrl.substring(0, 8) !== 'https://' &&
parentRelayUrl.substring(0, 2) !== '//') {
// Relative path: we append to the parent.
// We're relying on the server validating the parent parameter in this
// case. Because of this, parent may only be passed in the query, not fragment.
if (params.parent !== "") {
// Otherwise, relayUrl['..'] will be null, signaling transport
// code to ignore rpc calls since they cannot work without a
// relay URL with host qualification.
parentRelayUrl = getOrigin(params.parent) + parentRelayUrl;
}
}
relayUrl['..'] = parentRelayUrl;
var useLegacy = !!configRpc.useLegacyProtocol;
useLegacyProtocol['..'] = useLegacy;
if (useLegacy) {
transport = gadgets.rpctx.ifpc;
transport.init(process, transportReady);
}
// Here, we add a hook for the transport to actively set up
// gadget -> container communication. Running here ensures
// that relayUri info will be available.
if (transport.setup('..') === false) {
transport = fallbackTransport;
}
}
var requiredConfig = {
parentRelayUrl : gadgets.config.NonEmptyStringValidator
};
gadgets.config.register("rpc", requiredConfig, init);
}
return /** @scope gadgets.rpc */ {
/**
* Registers an RPC service.
* @param {String} serviceName Service name to register.
* @param {Function} handler Service handler.
*
* @member gadgets.rpc
*/
register: function(serviceName, handler) {
if (serviceName === CALLBACK_NAME || serviceName === ACK) {
throw new Error("Cannot overwrite callback/ack service");
}
if (serviceName === DEFAULT_NAME) {
throw new Error("Cannot overwrite default service:"
+ " use registerDefault");
}
services[serviceName] = handler;
},
/**
* Unregisters an RPC service.
* @param {String} serviceName Service name to unregister.
*
* @member gadgets.rpc
*/
unregister: function(serviceName) {
if (serviceName === CALLBACK_NAME || serviceName === ACK) {
throw new Error("Cannot delete callback/ack service");
}
if (serviceName === DEFAULT_NAME) {
throw new Error("Cannot delete default service:"
+ " use unregisterDefault");
}
delete services[serviceName];
},
/**
* Registers a default service handler to processes all unknown
* RPC calls which raise an exception by default.
* @param {Function} handler Service handler.
*
* @member gadgets.rpc
*/
registerDefault: function(handler) {
services[DEFAULT_NAME] = handler;
},
/**
* Unregisters the default service handler. Future unknown RPC
* calls will fail silently.
*
* @member gadgets.rpc
*/
unregisterDefault: function() {
delete services[DEFAULT_NAME];
},
/**
* Forces all subsequent calls to be made by a transport
* method that allows the caller to verify the message receiver
* (by way of the parent parameter, through getRelayUrl(...)).
* At present this means IFPC or WPM.
*/
forceParentVerifiable: function() {
if (!transport.isParentVerifiable()) {
transport = gadgets.rpctx.ifpc;
}
},
/**
* Calls an RPC service.
* @param {String} targetId Module Id of the RPC service provider.
* Empty if calling the parent container.
* @param {String} serviceName Service name to call.
* @param {Function|null} callback Callback function (if any) to process
* the return value of the RPC request.
* @param {*} var_args Parameters for the RPC request.
*
* @member gadgets.rpc
*/
call: function(targetId, serviceName, callback, var_args) {
targetId = targetId || '..';
// Default to the container calling.
var from = '..';
if (targetId === '..') {
from = window.name;
}
++callId;
if (callback) {
callbacks[callId] = callback;
}
var rpc = {
s: serviceName,
f: from,
c: callback ? callId : 0,
a: Array.prototype.slice.call(arguments, 3),
t: authToken[targetId],
l: useLegacyProtocol[targetId]
};
// If target is on the same domain, call method directly
if (callSameDomain(targetId, rpc)) {
return;
}
// Attempt to make call via a cross-domain transport.
var channel = useEarlyQueueing ? receiverTx[targetId] : transport;
if (!channel) {
// Not set up yet. Enqueue the rpc for such time as it is.
if (!earlyRpcQueue[targetId]) {
earlyRpcQueue[targetId] = [ rpc ];
} else {
earlyRpcQueue[targetId].push(rpc);
}
return;
}
// If we are told to use the legacy format, then we must
// default to IFPC.
if (useLegacyProtocol[targetId]) {
channel = gadgets.rpctx.ifpc;
}
if (channel.call(targetId, from, rpc) === false) {
// Fall back to IFPC. This behavior may be removed as IFPC is as well.
transport = fallbackTransport;
transport.call(targetId, from, rpc);
}
},
/**
* Gets the relay URL of a target frame.
* @param {String} targetId Name of the target frame.
* @return {String|undefined} Relay URL of the target frame.
*
* @member gadgets.rpc
*/
getRelayUrl: function(targetId) {
var url = relayUrl[targetId];
// Some RPC methods (wpm, for one) are unhappy with schemeless URLs.
if (url && url.indexOf('//') == 0) {
url = document.location.protocol + url;
}
return url;
},
/**
* Sets the relay URL of a target frame.
* @param {String} targetId Name of the target frame.
* @param {String} url Full relay URL of the target frame.
* @param {Boolean} opt_useLegacy True if this relay needs the legacy IFPC
* wire format.
*
* @member gadgets.rpc
*/
setRelayUrl: function(targetId, url, opt_useLegacy) {
relayUrl[targetId] = url;
useLegacyProtocol[targetId] = !!opt_useLegacy;
},
/**
* Sets the auth token of a target frame.
* @param {String} targetId Name of the target frame.
* @param {String} token The authentication token to use for all
* calls to or from this target id.
*
* @member gadgets.rpc
*/
setAuthToken: function(targetId, token) {
token = token || "";
// Coerce token to a String, ensuring that all authToken values
// are strings. This ensures correct comparison with URL params
// in the process(rpc) method.
authToken[targetId] = String(token);
setupFrame(targetId, token);
},
/**
* Helper method to retrieve the authToken for a given gadget.
*/
getAuthToken: function(targetId) {
return authToken[targetId];
},
/**
* Gets the RPC relay mechanism.
* @return {String} RPC relay mechanism. See above for
* a list of supported types.
*
* @member gadgets.rpc
*/
getRelayChannel: function() {
return transport.getCode();
},
/**
* Receives and processes an RPC request. (Not to be used directly.)
* Only used by IFPC.
* @param {Array.<String>} fragment An RPC request fragment encoded as
* an array. The first 4 elements are target id, source id & call id,
* total packet number, packet id. The last element stores the actual
* JSON-encoded and URI escaped packet data.
*
* @member gadgets.rpc
*/
receive: function(fragment) {
if (fragment.length > 4) {
// TODO parse fragment[1..3] to merge multi-fragment messages
process(gadgets.json.parse(
decodeURIComponent(fragment[fragment.length - 1])));
}
},
/**
* Receives and processes an RPC request sent via the same domain.
* (Not to be used directly). Converts the inbound rpc object's
* Array into a local Array to pass the process() Array test.
* @param {Object} rpc RPC object containing all request params
*/
receiveSameDomain: function(rpc) {
// Pass through to local process method but converting to a local Array
rpc.a = Array.prototype.slice.call(rpc.a);
window.setTimeout(function() { process(rpc); }, 0);
},
/**
* Helper method to get the protocol://host:port of an input URL.
*/
getOrigin: getOrigin,
/**
* Internal-only method used to initialize gadgets.rpc.
*/
init: function() {
// Conduct any global setup necessary for the chosen transport.
// Do so after gadgets.rpc definition to allow transport to access
// gadgets.rpc methods.
if (transport.init(process, transportReady) === false) {
transport = fallbackTransport;
}
},
/** Exported constant, for use by transports only. */
ACK: ACK
};
}();
// Initialize library/transport.
gadgets.rpc.init();
| No more falling back to IFPC (or other transport) given various failure conditions in initialization, setup, or calling of another transport. This makes the rpc lib much easier to debug while not removing anything that really ever had value.
Code review and other comments at:
http://codereview.appspot.com/91116
git-svn-id: 3f2e04d30bd9db331bbfc569b45e7de8c0d84ef0@794111 13f79535-47bb-0310-9956-ffa450edef68
| features/src/main/javascript/features/rpc/rpc.js | No more falling back to IFPC (or other transport) given various failure conditions in initialization, setup, or calling of another transport. This makes the rpc lib much easier to debug while not removing anything that really ever had value. | <ide><path>eatures/src/main/javascript/features/rpc/rpc.js
<ide>
<ide> // isGadget =~ isChild for the purposes of rpc (used only in setup).
<ide> var isGadget = (window.top !== window.self);
<del> var fallbackTransport = gadgets.rpctx.ifpc;
<add>
<add> // Fallback transport is simply a dummy impl that emits no errors
<add> // and logs info on calls it receives, to avoid undesired side-effects
<add> // from falling back to IFPC or some other transport.
<add> var fallbackTransport = (function() {
<add> function logFn(name) {
<add> return function() {
<add> gadgets.info("gadgets.rpc." + name + "(" +
<add> gadgets.json.stringify(arguments) +
<add> "): call ignored. [caller: " + document.location +
<add> ", isGadget: " + isGadget + "]");
<add> }
<add> }
<add> return {
<add> getCode: function() {
<add> return "noop";
<add> },
<add> isParentVerifiable: function() {
<add> return true; // Not really, but prevents transport assignment to IFPC.
<add> },
<add> init: logFn("init"),
<add> setup: logFn("setup"),
<add> call: logFn("call")
<add> }
<add> })();
<ide>
<ide> // Load the authentication token for speaking to the container
<ide> // from the gadget's parameters, or default to '0' if not found. |
|
Java | apache-2.0 | ded7472467f2babb1a1291afeada5887fd052fd2 | 0 | senseobservationsystems/sense-android-library,senseobservationsystems/sense-android-library | /**************************************************************************************************
* Copyright (C) 2010 Sense Observation Systems, Rotterdam, the Netherlands. All rights reserved. *
*************************************************************************************************/
package nl.sense_os.service.commonsense;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.zip.GZIPOutputStream;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import nl.sense_os.service.SenseServiceStub;
import nl.sense_os.service.constants.SenseDataTypes;
import nl.sense_os.service.constants.SensePrefs;
import nl.sense_os.service.constants.SensePrefs.Auth;
import nl.sense_os.service.constants.SensePrefs.Main.Advanced;
import nl.sense_os.service.constants.SenseUrls;
import nl.sense_os.service.constants.SensorData.SensorNames;
import nl.sense_os.service.push.GCMReceiver;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.util.Log;
/**
* Main interface for communicating with the CommonSense API.
*
* @author Steven Mulder <[email protected]>
*/
public class SenseApi {
private static final String TAG = "SenseApi";
private static final long CACHE_REFRESH = 1000l * 60 * 60; // 1 hour
private static SharedPreferences mainPrefs;
private static SharedPreferences authPrefs;
private static TelephonyManager telManager;
/**
* Gets a list of all registered sensors for a user at the CommonSense API. Uses caching for
* increased performance.
*
* @param context
* Application context, used for getting preferences.
* @return The list of sensors
* @throws IOException
* In case of communication failure to CommonSense
* @throws JSONException
* In case of unparseable response from CommonSense
*/
public static JSONArray getAllSensors(Context context) throws IOException, JSONException {
if (null == authPrefs) {
authPrefs = context.getSharedPreferences(SensePrefs.AUTH_PREFS, Context.MODE_PRIVATE);
}
// try to get list of sensors from the cache
try {
String cachedSensors = authPrefs.getString(Auth.SENSOR_LIST_COMPLETE, null);
long cacheTime = authPrefs.getLong(Auth.SENSOR_LIST_COMPLETE_TIME, 0);
boolean isOutdated = System.currentTimeMillis() - cacheTime > CACHE_REFRESH;
// return cached list of it is still valid
if (false == isOutdated && null != cachedSensors) {
return new JSONArray(cachedSensors);
}
} catch (Exception e) {
// unlikely to ever happen. Just get the list from CommonSense instead
Log.w(TAG, "Failed to get list of sensors from cache!", e);
}
// if we make it here, the list was not in the cache
Log.v(TAG, "List of sensor IDs is missing or outdated, refreshing...");
boolean done = false;
JSONArray result = new JSONArray();
int page = 0;
while (!done) {
// request fresh list of sensors for this device from CommonSense
String cookie = authPrefs.getString(Auth.LOGIN_COOKIE, null);
if (null == mainPrefs) {
mainPrefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS,
Context.MODE_PRIVATE);
}
boolean devMode = mainPrefs.getBoolean(Advanced.DEV_MODE, false);
if (devMode) {
Log.v(TAG, "Using development server to get registered sensors");
}
String url = devMode ? SenseUrls.DEV_ALL_SENSORS : SenseUrls.ALL_SENSORS;
url += "&page=" + page;
Map<String, String> response = SenseApi.request(context, url, null, cookie);
String responseCode = response.get("http response code");
if (!"200".equals(responseCode)) {
Log.w(TAG, "Failed to get list of sensors! Response code: " + responseCode);
throw new IOException("Incorrect response from CommonSense: " + responseCode);
}
// parse response and store the list
JSONObject content = new JSONObject(response.get("content"));
JSONArray sensorList = content.getJSONArray("sensors");
// put the sensor list in the result array
for (int i = 0; i < sensorList.length(); i++) {
result.put(sensorList.getJSONObject(i));
}
if (sensorList.length() < SenseUrls.PAGE_SIZE) {
// all sensors received
done = true;
} else {
// get the next page
page++;
}
}
// store the new sensor list
Editor authEditor = authPrefs.edit();
authEditor.putString(Auth.SENSOR_LIST_COMPLETE, result.toString());
authEditor.putLong(Auth.SENSOR_LIST_COMPLETE_TIME, System.currentTimeMillis());
authEditor.commit();
return result;
}
/**
* Gets the sensors that are connected to another sensor. Typically used
*
* @param context
* @param sensorId
* @return List of IDs for connected sensors
* @throws IOException
* @throws JSONException
*/
public static List<String> getConnectedSensors(Context context, String sensorId)
throws IOException, JSONException {
if (null == authPrefs) {
authPrefs = context.getSharedPreferences(SensePrefs.AUTH_PREFS, Context.MODE_PRIVATE);
}
if (null == mainPrefs) {
mainPrefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE);
}
// request fresh list of sensors for this device from CommonSense
String cookie = authPrefs.getString(Auth.LOGIN_COOKIE, null);
boolean devMode = mainPrefs.getBoolean(Advanced.DEV_MODE, false);
if (devMode) {
Log.v(TAG, "Using development server to get connected sensors");
}
String url = devMode ? SenseUrls.DEV_CONNECTED_SENSORS : SenseUrls.CONNECTED_SENSORS;
url = url.replace("<id>", sensorId);
Map<String, String> response = SenseApi.request(context, url, null, cookie);
String responseCode = response.get("http response code");
if (!"200".equals(responseCode)) {
Log.w(TAG, "Failed to get list of connected sensors! Response code: " + responseCode);
throw new IOException("Incorrect response from CommonSense: " + responseCode);
}
// parse response and store the list
JSONObject content = new JSONObject(response.get("content"));
JSONArray sensorList = content.getJSONArray("sensors");
List<String> result = new ArrayList<String>();
for (int i = 0; i < sensorList.length(); i++) {
JSONObject sensor = sensorList.getJSONObject(i);
result.add(sensor.getString("id"));
}
return result;
}
/**
* @param context
* Context for accessing phone details
* @return The default device type, i.e. the phone's model String
*/
public static String getDefaultDeviceType(Context context) {
if (null == authPrefs) {
authPrefs = context.getSharedPreferences(SensePrefs.AUTH_PREFS, Context.MODE_PRIVATE);
}
return authPrefs.getString(Auth.DEVICE_TYPE, Build.MODEL);
}
/**
* @param context
* Context for accessing phone details
* @return The default device UUID, e.g. the phone's IMEI String
*/
@TargetApi(9)
public static String getDefaultDeviceUuid(Context context) {
if (null == telManager) {
telManager = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE));
}
String uuid = telManager.getDeviceId();
if (null == uuid) {
// device has no IMEI, try using the Android serial code
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
uuid = Build.SERIAL;
} else {
Log.w(TAG, "Cannot get reliable device UUID!");
}
}
return uuid;
}
/**
* Get device configuration from commonSense
*
* @throws JSONException
* @throws IOException
*/
public static String getDeviceConfiguration(Context context) throws IOException, JSONException {
if (null == authPrefs) {
authPrefs = context.getSharedPreferences(SensePrefs.AUTH_PREFS, Context.MODE_PRIVATE);
}
if (null == mainPrefs) {
mainPrefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE);
}
String cookie = authPrefs.getString(Auth.LOGIN_COOKIE, null);
boolean devMode = mainPrefs.getBoolean(Advanced.DEV_MODE, false);
String url = devMode ? SenseUrls.DEV_DEVICE_UPDATE_CONFIGURATION
: SenseUrls.DEVICE_UPDATE_CONFIGURATION;
// Get the device ID
String device_id = getDeviceId(context);
url = url.replaceFirst("<id>", device_id);
Map<String, String> response = SenseApi.request(context, url, null, cookie);
String responseCode = response.get("http response code");
if (!"200".equals(responseCode)) {
Log.w(TAG, "Failed to get device configuration! Response code: " + responseCode);
throw new IOException("Incorrect response from CommonSense: " + responseCode);
}
return response.get("content");
}
/**
* Get specific configuration from commonSense
*
* @throws JSONException
* @throws IOException
*
*/
public static String getDeviceConfiguration(Context context, String configuration_id)
throws IOException, JSONException {
final SharedPreferences authPrefs = context.getSharedPreferences(SensePrefs.AUTH_PREFS,
Context.MODE_PRIVATE);
final SharedPreferences prefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS,
Context.MODE_PRIVATE);
String cookie = authPrefs.getString(Auth.LOGIN_COOKIE, null);
boolean devMode = prefs.getBoolean(Advanced.DEV_MODE, false);
String url = devMode ? SenseUrls.DEV_CONFIGURATION : SenseUrls.CONFIGURATION;
url = url.replaceFirst("<id>", configuration_id);
Map<String, String> response = SenseApi.request(context, url, null, cookie);
String responseCode = response.get("http response code");
if (!"200".equals(responseCode)) {
Log.w(TAG, "Failed to get Requirement! Response code: " + responseCode);
throw new IOException("Incorrect response from CommonSense: " + responseCode);
}
return response.get("content");
}
/**
* Get this device_id registered in common sense
*
* @param context
* @throws IOException
* @throws JSONException
*/
public static String getDeviceId(Context context) throws IOException, JSONException {
String device_id = null;
if (null == authPrefs) {
authPrefs = context.getSharedPreferences(SensePrefs.AUTH_PREFS, Context.MODE_PRIVATE);
}
if (null == mainPrefs) {
mainPrefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE);
}
String cookie = authPrefs.getString(Auth.LOGIN_COOKIE, null);
boolean devMode = mainPrefs.getBoolean(Advanced.DEV_MODE, false);
String url = devMode ? SenseUrls.DEV_DEVICES : SenseUrls.DEVICES;
Map<String, String> response = SenseApi.request(context, url, null, cookie);
String responseCode = response.get("http response code");
if (!"200".equals(responseCode)) {
Log.w(TAG, "Failed to get devices data: " + responseCode);
throw new IOException("Incorrect response from CommonSense: " + responseCode);
}
// check registration result
JSONObject res = new JSONObject(response.get("content"));
JSONArray arr = res.getJSONArray("devices");
String deviceType = getDefaultDeviceType(context);
String deviceUUID = getDefaultDeviceUuid(context);
for (int i = 0; i < arr.length(); i++) {
JSONObject row = arr.getJSONObject(i);
String cid = row.getString("id");
String ctype = row.getString("type");
String cuuid = row.getString("uuid");
if (deviceType.equals(ctype) && deviceUUID.equals(cuuid)) {
device_id = cid;
break;
}
}
return device_id;
}
private static List<JSONObject> getMatchingSensors(Context context, String name,
String description, String dataType) throws IOException, JSONException {
// get list of all registered sensors for this device
JSONArray sensors = getAllSensors(context);
// check sensors with similar names and descriptions in the list
List<JSONObject> result = new ArrayList<JSONObject>();
JSONObject sensor;
for (int i = 0; i < sensors.length(); i++) {
sensor = (JSONObject) sensors.get(i);
if (sensor.getString("name").equalsIgnoreCase(name)
&& ((null == description) || sensor.getString("device_type").equalsIgnoreCase(
description))
&& ((null == dataType) || sensor.getString("data_type").equalsIgnoreCase(
dataType))) {
result.add(sensor);
} else if (name.equals(SensorNames.ACCELEROMETER) || name.equals(SensorNames.ORIENT)
|| name.equals(SensorNames.GYRO) || name.equals(SensorNames.LIN_ACCELERATION)
|| name.equals(SensorNames.MAGNETIC_FIELD)
|| name.equals(SensorNames.ACCELEROMETER_EPI)
|| name.equals(SensorNames.ACCELEROMETER_BURST)
|| name.equals(SensorNames.GYRO_BURST) || name.equals(SensorNames.LINEAR_BURST)) {
// special case to take care of changed motion sensor descriptions since Gingerbread
if (name.equals(sensor.getString("name"))) {
// use inexact match
result.add(sensor);
}
}
}
return result;
}
/**
* Gets the sensor ID at CommonSense , which can be used to modify the sensor information and
* data.
*
* @param context
* Context for getting preferences
* @param name
* Sensor name, to match with registered sensors.
* @param description
* Sensor description (previously 'device_type'), to match with registered sensors.
* @param dataType
* Sensor data type, to match with registered sensors.
* @param deviceUuid
* (Optional) UUID of the device that should hold the sensor.
* @return String with the sensor's ID, or null if the sensor does not exist at CommonSense
* (yet).
* @throws IOException
* If the request to CommonSense failed.
* @throws JSONException
* If the response from CommonSense could not be parsed.
*/
public static String getSensorId(Context context, String name, String description,
String dataType, String deviceUuid) throws IOException, JSONException {
// get list of sensors with matching description
List<JSONObject> sensors = getMatchingSensors(context, name, description, dataType);
// check the devices that the sensors are connected to
String id = null;
JSONObject device;
for (JSONObject sensor : sensors) {
if (null != deviceUuid) {
// check if the device UUID matches
device = sensor.optJSONObject("device");
if (null != device && deviceUuid.equals(device.optString("uuid"))) {
id = sensor.getString("id");
break;
}
} else {
// we do not care about the device, just accept the first match we find
id = sensor.getString("id");
break;
}
}
return id;
}
/**
* Gets the URL at CommonSense to which the data must be sent.
*
* @param context
* Context for getting preferences
* @param name
* Sensor name, to match with registered sensors.
* @param description
* Sensor description (previously 'device_type'), to match with registered sensors.
* @param dataType
* Sensor data type, to match with registered sensors.
* @param deviceUuid
* (Optional) UUID of the device that holds the sensor. Set null to use the default
* device.
* @return String with the sensor's URL, or null if sensor does not have an ID (yet)
* @throws JSONException
* If there was unexpected response getting the sensor ID.
* @throws IOException
* If there was a problem during communication with CommonSense.
*/
public static String getSensorUrl(Context context, String name, String description,
String dataType, String deviceUuid) throws IOException, JSONException {
String id = getSensorId(context, name, description, dataType, deviceUuid);
if (id == null) {
Log.w(TAG, "Failed to get URL for sensor '" + name + "': sensor ID is not available");
return null;
}
if (null == mainPrefs) {
mainPrefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE);
}
boolean devMode = mainPrefs.getBoolean(Advanced.DEV_MODE, false);
// found the right sensor
if (dataType.equals(SenseDataTypes.FILE)) {
String url = devMode ? SenseUrls.DEV_SENSOR_FILE : SenseUrls.SENSOR_FILE;
return url.replaceFirst("<id>", id);
} else {
String url = devMode ? SenseUrls.DEV_SENSOR_DATA : SenseUrls.SENSOR_DATA;
return url.replaceFirst("<id>", id);
}
}
/**
* @param context
* Context for getting preferences
* @return The current CommonSense session ID
* @throws IllegalAccessException
* if the app ID is not valid
*/
public static String getSessionId(Context context) throws IllegalAccessException {
if (null == authPrefs) {
authPrefs = context.getSharedPreferences(SensePrefs.AUTH_PREFS, Context.MODE_PRIVATE);
}
return authPrefs.getString(Auth.LOGIN_COOKIE, null);
}
/**
* Gets user details from CommonSense
*
* @param context
* Context for getting preferences
* @return JSONObject with user if successful, null otherwise
* @throws JSONException
* In case of unparseable response from CommonSense
* @throws IOException
* In case of communication failure to CommonSense
*/
public static JSONObject getUser(Context context) throws IOException, JSONException {
if (null == authPrefs) {
authPrefs = context.getSharedPreferences(SensePrefs.AUTH_PREFS, Context.MODE_PRIVATE);
}
if (null == mainPrefs) {
mainPrefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE);
}
String cookie = authPrefs.getString(Auth.LOGIN_COOKIE, null);
boolean devMode = mainPrefs.getBoolean(Advanced.DEV_MODE, false);
String url = devMode ? SenseUrls.DEV_GET_CURRENT_USER : SenseUrls.GET_CURRENT_USER;
// perform actual request
Map<String, String> response = SenseApi.request(context, url, null, cookie);
String responseCode = response.get("http response code");
JSONObject result = null;
if ("200".equalsIgnoreCase(responseCode)) {
result = new JSONObject(response.get("content")).getJSONObject("user");
} else {
Log.w(TAG, "Failed to get user! Response code: " + responseCode);
throw new IOException("Incorrect response from CommonSense: " + responseCode);
}
return result;
}
/**
* @param hashMe
* "clear" password String to be hashed before sending it to CommonSense
* @return Hashed String
*/
public static String hashPassword(String hashMe) {
final byte[] unhashedBytes = hashMe.getBytes();
try {
final MessageDigest algorithm = MessageDigest.getInstance("MD5");
algorithm.reset();
algorithm.update(unhashedBytes);
final byte[] hashedBytes = algorithm.digest();
final StringBuffer hexString = new StringBuffer();
for (final byte element : hashedBytes) {
final String hex = Integer.toHexString(0xFF & element);
if (hex.length() == 1) {
hexString.append(0);
}
hexString.append(hex);
}
return hexString.toString();
} catch (final NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
/**
* Joins a group
*
* @param context
* Context for getting preferences
* @param groupId
* Id of the group to join
* @return true if joined successfully, false otherwise
* @throws JSONException
* In case of unparseable response from CommonSense
* @throws IOException
* In case of communication failure to CommonSense
*/
public static boolean joinGroup(Context context, String groupId) throws JSONException,
IOException {
if (null == authPrefs) {
authPrefs = context.getSharedPreferences(SensePrefs.AUTH_PREFS, Context.MODE_PRIVATE);
}
if (null == mainPrefs) {
mainPrefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE);
}
String cookie = authPrefs.getString(Auth.LOGIN_COOKIE, null);
boolean devMode = mainPrefs.getBoolean(Advanced.DEV_MODE, false);
// get userId
String userId = getUser(context).getString("id");
String url = devMode ? SenseUrls.DEV_JOIN_GROUP : SenseUrls.JOIN_GROUP;
url = url.replaceFirst("<id>", groupId);
// create JSON object to POST
final JSONObject data = new JSONObject();
final JSONArray users = new JSONArray();
final JSONObject item = new JSONObject();
final JSONObject user = new JSONObject();
user.put("id", userId);
item.put("user", user);
users.put(item);
data.put("users", users);
// perform actual request
Map<String, String> response = SenseApi.request(context, url, data, cookie);
String responseCode = response.get("http response code");
boolean result = false;
if ("201".equalsIgnoreCase(responseCode)) {
result = true;
} else {
Log.w(TAG, "Failed to join group! Response code: " + responseCode + "Response: "
+ response);
result = false;
}
return result;
}
/**
* Tries to log in at CommonSense using the supplied username and password. After login, the
* cookie containing the session ID is stored in the preferences.
*
* @param context
* Context for getting preferences
* @param username
* Username for authentication
* @param password
* Hashed password for authentication
* @return 0 if login completed successfully, -2 if login was forbidden, and -1 for any other
* errors.
* @throws JSONException
* In case of unparseable response from CommonSense
* @throws IOException
* In case of communication failure to CommonSense
* @see SenseServiceStub#changeLogin(String, String, nl.sense_os.service.ISenseServiceCallback)
*/
public static int login(Context context, String username, String password)
throws JSONException, IOException {
// preferences
if (null == authPrefs) {
authPrefs = context.getSharedPreferences(SensePrefs.AUTH_PREFS, Context.MODE_PRIVATE);
}
if (null == mainPrefs) {
mainPrefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE);
}
boolean devMode = mainPrefs.getBoolean(Advanced.DEV_MODE, false);
if (devMode) {
Log.v(TAG, "Using development server to log in");
}
final String url = devMode ? SenseUrls.DEV_LOGIN : SenseUrls.LOGIN;
final JSONObject user = new JSONObject();
user.put("username", username);
user.put("password", password);
// perform actual request
Map<String, String> response = request(context, url, user, null);
// if response code is not 200 (OK), the login was incorrect
String responseCode = response.get("http response code");
int result = -1;
if ("403".equalsIgnoreCase(responseCode)) {
Log.w(TAG, "CommonSense login refused! Response: forbidden!");
result = -2;
} else if (!"200".equalsIgnoreCase(responseCode)) {
Log.w(TAG, "CommonSense login failed! Response: " + responseCode);
result = -1;
} else {
// received 200 response
result = 0;
}
// get the cookie from the response
String cookie = response.get("set-cookie");
if (result == 0 && response.get("set-cookie") == null) {
// something went horribly wrong
Log.w(TAG, "CommonSense login failed: no cookie received?!");
result = -1;
}
// handle result
Editor authEditor = authPrefs.edit();
switch (result) {
case 0: // logged in
authEditor.putString(Auth.LOGIN_COOKIE, cookie);
authEditor.commit();
break;
case -1: // error
break;
case -2: // unauthorized
authEditor.remove(Auth.LOGIN_COOKIE);
authEditor.commit();
break;
default:
Log.e(TAG, "Unexpected login result: " + result);
}
return result;
}
/**
* Push GCM Registration ID for current device
*
* @param context
* Application context, used to read preferences.
* @param registrationId
* Registration ID given by google
* @throws IOException
* @throws JSONException
* @throws IllegalStateException
*/
public static void registerGCMId(Context context, String registrationId) throws IOException,
JSONException {
if (null == authPrefs) {
authPrefs = context.getSharedPreferences(SensePrefs.AUTH_PREFS, Context.MODE_PRIVATE);
}
if (null == mainPrefs) {
mainPrefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE);
}
// Check if already synced with common sense
String pref_registration_id = authPrefs.getString(Auth.GCM_REGISTRATION_ID, "");
if (registrationId.equals(pref_registration_id)) {
// GCM registration id is already sync with commonSense
return;
}
String cookie = authPrefs.getString(Auth.LOGIN_COOKIE, null);
boolean devMode = mainPrefs.getBoolean(Advanced.DEV_MODE, false);
String url = devMode ? SenseUrls.DEV_REGISTER_GCM_ID : SenseUrls.REGISTER_GCM_ID;
// Get the device ID
String device_id = getDeviceId(context);
if (device_id == null) {
// register GCM ID failed, can not get the device ID for this device
return;
}
url = url.replaceFirst("<id>", device_id);
final JSONObject data = new JSONObject();
data.put("registration_id", registrationId);
Map<String, String> response = SenseApi.request(context, url, data, cookie);
String responseCode = response.get("http response code");
if (!"200".equals(responseCode)) {
throw new IOException("Incorrect response from CommonSense: " + responseCode);
}
// check registration result
JSONObject res = new JSONObject(response.get("content"));
if (!registrationId.equals(res.getJSONObject("device").getString(GCMReceiver.KEY_GCM_ID))) {
throw new IllegalStateException("GCM registration_id not match with response");
}
Editor authEditor = authPrefs.edit();
authEditor.putString(Auth.GCM_REGISTRATION_ID, registrationId);
authEditor.commit();
}
/**
* Registers a new sensor for this device at CommonSense. Also connects the sensor to this
* device.
*
* @param context
* The application context, used to retrieve preferences.
* @param name
* The name of the sensor.
* @param displayName
* The sensor's pretty display name.
* @param description
* The sensor description (previously "device_type").
* @param dataType
* The sensor data type.
* @param value
* An example sensor value, used to determine the data structure for JSON type
* sensors.
* @param deviceType
* (Optional) Type of the device that holds the sensor. Set null to use the default
* device.
* @param deviceUuid
* (Optional) UUID of the device that holds the sensor. Set null to use the default
* device.
* @return The new sensor ID at CommonSense, or <code>null</code> if the registration failed.
* @throws JSONException
* In case of invalid sensor details or if the request returned unparseable
* response.
* @throws IOException
* In case of communication failure during creation of the sensor.
*/
public static String registerSensor(Context context, String name, String displayName,
String description, String dataType, String value, String deviceType, String deviceUuid)
throws JSONException, IOException {
if (null == authPrefs) {
authPrefs = context.getSharedPreferences(SensePrefs.AUTH_PREFS, Context.MODE_PRIVATE);
}
if (null == mainPrefs) {
mainPrefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE);
}
String cookie = authPrefs.getString(Auth.LOGIN_COOKIE, null);
boolean devMode = mainPrefs.getBoolean(Advanced.DEV_MODE, false);
// prepare request to create new sensor
String url = devMode ? SenseUrls.DEV_CREATE_SENSOR : SenseUrls.CREATE_SENSOR;
JSONObject postData = new JSONObject();
JSONObject sensor = new JSONObject();
sensor.put("name", name);
sensor.put("device_type", description);
sensor.put("display_name", displayName);
sensor.put("pager_type", "");
sensor.put("data_type", dataType);
if (dataType.compareToIgnoreCase(SenseDataTypes.JSON) == 0
|| dataType.compareToIgnoreCase(SenseDataTypes.JSON_TIME_SERIES) == 0) {
JSONObject dataStructJSon = null;
try {
dataStructJSon = new JSONObject(value);
JSONArray fieldNames = dataStructJSon.names();
for (int x = 0; x < fieldNames.length(); x++) {
String fieldName = fieldNames.getString(x);
int start = dataStructJSon.get(fieldName).getClass().getName().lastIndexOf(".");
dataStructJSon.put(fieldName, dataStructJSon.get(fieldName).getClass()
.getName().substring(start + 1));
}
} catch (JSONException e) {
// apparently the data structure cannot be parsed from the value
dataStructJSon = new JSONObject();
}
sensor.put("data_structure", dataStructJSon.toString().replaceAll("\"", "\\\""));
}
postData.put("sensor", sensor);
// perform actual request
Map<String, String> response = request(context, url, postData, cookie);
// check response code
String code = response.get("http response code");
if (!"201".equals(code)) {
Log.w(TAG, "Failed to register sensor at CommonSense! Response code: " + code);
throw new IOException("Incorrect response from CommonSense: " + code);
}
// retrieve the newly created sensor ID
String locationHeader = response.get("location");
String[] split = locationHeader.split("/");
String id = split[split.length - 1];
// get device properties from preferences, so it matches the properties in CommonSense
if (null == deviceUuid) {
deviceUuid = getDefaultDeviceUuid(context);
deviceType = getDefaultDeviceType(context);
}
// Add sensor to this device at CommonSense
url = devMode ? SenseUrls.DEV_ADD_SENSOR_TO_DEVICE : SenseUrls.ADD_SENSOR_TO_DEVICE;
url = url.replaceFirst("<id>", id);
postData = new JSONObject();
JSONObject device = new JSONObject();
device.put("type", deviceType);
device.put("uuid", deviceUuid);
postData.put("device", device);
response = request(context, url, postData, cookie);
// check response code
code = response.get("http response code");
if (!"201".equals(code)) {
Log.w(TAG, "Failed to add sensor to device at CommonSense! Response code: " + code);
throw new IOException("Incorrect response from CommonSense: " + code);
}
// store the new sensor in the preferences
sensor.put("id", id);
sensor.put("device", device);
JSONArray sensors = getAllSensors(context);
sensors.put(sensor);
Editor authEditor = authPrefs.edit();
authEditor.putString(Auth.SENSOR_LIST_COMPLETE, sensors.toString());
authEditor.commit();
Log.v(TAG, "Created sensor: '" + name + "' for device: '" + deviceType + "'");
// return the new sensor ID
return id;
}
/**
* Tries to register a new user at CommonSense.
*
* @param context
* Context for getting preferences
* @param username
* Username to register
* @param password
* Hashed password for the new user
* @return 0 if registration completed successfully, -2 if the user already exists, and -1 for
* any other unexpected responses.
* @throws JSONException
* In case of unparseable response from CommonSense
* @throws IOException
* In case of communication failure to CommonSense
* @see SenseServiceStub#register(String, String, String, String, String, String, String,
* String, String, nl.sense_os.service.ISenseServiceCallback)
*/
public static int registerUser(Context context, String username, String password, String name,
String surname, String email, String mobile) throws JSONException, IOException {
if (null == mainPrefs) {
mainPrefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE);
}
boolean devMode = mainPrefs.getBoolean(Advanced.DEV_MODE, false);
final String url = devMode ? SenseUrls.DEV_REG : SenseUrls.REG;
// create JSON object to POST
final JSONObject data = new JSONObject();
final JSONObject user = new JSONObject();
user.put("username", username);
user.put("password", password);
if (null != name) {
user.put("name", name);
}
if (null != surname) {
user.put("surname", surname);
}
if (null != email) {
user.put("email", email);
}
if (null != mobile) {
user.put("mobile", mobile);
}
data.put("user", user);
// perform actual request
Map<String, String> response = SenseApi.request(context, url, data, null);
String responseCode = response.get("http response code");
int result = -1;
if ("201".equalsIgnoreCase(responseCode)) {
result = 0;
} else if ("409".equalsIgnoreCase(responseCode)) {
Log.w(TAG, "Failed to register new user! User already exists");
result = -2;
} else {
Log.w(TAG, "Failed to register new user! Response code: " + responseCode);
result = -1;
}
return result;
}
/**
* Performs request at CommonSense API. Returns the response code, content, and headers.
*
* @param context
* Application context, used to read preferences.
* @param urlString
* Complete URL to perform request to.
* @param content
* (Optional) Content for the request. If the content is not null, the request method
* is automatically POST. The default method is GET.
* @param cookie
* (Optional) Cookie header for the request.
* @return Map with "content" and "http response code" fields, plus fields for all response
* headers.
* @throws IOException
*/
public static Map<String, String> request(Context context, String urlString,
JSONObject content, String cookie) throws IOException {
HttpURLConnection urlConnection = null;
HashMap<String, String> result = new HashMap<String, String>();
try {
// get compression preference
if (null == mainPrefs) {
mainPrefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS,
Context.MODE_PRIVATE);
}
final boolean compress = mainPrefs.getBoolean(Advanced.COMPRESS, true);
// open new URL connection channel.
URL url = new URL(urlString);
if ("https".equals(url.getProtocol().toLowerCase(Locale.ENGLISH))) {
trustAllHosts();
HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
https.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
urlConnection = https;
} else {
urlConnection = (HttpURLConnection) url.openConnection();
}
// some parameters
urlConnection.setUseCaches(false);
urlConnection.setInstanceFollowRedirects(false);
// set cookie (if available)
if (null != cookie) {
urlConnection.setRequestProperty("Cookie", cookie);
}
// send content (if available)
if (null != content) {
urlConnection.setDoOutput(true);
// When no charset is given in the Content-Type header "ISO-8859-1" should be
// assumed (see http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1).
// Because we're uploading UTF-8 the charset should be set to UTF-8.
urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
// send content
DataOutputStream printout;
if (compress) {
// do not set content size
urlConnection.setRequestProperty("Transfer-Encoding", "chunked");
urlConnection.setRequestProperty("Content-Encoding", "gzip");
GZIPOutputStream zipStream = new GZIPOutputStream(
urlConnection.getOutputStream());
printout = new DataOutputStream(zipStream);
} else {
// set content size
// The content length should be in bytes. We cannot use string length here
// because that counts the number of chars while not accounting for multibyte
// chars
int contentLength = content.toString().getBytes("UTF-8").length;
urlConnection.setFixedLengthStreamingMode(contentLength);
urlConnection.setRequestProperty("Content-Length", "" + contentLength);
printout = new DataOutputStream(urlConnection.getOutputStream());
}
// Write the string in UTF-8 encoding
printout.write(content.toString().getBytes("UTF-8"));
printout.flush();
printout.close();
}
// get response, or read error message
InputStream inputStream;
try {
inputStream = urlConnection.getInputStream();
} catch (IOException e) {
inputStream = urlConnection.getErrorStream();
}
if (null == inputStream) {
throw new IOException("could not get InputStream");
}
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream), 1024);
String line;
StringBuffer responseContent = new StringBuffer();
while ((line = reader.readLine()) != null) {
responseContent.append(line);
responseContent.append('\r');
}
result.put("content", responseContent.toString());
result.put("http response code", "" + urlConnection.getResponseCode());
// clean up
reader.close();
reader = null;
inputStream.close();
inputStream = null;
// get headers
Map<String, List<String>> headerFields = urlConnection.getHeaderFields();
String key, valueString;
List<String> value;
for (Entry<String, List<String>> entry : headerFields.entrySet()) {
key = entry.getKey();
value = entry.getValue();
if (null != key && null != value) {
key = key.toLowerCase(Locale.ENGLISH);
valueString = value.toString();
valueString = valueString.substring(1, valueString.length() - 1);
result.put(key, valueString);
}
}
return result;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}
/**
* Shares a sensor with a user or group
*
* @param context
* Context for getting preferences
* @param sensorId
* Id of the sensor to share
* @param userId
* Id of the user or group to share the sensor with
* @return true if shared successfully, false otherwise
* @throws JSONException
* In case of unparseable response from CommonSense
* @throws IOException
* In case of communication failure to CommonSense
*/
public static boolean shareSensor(Context context, String sensorId, String userId)
throws JSONException, IOException {
if (null == authPrefs) {
authPrefs = context.getSharedPreferences(SensePrefs.AUTH_PREFS, Context.MODE_PRIVATE);
}
if (null == mainPrefs) {
mainPrefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE);
}
String cookie = authPrefs.getString(Auth.LOGIN_COOKIE, null);
boolean devMode = mainPrefs.getBoolean(Advanced.DEV_MODE, false);
String url = devMode ? SenseUrls.DEV_SHARE_SENSOR : SenseUrls.SHARE_SENSOR;
url = url.replaceFirst("<id>", sensorId);
// create JSON object to POST
final JSONObject data = new JSONObject();
final JSONObject user = new JSONObject();
user.put("id", userId);
data.put("user", user);
// perform actual request
Map<String, String> response = SenseApi.request(context, url, data, cookie);
String responseCode = response.get("http response code");
boolean result = false;
if ("201".equalsIgnoreCase(responseCode)) {
result = true;
} else {
Log.w(TAG, "Failed to share sensor! Response code: " + responseCode);
result = false;
}
return result;
}
/**
* Trust every server - do not check for any certificate
*/
// TODO Solve issue with security certificate for HTTPS.
private static void trustAllHosts() {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[] {};
}
} };
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
e.printStackTrace();
}
}
}
| sense-android-library/src/nl/sense_os/service/commonsense/SenseApi.java | /**************************************************************************************************
* Copyright (C) 2010 Sense Observation Systems, Rotterdam, the Netherlands. All rights reserved. *
*************************************************************************************************/
package nl.sense_os.service.commonsense;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.zip.GZIPOutputStream;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import nl.sense_os.service.SenseServiceStub;
import nl.sense_os.service.constants.SenseDataTypes;
import nl.sense_os.service.constants.SensePrefs;
import nl.sense_os.service.constants.SensePrefs.Auth;
import nl.sense_os.service.constants.SensePrefs.Main.Advanced;
import nl.sense_os.service.constants.SenseUrls;
import nl.sense_os.service.constants.SensorData.SensorNames;
import nl.sense_os.service.push.GCMReceiver;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.util.Log;
/**
* Main interface for communicating with the CommonSense API.
*
* @author Steven Mulder <[email protected]>
*/
public class SenseApi {
private static final String TAG = "SenseApi";
private static final long CACHE_REFRESH = 1000l * 60 * 60; // 1 hour
private static SharedPreferences mainPrefs;
private static SharedPreferences authPrefs;
private static TelephonyManager telManager;
/**
* Gets a list of all registered sensors for a user at the CommonSense API. Uses caching for
* increased performance.
*
* @param context
* Application context, used for getting preferences.
* @return The list of sensors
* @throws IOException
* In case of communication failure to CommonSense
* @throws JSONException
* In case of unparseable response from CommonSense
*/
public static JSONArray getAllSensors(Context context) throws IOException, JSONException {
if (null == authPrefs) {
authPrefs = context.getSharedPreferences(SensePrefs.AUTH_PREFS, Context.MODE_PRIVATE);
}
// try to get list of sensors from the cache
try {
String cachedSensors = authPrefs.getString(Auth.SENSOR_LIST_COMPLETE, null);
long cacheTime = authPrefs.getLong(Auth.SENSOR_LIST_COMPLETE_TIME, 0);
boolean isOutdated = System.currentTimeMillis() - cacheTime > CACHE_REFRESH;
// return cached list of it is still valid
if (false == isOutdated && null != cachedSensors) {
return new JSONArray(cachedSensors);
}
} catch (Exception e) {
// unlikely to ever happen. Just get the list from CommonSense instead
Log.e(TAG, "Failed to get list of sensors from cache!", e);
}
// if we make it here, the list was not in the cache
Log.v(TAG, "List of sensor IDs is missing or outdated, refreshing...");
boolean done = false;
JSONArray result = new JSONArray();
int page = 0;
while (!done) {
// request fresh list of sensors for this device from CommonSense
String cookie = authPrefs.getString(Auth.LOGIN_COOKIE, null);
if (null == mainPrefs) {
mainPrefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS,
Context.MODE_PRIVATE);
}
boolean devMode = mainPrefs.getBoolean(Advanced.DEV_MODE, false);
if (devMode) {
Log.i(TAG, "Using development server to get registered sensors");
}
String url = devMode ? SenseUrls.DEV_ALL_SENSORS : SenseUrls.ALL_SENSORS;
url += "&page=" + page;
Map<String, String> response = SenseApi.request(context, url, null, cookie);
String responseCode = response.get("http response code");
if (!"200".equals(responseCode)) {
Log.w(TAG, "Failed to get list of sensors! Response code: " + responseCode);
throw new IOException("Incorrect response from CommonSense: " + responseCode);
}
// parse response and store the list
JSONObject content = new JSONObject(response.get("content"));
JSONArray sensorList = content.getJSONArray("sensors");
// put the sensor list in the result array
for (int i = 0; i < sensorList.length(); i++) {
result.put(sensorList.getJSONObject(i));
}
if (sensorList.length() < SenseUrls.PAGE_SIZE) {
// all sensors received
done = true;
} else {
// get the next page
page++;
}
}
// store the new sensor list
Editor authEditor = authPrefs.edit();
authEditor.putString(Auth.SENSOR_LIST_COMPLETE, result.toString());
authEditor.putLong(Auth.SENSOR_LIST_COMPLETE_TIME, System.currentTimeMillis());
authEditor.commit();
return result;
}
/**
* Gets the sensors that are connected to another sensor. Typically used
*
* @param context
* @param sensorId
* @return List of IDs for connected sensors
* @throws IOException
* @throws JSONException
*/
public static List<String> getConnectedSensors(Context context, String sensorId)
throws IOException, JSONException {
if (null == authPrefs) {
authPrefs = context.getSharedPreferences(SensePrefs.AUTH_PREFS, Context.MODE_PRIVATE);
}
if (null == mainPrefs) {
mainPrefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE);
}
// request fresh list of sensors for this device from CommonSense
String cookie = authPrefs.getString(Auth.LOGIN_COOKIE, null);
boolean devMode = mainPrefs.getBoolean(Advanced.DEV_MODE, false);
if (devMode) {
Log.i(TAG, "Using development server to get connected sensors");
}
String url = devMode ? SenseUrls.DEV_CONNECTED_SENSORS : SenseUrls.CONNECTED_SENSORS;
url = url.replace("<id>", sensorId);
Map<String, String> response = SenseApi.request(context, url, null, cookie);
String responseCode = response.get("http response code");
if (!"200".equals(responseCode)) {
Log.w(TAG, "Failed to get list of connected sensors! Response code: " + responseCode);
throw new IOException("Incorrect response from CommonSense: " + responseCode);
}
// parse response and store the list
JSONObject content = new JSONObject(response.get("content"));
JSONArray sensorList = content.getJSONArray("sensors");
List<String> result = new ArrayList<String>();
for (int i = 0; i < sensorList.length(); i++) {
JSONObject sensor = sensorList.getJSONObject(i);
result.add(sensor.getString("id"));
}
return result;
}
/**
* @param context
* Context for accessing phone details
* @return The default device type, i.e. the phone's model String
*/
public static String getDefaultDeviceType(Context context) {
if (null == authPrefs) {
authPrefs = context.getSharedPreferences(SensePrefs.AUTH_PREFS, Context.MODE_PRIVATE);
}
return authPrefs.getString(Auth.DEVICE_TYPE, Build.MODEL);
}
/**
* @param context
* Context for accessing phone details
* @return The default device UUID, e.g. the phone's IMEI String
*/
@TargetApi(9)
public static String getDefaultDeviceUuid(Context context) {
if (null == telManager) {
telManager = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE));
}
String uuid = telManager.getDeviceId();
if (null == uuid) {
// device has no IMEI, try using the Android serial code
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
uuid = Build.SERIAL;
} else {
Log.w(TAG, "Cannot get reliable device UUID!");
}
}
return uuid;
}
/**
* Get device configuration from commonSense
*
* @throws JSONException
* @throws IOException
*/
public static String getDeviceConfiguration(Context context) throws IOException, JSONException {
if (null == authPrefs) {
authPrefs = context.getSharedPreferences(SensePrefs.AUTH_PREFS, Context.MODE_PRIVATE);
}
if (null == mainPrefs) {
mainPrefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE);
}
String cookie = authPrefs.getString(Auth.LOGIN_COOKIE, null);
boolean devMode = mainPrefs.getBoolean(Advanced.DEV_MODE, false);
String url = devMode ? SenseUrls.DEV_DEVICE_UPDATE_CONFIGURATION
: SenseUrls.DEVICE_UPDATE_CONFIGURATION;
// Get the device ID
String device_id = getDeviceId(context);
url = url.replaceFirst("<id>", device_id);
Map<String, String> response = SenseApi.request(context, url, null, cookie);
String responseCode = response.get("http response code");
if (!"200".equals(responseCode)) {
Log.w(TAG, "Failed to get device configuration! Response code: " + responseCode);
throw new IOException("Incorrect response from CommonSense: " + responseCode);
}
return response.get("content");
}
/**
* Get specific configuration from commonSense
*
* @throws JSONException
* @throws IOException
*
*/
public static String getDeviceConfiguration(Context context, String configuration_id)
throws IOException, JSONException {
final SharedPreferences authPrefs = context.getSharedPreferences(SensePrefs.AUTH_PREFS,
Context.MODE_PRIVATE);
final SharedPreferences prefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS,
Context.MODE_PRIVATE);
String cookie = authPrefs.getString(Auth.LOGIN_COOKIE, null);
boolean devMode = prefs.getBoolean(Advanced.DEV_MODE, false);
String url = devMode ? SenseUrls.DEV_CONFIGURATION : SenseUrls.CONFIGURATION;
url = url.replaceFirst("<id>", configuration_id);
Map<String, String> response = SenseApi.request(context, url, null, cookie);
String responseCode = response.get("http response code");
if (!"200".equals(responseCode)) {
Log.w(TAG, "Failed to get Requirement! Response code: " + responseCode);
throw new IOException("Incorrect response from CommonSense: " + responseCode);
}
return response.get("content");
}
/**
* Get this device_id registered in common sense
*
* @param context
* @throws IOException
* @throws JSONException
*/
public static String getDeviceId(Context context) throws IOException, JSONException {
String device_id = null;
if (null == authPrefs) {
authPrefs = context.getSharedPreferences(SensePrefs.AUTH_PREFS, Context.MODE_PRIVATE);
}
if (null == mainPrefs) {
mainPrefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE);
}
String cookie = authPrefs.getString(Auth.LOGIN_COOKIE, null);
boolean devMode = mainPrefs.getBoolean(Advanced.DEV_MODE, false);
String url = devMode ? SenseUrls.DEV_DEVICES : SenseUrls.DEVICES;
Map<String, String> response = SenseApi.request(context, url, null, cookie);
String responseCode = response.get("http response code");
if (!"200".equals(responseCode)) {
Log.w(TAG, "Failed to get devices data: " + responseCode);
throw new IOException("Incorrect response from CommonSense: " + responseCode);
}
// check registration result
JSONObject res = new JSONObject(response.get("content"));
JSONArray arr = res.getJSONArray("devices");
String deviceType = getDefaultDeviceType(context);
String deviceUUID = getDefaultDeviceUuid(context);
for (int i = 0; i < arr.length(); i++) {
JSONObject row = arr.getJSONObject(i);
String cid = row.getString("id");
String ctype = row.getString("type");
String cuuid = row.getString("uuid");
if (deviceType.equals(ctype) && deviceUUID.equals(cuuid)) {
device_id = cid;
break;
}
}
return device_id;
}
private static List<JSONObject> getMatchingSensors(Context context, String name,
String description, String dataType) throws IOException, JSONException {
// get list of all registered sensors for this device
JSONArray sensors = getAllSensors(context);
// check sensors with similar names and descriptions in the list
List<JSONObject> result = new ArrayList<JSONObject>();
JSONObject sensor;
for (int i = 0; i < sensors.length(); i++) {
sensor = (JSONObject) sensors.get(i);
if (sensor.getString("name").equalsIgnoreCase(name)
&& ((null == description) || sensor.getString("device_type").equalsIgnoreCase(
description))
&& ((null == dataType) || sensor.getString("data_type").equalsIgnoreCase(
dataType))) {
result.add(sensor);
} else if (name.equals(SensorNames.ACCELEROMETER) || name.equals(SensorNames.ORIENT)
|| name.equals(SensorNames.GYRO) || name.equals(SensorNames.LIN_ACCELERATION)
|| name.equals(SensorNames.MAGNETIC_FIELD)
|| name.equals(SensorNames.ACCELEROMETER_EPI)
|| name.equals(SensorNames.ACCELEROMETER_BURST)
|| name.equals(SensorNames.GYRO_BURST) || name.equals(SensorNames.LINEAR_BURST)) {
// special case to take care of changed motion sensor descriptions since Gingerbread
if (name.equals(sensor.getString("name"))) {
// Log.d(TAG, "Using inexact match for '" + name + "' sensor ID...");
result.add(sensor);
}
}
}
return result;
}
/**
* Gets the sensor ID at CommonSense , which can be used to modify the sensor information and
* data.
*
* @param context
* Context for getting preferences
* @param name
* Sensor name, to match with registered sensors.
* @param description
* Sensor description (previously 'device_type'), to match with registered sensors.
* @param dataType
* Sensor data type, to match with registered sensors.
* @param deviceUuid
* (Optional) UUID of the device that should hold the sensor.
* @return String with the sensor's ID, or null if the sensor does not exist at CommonSense
* (yet).
* @throws IOException
* If the request to CommonSense failed.
* @throws JSONException
* If the response from CommonSense could not be parsed.
*/
public static String getSensorId(Context context, String name, String description,
String dataType, String deviceUuid) throws IOException, JSONException {
// Log.d(TAG, "Get sensor ID. name: '" + name + "', deviceUuid: '" + deviceUuid + "'");
// get list of sensors with matching description
List<JSONObject> sensors = getMatchingSensors(context, name, description, dataType);
// check the devices that the sensors are connected to
String id = null;
JSONObject device;
for (JSONObject sensor : sensors) {
if (null != deviceUuid) {
// check if the device UUID matches
device = sensor.optJSONObject("device");
if (null != device && deviceUuid.equals(device.optString("uuid"))) {
id = sensor.getString("id");
break;
}
} else {
// we do not care about the device, just accept the first match we find
id = sensor.getString("id");
break;
}
}
return id;
}
/**
* Gets the URL at CommonSense to which the data must be sent.
*
* @param context
* Context for getting preferences
* @param name
* Sensor name, to match with registered sensors.
* @param description
* Sensor description (previously 'device_type'), to match with registered sensors.
* @param dataType
* Sensor data type, to match with registered sensors.
* @param deviceUuid
* (Optional) UUID of the device that holds the sensor. Set null to use the default
* device.
* @return String with the sensor's URL, or null if sensor does not have an ID (yet)
* @throws JSONException
* If there was unexpected response getting the sensor ID.
* @throws IOException
* If there was a problem during communication with CommonSense.
*/
public static String getSensorUrl(Context context, String name, String description,
String dataType, String deviceUuid) throws IOException, JSONException {
String id = getSensorId(context, name, description, dataType, deviceUuid);
if (id == null) {
Log.e(TAG, "Failed to get URL for sensor '" + name + "': sensor ID is not available");
return null;
}
if (null == mainPrefs) {
mainPrefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE);
}
boolean devMode = mainPrefs.getBoolean(Advanced.DEV_MODE, false);
// found the right sensor
if (dataType.equals(SenseDataTypes.FILE)) {
String url = devMode ? SenseUrls.DEV_SENSOR_FILE : SenseUrls.SENSOR_FILE;
return url.replaceFirst("<id>", id);
} else {
String url = devMode ? SenseUrls.DEV_SENSOR_DATA : SenseUrls.SENSOR_DATA;
return url.replaceFirst("<id>", id);
}
}
/**
* @param context
* Context for getting preferences
* @return The current CommonSense session ID
* @throws IllegalAccessException
* if the app ID is not valid
*/
public static String getSessionId(Context context) throws IllegalAccessException {
if (null == authPrefs) {
authPrefs = context.getSharedPreferences(SensePrefs.AUTH_PREFS, Context.MODE_PRIVATE);
}
return authPrefs.getString(Auth.LOGIN_COOKIE, null);
}
/**
* Gets user details from CommonSense
*
* @param context
* Context for getting preferences
* @return JSONObject with user if successful, null otherwise
* @throws JSONException
* In case of unparseable response from CommonSense
* @throws IOException
* In case of communication failure to CommonSense
*/
public static JSONObject getUser(Context context) throws IOException, JSONException {
if (null == authPrefs) {
authPrefs = context.getSharedPreferences(SensePrefs.AUTH_PREFS, Context.MODE_PRIVATE);
}
if (null == mainPrefs) {
mainPrefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE);
}
String cookie = authPrefs.getString(Auth.LOGIN_COOKIE, null);
boolean devMode = mainPrefs.getBoolean(Advanced.DEV_MODE, false);
String url = devMode ? SenseUrls.DEV_GET_CURRENT_USER : SenseUrls.GET_CURRENT_USER;
// perform actual request
Map<String, String> response = SenseApi.request(context, url, null, cookie);
String responseCode = response.get("http response code");
JSONObject result = null;
if ("200".equalsIgnoreCase(responseCode)) {
result = new JSONObject(response.get("content")).getJSONObject("user");
} else {
Log.w(TAG, "Failed to get user! Response code: " + responseCode);
throw new IOException("Incorrect response from CommonSense: " + responseCode);
}
return result;
}
/**
* @param hashMe
* "clear" password String to be hashed before sending it to CommonSense
* @return Hashed String
*/
public static String hashPassword(String hashMe) {
final byte[] unhashedBytes = hashMe.getBytes();
try {
final MessageDigest algorithm = MessageDigest.getInstance("MD5");
algorithm.reset();
algorithm.update(unhashedBytes);
final byte[] hashedBytes = algorithm.digest();
final StringBuffer hexString = new StringBuffer();
for (final byte element : hashedBytes) {
final String hex = Integer.toHexString(0xFF & element);
if (hex.length() == 1) {
hexString.append(0);
}
hexString.append(hex);
}
return hexString.toString();
} catch (final NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
/**
* Joins a group
*
* @param context
* Context for getting preferences
* @param groupId
* Id of the group to join
* @return true if joined successfully, false otherwise
* @throws JSONException
* In case of unparseable response from CommonSense
* @throws IOException
* In case of communication failure to CommonSense
*/
public static boolean joinGroup(Context context, String groupId) throws JSONException,
IOException {
if (null == authPrefs) {
authPrefs = context.getSharedPreferences(SensePrefs.AUTH_PREFS, Context.MODE_PRIVATE);
}
if (null == mainPrefs) {
mainPrefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE);
}
String cookie = authPrefs.getString(Auth.LOGIN_COOKIE, null);
boolean devMode = mainPrefs.getBoolean(Advanced.DEV_MODE, false);
// get userId
String userId = getUser(context).getString("id");
String url = devMode ? SenseUrls.DEV_JOIN_GROUP : SenseUrls.JOIN_GROUP;
url = url.replaceFirst("<id>", groupId);
// create JSON object to POST
final JSONObject data = new JSONObject();
final JSONArray users = new JSONArray();
final JSONObject item = new JSONObject();
final JSONObject user = new JSONObject();
user.put("id", userId);
item.put("user", user);
users.put(item);
data.put("users", users);
// perform actual request
Map<String, String> response = SenseApi.request(context, url, data, cookie);
String responseCode = response.get("http response code");
boolean result = false;
if ("201".equalsIgnoreCase(responseCode)) {
result = true;
} else {
Log.w(TAG, "Failed to join group! Response code: " + responseCode + "Response: "
+ response);
result = false;
}
return result;
}
/**
* Tries to log in at CommonSense using the supplied username and password. After login, the
* cookie containing the session ID is stored in the preferences.
*
* @param context
* Context for getting preferences
* @param username
* Username for authentication
* @param password
* Hashed password for authentication
* @return 0 if login completed successfully, -2 if login was forbidden, and -1 for any other
* errors.
* @throws JSONException
* In case of unparseable response from CommonSense
* @throws IOException
* In case of communication failure to CommonSense
* @see SenseServiceStub#changeLogin(String, String, nl.sense_os.service.ISenseServiceCallback)
*/
public static int login(Context context, String username, String password)
throws JSONException, IOException {
// preferences
if (null == authPrefs) {
authPrefs = context.getSharedPreferences(SensePrefs.AUTH_PREFS, Context.MODE_PRIVATE);
}
if (null == mainPrefs) {
mainPrefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE);
}
boolean devMode = mainPrefs.getBoolean(Advanced.DEV_MODE, false);
if (devMode) {
Log.i(TAG, "Using development server to log in");
}
final String url = devMode ? SenseUrls.DEV_LOGIN : SenseUrls.LOGIN;
final JSONObject user = new JSONObject();
user.put("username", username);
user.put("password", password);
// perform actual request
Map<String, String> response = request(context, url, user, null);
// if response code is not 200 (OK), the login was incorrect
String responseCode = response.get("http response code");
int result = -1;
if ("403".equalsIgnoreCase(responseCode)) {
Log.w(TAG, "CommonSense login refused! Response: forbidden!");
result = -2;
} else if (!"200".equalsIgnoreCase(responseCode)) {
Log.w(TAG, "CommonSense login failed! Response: " + responseCode);
result = -1;
} else {
// received 200 response
result = 0;
}
// get the cookie from the response
String cookie = response.get("set-cookie");
if (result == 0 && response.get("set-cookie") == null) {
// something went horribly wrong
Log.w(TAG, "CommonSense login failed: no cookie received?!");
result = -1;
}
// handle result
Editor authEditor = authPrefs.edit();
switch (result) {
case 0: // logged in
authEditor.putString(Auth.LOGIN_COOKIE, cookie);
authEditor.commit();
break;
case -1: // error
break;
case -2: // unauthorized
authEditor.remove(Auth.LOGIN_COOKIE);
authEditor.commit();
break;
default:
Log.e(TAG, "Unexpected login result: " + result);
}
return result;
}
/**
* Push GCM Registration ID for current device
*
* @param context
* Application context, used to read preferences.
* @param registrationId
* Registration ID given by google
* @throws IOException
* @throws JSONException
* @throws IllegalStateException
*/
public static void registerGCMId(Context context, String registrationId) throws IOException,
JSONException {
if (null == authPrefs) {
authPrefs = context.getSharedPreferences(SensePrefs.AUTH_PREFS, Context.MODE_PRIVATE);
}
if (null == mainPrefs) {
mainPrefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE);
}
// Check if already synced with common sense
String pref_registration_id = authPrefs.getString(Auth.GCM_REGISTRATION_ID, "");
if (registrationId.equals(pref_registration_id)) {
// GCM registration id is already sync with commonSense
return;
}
String cookie = authPrefs.getString(Auth.LOGIN_COOKIE, null);
boolean devMode = mainPrefs.getBoolean(Advanced.DEV_MODE, false);
String url = devMode ? SenseUrls.DEV_REGISTER_GCM_ID : SenseUrls.REGISTER_GCM_ID;
// Get the device ID
String device_id = getDeviceId(context);
if (device_id == null) {
// register GCM ID failed, can not get the device ID for this device
return;
}
url = url.replaceFirst("<id>", device_id);
final JSONObject data = new JSONObject();
data.put("registration_id", registrationId);
Map<String, String> response = SenseApi.request(context, url, data, cookie);
String responseCode = response.get("http response code");
if (!"200".equals(responseCode)) {
throw new IOException("Incorrect response from CommonSense: " + responseCode);
}
// check registration result
JSONObject res = new JSONObject(response.get("content"));
if (!registrationId.equals(res.getJSONObject("device").getString(GCMReceiver.KEY_GCM_ID))) {
throw new IllegalStateException("GCM registration_id not match with response");
}
Editor authEditor = authPrefs.edit();
authEditor.putString(Auth.GCM_REGISTRATION_ID, registrationId);
authEditor.commit();
}
/**
* Registers a new sensor for this device at CommonSense. Also connects the sensor to this
* device.
*
* @param context
* The application context, used to retrieve preferences.
* @param name
* The name of the sensor.
* @param displayName
* The sensor's pretty display name.
* @param description
* The sensor description (previously "device_type").
* @param dataType
* The sensor data type.
* @param value
* An example sensor value, used to determine the data structure for JSON type
* sensors.
* @param deviceType
* (Optional) Type of the device that holds the sensor. Set null to use the default
* device.
* @param deviceUuid
* (Optional) UUID of the device that holds the sensor. Set null to use the default
* device.
* @return The new sensor ID at CommonSense, or <code>null</code> if the registration failed.
* @throws JSONException
* In case of invalid sensor details or if the request returned unparseable
* response.
* @throws IOException
* In case of communication failure during creation of the sensor.
*/
public static String registerSensor(Context context, String name, String displayName,
String description, String dataType, String value, String deviceType, String deviceUuid)
throws JSONException, IOException {
if (null == authPrefs) {
authPrefs = context.getSharedPreferences(SensePrefs.AUTH_PREFS, Context.MODE_PRIVATE);
}
if (null == mainPrefs) {
mainPrefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE);
}
String cookie = authPrefs.getString(Auth.LOGIN_COOKIE, null);
boolean devMode = mainPrefs.getBoolean(Advanced.DEV_MODE, false);
// prepare request to create new sensor
String url = devMode ? SenseUrls.DEV_CREATE_SENSOR : SenseUrls.CREATE_SENSOR;
JSONObject postData = new JSONObject();
JSONObject sensor = new JSONObject();
sensor.put("name", name);
sensor.put("device_type", description);
sensor.put("display_name", displayName);
sensor.put("pager_type", "");
sensor.put("data_type", dataType);
if (dataType.compareToIgnoreCase(SenseDataTypes.JSON) == 0
|| dataType.compareToIgnoreCase(SenseDataTypes.JSON_TIME_SERIES) == 0) {
JSONObject dataStructJSon = null;
try {
dataStructJSon = new JSONObject(value);
JSONArray fieldNames = dataStructJSon.names();
for (int x = 0; x < fieldNames.length(); x++) {
String fieldName = fieldNames.getString(x);
int start = dataStructJSon.get(fieldName).getClass().getName().lastIndexOf(".");
dataStructJSon.put(fieldName, dataStructJSon.get(fieldName).getClass()
.getName().substring(start + 1));
}
} catch (JSONException e) {
// apparently the data structure cannot be parsed from the value
dataStructJSon = new JSONObject();
}
sensor.put("data_structure", dataStructJSon.toString().replaceAll("\"", "\\\""));
}
postData.put("sensor", sensor);
// perform actual request
Map<String, String> response = request(context, url, postData, cookie);
// check response code
String code = response.get("http response code");
if (!"201".equals(code)) {
Log.e(TAG, "Failed to register sensor at CommonSense! Response code: " + code);
throw new IOException("Incorrect response from CommonSense: " + code);
}
// retrieve the newly created sensor ID
String locationHeader = response.get("location");
String[] split = locationHeader.split("/");
String id = split[split.length - 1];
// get device properties from preferences, so it matches the properties in CommonSense
if (null == deviceUuid) {
deviceUuid = getDefaultDeviceUuid(context);
deviceType = getDefaultDeviceType(context);
}
// Add sensor to this device at CommonSense
url = devMode ? SenseUrls.DEV_ADD_SENSOR_TO_DEVICE : SenseUrls.ADD_SENSOR_TO_DEVICE;
url = url.replaceFirst("<id>", id);
postData = new JSONObject();
JSONObject device = new JSONObject();
device.put("type", deviceType);
device.put("uuid", deviceUuid);
postData.put("device", device);
response = request(context, url, postData, cookie);
// check response code
code = response.get("http response code");
if (!"201".equals(code)) {
Log.e(TAG, "Failed to add sensor to device at CommonSense! Response code: " + code);
throw new IOException("Incorrect response from CommonSense: " + code);
}
// store the new sensor in the preferences
sensor.put("id", id);
sensor.put("device", device);
JSONArray sensors = getAllSensors(context);
sensors.put(sensor);
Editor authEditor = authPrefs.edit();
authEditor.putString(Auth.SENSOR_LIST_COMPLETE, sensors.toString());
authEditor.commit();
Log.v(TAG, "Created sensor: '" + name + "' for device: '" + deviceType + "'");
// return the new sensor ID
return id;
}
/**
* Tries to register a new user at CommonSense.
*
* @param context
* Context for getting preferences
* @param username
* Username to register
* @param password
* Hashed password for the new user
* @return 0 if registration completed successfully, -2 if the user already exists, and -1 for
* any other unexpected responses.
* @throws JSONException
* In case of unparseable response from CommonSense
* @throws IOException
* In case of communication failure to CommonSense
* @see SenseServiceStub#register(String, String, String, String, String, String, String,
* String, String, nl.sense_os.service.ISenseServiceCallback)
*/
public static int registerUser(Context context, String username, String password, String name,
String surname, String email, String mobile) throws JSONException, IOException {
if (null == mainPrefs) {
mainPrefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE);
}
boolean devMode = mainPrefs.getBoolean(Advanced.DEV_MODE, false);
final String url = devMode ? SenseUrls.DEV_REG : SenseUrls.REG;
// create JSON object to POST
final JSONObject data = new JSONObject();
final JSONObject user = new JSONObject();
user.put("username", username);
user.put("password", password);
if (null != name) {
user.put("name", name);
}
if (null != surname) {
user.put("surname", surname);
}
if (null != email) {
user.put("email", email);
}
if (null != mobile) {
user.put("mobile", mobile);
}
data.put("user", user);
// perform actual request
Map<String, String> response = SenseApi.request(context, url, data, null);
String responseCode = response.get("http response code");
int result = -1;
if ("201".equalsIgnoreCase(responseCode)) {
result = 0;
} else if ("409".equalsIgnoreCase(responseCode)) {
Log.w(TAG, "Error registering new user! User already exists");
result = -2;
} else {
Log.w(TAG, "Error registering new user! Response code: " + responseCode);
result = -1;
}
return result;
}
/**
* Performs request at CommonSense API. Returns the response code, content, and headers.
*
* @param context
* Application context, used to read preferences.
* @param urlString
* Complete URL to perform request to.
* @param content
* (Optional) Content for the request. If the content is not null, the request method
* is automatically POST. The default method is GET.
* @param cookie
* (Optional) Cookie header for the request.
* @return Map with "content" and "http response code" fields, plus fields for all response
* headers.
* @throws IOException
*/
public static Map<String, String> request(Context context, String urlString,
JSONObject content, String cookie) throws IOException {
HttpURLConnection urlConnection = null;
HashMap<String, String> result = new HashMap<String, String>();
try {
// Log.d(TAG, "API request: " + (content == null ? "GET" : "POST") + " " + urlString
// + " cookie:" + cookie);
// get compression preference
if (null == mainPrefs) {
mainPrefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS,
Context.MODE_PRIVATE);
}
final boolean compress = mainPrefs.getBoolean(Advanced.COMPRESS, true);
// open new URL connection channel.
URL url = new URL(urlString);
if ("https".equals(url.getProtocol().toLowerCase(Locale.ENGLISH))) {
trustAllHosts();
HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
https.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
urlConnection = https;
} else {
urlConnection = (HttpURLConnection) url.openConnection();
}
// some parameters
urlConnection.setUseCaches(false);
urlConnection.setInstanceFollowRedirects(false);
// set cookie (if available)
if (null != cookie) {
urlConnection.setRequestProperty("Cookie", cookie);
}
// send content (if available)
if (null != content) {
urlConnection.setDoOutput(true);
// When no charset is given in the Content-Type header "ISO-8859-1" should be
// assumed (see http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1).
// Because we're uploading UTF-8 the charset should be set to UTF-8.
urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
// send content
DataOutputStream printout;
if (compress) {
// do not set content size
urlConnection.setRequestProperty("Transfer-Encoding", "chunked");
urlConnection.setRequestProperty("Content-Encoding", "gzip");
GZIPOutputStream zipStream = new GZIPOutputStream(
urlConnection.getOutputStream());
printout = new DataOutputStream(zipStream);
} else {
// set content size
// The content length should be in bytes. We cannot use string length here
// because that counts the number of chars while not accounting for multibyte
// chars
int contentLength = content.toString().getBytes("UTF-8").length;
urlConnection.setFixedLengthStreamingMode(contentLength);
urlConnection.setRequestProperty("Content-Length", "" + contentLength);
printout = new DataOutputStream(urlConnection.getOutputStream());
}
// Write the string in UTF-8 encoding
printout.write(content.toString().getBytes("UTF-8"));
printout.flush();
printout.close();
}
// get response, or read error message
InputStream inputStream;
try {
inputStream = urlConnection.getInputStream();
} catch (IOException e) {
inputStream = urlConnection.getErrorStream();
}
if (null == inputStream) {
throw new IOException("could not get InputStream");
}
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream), 1024);
String line;
StringBuffer responseContent = new StringBuffer();
while ((line = reader.readLine()) != null) {
responseContent.append(line);
responseContent.append('\r');
}
result.put("content", responseContent.toString());
result.put("http response code", "" + urlConnection.getResponseCode());
// clean up
reader.close();
reader = null;
inputStream.close();
inputStream = null;
// get headers
Map<String, List<String>> headerFields = urlConnection.getHeaderFields();
String key, valueString;
List<String> value;
for (Entry<String, List<String>> entry : headerFields.entrySet()) {
key = entry.getKey();
value = entry.getValue();
if (null != key && null != value) {
key = key.toLowerCase(Locale.ENGLISH);
valueString = value.toString();
valueString = valueString.substring(1, valueString.length() - 1);
// Log.d(TAG, "Header field '" + key + "': '" + valueString + "'");
result.put(key, valueString);
} else {
// Log.d(TAG, "Skipped header field '" + key + "': '" + value + "'");
}
}
return result;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}
/**
* Shares a sensor with a user or group
*
* @param context
* Context for getting preferences
* @param sensorId
* Id of the sensor to share
* @param userId
* Id of the user or group to share the sensor with
* @return true if shared successfully, false otherwise
* @throws JSONException
* In case of unparseable response from CommonSense
* @throws IOException
* In case of communication failure to CommonSense
*/
public static boolean shareSensor(Context context, String sensorId, String userId)
throws JSONException, IOException {
if (null == authPrefs) {
authPrefs = context.getSharedPreferences(SensePrefs.AUTH_PREFS, Context.MODE_PRIVATE);
}
if (null == mainPrefs) {
mainPrefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE);
}
String cookie = authPrefs.getString(Auth.LOGIN_COOKIE, null);
boolean devMode = mainPrefs.getBoolean(Advanced.DEV_MODE, false);
String url = devMode ? SenseUrls.DEV_SHARE_SENSOR : SenseUrls.SHARE_SENSOR;
url = url.replaceFirst("<id>", sensorId);
// create JSON object to POST
final JSONObject data = new JSONObject();
final JSONObject user = new JSONObject();
user.put("id", userId);
data.put("user", user);
// perform actual request
Map<String, String> response = SenseApi.request(context, url, data, cookie);
String responseCode = response.get("http response code");
boolean result = false;
if ("201".equalsIgnoreCase(responseCode)) {
result = true;
} else {
Log.w(TAG, "Failed to share sensor! Response code: " + responseCode);
result = false;
}
return result;
}
/**
* Trust every server - do not check for any certificate
*/
// TODO Solve issue with security certificate for HTTPS.
private static void trustAllHosts() {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[] {};
}
} };
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
e.printStackTrace();
}
}
}
| Changed log levels to prevent confusion about errors being logged when a
sensor ID was not found. (see issue #54) | sense-android-library/src/nl/sense_os/service/commonsense/SenseApi.java | Changed log levels to prevent confusion about errors being logged when a sensor ID was not found. (see issue #54) | <ide><path>ense-android-library/src/nl/sense_os/service/commonsense/SenseApi.java
<ide>
<ide> } catch (Exception e) {
<ide> // unlikely to ever happen. Just get the list from CommonSense instead
<del> Log.e(TAG, "Failed to get list of sensors from cache!", e);
<add> Log.w(TAG, "Failed to get list of sensors from cache!", e);
<ide> }
<ide>
<ide> // if we make it here, the list was not in the cache
<ide> }
<ide> boolean devMode = mainPrefs.getBoolean(Advanced.DEV_MODE, false);
<ide> if (devMode) {
<del> Log.i(TAG, "Using development server to get registered sensors");
<add> Log.v(TAG, "Using development server to get registered sensors");
<ide> }
<ide> String url = devMode ? SenseUrls.DEV_ALL_SENSORS : SenseUrls.ALL_SENSORS;
<ide> url += "&page=" + page;
<ide> String cookie = authPrefs.getString(Auth.LOGIN_COOKIE, null);
<ide> boolean devMode = mainPrefs.getBoolean(Advanced.DEV_MODE, false);
<ide> if (devMode) {
<del> Log.i(TAG, "Using development server to get connected sensors");
<add> Log.v(TAG, "Using development server to get connected sensors");
<ide> }
<ide> String url = devMode ? SenseUrls.DEV_CONNECTED_SENSORS : SenseUrls.CONNECTED_SENSORS;
<ide> url = url.replace("<id>", sensorId);
<ide> || name.equals(SensorNames.GYRO_BURST) || name.equals(SensorNames.LINEAR_BURST)) {
<ide> // special case to take care of changed motion sensor descriptions since Gingerbread
<ide> if (name.equals(sensor.getString("name"))) {
<del> // Log.d(TAG, "Using inexact match for '" + name + "' sensor ID...");
<add> // use inexact match
<ide> result.add(sensor);
<ide> }
<ide> }
<ide> */
<ide> public static String getSensorId(Context context, String name, String description,
<ide> String dataType, String deviceUuid) throws IOException, JSONException {
<del>
<del> // Log.d(TAG, "Get sensor ID. name: '" + name + "', deviceUuid: '" + deviceUuid + "'");
<ide>
<ide> // get list of sensors with matching description
<ide> List<JSONObject> sensors = getMatchingSensors(context, name, description, dataType);
<ide> String id = getSensorId(context, name, description, dataType, deviceUuid);
<ide>
<ide> if (id == null) {
<del> Log.e(TAG, "Failed to get URL for sensor '" + name + "': sensor ID is not available");
<add> Log.w(TAG, "Failed to get URL for sensor '" + name + "': sensor ID is not available");
<ide> return null;
<ide> }
<ide>
<ide>
<ide> boolean devMode = mainPrefs.getBoolean(Advanced.DEV_MODE, false);
<ide> if (devMode) {
<del> Log.i(TAG, "Using development server to log in");
<add> Log.v(TAG, "Using development server to log in");
<ide> }
<ide> final String url = devMode ? SenseUrls.DEV_LOGIN : SenseUrls.LOGIN;
<ide> final JSONObject user = new JSONObject();
<ide> // check response code
<ide> String code = response.get("http response code");
<ide> if (!"201".equals(code)) {
<del> Log.e(TAG, "Failed to register sensor at CommonSense! Response code: " + code);
<add> Log.w(TAG, "Failed to register sensor at CommonSense! Response code: " + code);
<ide> throw new IOException("Incorrect response from CommonSense: " + code);
<ide> }
<ide>
<ide> // check response code
<ide> code = response.get("http response code");
<ide> if (!"201".equals(code)) {
<del> Log.e(TAG, "Failed to add sensor to device at CommonSense! Response code: " + code);
<add> Log.w(TAG, "Failed to add sensor to device at CommonSense! Response code: " + code);
<ide> throw new IOException("Incorrect response from CommonSense: " + code);
<ide> }
<ide>
<ide> if ("201".equalsIgnoreCase(responseCode)) {
<ide> result = 0;
<ide> } else if ("409".equalsIgnoreCase(responseCode)) {
<del> Log.w(TAG, "Error registering new user! User already exists");
<add> Log.w(TAG, "Failed to register new user! User already exists");
<ide> result = -2;
<ide> } else {
<del> Log.w(TAG, "Error registering new user! Response code: " + responseCode);
<add> Log.w(TAG, "Failed to register new user! Response code: " + responseCode);
<ide> result = -1;
<ide> }
<ide>
<ide> HttpURLConnection urlConnection = null;
<ide> HashMap<String, String> result = new HashMap<String, String>();
<ide> try {
<del> // Log.d(TAG, "API request: " + (content == null ? "GET" : "POST") + " " + urlString
<del> // + " cookie:" + cookie);
<ide>
<ide> // get compression preference
<ide> if (null == mainPrefs) {
<ide> key = key.toLowerCase(Locale.ENGLISH);
<ide> valueString = value.toString();
<ide> valueString = valueString.substring(1, valueString.length() - 1);
<del> // Log.d(TAG, "Header field '" + key + "': '" + valueString + "'");
<ide> result.put(key, valueString);
<del> } else {
<del> // Log.d(TAG, "Skipped header field '" + key + "': '" + value + "'");
<ide> }
<ide> }
<ide> |
|
JavaScript | mit | fae4504793d87a84853fcd9c8619a1c29a09d7a8 | 0 | lukasbestle/newdb,louischatriot/nedb,louischatriot/nedb,louischatriot/nedb,lukasbestle/newdb,lukasbestle/newdb | var should = require('chai').should()
, assert = require('chai').assert
, testDb = 'workspace/test.db'
, fs = require('fs')
, path = require('path')
, _ = require('underscore')
, async = require('async')
, model = require('../lib/model')
, Datastore = require('../lib/datastore')
, Persistence = require('../lib/persistence')
, Cursor = require('../lib/cursor')
;
describe('Cursor', function () {
var d;
beforeEach(function (done) {
d = new Datastore({ filename: testDb });
d.filename.should.equal(testDb);
d.inMemoryOnly.should.equal(false);
async.waterfall([
function (cb) {
Persistence.ensureDirectoryExists(path.dirname(testDb), function () {
fs.exists(testDb, function (exists) {
if (exists) {
fs.unlink(testDb, cb);
} else { return cb(); }
});
});
}
, function (cb) {
d.loadDatabase(function (err) {
assert.isNull(err);
d.getAllData().length.should.equal(0);
return cb();
});
}
], done);
});
describe('Without sorting', function () {
beforeEach(function (done) {
d.insert({ age: 5 }, function (err) {
d.insert({ age: 57 }, function (err) {
d.insert({ age: 52 }, function (err) {
d.insert({ age: 23 }, function (err) {
d.insert({ age: 89 }, function (err) {
return done();
});
});
});
});
});
});
it('Without query, an empty query or a simple query and no skip or limit', function (done) {
async.waterfall([
function (cb) {
var cursor = new Cursor(d);
cursor.exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(5);
_.filter(docs, function(doc) { return doc.age === 5; })[0].age.should.equal(5);
_.filter(docs, function(doc) { return doc.age === 57; })[0].age.should.equal(57);
_.filter(docs, function(doc) { return doc.age === 52; })[0].age.should.equal(52);
_.filter(docs, function(doc) { return doc.age === 23; })[0].age.should.equal(23);
_.filter(docs, function(doc) { return doc.age === 89; })[0].age.should.equal(89);
cb();
});
}
, function (cb) {
var cursor = new Cursor(d, {});
cursor.exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(5);
_.filter(docs, function(doc) { return doc.age === 5; })[0].age.should.equal(5);
_.filter(docs, function(doc) { return doc.age === 57; })[0].age.should.equal(57);
_.filter(docs, function(doc) { return doc.age === 52; })[0].age.should.equal(52);
_.filter(docs, function(doc) { return doc.age === 23; })[0].age.should.equal(23);
_.filter(docs, function(doc) { return doc.age === 89; })[0].age.should.equal(89);
cb();
});
}
, function (cb) {
var cursor = new Cursor(d, { age: { $gt: 23 } });
cursor.exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(3);
_.filter(docs, function(doc) { return doc.age === 57; })[0].age.should.equal(57);
_.filter(docs, function(doc) { return doc.age === 52; })[0].age.should.equal(52);
_.filter(docs, function(doc) { return doc.age === 89; })[0].age.should.equal(89);
cb();
});
}
], done);
});
it('With an empty collection', function (done) {
async.waterfall([
function (cb) {
d.remove({}, { multi: true }, function(err) { return cb(err); })
}
, function (cb) {
var cursor = new Cursor(d);
cursor.exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(0);
cb();
});
}
], done);
});
it('With a limit', function (done) {
var cursor = new Cursor(d);
cursor.limit(3);
cursor.exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(3);
// No way to predict which results are returned of course ...
done();
});
});
it('With a skip', function (done) {
var cursor = new Cursor(d);
cursor.skip(2).exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(3);
// No way to predict which results are returned of course ...
done();
});
});
it('With a limit and a skip and method chaining', function (done) {
var cursor = new Cursor(d);
cursor.limit(4).skip(3); // Only way to know that the right number of results was skipped is if limit + skip > number of results
cursor.exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(2);
// No way to predict which results are returned of course ...
done();
});
});
}); // ===== End of 'Without sorting' =====
describe('Sorting of the results', function () {
beforeEach(function (done) {
// We don't know the order in which docs wil be inserted but we ensure correctness by testing both sort orders
d.insert({ age: 5 }, function (err) {
d.insert({ age: 57 }, function (err) {
d.insert({ age: 52 }, function (err) {
d.insert({ age: 23 }, function (err) {
d.insert({ age: 89 }, function (err) {
return done();
});
});
});
});
});
});
it('Using one sort', function (done) {
var cursor, i;
cursor = new Cursor(d, {});
cursor.sort({ age: 1 });
cursor.exec(function (err, docs) {
assert.isNull(err);
// Results are in ascending order
for (i = 0; i < docs.length - 1; i += 1) {
assert(docs[i].age < docs[i + 1].age)
}
cursor.sort({ age: -1 });
cursor.exec(function (err, docs) {
assert.isNull(err);
// Results are in descending order
for (i = 0; i < docs.length - 1; i += 1) {
assert(docs[i].age > docs[i + 1].age)
}
done();
});
});
});
it("Sorting strings with custom string comparison function", function (done) {
var db = new Datastore({ inMemoryOnly: true, autoload: true
, compareStrings: function (a, b) { return a.length - b.length; }
});
db.insert({ name: 'alpha' });
db.insert({ name: 'charlie' });
db.insert({ name: 'zulu' });
db.find({}).sort({ name: 1 }).exec(function (err, docs) {
_.pluck(docs, 'name')[0].should.equal('zulu');
_.pluck(docs, 'name')[1].should.equal('alpha');
_.pluck(docs, 'name')[2].should.equal('charlie');
delete db.compareStrings;
db.find({}).sort({ name: 1 }).exec(function (err, docs) {
_.pluck(docs, 'name')[0].should.equal('alpha');
_.pluck(docs, 'name')[1].should.equal('charlie');
_.pluck(docs, 'name')[2].should.equal('zulu');
done();
});
});
});
it('With an empty collection', function (done) {
async.waterfall([
function (cb) {
d.remove({}, { multi: true }, function(err) { return cb(err); })
}
, function (cb) {
var cursor = new Cursor(d);
cursor.sort({ age: 1 });
cursor.exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(0);
cb();
});
}
], done);
});
it('Ability to chain sorting and exec', function (done) {
var i;
async.waterfall([
function (cb) {
var cursor = new Cursor(d);
cursor.sort({ age: 1 }).exec(function (err, docs) {
assert.isNull(err);
// Results are in ascending order
for (i = 0; i < docs.length - 1; i += 1) {
assert(docs[i].age < docs[i + 1].age)
}
cb();
});
}
, function (cb) {
var cursor = new Cursor(d);
cursor.sort({ age: -1 }).exec(function (err, docs) {
assert.isNull(err);
// Results are in descending order
for (i = 0; i < docs.length - 1; i += 1) {
assert(docs[i].age > docs[i + 1].age)
}
cb();
});
}
], done);
});
it('Using limit and sort', function (done) {
var i;
async.waterfall([
function (cb) {
var cursor = new Cursor(d);
cursor.sort({ age: 1 }).limit(3).exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(3);
docs[0].age.should.equal(5);
docs[1].age.should.equal(23);
docs[2].age.should.equal(52);
cb();
});
}
, function (cb) {
var cursor = new Cursor(d);
cursor.sort({ age: -1 }).limit(2).exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(2);
docs[0].age.should.equal(89);
docs[1].age.should.equal(57);
cb();
});
}
], done);
});
it('Using a limit higher than total number of docs shouldnt cause an error', function (done) {
var i;
async.waterfall([
function (cb) {
var cursor = new Cursor(d);
cursor.sort({ age: 1 }).limit(7).exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(5);
docs[0].age.should.equal(5);
docs[1].age.should.equal(23);
docs[2].age.should.equal(52);
docs[3].age.should.equal(57);
docs[4].age.should.equal(89);
cb();
});
}
], done);
});
it('Using limit and skip with sort', function (done) {
var i;
async.waterfall([
function (cb) {
var cursor = new Cursor(d);
cursor.sort({ age: 1 }).limit(1).skip(2).exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(1);
docs[0].age.should.equal(52);
cb();
});
}
, function (cb) {
var cursor = new Cursor(d);
cursor.sort({ age: 1 }).limit(3).skip(1).exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(3);
docs[0].age.should.equal(23);
docs[1].age.should.equal(52);
docs[2].age.should.equal(57);
cb();
});
}
, function (cb) {
var cursor = new Cursor(d);
cursor.sort({ age: -1 }).limit(2).skip(2).exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(2);
docs[0].age.should.equal(52);
docs[1].age.should.equal(23);
cb();
});
}
], done);
});
it('Using too big a limit and a skip with sort', function (done) {
var i;
async.waterfall([
function (cb) {
var cursor = new Cursor(d);
cursor.sort({ age: 1 }).limit(8).skip(2).exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(3);
docs[0].age.should.equal(52);
docs[1].age.should.equal(57);
docs[2].age.should.equal(89);
cb();
});
}
], done);
});
it('Using too big a skip with sort should return no result', function (done) {
var i;
async.waterfall([
function (cb) {
var cursor = new Cursor(d);
cursor.sort({ age: 1 }).skip(5).exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(0);
cb();
});
}
, function (cb) {
var cursor = new Cursor(d);
cursor.sort({ age: 1 }).skip(7).exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(0);
cb();
});
}
, function (cb) {
var cursor = new Cursor(d);
cursor.sort({ age: 1 }).limit(3).skip(7).exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(0);
cb();
});
}
, function (cb) {
var cursor = new Cursor(d);
cursor.sort({ age: 1 }).limit(6).skip(7).exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(0);
cb();
});
}
], done);
});
it('Sorting strings', function (done) {
async.waterfall([
function (cb) {
d.remove({}, { multi: true }, function (err) {
if (err) { return cb(err); }
d.insert({ name: 'jako'}, function () {
d.insert({ name: 'jakeb' }, function () {
d.insert({ name: 'sue' }, function () {
return cb();
});
});
});
});
}
, function (cb) {
var cursor = new Cursor(d, {});
cursor.sort({ name: 1 }).exec(function (err, docs) {
docs.length.should.equal(3);
docs[0].name.should.equal('jakeb');
docs[1].name.should.equal('jako');
docs[2].name.should.equal('sue');
return cb();
});
}
, function (cb) {
var cursor = new Cursor(d, {});
cursor.sort({ name: -1 }).exec(function (err, docs) {
docs.length.should.equal(3);
docs[0].name.should.equal('sue');
docs[1].name.should.equal('jako');
docs[2].name.should.equal('jakeb');
return cb();
});
}
], done);
});
it('Sorting nested fields with dates', function (done) {
var doc1, doc2, doc3;
async.waterfall([
function (cb) {
d.remove({}, { multi: true }, function (err) {
if (err) { return cb(err); }
d.insert({ event: { recorded: new Date(400) } }, function (err, _doc1) {
doc1 = _doc1;
d.insert({ event: { recorded: new Date(60000) } }, function (err, _doc2) {
doc2 = _doc2;
d.insert({ event: { recorded: new Date(32) } }, function (err, _doc3) {
doc3 = _doc3;
return cb();
});
});
});
});
}
, function (cb) {
var cursor = new Cursor(d, {});
cursor.sort({ "event.recorded": 1 }).exec(function (err, docs) {
docs.length.should.equal(3);
docs[0]._id.should.equal(doc3._id);
docs[1]._id.should.equal(doc1._id);
docs[2]._id.should.equal(doc2._id);
return cb();
});
}
, function (cb) {
var cursor = new Cursor(d, {});
cursor.sort({ "event.recorded": -1 }).exec(function (err, docs) {
docs.length.should.equal(3);
docs[0]._id.should.equal(doc2._id);
docs[1]._id.should.equal(doc1._id);
docs[2]._id.should.equal(doc3._id);
return cb();
});
}
], done);
});
it('Sorting when some fields are undefined', function (done) {
async.waterfall([
function (cb) {
d.remove({}, { multi: true }, function (err) {
if (err) { return cb(err); }
d.insert({ name: 'jako', other: 2 }, function () {
d.insert({ name: 'jakeb', other: 3 }, function () {
d.insert({ name: 'sue' }, function () {
d.insert({ name: 'henry', other: 4 }, function () {
return cb();
});
});
});
});
});
}
, function (cb) {
var cursor = new Cursor(d, {});
cursor.sort({ other: 1 }).exec(function (err, docs) {
docs.length.should.equal(4);
docs[0].name.should.equal('sue');
assert.isUndefined(docs[0].other);
docs[1].name.should.equal('jako');
docs[1].other.should.equal(2);
docs[2].name.should.equal('jakeb');
docs[2].other.should.equal(3);
docs[3].name.should.equal('henry');
docs[3].other.should.equal(4);
return cb();
});
}
, function (cb) {
var cursor = new Cursor(d, { name: { $in: [ 'suzy', 'jakeb', 'jako' ] } });
cursor.sort({ other: -1 }).exec(function (err, docs) {
docs.length.should.equal(2);
docs[0].name.should.equal('jakeb');
docs[0].other.should.equal(3);
docs[1].name.should.equal('jako');
docs[1].other.should.equal(2);
return cb();
});
}
], done);
});
it('Sorting when all fields are undefined', function (done) {
async.waterfall([
function (cb) {
d.remove({}, { multi: true }, function (err) {
if (err) { return cb(err); }
d.insert({ name: 'jako'}, function () {
d.insert({ name: 'jakeb' }, function () {
d.insert({ name: 'sue' }, function () {
return cb();
});
});
});
});
}
, function (cb) {
var cursor = new Cursor(d, {});
cursor.sort({ other: 1 }).exec(function (err, docs) {
docs.length.should.equal(3);
return cb();
});
}
, function (cb) {
var cursor = new Cursor(d, { name: { $in: [ 'sue', 'jakeb', 'jakob' ] } });
cursor.sort({ other: -1 }).exec(function (err, docs) {
docs.length.should.equal(2);
return cb();
});
}
], done);
});
it('Multiple consecutive sorts', function(done) {
async.waterfall([
function (cb) {
d.remove({}, { multi: true }, function (err) {
if (err) { return cb(err); }
d.insert({ name: 'jako', age: 43, nid: 1 }, function () {
d.insert({ name: 'jakeb', age: 43, nid: 2 }, function () {
d.insert({ name: 'sue', age: 12, nid: 3 }, function () {
d.insert({ name: 'zoe', age: 23, nid: 4 }, function () {
d.insert({ name: 'jako', age: 35, nid: 5 }, function () {
return cb();
});
});
});
});
});
});
}
, function (cb) {
var cursor = new Cursor(d, {});
cursor.sort({ name: 1, age: -1 }).exec(function (err, docs) {
docs.length.should.equal(5);
docs[0].nid.should.equal(2);
docs[1].nid.should.equal(1);
docs[2].nid.should.equal(5);
docs[3].nid.should.equal(3);
docs[4].nid.should.equal(4);
return cb();
});
}
, function (cb) {
var cursor = new Cursor(d, {});
cursor.sort({ name: 1, age: 1 }).exec(function (err, docs) {
docs.length.should.equal(5);
docs[0].nid.should.equal(2);
docs[1].nid.should.equal(5);
docs[2].nid.should.equal(1);
docs[3].nid.should.equal(3);
docs[4].nid.should.equal(4);
return cb();
});
}
, function (cb) {
var cursor = new Cursor(d, {});
cursor.sort({ age: 1, name: 1 }).exec(function (err, docs) {
docs.length.should.equal(5);
docs[0].nid.should.equal(3);
docs[1].nid.should.equal(4);
docs[2].nid.should.equal(5);
docs[3].nid.should.equal(2);
docs[4].nid.should.equal(1);
return cb();
});
}
, function (cb) {
var cursor = new Cursor(d, {});
cursor.sort({ age: 1, name: -1 }).exec(function (err, docs) {
docs.length.should.equal(5);
docs[0].nid.should.equal(3);
docs[1].nid.should.equal(4);
docs[2].nid.should.equal(5);
docs[3].nid.should.equal(1);
docs[4].nid.should.equal(2);
return cb();
});
}
], done); });
it('Similar data, multiple consecutive sorts', function(done) {
var i, j, id
, companies = [ 'acme', 'milkman', 'zoinks' ]
, entities = []
;
async.waterfall([
function (cb) {
d.remove({}, { multi: true }, function (err) {
if (err) { return cb(err); }
id = 1;
for (i = 0; i < companies.length; i++) {
for (j = 5; j <= 100; j += 5) {
entities.push({
company: companies[i],
cost: j,
nid: id
});
id++;
}
}
async.each(entities, function(entity, callback) {
d.insert(entity, function() {
callback();
});
}, function(err) {
return cb();
});
});
}
, function (cb) {
var cursor = new Cursor(d, {});
cursor.sort({ company: 1, cost: 1 }).exec(function (err, docs) {
docs.length.should.equal(60);
for (var i = 0; i < docs.length; i++) {
docs[i].nid.should.equal(i+1);
};
return cb();
});
}
], done); });
}); // ===== End of 'Sorting' =====
describe('Projections', function () {
var doc1, doc2, doc3, doc4, doc0;
beforeEach(function (done) {
// We don't know the order in which docs wil be inserted but we ensure correctness by testing both sort orders
d.insert({ age: 5, name: 'Jo', planet: 'B', toys: { bebe: true, ballon: 'much' } }, function (err, _doc0) {
doc0 = _doc0;
d.insert({ age: 57, name: 'Louis', planet: 'R', toys: { ballon: 'yeah', bebe: false } }, function (err, _doc1) {
doc1 = _doc1;
d.insert({ age: 52, name: 'Grafitti', planet: 'C', toys: { bebe: 'kind of' } }, function (err, _doc2) {
doc2 = _doc2;
d.insert({ age: 23, name: 'LM', planet: 'S' }, function (err, _doc3) {
doc3 = _doc3;
d.insert({ age: 89, planet: 'Earth' }, function (err, _doc4) {
doc4 = _doc4;
return done();
});
});
});
});
});
});
it('Takes all results if no projection or empty object given', function (done) {
var cursor = new Cursor(d, {});
cursor.sort({ age: 1 }); // For easier finding
cursor.exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(5);
assert.deepEqual(docs[0], doc0);
assert.deepEqual(docs[1], doc3);
assert.deepEqual(docs[2], doc2);
assert.deepEqual(docs[3], doc1);
assert.deepEqual(docs[4], doc4);
cursor.projection({});
cursor.exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(5);
assert.deepEqual(docs[0], doc0);
assert.deepEqual(docs[1], doc3);
assert.deepEqual(docs[2], doc2);
assert.deepEqual(docs[3], doc1);
assert.deepEqual(docs[4], doc4);
done();
});
});
});
it('Can take only the expected fields', function (done) {
var cursor = new Cursor(d, {});
cursor.sort({ age: 1 }); // For easier finding
cursor.projection({ age: 1, name: 1 });
cursor.exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(5);
// Takes the _id by default
assert.deepEqual(docs[0], { age: 5, name: 'Jo', _id: doc0._id });
assert.deepEqual(docs[1], { age: 23, name: 'LM', _id: doc3._id });
assert.deepEqual(docs[2], { age: 52, name: 'Grafitti', _id: doc2._id });
assert.deepEqual(docs[3], { age: 57, name: 'Louis', _id: doc1._id });
assert.deepEqual(docs[4], { age: 89, _id: doc4._id }); // No problems if one field to take doesn't exist
cursor.projection({ age: 1, name: 1, _id: 0 });
cursor.exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(5);
assert.deepEqual(docs[0], { age: 5, name: 'Jo' });
assert.deepEqual(docs[1], { age: 23, name: 'LM' });
assert.deepEqual(docs[2], { age: 52, name: 'Grafitti' });
assert.deepEqual(docs[3], { age: 57, name: 'Louis' });
assert.deepEqual(docs[4], { age: 89 }); // No problems if one field to take doesn't exist
done();
});
});
});
it('Can omit only the expected fields', function (done) {
var cursor = new Cursor(d, {});
cursor.sort({ age: 1 }); // For easier finding
cursor.projection({ age: 0, name: 0 });
cursor.exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(5);
// Takes the _id by default
assert.deepEqual(docs[0], { planet: 'B', _id: doc0._id, toys: { bebe: true, ballon: 'much' } });
assert.deepEqual(docs[1], { planet: 'S', _id: doc3._id });
assert.deepEqual(docs[2], { planet: 'C', _id: doc2._id, toys: { bebe: 'kind of' } });
assert.deepEqual(docs[3], { planet: 'R', _id: doc1._id, toys: { bebe: false, ballon: 'yeah' } });
assert.deepEqual(docs[4], { planet: 'Earth', _id: doc4._id });
cursor.projection({ age: 0, name: 0, _id: 0 });
cursor.exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(5);
assert.deepEqual(docs[0], { planet: 'B', toys: { bebe: true, ballon: 'much' } });
assert.deepEqual(docs[1], { planet: 'S' });
assert.deepEqual(docs[2], { planet: 'C', toys: { bebe: 'kind of' } });
assert.deepEqual(docs[3], { planet: 'R', toys: { bebe: false, ballon: 'yeah' } });
assert.deepEqual(docs[4], { planet: 'Earth' });
done();
});
});
});
it('Cannot use both modes except for _id', function (done) {
var cursor = new Cursor(d, {});
cursor.sort({ age: 1 }); // For easier finding
cursor.projection({ age: 1, name: 0 });
cursor.exec(function (err, docs) {
assert.isNotNull(err);
assert.isUndefined(docs);
cursor.projection({ age: 1, _id: 0 });
cursor.exec(function (err, docs) {
assert.isNull(err);
assert.deepEqual(docs[0], { age: 5 });
assert.deepEqual(docs[1], { age: 23 });
assert.deepEqual(docs[2], { age: 52 });
assert.deepEqual(docs[3], { age: 57 });
assert.deepEqual(docs[4], { age: 89 });
cursor.projection({ age: 0, toys: 0, planet: 0, _id: 1 });
cursor.exec(function (err, docs) {
assert.isNull(err);
assert.deepEqual(docs[0], { name: 'Jo', _id: doc0._id });
assert.deepEqual(docs[1], { name: 'LM', _id: doc3._id });
assert.deepEqual(docs[2], { name: 'Grafitti', _id: doc2._id });
assert.deepEqual(docs[3], { name: 'Louis', _id: doc1._id });
assert.deepEqual(docs[4], { _id: doc4._id });
done();
});
});
});
});
it("Projections on embedded documents - omit type", function (done) {
var cursor = new Cursor(d, {});
cursor.sort({ age: 1 }); // For easier finding
cursor.projection({ name: 0, planet: 0, 'toys.bebe': 0, _id: 0 });
cursor.exec(function (err, docs) {
assert.deepEqual(docs[0], { age: 5, toys: { ballon: 'much' } });
assert.deepEqual(docs[1], { age: 23 });
assert.deepEqual(docs[2], { age: 52, toys: {} });
assert.deepEqual(docs[3], { age: 57, toys: { ballon: 'yeah' } });
assert.deepEqual(docs[4], { age: 89 });
done();
});
});
}); // ==== End of 'Projections' ====
});
| test/cursor.test.js | var should = require('chai').should()
, assert = require('chai').assert
, testDb = 'workspace/test.db'
, fs = require('fs')
, path = require('path')
, _ = require('underscore')
, async = require('async')
, model = require('../lib/model')
, Datastore = require('../lib/datastore')
, Persistence = require('../lib/persistence')
, Cursor = require('../lib/cursor')
;
describe('Cursor', function () {
var d;
beforeEach(function (done) {
d = new Datastore({ filename: testDb });
d.filename.should.equal(testDb);
d.inMemoryOnly.should.equal(false);
async.waterfall([
function (cb) {
Persistence.ensureDirectoryExists(path.dirname(testDb), function () {
fs.exists(testDb, function (exists) {
if (exists) {
fs.unlink(testDb, cb);
} else { return cb(); }
});
});
}
, function (cb) {
d.loadDatabase(function (err) {
assert.isNull(err);
d.getAllData().length.should.equal(0);
return cb();
});
}
], done);
});
describe('Without sorting', function () {
beforeEach(function (done) {
d.insert({ age: 5 }, function (err) {
d.insert({ age: 57 }, function (err) {
d.insert({ age: 52 }, function (err) {
d.insert({ age: 23 }, function (err) {
d.insert({ age: 89 }, function (err) {
return done();
});
});
});
});
});
});
it('Without query, an empty query or a simple query and no skip or limit', function (done) {
async.waterfall([
function (cb) {
var cursor = new Cursor(d);
cursor.exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(5);
_.filter(docs, function(doc) { return doc.age === 5; })[0].age.should.equal(5);
_.filter(docs, function(doc) { return doc.age === 57; })[0].age.should.equal(57);
_.filter(docs, function(doc) { return doc.age === 52; })[0].age.should.equal(52);
_.filter(docs, function(doc) { return doc.age === 23; })[0].age.should.equal(23);
_.filter(docs, function(doc) { return doc.age === 89; })[0].age.should.equal(89);
cb();
});
}
, function (cb) {
var cursor = new Cursor(d, {});
cursor.exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(5);
_.filter(docs, function(doc) { return doc.age === 5; })[0].age.should.equal(5);
_.filter(docs, function(doc) { return doc.age === 57; })[0].age.should.equal(57);
_.filter(docs, function(doc) { return doc.age === 52; })[0].age.should.equal(52);
_.filter(docs, function(doc) { return doc.age === 23; })[0].age.should.equal(23);
_.filter(docs, function(doc) { return doc.age === 89; })[0].age.should.equal(89);
cb();
});
}
, function (cb) {
var cursor = new Cursor(d, { age: { $gt: 23 } });
cursor.exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(3);
_.filter(docs, function(doc) { return doc.age === 57; })[0].age.should.equal(57);
_.filter(docs, function(doc) { return doc.age === 52; })[0].age.should.equal(52);
_.filter(docs, function(doc) { return doc.age === 89; })[0].age.should.equal(89);
cb();
});
}
], done);
});
it('With an empty collection', function (done) {
async.waterfall([
function (cb) {
d.remove({}, { multi: true }, function(err) { return cb(err); })
}
, function (cb) {
var cursor = new Cursor(d);
cursor.exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(0);
cb();
});
}
], done);
});
it('With a limit', function (done) {
var cursor = new Cursor(d);
cursor.limit(3);
cursor.exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(3);
// No way to predict which results are returned of course ...
done();
});
});
it('With a skip', function (done) {
var cursor = new Cursor(d);
cursor.skip(2).exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(3);
// No way to predict which results are returned of course ...
done();
});
});
it('With a limit and a skip and method chaining', function (done) {
var cursor = new Cursor(d);
cursor.limit(4).skip(3); // Only way to know that the right number of results was skipped is if limit + skip > number of results
cursor.exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(2);
// No way to predict which results are returned of course ...
done();
});
});
}); // ===== End of 'Without sorting' =====
describe('Sorting of the results', function () {
beforeEach(function (done) {
// We don't know the order in which docs wil be inserted but we ensure correctness by testing both sort orders
d.insert({ age: 5 }, function (err) {
d.insert({ age: 57 }, function (err) {
d.insert({ age: 52 }, function (err) {
d.insert({ age: 23 }, function (err) {
d.insert({ age: 89 }, function (err) {
return done();
});
});
});
});
});
});
it('Using one sort', function (done) {
var cursor, i;
cursor = new Cursor(d, {});
cursor.sort({ age: 1 });
cursor.exec(function (err, docs) {
assert.isNull(err);
// Results are in ascending order
for (i = 0; i < docs.length - 1; i += 1) {
assert(docs[i].age < docs[i + 1].age)
}
cursor.sort({ age: -1 });
cursor.exec(function (err, docs) {
assert.isNull(err);
// Results are in descending order
for (i = 0; i < docs.length - 1; i += 1) {
assert(docs[i].age > docs[i + 1].age)
}
done();
});
});
});
it("Sorting strings with custom string comparison function", function (done) {
var db = new Datastore({ inMemoryOnly: true, autoload: true
, compareStrings: function (a, b) { return a.length - b.length; }
});
db.insert({ name: 'alpha' });
db.insert({ name: 'charlie' });
db.insert({ name: 'zulu' });
db.find({}).sort({ name: 1 }).exec(function (err, docs) {
_.pluck(docs, 'name')[0].should.equal('zulu');
_.pluck(docs, 'name')[1].should.equal('alpha');
_.pluck(docs, 'name')[2].should.equal('charlie');
delete db.compareStrings;
db.find({}).sort({ name: 1 }).exec(function (err, docs) {
_.pluck(docs, 'name')[0].should.equal('alpha');
_.pluck(docs, 'name')[1].should.equal('charlie');
_.pluck(docs, 'name')[2].should.equal('zulu');
done();
});
});
});
it('With an empty collection', function (done) {
async.waterfall([
function (cb) {
d.remove({}, { multi: true }, function(err) { return cb(err); })
}
, function (cb) {
var cursor = new Cursor(d);
cursor.sort({ age: 1 });
cursor.exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(0);
cb();
});
}
], done);
});
it('Ability to chain sorting and exec', function (done) {
var i;
async.waterfall([
function (cb) {
var cursor = new Cursor(d);
cursor.sort({ age: 1 }).exec(function (err, docs) {
assert.isNull(err);
// Results are in ascending order
for (i = 0; i < docs.length - 1; i += 1) {
assert(docs[i].age < docs[i + 1].age)
}
cb();
});
}
, function (cb) {
var cursor = new Cursor(d);
cursor.sort({ age: -1 }).exec(function (err, docs) {
assert.isNull(err);
// Results are in descending order
for (i = 0; i < docs.length - 1; i += 1) {
assert(docs[i].age > docs[i + 1].age)
}
cb();
});
}
], done);
});
it('Using limit and sort', function (done) {
var i;
async.waterfall([
function (cb) {
var cursor = new Cursor(d);
cursor.sort({ age: 1 }).limit(3).exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(3);
docs[0].age.should.equal(5);
docs[1].age.should.equal(23);
docs[2].age.should.equal(52);
cb();
});
}
, function (cb) {
var cursor = new Cursor(d);
cursor.sort({ age: -1 }).limit(2).exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(2);
docs[0].age.should.equal(89);
docs[1].age.should.equal(57);
cb();
});
}
], done);
});
it('Using a limit higher than total number of docs shouldnt cause an error', function (done) {
var i;
async.waterfall([
function (cb) {
var cursor = new Cursor(d);
cursor.sort({ age: 1 }).limit(7).exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(5);
docs[0].age.should.equal(5);
docs[1].age.should.equal(23);
docs[2].age.should.equal(52);
docs[3].age.should.equal(57);
docs[4].age.should.equal(89);
cb();
});
}
], done);
});
it('Using limit and skip with sort', function (done) {
var i;
async.waterfall([
function (cb) {
var cursor = new Cursor(d);
cursor.sort({ age: 1 }).limit(1).skip(2).exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(1);
docs[0].age.should.equal(52);
cb();
});
}
, function (cb) {
var cursor = new Cursor(d);
cursor.sort({ age: 1 }).limit(3).skip(1).exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(3);
docs[0].age.should.equal(23);
docs[1].age.should.equal(52);
docs[2].age.should.equal(57);
cb();
});
}
, function (cb) {
var cursor = new Cursor(d);
cursor.sort({ age: -1 }).limit(2).skip(2).exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(2);
docs[0].age.should.equal(52);
docs[1].age.should.equal(23);
cb();
});
}
], done);
});
it('Using too big a limit and a skip with sort', function (done) {
var i;
async.waterfall([
function (cb) {
var cursor = new Cursor(d);
cursor.sort({ age: 1 }).limit(8).skip(2).exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(3);
docs[0].age.should.equal(52);
docs[1].age.should.equal(57);
docs[2].age.should.equal(89);
cb();
});
}
], done);
});
it('Using too big a skip with sort should return no result', function (done) {
var i;
async.waterfall([
function (cb) {
var cursor = new Cursor(d);
cursor.sort({ age: 1 }).skip(5).exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(0);
cb();
});
}
, function (cb) {
var cursor = new Cursor(d);
cursor.sort({ age: 1 }).skip(7).exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(0);
cb();
});
}
, function (cb) {
var cursor = new Cursor(d);
cursor.sort({ age: 1 }).limit(3).skip(7).exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(0);
cb();
});
}
, function (cb) {
var cursor = new Cursor(d);
cursor.sort({ age: 1 }).limit(6).skip(7).exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(0);
cb();
});
}
], done);
});
it('Sorting strings', function (done) {
async.waterfall([
function (cb) {
d.remove({}, { multi: true }, function (err) {
if (err) { return cb(err); }
d.insert({ name: 'jako'}, function () {
d.insert({ name: 'jakeb' }, function () {
d.insert({ name: 'sue' }, function () {
return cb();
});
});
});
});
}
, function (cb) {
var cursor = new Cursor(d, {});
cursor.sort({ name: 1 }).exec(function (err, docs) {
docs.length.should.equal(3);
docs[0].name.should.equal('jakeb');
docs[1].name.should.equal('jako');
docs[2].name.should.equal('sue');
return cb();
});
}
, function (cb) {
var cursor = new Cursor(d, {});
cursor.sort({ name: -1 }).exec(function (err, docs) {
docs.length.should.equal(3);
docs[0].name.should.equal('sue');
docs[1].name.should.equal('jako');
docs[2].name.should.equal('jakeb');
return cb();
});
}
], done);
});
it('Sorting nested fields with dates', function (done) {
var doc1, doc2, doc3;
async.waterfall([
function (cb) {
d.remove({}, { multi: true }, function (err) {
if (err) { return cb(err); }
d.insert({ event: { recorded: new Date(400) } }, function (err, _doc1) {
doc1 = _doc1;
d.insert({ event: { recorded: new Date(60000) } }, function (err, _doc2) {
doc2 = _doc2;
d.insert({ event: { recorded: new Date(32) } }, function (err, _doc3) {
doc3 = _doc3;
return cb();
});
});
});
});
}
, function (cb) {
var cursor = new Cursor(d, {});
cursor.sort({ "event.recorded": 1 }).exec(function (err, docs) {
docs.length.should.equal(3);
docs[0]._id.should.equal(doc3._id);
docs[1]._id.should.equal(doc1._id);
docs[2]._id.should.equal(doc2._id);
return cb();
});
}
, function (cb) {
var cursor = new Cursor(d, {});
cursor.sort({ "event.recorded": -1 }).exec(function (err, docs) {
docs.length.should.equal(3);
docs[0]._id.should.equal(doc2._id);
docs[1]._id.should.equal(doc1._id);
docs[2]._id.should.equal(doc3._id);
return cb();
});
}
], done);
});
it('Sorting when some fields are undefined', function (done) {
async.waterfall([
function (cb) {
d.remove({}, { multi: true }, function (err) {
if (err) { return cb(err); }
d.insert({ name: 'jako', other: 2 }, function () {
d.insert({ name: 'jakeb', other: 3 }, function () {
d.insert({ name: 'sue' }, function () {
d.insert({ name: 'henry', other: 4 }, function () {
return cb();
});
});
});
});
});
}
, function (cb) {
var cursor = new Cursor(d, {});
cursor.sort({ other: 1 }).exec(function (err, docs) {
docs.length.should.equal(4);
docs[0].name.should.equal('sue');
assert.isUndefined(docs[0].other);
docs[1].name.should.equal('jako');
docs[1].other.should.equal(2);
docs[2].name.should.equal('jakeb');
docs[2].other.should.equal(3);
docs[3].name.should.equal('henry');
docs[3].other.should.equal(4);
return cb();
});
}
, function (cb) {
var cursor = new Cursor(d, { name: { $in: [ 'suzy', 'jakeb', 'jako' ] } });
cursor.sort({ other: -1 }).exec(function (err, docs) {
docs.length.should.equal(2);
docs[0].name.should.equal('jakeb');
docs[0].other.should.equal(3);
docs[1].name.should.equal('jako');
docs[1].other.should.equal(2);
return cb();
});
}
], done);
});
it('Sorting when all fields are undefined', function (done) {
async.waterfall([
function (cb) {
d.remove({}, { multi: true }, function (err) {
if (err) { return cb(err); }
d.insert({ name: 'jako'}, function () {
d.insert({ name: 'jakeb' }, function () {
d.insert({ name: 'sue' }, function () {
return cb();
});
});
});
});
}
, function (cb) {
var cursor = new Cursor(d, {});
cursor.sort({ other: 1 }).exec(function (err, docs) {
docs.length.should.equal(3);
return cb();
});
}
, function (cb) {
var cursor = new Cursor(d, { name: { $in: [ 'sue', 'jakeb', 'jakob' ] } });
cursor.sort({ other: -1 }).exec(function (err, docs) {
docs.length.should.equal(2);
return cb();
});
}
], done);
});
it('Multiple consecutive sorts', function(done) {
async.waterfall([
function (cb) {
d.remove({}, { multi: true }, function (err) {
if (err) { return cb(err); }
d.insert({ name: 'jako', age: 43, nid: 1 }, function () {
d.insert({ name: 'jakeb', age: 43, nid: 2 }, function () {
d.insert({ name: 'sue', age: 12, nid: 3 }, function () {
d.insert({ name: 'zoe', age: 23, nid: 4 }, function () {
d.insert({ name: 'jako', age: 35, nid: 5 }, function () {
return cb();
});
});
});
});
});
});
}
, function (cb) {
var cursor = new Cursor(d, {});
cursor.sort({ name: 1, age: -1 }).exec(function (err, docs) {
docs.length.should.equal(5);
docs[0].nid.should.equal(2);
docs[1].nid.should.equal(1);
docs[2].nid.should.equal(5);
docs[3].nid.should.equal(3);
docs[4].nid.should.equal(4);
return cb();
});
}
, function (cb) {
var cursor = new Cursor(d, {});
cursor.sort({ name: 1, age: 1 }).exec(function (err, docs) {
docs.length.should.equal(5);
docs[0].nid.should.equal(2);
docs[1].nid.should.equal(5);
docs[2].nid.should.equal(1);
docs[3].nid.should.equal(3);
docs[4].nid.should.equal(4);
return cb();
});
}
, function (cb) {
var cursor = new Cursor(d, {});
cursor.sort({ age: 1, name: 1 }).exec(function (err, docs) {
docs.length.should.equal(5);
docs[0].nid.should.equal(3);
docs[1].nid.should.equal(4);
docs[2].nid.should.equal(5);
docs[3].nid.should.equal(2);
docs[4].nid.should.equal(1);
return cb();
});
}
, function (cb) {
var cursor = new Cursor(d, {});
cursor.sort({ age: 1, name: -1 }).exec(function (err, docs) {
docs.length.should.equal(5);
docs[0].nid.should.equal(3);
docs[1].nid.should.equal(4);
docs[2].nid.should.equal(5);
docs[3].nid.should.equal(1);
docs[4].nid.should.equal(2);
return cb();
});
}
], done); });
it('Similar data, multiple consecutive sorts', function(done) {
var i, j, id
, companies = [ 'acme', 'milkman', 'zoinks' ]
, entities = []
;
async.waterfall([
function (cb) {
d.remove({}, { multi: true }, function (err) {
if (err) { return cb(err); }
id = 1;
for (i = 0; i < companies.length; i++) {
for (j = 5; j <= 100; j += 5) {
entities.push({
company: companies[i],
cost: j,
nid: id
});
id++;
}
}
async.each(entities, function(entity, callback) {
d.insert(entity, function() {
callback();
});
}, function(err) {
return cb();
});
});
}
, function (cb) {
var cursor = new Cursor(d, {});
cursor.sort({ company: 1, cost: 1 }).exec(function (err, docs) {
docs.length.should.equal(60);
for (var i = 0; i < docs.length; i++) {
docs[i].nid.should.equal(i+1);
};
return cb();
});
}
], done); });
}); // ===== End of 'Sorting' =====
describe('Projections', function () {
var doc1, doc2, doc3, doc4, doc0;
beforeEach(function (done) {
// We don't know the order in which docs wil be inserted but we ensure correctness by testing both sort orders
d.insert({ age: 5, name: 'Jo', planet: 'B', toys: { bebe: true, ballon: 'much' } }, function (err, _doc0) {
doc0 = _doc0;
d.insert({ age: 57, name: 'Louis', planet: 'R', toys: { ballon: 'yeah', bebe: false } }, function (err, _doc1) {
doc1 = _doc1;
d.insert({ age: 52, name: 'Grafitti', planet: 'C' }, function (err, _doc2) {
doc2 = _doc2;
d.insert({ age: 23, name: 'LM', planet: 'S' }, function (err, _doc3) {
doc3 = _doc3;
d.insert({ age: 89, planet: 'Earth' }, function (err, _doc4) {
doc4 = _doc4;
return done();
});
});
});
});
});
});
it('Takes all results if no projection or empty object given', function (done) {
var cursor = new Cursor(d, {});
cursor.sort({ age: 1 }); // For easier finding
cursor.exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(5);
assert.deepEqual(docs[0], doc0);
assert.deepEqual(docs[1], doc3);
assert.deepEqual(docs[2], doc2);
assert.deepEqual(docs[3], doc1);
assert.deepEqual(docs[4], doc4);
cursor.projection({});
cursor.exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(5);
assert.deepEqual(docs[0], doc0);
assert.deepEqual(docs[1], doc3);
assert.deepEqual(docs[2], doc2);
assert.deepEqual(docs[3], doc1);
assert.deepEqual(docs[4], doc4);
done();
});
});
});
it('Can take only the expected fields', function (done) {
var cursor = new Cursor(d, {});
cursor.sort({ age: 1 }); // For easier finding
cursor.projection({ age: 1, name: 1 });
cursor.exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(5);
// Takes the _id by default
assert.deepEqual(docs[0], { age: 5, name: 'Jo', _id: doc0._id });
assert.deepEqual(docs[1], { age: 23, name: 'LM', _id: doc3._id });
assert.deepEqual(docs[2], { age: 52, name: 'Grafitti', _id: doc2._id });
assert.deepEqual(docs[3], { age: 57, name: 'Louis', _id: doc1._id });
assert.deepEqual(docs[4], { age: 89, _id: doc4._id }); // No problems if one field to take doesn't exist
cursor.projection({ age: 1, name: 1, _id: 0 });
cursor.exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(5);
assert.deepEqual(docs[0], { age: 5, name: 'Jo' });
assert.deepEqual(docs[1], { age: 23, name: 'LM' });
assert.deepEqual(docs[2], { age: 52, name: 'Grafitti' });
assert.deepEqual(docs[3], { age: 57, name: 'Louis' });
assert.deepEqual(docs[4], { age: 89 }); // No problems if one field to take doesn't exist
done();
});
});
});
it('Can omit only the expected fields', function (done) {
var cursor = new Cursor(d, {});
cursor.sort({ age: 1 }); // For easier finding
cursor.projection({ age: 0, name: 0 });
cursor.exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(5);
// Takes the _id by default
assert.deepEqual(docs[0], { planet: 'B', _id: doc0._id, toys: { bebe: true, ballon: 'much' } });
assert.deepEqual(docs[1], { planet: 'S', _id: doc3._id });
assert.deepEqual(docs[2], { planet: 'C', _id: doc2._id });
assert.deepEqual(docs[3], { planet: 'R', _id: doc1._id, toys: { bebe: false, ballon: 'yeah' } });
assert.deepEqual(docs[4], { planet: 'Earth', _id: doc4._id });
cursor.projection({ age: 0, name: 0, _id: 0 });
cursor.exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(5);
assert.deepEqual(docs[0], { planet: 'B', toys: { bebe: true, ballon: 'much' } });
assert.deepEqual(docs[1], { planet: 'S' });
assert.deepEqual(docs[2], { planet: 'C' });
assert.deepEqual(docs[3], { planet: 'R', toys: { bebe: false, ballon: 'yeah' } });
assert.deepEqual(docs[4], { planet: 'Earth' });
done();
});
});
});
it('Cannot use both modes except for _id', function (done) {
var cursor = new Cursor(d, {});
cursor.sort({ age: 1 }); // For easier finding
cursor.projection({ age: 1, name: 0 });
cursor.exec(function (err, docs) {
assert.isNotNull(err);
assert.isUndefined(docs);
cursor.projection({ age: 1, _id: 0 });
cursor.exec(function (err, docs) {
assert.isNull(err);
assert.deepEqual(docs[0], { age: 5 });
assert.deepEqual(docs[1], { age: 23 });
assert.deepEqual(docs[2], { age: 52 });
assert.deepEqual(docs[3], { age: 57 });
assert.deepEqual(docs[4], { age: 89 });
cursor.projection({ age: 0, toys: 0, planet: 0, _id: 1 });
cursor.exec(function (err, docs) {
assert.isNull(err);
assert.deepEqual(docs[0], { name: 'Jo', _id: doc0._id });
assert.deepEqual(docs[1], { name: 'LM', _id: doc3._id });
assert.deepEqual(docs[2], { name: 'Grafitti', _id: doc2._id });
assert.deepEqual(docs[3], { name: 'Louis', _id: doc1._id });
assert.deepEqual(docs[4], { _id: doc4._id });
done();
});
});
});
});
it.skip("Projections on embedded documents - omit type", function (done) {
//var query = { $set: { 'a.b': 1, 'a.c': 'world', 'single': true } };
//var obj = model.modify({}, query);
//console.log("==================");
//console.log(obj);
//obj = model.modify(obj, { $unset: { 'a.b': true, 'a.c': true } });
//console.log("==================");
//console.log(obj);
var obj = model.modify({ argh: true }, { $unset: { 'nope.nono': 'but yes' } });
console.log(obj);
done();
//var cursor = new Cursor(d, { age: 23 });
//cursor.sort({ age: 1 }); // For easier finding
//cursor.projection({ name: 0, planet: 0, 'toys.bebe': 0 });
//cursor.exec(function (err, docs) {
//console.log(docs);
//done();
//});
});
}); // ==== End of 'Projections' ====
});
| Can use omit projections on nested documents
| test/cursor.test.js | Can use omit projections on nested documents | <ide><path>est/cursor.test.js
<ide> doc0 = _doc0;
<ide> d.insert({ age: 57, name: 'Louis', planet: 'R', toys: { ballon: 'yeah', bebe: false } }, function (err, _doc1) {
<ide> doc1 = _doc1;
<del> d.insert({ age: 52, name: 'Grafitti', planet: 'C' }, function (err, _doc2) {
<add> d.insert({ age: 52, name: 'Grafitti', planet: 'C', toys: { bebe: 'kind of' } }, function (err, _doc2) {
<ide> doc2 = _doc2;
<ide> d.insert({ age: 23, name: 'LM', planet: 'S' }, function (err, _doc3) {
<ide> doc3 = _doc3;
<ide> // Takes the _id by default
<ide> assert.deepEqual(docs[0], { planet: 'B', _id: doc0._id, toys: { bebe: true, ballon: 'much' } });
<ide> assert.deepEqual(docs[1], { planet: 'S', _id: doc3._id });
<del> assert.deepEqual(docs[2], { planet: 'C', _id: doc2._id });
<add> assert.deepEqual(docs[2], { planet: 'C', _id: doc2._id, toys: { bebe: 'kind of' } });
<ide> assert.deepEqual(docs[3], { planet: 'R', _id: doc1._id, toys: { bebe: false, ballon: 'yeah' } });
<ide> assert.deepEqual(docs[4], { planet: 'Earth', _id: doc4._id });
<ide>
<ide> docs.length.should.equal(5);
<ide> assert.deepEqual(docs[0], { planet: 'B', toys: { bebe: true, ballon: 'much' } });
<ide> assert.deepEqual(docs[1], { planet: 'S' });
<del> assert.deepEqual(docs[2], { planet: 'C' });
<add> assert.deepEqual(docs[2], { planet: 'C', toys: { bebe: 'kind of' } });
<ide> assert.deepEqual(docs[3], { planet: 'R', toys: { bebe: false, ballon: 'yeah' } });
<ide> assert.deepEqual(docs[4], { planet: 'Earth' });
<ide>
<ide> });
<ide> });
<ide>
<del> it.skip("Projections on embedded documents - omit type", function (done) {
<del> //var query = { $set: { 'a.b': 1, 'a.c': 'world', 'single': true } };
<del> //var obj = model.modify({}, query);
<del>
<del> //console.log("==================");
<del> //console.log(obj);
<del>
<del> //obj = model.modify(obj, { $unset: { 'a.b': true, 'a.c': true } });
<del>
<del> //console.log("==================");
<del> //console.log(obj);
<del>
<del> var obj = model.modify({ argh: true }, { $unset: { 'nope.nono': 'but yes' } });
<del>
<del> console.log(obj);
<del>
<del> done();
<del>
<del> //var cursor = new Cursor(d, { age: 23 });
<del> //cursor.sort({ age: 1 }); // For easier finding
<del> //cursor.projection({ name: 0, planet: 0, 'toys.bebe': 0 });
<del> //cursor.exec(function (err, docs) {
<del> //console.log(docs);
<del>
<del> //done();
<del> //});
<add> it("Projections on embedded documents - omit type", function (done) {
<add> var cursor = new Cursor(d, {});
<add> cursor.sort({ age: 1 }); // For easier finding
<add> cursor.projection({ name: 0, planet: 0, 'toys.bebe': 0, _id: 0 });
<add> cursor.exec(function (err, docs) {
<add> assert.deepEqual(docs[0], { age: 5, toys: { ballon: 'much' } });
<add> assert.deepEqual(docs[1], { age: 23 });
<add> assert.deepEqual(docs[2], { age: 52, toys: {} });
<add> assert.deepEqual(docs[3], { age: 57, toys: { ballon: 'yeah' } });
<add> assert.deepEqual(docs[4], { age: 89 });
<add>
<add> done();
<add> });
<ide> });
<ide>
<ide> }); // ==== End of 'Projections' ==== |
|
Java | apache-2.0 | error: pathspec 'cdap-master/src/test/java/co/cask/cdap/data/tools/DatasetUpgraderTest.java' did not match any file(s) known to git
| 03bef1dc3babf0d877a1f16c948e58816bad34c9 | 1 | mpouttuclarke/cdap,caskdata/cdap,anthcp/cdap,hsaputra/cdap,hsaputra/cdap,anthcp/cdap,hsaputra/cdap,anthcp/cdap,mpouttuclarke/cdap,mpouttuclarke/cdap,caskdata/cdap,chtyim/cdap,caskdata/cdap,hsaputra/cdap,chtyim/cdap,chtyim/cdap,hsaputra/cdap,anthcp/cdap,caskdata/cdap,mpouttuclarke/cdap,mpouttuclarke/cdap,chtyim/cdap,anthcp/cdap,caskdata/cdap,caskdata/cdap,chtyim/cdap,chtyim/cdap | /*
* Copyright © 2015 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package co.cask.cdap.data.tools;
import co.cask.cdap.api.dataset.DatasetSpecification;
import co.cask.cdap.api.dataset.lib.FileSet;
import co.cask.cdap.api.dataset.lib.FileSetProperties;
import co.cask.cdap.api.dataset.lib.PartitionedFileSet;
import co.cask.cdap.api.dataset.lib.PartitionedFileSetProperties;
import co.cask.cdap.api.dataset.lib.Partitioning;
import co.cask.cdap.common.namespace.NamespacedLocationFactory;
import co.cask.cdap.data2.dataset2.DatasetFramework;
import co.cask.cdap.data2.dataset2.DatasetFrameworkTestUtil;
import co.cask.cdap.data2.dataset2.lib.partitioned.PartitionedFileSetDefinition;
import co.cask.cdap.proto.Id;
import co.cask.tephra.TransactionAware;
import co.cask.tephra.TransactionExecutor;
import co.cask.tephra.TransactionExecutorFactory;
import com.google.common.collect.Iterables;
import com.google.inject.Injector;
import org.apache.twill.filesystem.LocationFactory;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
public class DatasetUpgraderTest {
@ClassRule
public static DatasetFrameworkTestUtil dsFrameworkUtil = new DatasetFrameworkTestUtil();
private static DatasetUpgrader upgrader;
private static DatasetFramework framework;
@BeforeClass
public static void setup() throws Exception {
framework = dsFrameworkUtil.getFramework();
Injector injector = dsFrameworkUtil.getInjector();
upgrader = new DatasetUpgrader(dsFrameworkUtil.getConfiguration(), null,
injector.getInstance(LocationFactory.class),
injector.getInstance(NamespacedLocationFactory.class),
null, framework, new TransactionExecutorFactory() {
@Override
public TransactionExecutor createExecutor(Iterable<TransactionAware> txAwares) {
return dsFrameworkUtil.newTransactionExecutor(Iterables.toArray(txAwares, TransactionAware.class));
}
});
}
static final Id.DatasetInstance FS1 = Id.DatasetInstance.from("test", "fs1");
static final Id.DatasetInstance FS2 = Id.DatasetInstance.from("dummy", "fs2");
static final Id.DatasetInstance FS3 = Id.DatasetInstance.from("default", "fs3");
static final Id.DatasetInstance FS4 = Id.DatasetInstance.from("dummy", "fs4");
static final Id.DatasetInstance PFS1 = Id.DatasetInstance.from("test", "pfs1");
static final Id.DatasetInstance PFS2 = Id.DatasetInstance.from("default", "pfs2");
static final Id.DatasetInstance TPFS1 = Id.DatasetInstance.from("test", "tpfs1");
static final Id.DatasetInstance TPFS2 = Id.DatasetInstance.from("test", "tpfs2");
@Test
public void testFileSetUpgrade() throws Exception {
framework.createNamespace(Id.Namespace.from("test"));
framework.createNamespace(Id.Namespace.from("dummy"));
framework.addInstance(FileSet.class.getName(), FS1,
FileSetProperties.builder().setBasePath("/temp/fs1").build());
DatasetSpecification spec = framework.getDatasetSpec(FS1);
Assert.assertTrue(FileSetProperties.getBasePath(spec.getProperties()).startsWith("/"));
Assert.assertNotNull(upgrader.containsFileSetWithAbsolutePath(spec));
DatasetSpecification newSpec = upgrader.migrateDatasetSpec(spec);
Assert.assertFalse(FileSetProperties.getBasePath(newSpec.getProperties()).startsWith("/"));
Assert.assertNull(upgrader.containsFileSetWithAbsolutePath(newSpec));
framework.addInstance(FileSet.class.getName(), FS2,
FileSetProperties.builder().setBasePath("temp/fs2").build());
spec = framework.getDatasetSpec(FS2);
Assert.assertNull(upgrader.containsFileSetWithAbsolutePath(spec));
framework.addInstance("fileSet", FS3,
FileSetProperties.builder().setBasePath("//temp/fs3").build());
spec = framework.getDatasetSpec(FS1);
Assert.assertTrue(FileSetProperties.getBasePath(spec.getProperties()).startsWith("/"));
Assert.assertNotNull(upgrader.containsFileSetWithAbsolutePath(spec));
newSpec = upgrader.migrateDatasetSpec(spec);
Assert.assertFalse(FileSetProperties.getBasePath(newSpec.getProperties()).startsWith("/"));
Assert.assertNull(upgrader.containsFileSetWithAbsolutePath(newSpec));
framework.addInstance("fileSet", FS4,
FileSetProperties.builder().setBasePath("temp/fs4").build());
spec = framework.getDatasetSpec(FS2);
Assert.assertNull(upgrader.containsFileSetWithAbsolutePath(spec));
Partitioning partitioning = Partitioning.builder().addField("x", Partitioning.FieldType.STRING).build();
framework.addInstance(PartitionedFileSet.class.getName(), PFS1,
PartitionedFileSetProperties.builder()
.setPartitioning(partitioning)
.setBasePath("/temp/pfs1").build());
spec = framework.getDatasetSpec(PFS1);
Assert.assertTrue(FileSetProperties.getBasePath(spec.getProperties()).startsWith("/"));
Assert.assertTrue(FileSetProperties.getBasePath(spec.getSpecification(PartitionedFileSetDefinition.FILESET_NAME)
.getProperties()).startsWith("/"));
Assert.assertNotNull(upgrader.containsFileSetWithAbsolutePath(spec));
newSpec = upgrader.migrateDatasetSpec(spec);
Assert.assertEquals(spec.getSpecification(PartitionedFileSetDefinition.PARTITION_TABLE_NAME),
newSpec.getSpecification(PartitionedFileSetDefinition.PARTITION_TABLE_NAME));
Assert.assertFalse(FileSetProperties.getBasePath(newSpec.getProperties()).startsWith("/"));
Assert.assertFalse(FileSetProperties.getBasePath(newSpec.getSpecification(PartitionedFileSetDefinition.FILESET_NAME)
.getProperties()).startsWith("/"));
Assert.assertNull(upgrader.containsFileSetWithAbsolutePath(newSpec));
framework.addInstance(PartitionedFileSet.class.getName(), PFS2,
PartitionedFileSetProperties.builder()
.setPartitioning(partitioning)
.setBasePath("temp/pfs2").build());
spec = framework.getDatasetSpec(PFS2);
Assert.assertNull(upgrader.containsFileSetWithAbsolutePath(spec));
framework.addInstance(PartitionedFileSet.class.getName(), TPFS1,
FileSetProperties.builder().setBasePath("///temp/tpfs1").build());
spec = framework.getDatasetSpec(TPFS1);
Assert.assertTrue(FileSetProperties.getBasePath(spec.getProperties()).startsWith("/"));
Assert.assertTrue(FileSetProperties.getBasePath(spec.getSpecification(PartitionedFileSetDefinition.FILESET_NAME)
.getProperties()).startsWith("/"));
Assert.assertNotNull(upgrader.containsFileSetWithAbsolutePath(spec));
newSpec = upgrader.migrateDatasetSpec(spec);
Assert.assertEquals(spec.getSpecification(PartitionedFileSetDefinition.PARTITION_TABLE_NAME),
newSpec.getSpecification(PartitionedFileSetDefinition.PARTITION_TABLE_NAME));
Assert.assertFalse(FileSetProperties.getBasePath(newSpec.getProperties()).startsWith("/"));
Assert.assertFalse(FileSetProperties.getBasePath(newSpec.getSpecification(PartitionedFileSetDefinition.FILESET_NAME)
.getProperties()).startsWith("/"));
Assert.assertNull(upgrader.containsFileSetWithAbsolutePath(newSpec));
framework.addInstance(PartitionedFileSet.class.getName(), TPFS2,
FileSetProperties.builder().setBasePath("temp/tpfs2").build());
spec = framework.getDatasetSpec(TPFS2);
Assert.assertNull(upgrader.containsFileSetWithAbsolutePath(spec));
}
}
| cdap-master/src/test/java/co/cask/cdap/data/tools/DatasetUpgraderTest.java | add test case that was left out by previous commit
| cdap-master/src/test/java/co/cask/cdap/data/tools/DatasetUpgraderTest.java | add test case that was left out by previous commit | <ide><path>dap-master/src/test/java/co/cask/cdap/data/tools/DatasetUpgraderTest.java
<add>/*
<add> * Copyright © 2015 Cask Data, Inc.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not
<add> * use this file except in compliance with the License. You may obtain a copy of
<add> * the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
<add> * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
<add> * License for the specific language governing permissions and limitations under
<add> * the License.
<add> */
<add>
<add>package co.cask.cdap.data.tools;
<add>
<add>import co.cask.cdap.api.dataset.DatasetSpecification;
<add>import co.cask.cdap.api.dataset.lib.FileSet;
<add>import co.cask.cdap.api.dataset.lib.FileSetProperties;
<add>import co.cask.cdap.api.dataset.lib.PartitionedFileSet;
<add>import co.cask.cdap.api.dataset.lib.PartitionedFileSetProperties;
<add>import co.cask.cdap.api.dataset.lib.Partitioning;
<add>import co.cask.cdap.common.namespace.NamespacedLocationFactory;
<add>import co.cask.cdap.data2.dataset2.DatasetFramework;
<add>import co.cask.cdap.data2.dataset2.DatasetFrameworkTestUtil;
<add>import co.cask.cdap.data2.dataset2.lib.partitioned.PartitionedFileSetDefinition;
<add>import co.cask.cdap.proto.Id;
<add>import co.cask.tephra.TransactionAware;
<add>import co.cask.tephra.TransactionExecutor;
<add>import co.cask.tephra.TransactionExecutorFactory;
<add>import com.google.common.collect.Iterables;
<add>import com.google.inject.Injector;
<add>import org.apache.twill.filesystem.LocationFactory;
<add>import org.junit.Assert;
<add>import org.junit.BeforeClass;
<add>import org.junit.ClassRule;
<add>import org.junit.Test;
<add>
<add>public class DatasetUpgraderTest {
<add>
<add> @ClassRule
<add> public static DatasetFrameworkTestUtil dsFrameworkUtil = new DatasetFrameworkTestUtil();
<add>
<add> private static DatasetUpgrader upgrader;
<add> private static DatasetFramework framework;
<add>
<add> @BeforeClass
<add> public static void setup() throws Exception {
<add>
<add> framework = dsFrameworkUtil.getFramework();
<add> Injector injector = dsFrameworkUtil.getInjector();
<add> upgrader = new DatasetUpgrader(dsFrameworkUtil.getConfiguration(), null,
<add> injector.getInstance(LocationFactory.class),
<add> injector.getInstance(NamespacedLocationFactory.class),
<add> null, framework, new TransactionExecutorFactory() {
<add> @Override
<add> public TransactionExecutor createExecutor(Iterable<TransactionAware> txAwares) {
<add> return dsFrameworkUtil.newTransactionExecutor(Iterables.toArray(txAwares, TransactionAware.class));
<add> }
<add> });
<add> }
<add>
<add> static final Id.DatasetInstance FS1 = Id.DatasetInstance.from("test", "fs1");
<add> static final Id.DatasetInstance FS2 = Id.DatasetInstance.from("dummy", "fs2");
<add> static final Id.DatasetInstance FS3 = Id.DatasetInstance.from("default", "fs3");
<add> static final Id.DatasetInstance FS4 = Id.DatasetInstance.from("dummy", "fs4");
<add> static final Id.DatasetInstance PFS1 = Id.DatasetInstance.from("test", "pfs1");
<add> static final Id.DatasetInstance PFS2 = Id.DatasetInstance.from("default", "pfs2");
<add> static final Id.DatasetInstance TPFS1 = Id.DatasetInstance.from("test", "tpfs1");
<add> static final Id.DatasetInstance TPFS2 = Id.DatasetInstance.from("test", "tpfs2");
<add>
<add> @Test
<add> public void testFileSetUpgrade() throws Exception {
<add> framework.createNamespace(Id.Namespace.from("test"));
<add> framework.createNamespace(Id.Namespace.from("dummy"));
<add>
<add> framework.addInstance(FileSet.class.getName(), FS1,
<add> FileSetProperties.builder().setBasePath("/temp/fs1").build());
<add> DatasetSpecification spec = framework.getDatasetSpec(FS1);
<add> Assert.assertTrue(FileSetProperties.getBasePath(spec.getProperties()).startsWith("/"));
<add> Assert.assertNotNull(upgrader.containsFileSetWithAbsolutePath(spec));
<add> DatasetSpecification newSpec = upgrader.migrateDatasetSpec(spec);
<add> Assert.assertFalse(FileSetProperties.getBasePath(newSpec.getProperties()).startsWith("/"));
<add> Assert.assertNull(upgrader.containsFileSetWithAbsolutePath(newSpec));
<add>
<add> framework.addInstance(FileSet.class.getName(), FS2,
<add> FileSetProperties.builder().setBasePath("temp/fs2").build());
<add> spec = framework.getDatasetSpec(FS2);
<add> Assert.assertNull(upgrader.containsFileSetWithAbsolutePath(spec));
<add>
<add> framework.addInstance("fileSet", FS3,
<add> FileSetProperties.builder().setBasePath("//temp/fs3").build());
<add> spec = framework.getDatasetSpec(FS1);
<add> Assert.assertTrue(FileSetProperties.getBasePath(spec.getProperties()).startsWith("/"));
<add> Assert.assertNotNull(upgrader.containsFileSetWithAbsolutePath(spec));
<add> newSpec = upgrader.migrateDatasetSpec(spec);
<add> Assert.assertFalse(FileSetProperties.getBasePath(newSpec.getProperties()).startsWith("/"));
<add> Assert.assertNull(upgrader.containsFileSetWithAbsolutePath(newSpec));
<add>
<add> framework.addInstance("fileSet", FS4,
<add> FileSetProperties.builder().setBasePath("temp/fs4").build());
<add> spec = framework.getDatasetSpec(FS2);
<add> Assert.assertNull(upgrader.containsFileSetWithAbsolutePath(spec));
<add>
<add> Partitioning partitioning = Partitioning.builder().addField("x", Partitioning.FieldType.STRING).build();
<add>
<add> framework.addInstance(PartitionedFileSet.class.getName(), PFS1,
<add> PartitionedFileSetProperties.builder()
<add> .setPartitioning(partitioning)
<add> .setBasePath("/temp/pfs1").build());
<add> spec = framework.getDatasetSpec(PFS1);
<add> Assert.assertTrue(FileSetProperties.getBasePath(spec.getProperties()).startsWith("/"));
<add> Assert.assertTrue(FileSetProperties.getBasePath(spec.getSpecification(PartitionedFileSetDefinition.FILESET_NAME)
<add> .getProperties()).startsWith("/"));
<add> Assert.assertNotNull(upgrader.containsFileSetWithAbsolutePath(spec));
<add> newSpec = upgrader.migrateDatasetSpec(spec);
<add> Assert.assertEquals(spec.getSpecification(PartitionedFileSetDefinition.PARTITION_TABLE_NAME),
<add> newSpec.getSpecification(PartitionedFileSetDefinition.PARTITION_TABLE_NAME));
<add> Assert.assertFalse(FileSetProperties.getBasePath(newSpec.getProperties()).startsWith("/"));
<add> Assert.assertFalse(FileSetProperties.getBasePath(newSpec.getSpecification(PartitionedFileSetDefinition.FILESET_NAME)
<add> .getProperties()).startsWith("/"));
<add> Assert.assertNull(upgrader.containsFileSetWithAbsolutePath(newSpec));
<add>
<add> framework.addInstance(PartitionedFileSet.class.getName(), PFS2,
<add> PartitionedFileSetProperties.builder()
<add> .setPartitioning(partitioning)
<add> .setBasePath("temp/pfs2").build());
<add> spec = framework.getDatasetSpec(PFS2);
<add> Assert.assertNull(upgrader.containsFileSetWithAbsolutePath(spec));
<add>
<add> framework.addInstance(PartitionedFileSet.class.getName(), TPFS1,
<add> FileSetProperties.builder().setBasePath("///temp/tpfs1").build());
<add> spec = framework.getDatasetSpec(TPFS1);
<add> Assert.assertTrue(FileSetProperties.getBasePath(spec.getProperties()).startsWith("/"));
<add> Assert.assertTrue(FileSetProperties.getBasePath(spec.getSpecification(PartitionedFileSetDefinition.FILESET_NAME)
<add> .getProperties()).startsWith("/"));
<add> Assert.assertNotNull(upgrader.containsFileSetWithAbsolutePath(spec));
<add> newSpec = upgrader.migrateDatasetSpec(spec);
<add> Assert.assertEquals(spec.getSpecification(PartitionedFileSetDefinition.PARTITION_TABLE_NAME),
<add> newSpec.getSpecification(PartitionedFileSetDefinition.PARTITION_TABLE_NAME));
<add> Assert.assertFalse(FileSetProperties.getBasePath(newSpec.getProperties()).startsWith("/"));
<add> Assert.assertFalse(FileSetProperties.getBasePath(newSpec.getSpecification(PartitionedFileSetDefinition.FILESET_NAME)
<add> .getProperties()).startsWith("/"));
<add> Assert.assertNull(upgrader.containsFileSetWithAbsolutePath(newSpec));
<add>
<add> framework.addInstance(PartitionedFileSet.class.getName(), TPFS2,
<add> FileSetProperties.builder().setBasePath("temp/tpfs2").build());
<add> spec = framework.getDatasetSpec(TPFS2);
<add> Assert.assertNull(upgrader.containsFileSetWithAbsolutePath(spec));
<add> }
<add>
<add>} |
|
Java | apache-2.0 | 9f680f1626ead9381ad1e6d9c0b5d094ca7f7178 | 0 | robinverduijn/gradle,gstevey/gradle,robinverduijn/gradle,robinverduijn/gradle,gradle/gradle,lsmaira/gradle,gradle/gradle,blindpirate/gradle,blindpirate/gradle,lsmaira/gradle,blindpirate/gradle,gradle/gradle,robinverduijn/gradle,gradle/gradle,lsmaira/gradle,gradle/gradle,gstevey/gradle,lsmaira/gradle,blindpirate/gradle,lsmaira/gradle,robinverduijn/gradle,gstevey/gradle,gradle/gradle,gstevey/gradle,robinverduijn/gradle,lsmaira/gradle,blindpirate/gradle,lsmaira/gradle,robinverduijn/gradle,robinverduijn/gradle,gstevey/gradle,gstevey/gradle,blindpirate/gradle,gstevey/gradle,lsmaira/gradle,gradle/gradle,blindpirate/gradle,blindpirate/gradle,robinverduijn/gradle,robinverduijn/gradle,gstevey/gradle,lsmaira/gradle,gradle/gradle,lsmaira/gradle,gstevey/gradle,blindpirate/gradle,blindpirate/gradle,robinverduijn/gradle,gradle/gradle,gradle/gradle | /*
* Copyright 2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.messaging.remote.internal.inet;
import org.gradle.messaging.remote.Address;
import org.gradle.messaging.remote.internal.ConnectCompletion;
import org.gradle.messaging.remote.internal.ConnectException;
import org.gradle.messaging.remote.internal.OutgoingConnector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.*;
import java.nio.channels.SocketChannel;
import java.util.List;
public class TcpOutgoingConnector implements OutgoingConnector {
private static final Logger LOGGER = LoggerFactory.getLogger(TcpOutgoingConnector.class);
private static final int CONNECT_TIMEOUT = 10000;
private static final int MAXIMUM_RETRIES = 3;
public ConnectCompletion connect(Address destinationAddress) throws ConnectException {
if (!(destinationAddress instanceof InetEndpoint)) {
throw new IllegalArgumentException(String.format("Cannot create a connection to address of unknown type: %s.", destinationAddress));
}
InetEndpoint address = (InetEndpoint) destinationAddress;
LOGGER.debug("Attempting to connect to {}.", address);
// Try each address in turn. Not all of them are necessarily reachable (eg when socket option IPV6_V6ONLY
// is on - the default for debian and others), so we will try each of them until we can connect
List<InetAddress> candidateAddresses = address.getCandidates();
// Now try each address
try {
Exception lastFailure = null;
for (InetAddress candidate : candidateAddresses) {
LOGGER.debug("Trying to connect to address {}.", candidate);
SocketChannel socketChannel;
try {
socketChannel = tryConnect(address, candidate);
} catch (SocketException e) {
LOGGER.debug("Cannot connect to address {}, skipping.", candidate);
lastFailure = e;
continue;
} catch (SocketTimeoutException e) {
LOGGER.debug("Timeout connecting to address {}, skipping.", candidate);
lastFailure = e;
continue;
}
LOGGER.debug("Connected to address {}.", socketChannel.socket().getRemoteSocketAddress());
return new SocketConnectCompletion(socketChannel);
}
throw new ConnectException(String.format("Could not connect to server %s. Tried addresses: %s.",
destinationAddress, candidateAddresses), lastFailure);
} catch (ConnectException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(String.format("Could not connect to server %s. Tried addresses: %s.",
destinationAddress, candidateAddresses), e);
}
}
private SocketChannel tryConnect(InetEndpoint address, InetAddress candidate) throws IOException {
for (int i=0; i< MAXIMUM_RETRIES; i++) {
SocketChannel socketChannel = SocketChannel.open();
try {
socketChannel.socket().connect(new InetSocketAddress(candidate, address.getPort()), CONNECT_TIMEOUT);
} catch (IOException e) {
socketChannel.close();
throw e;
}
if (!detectSelfConnect(socketChannel)) {
return socketChannel;
}
LOGGER.debug("Retrying connection... {}/{}", i, MAXIMUM_RETRIES);
socketChannel.close();
}
throw new SocketException("Exceeded retries after detecting TCP self-connect.");
}
boolean detectSelfConnect(SocketChannel socketChannel) {
Socket socket = socketChannel.socket();
SocketAddress localAddress = socket.getLocalSocketAddress();
SocketAddress remoteAddress = socket.getRemoteSocketAddress();
if (localAddress.equals(remoteAddress)) {
LOGGER.debug("Detected that socket was bound to {} while connecting to {}. This looks like the socket connected to itself.",
localAddress, remoteAddress);
return true;
}
return false;
}
}
| subprojects/messaging/src/main/java/org/gradle/messaging/remote/internal/inet/TcpOutgoingConnector.java | /*
* Copyright 2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.messaging.remote.internal.inet;
import org.gradle.messaging.remote.Address;
import org.gradle.messaging.remote.internal.ConnectCompletion;
import org.gradle.messaging.remote.internal.ConnectException;
import org.gradle.messaging.remote.internal.OutgoingConnector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.*;
import java.nio.channels.SocketChannel;
import java.util.List;
public class TcpOutgoingConnector implements OutgoingConnector {
private static final Logger LOGGER = LoggerFactory.getLogger(TcpOutgoingConnector.class);
private static final int CONNECT_TIMEOUT = 10000;
private static final int MAXIMUM_RETRIES = 3;
public ConnectCompletion connect(Address destinationAddress) throws ConnectException {
if (!(destinationAddress instanceof InetEndpoint)) {
throw new IllegalArgumentException(String.format("Cannot create a connection to address of unknown type: %s.", destinationAddress));
}
InetEndpoint address = (InetEndpoint) destinationAddress;
LOGGER.debug("Attempting to connect to {}.", address);
// Try each address in turn. Not all of them are necessarily reachable (eg when socket option IPV6_V6ONLY
// is on - the default for debian and others), so we will try each of them until we can connect
List<InetAddress> candidateAddresses = address.getCandidates();
// Now try each address
try {
Exception lastFailure = null;
for (InetAddress candidate : candidateAddresses) {
LOGGER.debug("Trying to connect to address {}.", candidate);
SocketChannel socketChannel;
try {
socketChannel = tryConnect(address, candidate);
} catch (SocketException e) {
LOGGER.debug("Cannot connect to address {}, skipping.", candidate);
lastFailure = e;
continue;
} catch (SocketTimeoutException e) {
LOGGER.debug("Timeout connecting to address {}, skipping.", candidate);
lastFailure = e;
continue;
}
LOGGER.debug("Connected to address {}.", socketChannel.socket().getRemoteSocketAddress());
return new SocketConnectCompletion(socketChannel);
}
throw new ConnectException(String.format("Could not connect to server %s. Tried addresses: %s.",
destinationAddress, candidateAddresses), lastFailure);
} catch (ConnectException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(String.format("Could not connect to server %s. Tried addresses: %s.",
destinationAddress, candidateAddresses), e);
}
}
private SocketChannel tryConnect(InetEndpoint address, InetAddress candidate) throws IOException {
for (int i=0; i< MAXIMUM_RETRIES; i++) {
SocketChannel socketChannel = SocketChannel.open();
socketChannel.socket().connect(new InetSocketAddress(candidate, address.getPort()), CONNECT_TIMEOUT);
if (!detectSelfConnect(socketChannel)) {
return socketChannel;
}
LOGGER.info("Retrying connection... {}/{}", i, MAXIMUM_RETRIES);
socketChannel.close();
}
throw new SocketException("Exceeded retries after detecting TCP self-connect.");
}
boolean detectSelfConnect(SocketChannel socketChannel) {
Socket socket = socketChannel.socket();
SocketAddress localAddress = socket.getLocalSocketAddress();
SocketAddress remoteAddress = socket.getRemoteSocketAddress();
if (localAddress.equals(remoteAddress)) {
LOGGER.info("Detected that socket was bound to {} while connecting to {}. This looks like the socket connected to itself.",
localAddress, remoteAddress);
return true;
}
return false;
}
}
| Fix review items
+review REVIEW-5610
| subprojects/messaging/src/main/java/org/gradle/messaging/remote/internal/inet/TcpOutgoingConnector.java | Fix review items | <ide><path>ubprojects/messaging/src/main/java/org/gradle/messaging/remote/internal/inet/TcpOutgoingConnector.java
<ide> private SocketChannel tryConnect(InetEndpoint address, InetAddress candidate) throws IOException {
<ide> for (int i=0; i< MAXIMUM_RETRIES; i++) {
<ide> SocketChannel socketChannel = SocketChannel.open();
<del> socketChannel.socket().connect(new InetSocketAddress(candidate, address.getPort()), CONNECT_TIMEOUT);
<add>
<add> try {
<add> socketChannel.socket().connect(new InetSocketAddress(candidate, address.getPort()), CONNECT_TIMEOUT);
<add> } catch (IOException e) {
<add> socketChannel.close();
<add> throw e;
<add> }
<add>
<ide> if (!detectSelfConnect(socketChannel)) {
<ide> return socketChannel;
<ide> }
<del> LOGGER.info("Retrying connection... {}/{}", i, MAXIMUM_RETRIES);
<add> LOGGER.debug("Retrying connection... {}/{}", i, MAXIMUM_RETRIES);
<ide> socketChannel.close();
<ide> }
<ide> throw new SocketException("Exceeded retries after detecting TCP self-connect.");
<ide> SocketAddress localAddress = socket.getLocalSocketAddress();
<ide> SocketAddress remoteAddress = socket.getRemoteSocketAddress();
<ide> if (localAddress.equals(remoteAddress)) {
<del> LOGGER.info("Detected that socket was bound to {} while connecting to {}. This looks like the socket connected to itself.",
<add> LOGGER.debug("Detected that socket was bound to {} while connecting to {}. This looks like the socket connected to itself.",
<ide> localAddress, remoteAddress);
<ide> return true;
<ide> } |
|
Java | agpl-3.0 | c9c91f9fca59f2fc11a614a7a69dcb75ba7bc988 | 0 | duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test | ef49130c-2e60-11e5-9284-b827eb9e62be | hello.java | ef2d5f18-2e60-11e5-9284-b827eb9e62be | ef49130c-2e60-11e5-9284-b827eb9e62be | hello.java | ef49130c-2e60-11e5-9284-b827eb9e62be | <ide><path>ello.java
<del>ef2d5f18-2e60-11e5-9284-b827eb9e62be
<add>ef49130c-2e60-11e5-9284-b827eb9e62be |
|
JavaScript | mit | f9550f872058dc8ef747b57b00e30f0b7d314798 | 0 | blueimp/jQuery-File-Upload,blueimp/jQuery-File-Upload,blueimp/jQuery-File-Upload,blueimp/jQuery-File-Upload,blueimp/jQuery-File-Upload,blueimp/jQuery-File-Upload | /*
* jQuery File Upload Image Preview & Resize Plugin
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2013, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* https://opensource.org/licenses/MIT
*/
/* global define, require */
(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
define([
'jquery',
'load-image',
'load-image-meta',
'load-image-scale',
'load-image-exif',
'canvas-to-blob',
'./jquery.fileupload-process'
], factory);
} else if (typeof exports === 'object') {
// Node/CommonJS:
factory(
require('jquery'),
require('blueimp-load-image/js/load-image'),
require('blueimp-load-image/js/load-image-meta'),
require('blueimp-load-image/js/load-image-scale'),
require('blueimp-load-image/js/load-image-exif'),
require('blueimp-canvas-to-blob'),
require('./jquery.fileupload-process')
);
} else {
// Browser globals:
factory(window.jQuery, window.loadImage);
}
})(function ($, loadImage) {
'use strict';
// Prepend to the default processQueue:
$.blueimp.fileupload.prototype.options.processQueue.unshift(
{
action: 'loadImageMetaData',
disableImageHead: '@',
disableExif: '@',
disableExifThumbnail: '@',
disableExifSub: '@',
disableExifGps: '@',
disabled: '@disableImageMetaDataLoad'
},
{
action: 'loadImage',
// Use the action as prefix for the "@" options:
prefix: true,
fileTypes: '@',
maxFileSize: '@',
noRevoke: '@',
disabled: '@disableImageLoad'
},
{
action: 'resizeImage',
// Use "image" as prefix for the "@" options:
prefix: 'image',
maxWidth: '@',
maxHeight: '@',
minWidth: '@',
minHeight: '@',
crop: '@',
orientation: '@',
forceResize: '@',
disabled: '@disableImageResize'
},
{
action: 'saveImage',
quality: '@imageQuality',
type: '@imageType',
disabled: '@disableImageResize'
},
{
action: 'saveImageMetaData',
disabled: '@disableImageMetaDataSave'
},
{
action: 'resizeImage',
// Use "preview" as prefix for the "@" options:
prefix: 'preview',
maxWidth: '@',
maxHeight: '@',
minWidth: '@',
minHeight: '@',
crop: '@',
orientation: '@',
thumbnail: '@',
canvas: '@',
disabled: '@disableImagePreview'
},
{
action: 'setImage',
name: '@imagePreviewName',
disabled: '@disableImagePreview'
},
{
action: 'deleteImageReferences',
disabled: '@disableImageReferencesDeletion'
}
);
// The File Upload Resize plugin extends the fileupload widget
// with image resize functionality:
$.widget('blueimp.fileupload', $.blueimp.fileupload, {
options: {
// The regular expression for the types of images to load:
// matched against the file type:
loadImageFileTypes: /^image\/(gif|jpeg|png|svg\+xml)$/,
// The maximum file size of images to load:
loadImageMaxFileSize: 10000000, // 10MB
// The maximum width of resized images:
imageMaxWidth: 1920,
// The maximum height of resized images:
imageMaxHeight: 1080,
// Defines the image orientation (1-8) or takes the orientation
// value from Exif data if set to true:
imageOrientation: true,
// Define if resized images should be cropped or only scaled:
imageCrop: false,
// Disable the resize image functionality by default:
disableImageResize: true,
// The maximum width of the preview images:
previewMaxWidth: 80,
// The maximum height of the preview images:
previewMaxHeight: 80,
// Defines the preview orientation (1-8) or takes the orientation
// value from Exif data if set to true:
previewOrientation: true,
// Create the preview using the Exif data thumbnail:
previewThumbnail: true,
// Define if preview images should be cropped or only scaled:
previewCrop: false,
// Define if preview images should be resized as canvas elements:
previewCanvas: true
},
processActions: {
// Loads the image given via data.files and data.index
// as img element, if the browser supports the File API.
// Accepts the options fileTypes (regular expression)
// and maxFileSize (integer) to limit the files to load:
loadImage: function (data, options) {
if (options.disabled) {
return data;
}
var that = this,
file = data.files[data.index],
// eslint-disable-next-line new-cap
dfd = $.Deferred();
if (
($.type(options.maxFileSize) === 'number' &&
file.size > options.maxFileSize) ||
(options.fileTypes && !options.fileTypes.test(file.type)) ||
!loadImage(
file,
function (img) {
if (img.src) {
data.img = img;
}
dfd.resolveWith(that, [data]);
},
options
)
) {
return data;
}
return dfd.promise();
},
// Resizes the image given as data.canvas or data.img
// and updates data.canvas or data.img with the resized image.
// Also stores the resized image as preview property.
// Accepts the options maxWidth, maxHeight, minWidth,
// minHeight, canvas and crop:
resizeImage: function (data, options) {
if (options.disabled || !(data.canvas || data.img)) {
return data;
}
// eslint-disable-next-line no-param-reassign
options = $.extend({ canvas: true }, options);
var that = this,
// eslint-disable-next-line new-cap
dfd = $.Deferred(),
img = (options.canvas && data.canvas) || data.img,
resolve = function (newImg) {
if (
newImg &&
(newImg.width !== img.width ||
newImg.height !== img.height ||
options.forceResize)
) {
data[newImg.getContext ? 'canvas' : 'img'] = newImg;
}
data.preview = newImg;
dfd.resolveWith(that, [data]);
},
thumbnail;
if (data.exif) {
if (options.orientation === true && !loadImage.orientation) {
options.orientation = data.exif.get('Orientation');
}
if (options.thumbnail) {
thumbnail = data.exif.get('Thumbnail');
if (thumbnail) {
loadImage(thumbnail, resolve, options);
return dfd.promise();
}
}
// Prevent orienting the same image twice:
if (data.orientation) {
delete options.orientation;
} else {
data.orientation = options.orientation;
}
}
if (img) {
resolve(loadImage.scale(img, options));
return dfd.promise();
}
return data;
},
// Saves the processed image given as data.canvas
// inplace at data.index of data.files:
saveImage: function (data, options) {
if (!data.canvas || options.disabled) {
return data;
}
var that = this,
file = data.files[data.index],
// eslint-disable-next-line new-cap
dfd = $.Deferred();
if (data.canvas.toBlob) {
data.canvas.toBlob(
function (blob) {
if (!blob.name) {
if (file.type === blob.type) {
blob.name = file.name;
} else if (file.name) {
blob.name = file.name.replace(
/\.\w+$/,
'.' + blob.type.substr(6)
);
}
}
// Don't restore invalid meta data:
if (file.type !== blob.type) {
delete data.imageHead;
}
// Store the created blob at the position
// of the original file in the files list:
data.files[data.index] = blob;
dfd.resolveWith(that, [data]);
},
options.type || file.type,
options.quality
);
} else {
return data;
}
return dfd.promise();
},
loadImageMetaData: function (data, options) {
if (options.disabled) {
return data;
}
var that = this,
// eslint-disable-next-line new-cap
dfd = $.Deferred();
loadImage.parseMetaData(
data.files[data.index],
function (result) {
$.extend(data, result);
dfd.resolveWith(that, [data]);
},
options
);
return dfd.promise();
},
saveImageMetaData: function (data, options) {
if (
!(
data.imageHead &&
data.canvas &&
data.canvas.toBlob &&
!options.disabled
)
) {
return data;
}
var that = this,
file = data.files[data.index],
// eslint-disable-next-line new-cap
dfd = $.Deferred();
if (options.orientation === true || loadImage.orientation) {
// Reset Exif Orientation data:
loadImage.writeExifData(data.imageHead, data, 'Orientation', 1);
}
loadImage.replaceHead(file, data.imageHead, function (blob) {
blob.name = file.name;
data.files[data.index] = blob;
dfd.resolveWith(that, [data]);
});
return dfd.promise();
},
// Sets the resized version of the image as a property of the
// file object, must be called after "saveImage":
setImage: function (data, options) {
if (data.preview && !options.disabled) {
data.files[data.index][options.name || 'preview'] = data.preview;
}
return data;
},
deleteImageReferences: function (data, options) {
if (!options.disabled) {
delete data.img;
delete data.canvas;
delete data.preview;
delete data.imageHead;
}
return data;
}
}
});
});
| js/jquery.fileupload-image.js | /*
* jQuery File Upload Image Preview & Resize Plugin
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2013, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* https://opensource.org/licenses/MIT
*/
/* global define, require */
(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
define([
'jquery',
'load-image',
'load-image-meta',
'load-image-scale',
'load-image-exif',
'canvas-to-blob',
'./jquery.fileupload-process'
], factory);
} else if (typeof exports === 'object') {
// Node/CommonJS:
factory(
require('jquery'),
require('blueimp-load-image/js/load-image'),
require('blueimp-load-image/js/load-image-meta'),
require('blueimp-load-image/js/load-image-scale'),
require('blueimp-load-image/js/load-image-exif'),
require('blueimp-canvas-to-blob'),
require('./jquery.fileupload-process')
);
} else {
// Browser globals:
factory(window.jQuery, window.loadImage);
}
})(function ($, loadImage) {
'use strict';
// Prepend to the default processQueue:
$.blueimp.fileupload.prototype.options.processQueue.unshift(
{
action: 'loadImageMetaData',
disableImageHead: '@',
disableExif: '@',
disableExifThumbnail: '@',
disableExifSub: '@',
disableExifGps: '@',
disabled: '@disableImageMetaDataLoad'
},
{
action: 'loadImage',
// Use the action as prefix for the "@" options:
prefix: true,
fileTypes: '@',
maxFileSize: '@',
noRevoke: '@',
disabled: '@disableImageLoad'
},
{
action: 'resizeImage',
// Use "image" as prefix for the "@" options:
prefix: 'image',
maxWidth: '@',
maxHeight: '@',
minWidth: '@',
minHeight: '@',
crop: '@',
orientation: '@',
forceResize: '@',
disabled: '@disableImageResize'
},
{
action: 'saveImage',
quality: '@imageQuality',
type: '@imageType',
disabled: '@disableImageResize'
},
{
action: 'saveImageMetaData',
disabled: '@disableImageMetaDataSave'
},
{
action: 'resizeImage',
// Use "preview" as prefix for the "@" options:
prefix: 'preview',
maxWidth: '@',
maxHeight: '@',
minWidth: '@',
minHeight: '@',
crop: '@',
orientation: '@',
thumbnail: '@',
canvas: '@',
disabled: '@disableImagePreview'
},
{
action: 'setImage',
name: '@imagePreviewName',
disabled: '@disableImagePreview'
},
{
action: 'deleteImageReferences',
disabled: '@disableImageReferencesDeletion'
}
);
// The File Upload Resize plugin extends the fileupload widget
// with image resize functionality:
$.widget('blueimp.fileupload', $.blueimp.fileupload, {
options: {
// The regular expression for the types of images to load:
// matched against the file type:
loadImageFileTypes: /^image\/(gif|jpeg|png|svg\+xml)$/,
// The maximum file size of images to load:
loadImageMaxFileSize: 10000000, // 10MB
// The maximum width of resized images:
imageMaxWidth: 1920,
// The maximum height of resized images:
imageMaxHeight: 1080,
// Defines the image orientation (1-8) or takes the orientation
// value from Exif data if set to true:
imageOrientation: false,
// Define if resized images should be cropped or only scaled:
imageCrop: false,
// Disable the resize image functionality by default:
disableImageResize: true,
// The maximum width of the preview images:
previewMaxWidth: 80,
// The maximum height of the preview images:
previewMaxHeight: 80,
// Defines the preview orientation (1-8) or takes the orientation
// value from Exif data if set to true:
previewOrientation: true,
// Create the preview using the Exif data thumbnail:
previewThumbnail: true,
// Define if preview images should be cropped or only scaled:
previewCrop: false,
// Define if preview images should be resized as canvas elements:
previewCanvas: true
},
processActions: {
// Loads the image given via data.files and data.index
// as img element, if the browser supports the File API.
// Accepts the options fileTypes (regular expression)
// and maxFileSize (integer) to limit the files to load:
loadImage: function (data, options) {
if (options.disabled) {
return data;
}
var that = this,
file = data.files[data.index],
// eslint-disable-next-line new-cap
dfd = $.Deferred();
if (
($.type(options.maxFileSize) === 'number' &&
file.size > options.maxFileSize) ||
(options.fileTypes && !options.fileTypes.test(file.type)) ||
!loadImage(
file,
function (img) {
if (img.src) {
data.img = img;
}
dfd.resolveWith(that, [data]);
},
options
)
) {
return data;
}
return dfd.promise();
},
// Resizes the image given as data.canvas or data.img
// and updates data.canvas or data.img with the resized image.
// Also stores the resized image as preview property.
// Accepts the options maxWidth, maxHeight, minWidth,
// minHeight, canvas and crop:
resizeImage: function (data, options) {
if (options.disabled || !(data.canvas || data.img)) {
return data;
}
// eslint-disable-next-line no-param-reassign
options = $.extend({ canvas: true }, options);
var that = this,
// eslint-disable-next-line new-cap
dfd = $.Deferred(),
img = (options.canvas && data.canvas) || data.img,
resolve = function (newImg) {
if (
newImg &&
(newImg.width !== img.width ||
newImg.height !== img.height ||
options.forceResize)
) {
data[newImg.getContext ? 'canvas' : 'img'] = newImg;
}
data.preview = newImg;
dfd.resolveWith(that, [data]);
},
thumbnail;
if (data.exif) {
if (options.orientation === true && !loadImage.orientation) {
options.orientation = data.exif.get('Orientation');
}
if (options.thumbnail) {
thumbnail = data.exif.get('Thumbnail');
if (thumbnail) {
loadImage(thumbnail, resolve, options);
return dfd.promise();
}
}
// Prevent orienting the same image twice:
if (data.orientation) {
delete options.orientation;
} else {
data.orientation = options.orientation;
}
}
if (img) {
resolve(loadImage.scale(img, options));
return dfd.promise();
}
return data;
},
// Saves the processed image given as data.canvas
// inplace at data.index of data.files:
saveImage: function (data, options) {
if (!data.canvas || options.disabled) {
return data;
}
var that = this,
file = data.files[data.index],
// eslint-disable-next-line new-cap
dfd = $.Deferred();
if (data.canvas.toBlob) {
data.canvas.toBlob(
function (blob) {
if (!blob.name) {
if (file.type === blob.type) {
blob.name = file.name;
} else if (file.name) {
blob.name = file.name.replace(
/\.\w+$/,
'.' + blob.type.substr(6)
);
}
}
// Don't restore invalid meta data:
if (file.type !== blob.type) {
delete data.imageHead;
}
// Store the created blob at the position
// of the original file in the files list:
data.files[data.index] = blob;
dfd.resolveWith(that, [data]);
},
options.type || file.type,
options.quality
);
} else {
return data;
}
return dfd.promise();
},
loadImageMetaData: function (data, options) {
if (options.disabled) {
return data;
}
var that = this,
// eslint-disable-next-line new-cap
dfd = $.Deferred();
loadImage.parseMetaData(
data.files[data.index],
function (result) {
$.extend(data, result);
dfd.resolveWith(that, [data]);
},
options
);
return dfd.promise();
},
saveImageMetaData: function (data, options) {
if (
!(
data.imageHead &&
data.canvas &&
data.canvas.toBlob &&
!options.disabled
)
) {
return data;
}
var file = data.files[data.index],
blob = new Blob(
[
data.imageHead,
// Resized images always have a head size of 20 bytes,
// including the JPEG marker and a minimal JFIF header:
this._blobSlice.call(file, 20)
],
{ type: file.type }
);
blob.name = file.name;
data.files[data.index] = blob;
return data;
},
// Sets the resized version of the image as a property of the
// file object, must be called after "saveImage":
setImage: function (data, options) {
if (data.preview && !options.disabled) {
data.files[data.index][options.name || 'preview'] = data.preview;
}
return data;
},
deleteImageReferences: function (data, options) {
if (!options.disabled) {
delete data.img;
delete data.canvas;
delete data.preview;
delete data.imageHead;
}
return data;
}
}
});
});
| Save updated Exif Orientation data in image file.
| js/jquery.fileupload-image.js | Save updated Exif Orientation data in image file. | <ide><path>s/jquery.fileupload-image.js
<ide> imageMaxHeight: 1080,
<ide> // Defines the image orientation (1-8) or takes the orientation
<ide> // value from Exif data if set to true:
<del> imageOrientation: false,
<add> imageOrientation: true,
<ide> // Define if resized images should be cropped or only scaled:
<ide> imageCrop: false,
<ide> // Disable the resize image functionality by default:
<ide> ) {
<ide> return data;
<ide> }
<del> var file = data.files[data.index],
<del> blob = new Blob(
<del> [
<del> data.imageHead,
<del> // Resized images always have a head size of 20 bytes,
<del> // including the JPEG marker and a minimal JFIF header:
<del> this._blobSlice.call(file, 20)
<del> ],
<del> { type: file.type }
<del> );
<del> blob.name = file.name;
<del> data.files[data.index] = blob;
<del> return data;
<add> var that = this,
<add> file = data.files[data.index],
<add> // eslint-disable-next-line new-cap
<add> dfd = $.Deferred();
<add> if (options.orientation === true || loadImage.orientation) {
<add> // Reset Exif Orientation data:
<add> loadImage.writeExifData(data.imageHead, data, 'Orientation', 1);
<add> }
<add> loadImage.replaceHead(file, data.imageHead, function (blob) {
<add> blob.name = file.name;
<add> data.files[data.index] = blob;
<add> dfd.resolveWith(that, [data]);
<add> });
<add> return dfd.promise();
<ide> },
<ide>
<ide> // Sets the resized version of the image as a property of the |
|
Java | bsd-2-clause | 7c5fd18b01d9d157928c2588151c19307c76e5d7 | 0 | rinfo/rdl,rinfo/rdl,rinfo/rdl,rinfo/rdl,rinfo/rdl,rinfo/rdl | package se.lagrummet.rinfo.collector;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class AbstractCollectScheduler {
private final Logger logger = LoggerFactory.getLogger(AbstractCollectScheduler.class);
public static final int DEFAULT_INITIAL_DELAY = 0;
public static final int DEFAULT_SCHEDULE_INTERVAL = 600;
public static final String DEFAULT_TIME_UNIT_NAME = "SECONDS";
private int initialDelay = DEFAULT_INITIAL_DELAY;
private int scheduleInterval = DEFAULT_SCHEDULE_INTERVAL;
private TimeUnit timeUnit = TimeUnit.valueOf(DEFAULT_TIME_UNIT_NAME);
private ScheduledExecutorService scheduleService;
private ExecutorService defaultExecutorService =
Executors.newSingleThreadExecutor();
private ConcurrentLinkedQueue<URL> feedQueue =
new ConcurrentLinkedQueue<URL>();
private List<URL> feedInProcess =
Collections.synchronizedList(new ArrayList<URL>());
public int getInitialDelay() {
return initialDelay;
}
public void setInitialDelay(int initialDelay) {
this.initialDelay = initialDelay;
}
public int getScheduleInterval() {
return scheduleInterval;
}
public void setScheduleInterval(int scheduleInterval) {
this.scheduleInterval = scheduleInterval;
}
public String getTimeUnitName() {
return timeUnit.toString();
}
public void setTimeUnitName(String timeUnitName) {
this.timeUnit = TimeUnit.valueOf(timeUnitName);
}
/**
* Get default single threaded executor. Override to implement other thread
* executor strategy.
* @return
*/
public ExecutorService getExecutorService() {
return defaultExecutorService;
}
/**
* @return Collection of approved source feed URLs.
*/
public abstract Collection<URL> getSourceFeedUrls();
/**
* Perform collect of feed from the given URL.
* @param feedUrl
* @param lastInBatch
*/
protected abstract void collectFeed(URL feedUrl, boolean lastInBatch);
/**
* Initiate a fixed rate schedule for collecting all feeds, with an interval
* of <code>scheduleInterval</code>, unless it is set to -1.
*/
public void startup() {
if (scheduleInterval == -1) {
logger.info("Disabled scheduled collects.");
} else {
scheduleService = Executors.newSingleThreadScheduledExecutor();
scheduleService.scheduleAtFixedRate(
new Runnable() {
public void run() { collectAllFeeds(); }
} ,
initialDelay, scheduleInterval, timeUnit);
String unitName = timeUnit.toString().toLowerCase();
logger.info("Scheduled collect every "+scheduleInterval +
" "+unitName+" (starting in "+initialDelay+" "+unitName+").");
}
}
/**
* Shuts down the fixed rate collect schedule and aborts all queued up
* collects that have not yet started. All currently running collects are
* allowed to finish.
*/
public void shutdown() {
if (scheduleService != null) {
scheduleService.shutdown();
}
getExecutorService().shutdown();
if (feedQueue != null) {
if (feedQueue.size() > 0) {
String feeds = "";
for (URL u : feedQueue) {
feeds += "<"+u+">, ";
}
feedQueue.clear();
StringUtils.removeEnd(feeds, ", ");
logger.info("Shutdown prevented the following scheduled feeds to "
+ "be collected: " + feeds);
}
}
}
/**
* Schedule all source feeds for collect.
*/
public void collectAllFeeds() {
Collection<URL> sourceFeedUrls = getSourceFeedUrls();
if (sourceFeedUrls != null) {
logger.info("Starting scheduling for collect of " +
sourceFeedUrls.size() + " source feeds.");
for (URL feedUrl : sourceFeedUrls) {
enqueueCollect(feedUrl);
}
logger.info("Done scheduling source feeds.");
} else {
logger.info("No source feeds to schedule.");
}
}
/**
* Schedule feed to be collected.
*
* @param feedUrl The URL of the feed to collect.
* @return true if the URL was added to the queue, false if it already was
* enqueued.
* @throws NotAllowedSourceFeedException if feed URL is not on the list of
* approved sources.
*/
public boolean triggerFeedCollect(final URL feedUrl)
throws NotAllowedSourceFeedException {
if (!getSourceFeedUrls().contains(feedUrl)) {
throw new NotAllowedSourceFeedException(
"Called triggerFeedCollect with disallowed " +
"feed url: <"+feedUrl+">");
}
return enqueueCollect(feedUrl);
}
private synchronized boolean enqueueCollect(final URL feedUrl) {
if (feedQueue.contains(feedUrl) || feedInProcess.contains(feedUrl)) {
logger.info("Feed <"+feedUrl+"> is already scheduled for collect.");
return false;
} else {
feedQueue.add(feedUrl);
logger.info("Scheduling collect of <"+feedUrl+">.");
getExecutorService().execute(
new Runnable() {
public void run() { executeCollect(); }
}
);
return true;
}
}
private synchronized URL getNextFeed() {
URL feedUrl = feedQueue.peek();
if (feedUrl != null) {
feedInProcess.add(feedUrl);
feedQueue.remove(feedUrl);
}
return feedUrl;
}
private void executeCollect() {
URL feedUrl = getNextFeed();
if (feedUrl != null) {
try {
collectFeed(feedUrl, true);
} finally {
feedInProcess.remove(feedUrl);
}
logger.info("Completed collect of <"+feedUrl+">.");
}
}
}
| packages/java/rinfo-collector/src/main/java/se/lagrummet/rinfo/collector/AbstractCollectScheduler.java | package se.lagrummet.rinfo.collector;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class AbstractCollectScheduler {
private final Logger logger = LoggerFactory.getLogger(AbstractCollectScheduler.class);
public static final int DEFAULT_INITIAL_DELAY = 0;
public static final int DEFAULT_SCHEDULE_INTERVAL = 600;
public static final String DEFAULT_TIME_UNIT_NAME = "SECONDS";
private int initialDelay = DEFAULT_INITIAL_DELAY;
private int scheduleInterval = DEFAULT_SCHEDULE_INTERVAL;
private TimeUnit timeUnit;
private ScheduledExecutorService scheduleService;
private ExecutorService defaultExecutorService =
Executors.newSingleThreadExecutor();
private ConcurrentLinkedQueue<URL> feedQueue =
new ConcurrentLinkedQueue<URL>();
private List<URL> feedInProcess =
Collections.synchronizedList(new ArrayList<URL>());
public int getInitialDelay() {
return initialDelay;
}
public void setInitialDelay(int initialDelay) {
this.initialDelay = initialDelay;
}
public int getScheduleInterval() {
return scheduleInterval;
}
public void setScheduleInterval(int scheduleInterval) {
this.scheduleInterval = scheduleInterval;
}
public String getTimeUnitName() {
return timeUnit.toString();
}
public void setTimeUnitName(String timeUnitName) {
this.timeUnit = TimeUnit.valueOf(timeUnitName);
}
/**
* Get default single threaded executor. Override to implement other thread
* executor strategy.
* @return
*/
public ExecutorService getExecutorService() {
return defaultExecutorService;
}
/**
* @return Collection of approved source feed URLs.
*/
public abstract Collection<URL> getSourceFeedUrls();
/**
* Perform collect of feed from the given URL.
* @param feedUrl
* @param lastInBatch
*/
protected abstract void collectFeed(URL feedUrl, boolean lastInBatch);
/**
* Initiate a fixed rate schedule for collecting all feeds, with an interval
* of <code>scheduleInterval</code>, unless it is set to -1.
*/
public void startup() {
if (scheduleInterval == -1) {
logger.info("Disabled scheduled collects.");
} else {
scheduleService = Executors.newSingleThreadScheduledExecutor();
scheduleService.scheduleAtFixedRate(
new Runnable() {
public void run() { collectAllFeeds(); }
} ,
initialDelay, scheduleInterval, timeUnit);
String unitName = timeUnit.toString().toLowerCase();
logger.info("Scheduled collect every "+scheduleInterval +
" "+unitName+" (starting in "+initialDelay+" "+unitName+").");
}
}
/**
* Shuts down the fixed rate collect schedule and aborts all queued up
* collects that have not yet started. All currently running collects are
* allowed to finish.
*/
public void shutdown() {
if (scheduleService != null) {
scheduleService.shutdown();
}
getExecutorService().shutdown();
if (feedQueue != null) {
if (feedQueue.size() > 0) {
String feeds = "";
for (URL u : feedQueue) {
feeds += "<"+u+">, ";
}
feedQueue.clear();
StringUtils.removeEnd(feeds, ", ");
logger.info("Shutdown prevented the following scheduled feeds to "
+ "be collected: " + feeds);
}
}
}
/**
* Schedule all source feeds for collect.
*/
public void collectAllFeeds() {
Collection<URL> sourceFeedUrls = getSourceFeedUrls();
if (sourceFeedUrls != null) {
logger.info("Starting scheduling for collect of " +
sourceFeedUrls.size() + " source feeds.");
for (URL feedUrl : sourceFeedUrls) {
enqueueCollect(feedUrl);
}
logger.info("Done scheduling source feeds.");
} else {
logger.info("No source feeds to schedule.");
}
}
/**
* Schedule feed to be collected.
*
* @param feedUrl The URL of the feed to collect.
* @return true if the URL was added to the queue, false if it already was
* enqueued.
* @throws NotAllowedSourceFeedException if feed URL is not on the list of
* approved sources.
*/
public boolean triggerFeedCollect(final URL feedUrl)
throws NotAllowedSourceFeedException {
if (!getSourceFeedUrls().contains(feedUrl)) {
throw new NotAllowedSourceFeedException(
"Called triggerFeedCollect with disallowed " +
"feed url: <"+feedUrl+">");
}
return enqueueCollect(feedUrl);
}
private synchronized boolean enqueueCollect(final URL feedUrl) {
if (feedQueue.contains(feedUrl) || feedInProcess.contains(feedUrl)) {
logger.info("Feed <"+feedUrl+"> is already scheduled for collect.");
return false;
} else {
feedQueue.add(feedUrl);
logger.info("Scheduling collect of <"+feedUrl+">.");
getExecutorService().execute(
new Runnable() {
public void run() { executeCollect(); }
}
);
return true;
}
}
private synchronized URL getNextFeed() {
URL feedUrl = feedQueue.peek();
if (feedUrl != null) {
feedInProcess.add(feedUrl);
feedQueue.remove(feedUrl);
}
return feedUrl;
}
private void executeCollect() {
URL feedUrl = getNextFeed();
if (feedUrl != null) {
try {
collectFeed(feedUrl, true);
} finally {
feedInProcess.remove(feedUrl);
}
logger.info("Completed collect of <"+feedUrl+">.");
}
}
}
| AbstractCollectScheduler now sets default timeUnit.
git-svn-id: 35b8e6ee5634bb8613abb5ca40977defa3069cb2@671 f32dfbcc-ef79-4080-89f5-1451246e9e1e
| packages/java/rinfo-collector/src/main/java/se/lagrummet/rinfo/collector/AbstractCollectScheduler.java | AbstractCollectScheduler now sets default timeUnit. | <ide><path>ackages/java/rinfo-collector/src/main/java/se/lagrummet/rinfo/collector/AbstractCollectScheduler.java
<ide>
<ide> private int initialDelay = DEFAULT_INITIAL_DELAY;
<ide> private int scheduleInterval = DEFAULT_SCHEDULE_INTERVAL;
<del> private TimeUnit timeUnit;
<add> private TimeUnit timeUnit = TimeUnit.valueOf(DEFAULT_TIME_UNIT_NAME);
<ide>
<ide> private ScheduledExecutorService scheduleService;
<ide> |
|
Java | apache-2.0 | 1b6e8d654165ab058a30bb4209377d2763de4522 | 0 | tbrooks8/Aeron,tbrooks8/Aeron,jerrinot/Aeron,qed-/Aeron,rlankenau/Aeron,mikeb01/Aeron,qed-/Aeron,RussellWilby/Aeron,real-logic/Aeron,jessefugitt/Aeron,real-logic/Aeron,EvilMcJerkface/Aeron,galderz/Aeron,jessefugitt/Aeron,UIKit0/Aeron,oleksiyp/Aeron,tbrooks8/Aeron,buybackoff/Aeron,EvilMcJerkface/Aeron,jerrinot/Aeron,johnpr01/Aeron,RussellWilby/Aeron,UIKit0/Aeron,mikeb01/Aeron,johnpr01/Aeron,strangelydim/Aeron,gkamal/Aeron,oleksiyp/Aeron,EvilMcJerkface/Aeron,UIKit0/Aeron,galderz/Aeron,rlankenau/Aeron,mikeb01/Aeron,mikeb01/Aeron,oleksiyp/Aeron,lennartj/Aeron,jerrinot/Aeron,rlankenau/Aeron,gkamal/Aeron,ycaihua/Aeron,buybackoff/Aeron,real-logic/Aeron,ycaihua/Aeron,strangelydim/Aeron,gkamal/Aeron,EvilMcJerkface/Aeron,real-logic/Aeron,lennartj/Aeron,qed-/Aeron,jessefugitt/Aeron,strangelydim/Aeron,johnpr01/Aeron,qed-/Aeron,buybackoff/Aeron,ycaihua/Aeron,galderz/Aeron,RussellWilby/Aeron,galderz/Aeron,lennartj/Aeron | /*
* Copyright 2014 Real Logic Ltd.
*
* 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 uk.co.real_logic.aeron.driver;
import uk.co.real_logic.aeron.common.TermHelper;
import uk.co.real_logic.aeron.common.TimerWheel;
import uk.co.real_logic.aeron.common.concurrent.AtomicBuffer;
import uk.co.real_logic.aeron.common.concurrent.logbuffer.FrameDescriptor;
import uk.co.real_logic.aeron.common.concurrent.logbuffer.LogBuffer;
import uk.co.real_logic.aeron.common.concurrent.logbuffer.LogScanner;
import uk.co.real_logic.aeron.common.event.EventCode;
import uk.co.real_logic.aeron.common.event.EventLogger;
import uk.co.real_logic.aeron.common.protocol.DataHeaderFlyweight;
import uk.co.real_logic.aeron.common.protocol.HeaderFlyweight;
import uk.co.real_logic.aeron.common.status.BufferPositionReporter;
import uk.co.real_logic.aeron.driver.buffer.RawLog;
import uk.co.real_logic.aeron.driver.buffer.TermBuffers;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static uk.co.real_logic.aeron.common.BitUtil.align;
import static uk.co.real_logic.aeron.common.TermHelper.termIdToBufferIndex;
import static uk.co.real_logic.aeron.common.concurrent.logbuffer.LogBufferDescriptor.*;
/**
* Publication to be sent to registered subscribers.
*/
public class DriverPublication implements AutoCloseable
{
/** Initial heartbeat timeout (cancelled by SM) */
public static final int INITIAL_HEARTBEAT_TIMEOUT_MS = 100;
public static final long INITIAL_HEARTBEAT_TIMEOUT_NS = MILLISECONDS.toNanos(INITIAL_HEARTBEAT_TIMEOUT_MS);
/** Heartbeat after data sent */
public static final int HEARTBEAT_TIMEOUT_MS = 500;
public static final long HEARTBEAT_TIMEOUT_NS = MILLISECONDS.toNanos(HEARTBEAT_TIMEOUT_MS);
/** Publication is still active. */
public static final int ACTIVE = 1;
/** Client is now closed and stream should be flushed and then cleaned up. */
public static final int EOF = 2;
/** Publication has been flushed to the media. */
public static final int FLUSHED = 3;
private final TimerWheel timerWheel;
private final int sessionId;
private final int streamId;
private final AtomicInteger activeTermId;
private final AtomicLong timeOfLastSendOrHeartbeat;
private final int headerLength;
private final int mtuLength;
private final ByteBuffer scratchByteBuffer = ByteBuffer.allocateDirect(DataHeaderFlyweight.HEADER_LENGTH);
private final AtomicBuffer scratchAtomicBuffer = new AtomicBuffer(scratchByteBuffer);
private final LogScanner[] logScanners = new LogScanner[TermHelper.BUFFER_COUNT];
private final LogScanner[] retransmitLogScanners = new LogScanner[TermHelper.BUFFER_COUNT];
private final ByteBuffer[] sendBuffers = new ByteBuffer[TermHelper.BUFFER_COUNT];
private final AtomicLong positionLimit;
private final SendChannelEndpoint mediaEndpoint;
private final TermBuffers termBuffers;
private final BufferPositionReporter limitReporter;
private final ClientLiveness clientLiveness;
private final DataHeaderFlyweight dataHeader = new DataHeaderFlyweight();
private final DataHeaderFlyweight retransmitDataHeader = new DataHeaderFlyweight();
private final DataHeaderFlyweight sendDataHeader = new DataHeaderFlyweight();
private final int positionBitsToShift;
private final int initialTermId;
private final EventLogger logger;
private final AtomicInteger status = new AtomicInteger(ACTIVE);
private int nextTermOffset = 0;
private int activeIndex = 0;
private int retransmitIndex = 0;
private int statusMessagesSeenCount = 0;
private long nextOffsetPosition = 0;
private long timeOfFlush = 0;
private final InetSocketAddress dstAddress;
public DriverPublication(final SendChannelEndpoint mediaEndpoint,
final TimerWheel timerWheel,
final TermBuffers termBuffers,
final BufferPositionReporter limitReporter,
final ClientLiveness clientLiveness,
final int sessionId,
final int streamId,
final int initialTermId,
final int headerLength,
final int mtuLength,
final long initialPositionLimit,
final EventLogger logger)
{
this.mediaEndpoint = mediaEndpoint;
this.termBuffers = termBuffers;
this.logger = logger;
this.dstAddress = mediaEndpoint.udpChannel().remoteData();
this.timerWheel = timerWheel;
this.limitReporter = limitReporter;
this.clientLiveness = clientLiveness;
this.sessionId = sessionId;
this.streamId = streamId;
this.headerLength = headerLength;
this.mtuLength = mtuLength;
this.activeIndex = termIdToBufferIndex(initialTermId);
final RawLog[] rawLogs = termBuffers.buffers();
for (int i = 0; i < rawLogs.length; i++)
{
logScanners[i] = newScanner(rawLogs[i]);
retransmitLogScanners[i] = newScanner(rawLogs[i]);
sendBuffers[i] = duplicateLogBuffer(rawLogs[i]);
}
final int termCapacity = logScanners[0].capacity();
positionLimit = new AtomicLong(initialPositionLimit);
activeTermId = new AtomicInteger(initialTermId);
final long now = timerWheel.now();
timeOfLastSendOrHeartbeat = new AtomicLong(now);
this.positionBitsToShift = Integer.numberOfTrailingZeros(termCapacity);
this.initialTermId = initialTermId;
limitReporter.position(termCapacity / 2);
}
public void close()
{
termBuffers.close();
limitReporter.close();
}
public int send()
{
int workCount = 0;
if (status() != FLUSHED)
{
try
{
final int availableWindow = (int)(positionLimit.get() - nextOffsetPosition);
final int scanLimit = Math.min(availableWindow, mtuLength);
LogScanner scanner = logScanners[activeIndex];
workCount += scanner.scanNext(this::onSendFrame, scanLimit);
if (scanner.isComplete())
{
activeIndex = TermHelper.rotateNext(activeIndex);
activeTermId.lazySet(activeTermId.get() + 1);
scanner = logScanners[activeIndex];
scanner.seek(0);
}
limitReporter.position(calculatePosition(scanner.offset()) + scanner.capacity());
}
catch (final Exception ex)
{
logger.logException(ex);
}
}
return workCount;
}
public SendChannelEndpoint sendChannelEndpoint()
{
return mediaEndpoint;
}
public int sessionId()
{
return sessionId;
}
public int streamId()
{
return streamId;
}
public void updatePositionLimitFromStatusMessage(final long limit)
{
positionLimit.lazySet(limit);
statusMessagesSeenCount++; // we also got an SM, so w00t!
}
/**
* This is performed on the {@link DriverConductor} thread
*/
public boolean heartbeatCheck()
{
final long timeout = statusMessagesSeenCount > 0 ? HEARTBEAT_TIMEOUT_NS : INITIAL_HEARTBEAT_TIMEOUT_NS;
final long timeSinceLastHeartbeat = timerWheel.now() - timeOfLastSendOrHeartbeat.get();
if (timeSinceLastHeartbeat > timeout)
{
sendHeartbeat();
return true;
}
return false;
}
/**
* This is performed on the {@link DriverConductor} thread
*/
public int cleanLogBuffer()
{
for (final LogBuffer logBuffer : logScanners)
{
if (logBuffer.status() == NEEDS_CLEANING && logBuffer.compareAndSetStatus(NEEDS_CLEANING, IN_CLEANING))
{
logBuffer.clean();
return 1;
}
}
return 0;
}
public long timeOfLastKeepaliveFromClient()
{
return clientLiveness.timeOfLastKeepalive();
}
public int status()
{
return status.get();
}
public void status(final int status)
{
this.status.lazySet(status);
}
public boolean isFlushed()
{
return status() != ACTIVE && logScanners[activeIndex].isFlushed();
}
public int statusMessagesSeenCount()
{
return statusMessagesSeenCount;
}
public void timeOfFlush(final long timestamp)
{
timeOfFlush = timestamp;
}
public long timeOfFlush()
{
return timeOfFlush;
}
public void onRetransmit(final int termId, final int termOffset, final int length)
{
retransmitIndex = determineIndexByTermId(termId);
if (-1 != retransmitIndex)
{
final LogScanner scanner = retransmitLogScanners[retransmitIndex];
scanner.seek(termOffset);
int remainingBytes = length;
do
{
remainingBytes -= scanner.scanNext(this::onSendRetransmit, Math.min(remainingBytes, mtuLength));
}
while (remainingBytes > 0);
}
}
private ByteBuffer duplicateLogBuffer(final RawLog log)
{
final ByteBuffer buffer = log.logBuffer().duplicateByteBuffer();
buffer.clear();
return buffer;
}
private LogScanner newScanner(final RawLog log)
{
return new LogScanner(log.logBuffer(), log.stateBuffer(), headerLength);
}
private int determineIndexByTermId(final int termId)
{
if (termId == activeTermId.get())
{
return activeIndex;
}
else if (termId == activeTermId.get() - 1)
{
return TermHelper.rotatePrevious(activeIndex);
}
return -1;
}
/**
* Function used as a callback for {@link LogScanner.AvailabilityHandler}
*/
private void onSendFrame(final AtomicBuffer buffer, final int offset, final int length)
{
// at this point sendBuffer wraps the same underlying
// ByteBuffer as the buffer parameter
final ByteBuffer sendBuffer = sendBuffers[activeIndex];
sendBuffer.limit(offset + length);
sendBuffer.position(offset);
// if we have a 0 length data message, it is most likely padding, so we will want to adjust it before sending.
// a padding frame may be embedded in a batch that is received. Don't need to adjust that one.
if (DataHeaderFlyweight.HEADER_LENGTH == length)
{
sendDataHeader.wrap(buffer, offset);
if (sendDataHeader.headerType() == PADDING_FRAME_TYPE)
{
final short flags = (short)(sendDataHeader.flags() | DataHeaderFlyweight.PADDING_FLAG);
sendDataHeader.flags(flags);
sendDataHeader.headerType(HeaderFlyweight.HDR_TYPE_DATA);
// the frameLength field will be the length of the padding. But the PADDING flag tells the receiver
// what to do.
}
}
try
{
final int bytesSent = mediaEndpoint.sendTo(sendBuffer, dstAddress);
if (length != bytesSent)
{
throw new IllegalStateException("could not send all of message: " + bytesSent + "/" + length);
}
updateTimeOfLastSendOrHeartbeat(timerWheel.now());
nextTermOffset = align(offset + length, FrameDescriptor.FRAME_ALIGNMENT);
nextOffsetPosition = calculatePosition(nextTermOffset);
}
catch (final Exception ex)
{
logger.logException(ex);
}
}
private void onSendRetransmit(final AtomicBuffer buffer, final int offset, final int length)
{
// use retransmitBuffers, but need to know which one... so, use DataHeaderFlyweight to grab it
retransmitDataHeader.wrap(buffer, offset); // TODO: Is this really used?
final ByteBuffer termRetransmitBuffer = sendBuffers[retransmitIndex];
termRetransmitBuffer.position(offset);
termRetransmitBuffer.limit(offset + length);
try
{
final int bytesSent = mediaEndpoint.sendTo(termRetransmitBuffer, dstAddress);
if (bytesSent != length)
{
logger.log(EventCode.COULD_NOT_FIND_INTERFACE, termRetransmitBuffer, offset, length, dstAddress);
}
}
catch (final Exception ex)
{
logger.logException(ex);
}
}
/**
* This is performed on the {@link DriverConductor} thread
*/
private void sendHeartbeat()
{
// called from conductor thread on timeout
// used for both initial setup 0 length data as well as heartbeats
// send 0 length data frame with current termOffset
dataHeader.wrap(scratchAtomicBuffer, 0);
dataHeader.sessionId(sessionId)
.streamId(streamId)
.termId(activeTermId.get())
.termOffset(nextTermOffset)
.frameLength(DataHeaderFlyweight.HEADER_LENGTH)
.headerType(HeaderFlyweight.HDR_TYPE_DATA)
.flags(DataHeaderFlyweight.BEGIN_AND_END_FLAGS)
.version(HeaderFlyweight.CURRENT_VERSION);
scratchByteBuffer.position(0);
scratchByteBuffer.limit(DataHeaderFlyweight.HEADER_LENGTH);
try
{
final int bytesSent = mediaEndpoint.sendTo(scratchByteBuffer, dstAddress);
if (DataHeaderFlyweight.HEADER_LENGTH != bytesSent)
{
logger.log(EventCode.ERROR_SENDING_HEARTBEAT_PACKET, scratchByteBuffer, 0,
DataHeaderFlyweight.HEADER_LENGTH, dstAddress);
}
updateTimeOfLastSendOrHeartbeat(timerWheel.now());
}
catch (final Exception ex)
{
logger.logException(ex);
}
}
private long calculatePosition(final int currentTail)
{
return TermHelper.calculatePosition(activeTermId.get(), currentTail, positionBitsToShift, initialTermId);
}
private void updateTimeOfLastSendOrHeartbeat(final long time)
{
timeOfLastSendOrHeartbeat.lazySet(time);
}
}
| aeron-driver/src/main/java/uk/co/real_logic/aeron/driver/DriverPublication.java | /*
* Copyright 2014 Real Logic Ltd.
*
* 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 uk.co.real_logic.aeron.driver;
import uk.co.real_logic.aeron.common.TermHelper;
import uk.co.real_logic.aeron.common.TimerWheel;
import uk.co.real_logic.aeron.common.concurrent.AtomicBuffer;
import uk.co.real_logic.aeron.common.concurrent.logbuffer.FrameDescriptor;
import uk.co.real_logic.aeron.common.concurrent.logbuffer.LogBuffer;
import uk.co.real_logic.aeron.common.concurrent.logbuffer.LogScanner;
import uk.co.real_logic.aeron.common.event.EventCode;
import uk.co.real_logic.aeron.common.event.EventLogger;
import uk.co.real_logic.aeron.common.protocol.DataHeaderFlyweight;
import uk.co.real_logic.aeron.common.protocol.HeaderFlyweight;
import uk.co.real_logic.aeron.common.status.BufferPositionReporter;
import uk.co.real_logic.aeron.driver.buffer.RawLog;
import uk.co.real_logic.aeron.driver.buffer.TermBuffers;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static uk.co.real_logic.aeron.common.BitUtil.align;
import static uk.co.real_logic.aeron.common.TermHelper.termIdToBufferIndex;
import static uk.co.real_logic.aeron.common.concurrent.logbuffer.LogBufferDescriptor.*;
/**
* Publication to be sent to registered subscribers.
*/
public class DriverPublication implements AutoCloseable
{
/** Initial heartbeat timeout (cancelled by SM) */
public static final int INITIAL_HEARTBEAT_TIMEOUT_MS = 100;
public static final long INITIAL_HEARTBEAT_TIMEOUT_NS = MILLISECONDS.toNanos(INITIAL_HEARTBEAT_TIMEOUT_MS);
/** Heartbeat after data sent */
public static final int HEARTBEAT_TIMEOUT_MS = 500;
public static final long HEARTBEAT_TIMEOUT_NS = MILLISECONDS.toNanos(HEARTBEAT_TIMEOUT_MS);
/** Publication is still active. */
public static final int ACTIVE = 1;
/** Client is now closed and stream should be flushed and then cleaned up. */
public static final int EOF = 2;
/** Publication has been flushed to the media. */
public static final int FLUSHED = 3;
private final TimerWheel timerWheel;
private final int sessionId;
private final int streamId;
private final AtomicInteger activeTermId;
private final AtomicLong timeOfLastSendOrHeartbeat;
private final int headerLength;
private final int mtuLength;
private final ByteBuffer scratchByteBuffer = ByteBuffer.allocateDirect(DataHeaderFlyweight.HEADER_LENGTH);
private final AtomicBuffer scratchAtomicBuffer = new AtomicBuffer(scratchByteBuffer);
private final LogScanner[] logScanners = new LogScanner[TermHelper.BUFFER_COUNT];
private final LogScanner[] retransmitLogScanners = new LogScanner[TermHelper.BUFFER_COUNT];
private final ByteBuffer[] sendBuffers = new ByteBuffer[TermHelper.BUFFER_COUNT];
private final AtomicLong positionLimit;
private final SendChannelEndpoint mediaEndpoint;
private final TermBuffers termBuffers;
private final BufferPositionReporter limitReporter;
private final ClientLiveness clientLiveness;
private final DataHeaderFlyweight dataHeader = new DataHeaderFlyweight();
private final DataHeaderFlyweight retransmitDataHeader = new DataHeaderFlyweight();
private final DataHeaderFlyweight sendDataHeader = new DataHeaderFlyweight();
private final int positionBitsToShift;
private final int initialTermId;
private final EventLogger logger;
private final AtomicInteger status = new AtomicInteger(ACTIVE);
private int nextTermOffset = 0;
private int activeIndex = 0;
private int retransmitIndex = 0;
private int statusMessagesSeenCount = 0;
private long nextOffsetPosition = 0;
private long timeOfFlush = 0;
private final InetSocketAddress dstAddress;
public DriverPublication(final SendChannelEndpoint mediaEndpoint,
final TimerWheel timerWheel,
final TermBuffers termBuffers,
final BufferPositionReporter limitReporter,
final ClientLiveness clientLiveness,
final int sessionId,
final int streamId,
final int initialTermId,
final int headerLength,
final int mtuLength,
final long initialPositionLimit,
final EventLogger logger)
{
this.mediaEndpoint = mediaEndpoint;
this.termBuffers = termBuffers;
this.logger = logger;
this.dstAddress = mediaEndpoint.udpChannel().remoteData();
this.timerWheel = timerWheel;
this.limitReporter = limitReporter;
this.clientLiveness = clientLiveness;
this.sessionId = sessionId;
this.streamId = streamId;
this.headerLength = headerLength;
this.mtuLength = mtuLength;
this.activeIndex = termIdToBufferIndex(initialTermId);
final RawLog[] rawLogs = termBuffers.buffers();
for (int i = 0; i < rawLogs.length; i++)
{
logScanners[i] = newScanner(rawLogs[i]);
retransmitLogScanners[i] = newScanner(rawLogs[i]);
sendBuffers[i] = duplicateLogBuffer(rawLogs[i]);
}
final int termCapacity = logScanners[0].capacity();
positionLimit = new AtomicLong(initialPositionLimit);
activeTermId = new AtomicInteger(initialTermId);
final long now = timerWheel.now();
timeOfLastSendOrHeartbeat = new AtomicLong(now);
this.positionBitsToShift = Integer.numberOfTrailingZeros(termCapacity);
this.initialTermId = initialTermId;
limitReporter.position(termCapacity / 2);
}
public void close()
{
termBuffers.close();
limitReporter.close();
}
public int send()
{
int workCount = 0;
if (status() != FLUSHED)
{
try
{
final int availableWindow = (int)(positionLimit.get() - nextOffsetPosition);
final int scanLimit = Math.min(availableWindow, mtuLength);
LogScanner scanner = logScanners[activeIndex];
workCount += scanner.scanNext(this::onSendFrame, scanLimit);
if (scanner.isComplete())
{
activeIndex = TermHelper.rotateNext(activeIndex);
activeTermId.lazySet(activeTermId.get() + 1);
scanner = logScanners[activeIndex];
scanner.seek(0);
}
limitReporter.position(calculatePosition(scanner.offset()) + scanner.capacity());
}
catch (final Exception ex)
{
logger.logException(ex);
}
}
return workCount;
}
public SendChannelEndpoint sendChannelEndpoint()
{
return mediaEndpoint;
}
public int sessionId()
{
return sessionId;
}
public int streamId()
{
return streamId;
}
public void updatePositionLimitFromStatusMessage(final long limit)
{
positionLimit.lazySet(limit);
statusMessagesSeenCount++; // we also got an SM, so w00t!
}
/**
* This is performed on the {@link DriverConductor} thread
*/
public boolean heartbeatCheck()
{
final long timeout = statusMessagesSeenCount > 0 ? HEARTBEAT_TIMEOUT_NS : INITIAL_HEARTBEAT_TIMEOUT_NS;
final long timeSinceLastHeartbeat = timerWheel.now() - timeOfLastSendOrHeartbeat.get();
if (timeSinceLastHeartbeat > timeout)
{
sendHeartbeat();
return true;
}
return false;
}
/**
* This is performed on the {@link DriverConductor} thread
*/
public int cleanLogBuffer()
{
for (final LogBuffer logBuffer : logScanners)
{
if (logBuffer.status() == NEEDS_CLEANING && logBuffer.compareAndSetStatus(NEEDS_CLEANING, IN_CLEANING))
{
logBuffer.clean();
return 1;
}
}
return 0;
}
public long timeOfLastKeepaliveFromClient()
{
return clientLiveness.timeOfLastKeepalive();
}
public int status()
{
return status.get();
}
public void status(final int status)
{
this.status.lazySet(status);
}
public boolean isFlushed()
{
return status() != ACTIVE && logScanners[activeIndex].isFlushed();
}
public int statusMessagesSeenCount()
{
return statusMessagesSeenCount;
}
public void timeOfFlush(final long timestamp)
{
timeOfFlush = timestamp;
}
public long timeOfFlush()
{
return timeOfFlush;
}
public void onRetransmit(final int termId, final int termOffset, final int length)
{
retransmitIndex = determineIndexByTermId(termId);
if (-1 != retransmitIndex)
{
final LogScanner scanner = retransmitLogScanners[retransmitIndex];
scanner.seek(termOffset);
int remainingBytes = length;
do
{
remainingBytes -= scanner.scanNext(this::onSendRetransmit, Math.min(remainingBytes, mtuLength));
}
while (remainingBytes > 0);
}
}
private ByteBuffer duplicateLogBuffer(final RawLog log)
{
final ByteBuffer buffer = log.logBuffer().duplicateByteBuffer();
buffer.clear();
return buffer;
}
private LogScanner newScanner(final RawLog log)
{
return new LogScanner(log.logBuffer(), log.stateBuffer(), headerLength);
}
private int determineIndexByTermId(final int termId)
{
if (termId == activeTermId.get())
{
return activeIndex;
}
else if (termId == activeTermId.get() - 1)
{
return TermHelper.rotatePrevious(activeIndex);
}
return -1;
}
/**
* Function used as a callback for {@link LogScanner.AvailabilityHandler}
*/
private void onSendFrame(final AtomicBuffer buffer, final int offset, final int length)
{
// at this point sendBuffer wraps the same underlying
// ByteBuffer as the buffer parameter
final ByteBuffer sendBuffer = sendBuffers[activeIndex];
sendBuffer.limit(offset + length);
sendBuffer.position(offset);
// if we have a 0 length data message, it is most likely padding, so we will want to adjust it before sending.
// a padding frame may be embedded in a batch that is received. Don't need to adjust that one.
if (DataHeaderFlyweight.HEADER_LENGTH == length)
{
sendDataHeader.wrap(buffer, offset);
if (sendDataHeader.headerType() == PADDING_FRAME_TYPE)
{
final short flags = (short)(sendDataHeader.flags() | DataHeaderFlyweight.PADDING_FLAG);
sendDataHeader.flags(flags);
sendDataHeader.headerType(HeaderFlyweight.HDR_TYPE_DATA);
// the frameLength field will be the length of the padding. But the PADDING flag tells the receiver
// what to do.
}
}
try
{
final int bytesSent = mediaEndpoint.sendTo(sendBuffer, dstAddress);
if (length != bytesSent)
{
throw new IllegalStateException("could not send all of message: " + bytesSent + "/" + length);
}
updateTimeOfLastSendOrHeartbeat(timerWheel.now());
nextTermOffset = align(offset + length, FrameDescriptor.FRAME_ALIGNMENT);
nextOffsetPosition =
TermHelper.calculatePosition(activeTermId.get(), nextTermOffset, positionBitsToShift, initialTermId);
}
catch (final Exception ex)
{
logger.logException(ex);
}
}
private void onSendRetransmit(final AtomicBuffer buffer, final int offset, final int length)
{
// use retransmitBuffers, but need to know which one... so, use DataHeaderFlyweight to grab it
retransmitDataHeader.wrap(buffer, offset); // TODO: Is this really used?
final ByteBuffer termRetransmitBuffer = sendBuffers[retransmitIndex];
termRetransmitBuffer.position(offset);
termRetransmitBuffer.limit(offset + length);
try
{
final int bytesSent = mediaEndpoint.sendTo(termRetransmitBuffer, dstAddress);
if (bytesSent != length)
{
logger.log(EventCode.COULD_NOT_FIND_INTERFACE, termRetransmitBuffer, offset, length, dstAddress);
}
}
catch (final Exception ex)
{
logger.logException(ex);
}
}
/**
* This is performed on the {@link DriverConductor} thread
*/
private void sendHeartbeat()
{
// called from conductor thread on timeout
// used for both initial setup 0 length data as well as heartbeats
// send 0 length data frame with current termOffset
dataHeader.wrap(scratchAtomicBuffer, 0);
dataHeader.sessionId(sessionId)
.streamId(streamId)
.termId(activeTermId.get())
.termOffset(nextTermOffset)
.frameLength(DataHeaderFlyweight.HEADER_LENGTH)
.headerType(HeaderFlyweight.HDR_TYPE_DATA)
.flags(DataHeaderFlyweight.BEGIN_AND_END_FLAGS)
.version(HeaderFlyweight.CURRENT_VERSION);
scratchByteBuffer.position(0);
scratchByteBuffer.limit(DataHeaderFlyweight.HEADER_LENGTH);
try
{
final int bytesSent = mediaEndpoint.sendTo(scratchByteBuffer, dstAddress);
if (DataHeaderFlyweight.HEADER_LENGTH != bytesSent)
{
logger.log(EventCode.ERROR_SENDING_HEARTBEAT_PACKET, scratchByteBuffer, 0,
DataHeaderFlyweight.HEADER_LENGTH, dstAddress);
}
updateTimeOfLastSendOrHeartbeat(timerWheel.now());
}
catch (final Exception ex)
{
logger.logException(ex);
}
}
private long calculatePosition(final int currentTail)
{
return TermHelper.calculatePosition(activeTermId.get(), currentTail, positionBitsToShift, initialTermId);
}
private void updateTimeOfLastSendOrHeartbeat(final long time)
{
timeOfLastSendOrHeartbeat.lazySet(time);
}
}
| [Java] DRY by using existing method.
| aeron-driver/src/main/java/uk/co/real_logic/aeron/driver/DriverPublication.java | [Java] DRY by using existing method. | <ide><path>eron-driver/src/main/java/uk/co/real_logic/aeron/driver/DriverPublication.java
<ide> updateTimeOfLastSendOrHeartbeat(timerWheel.now());
<ide>
<ide> nextTermOffset = align(offset + length, FrameDescriptor.FRAME_ALIGNMENT);
<del>
<del> nextOffsetPosition =
<del> TermHelper.calculatePosition(activeTermId.get(), nextTermOffset, positionBitsToShift, initialTermId);
<add> nextOffsetPosition = calculatePosition(nextTermOffset);
<ide> }
<ide> catch (final Exception ex)
<ide> { |
|
Java | agpl-3.0 | 9e029536540e81d4d0b1854515889ab5c49c4903 | 0 | UniversityOfHawaii/kfs,ua-eas/kfs-devops-automation-fork,kuali/kfs,smith750/kfs,kuali/kfs,quikkian-ua-devops/will-financials,ua-eas/kfs-devops-automation-fork,kkronenb/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/kfs,quikkian-ua-devops/will-financials,kuali/kfs,kkronenb/kfs,quikkian-ua-devops/kfs,kkronenb/kfs,smith750/kfs,kuali/kfs,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/will-financials,bhutchinson/kfs,bhutchinson/kfs,ua-eas/kfs,ua-eas/kfs-devops-automation-fork,ua-eas/kfs-devops-automation-fork,bhutchinson/kfs,quikkian-ua-devops/kfs,quikkian-ua-devops/kfs,ua-eas/kfs,bhutchinson/kfs,kuali/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/will-financials,ua-eas/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/kfs,ua-eas/kfs,ua-eas/kfs,quikkian-ua-devops/kfs,smith750/kfs,UniversityOfHawaii/kfs,kkronenb/kfs,quikkian-ua-devops/will-financials,smith750/kfs | /*
* Copyright 2006-2007 The Kuali Foundation.
*
* Licensed under the Educational Community License, Version 1.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/ecl1.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.purap.document.web.struts;
import java.io.ByteArrayOutputStream;
import java.sql.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.StringTokenizer;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.kuali.kfs.module.purap.PurapAuthorizationConstants;
import org.kuali.kfs.module.purap.PurapConstants;
import org.kuali.kfs.module.purap.PurapKeyConstants;
import org.kuali.kfs.module.purap.PurapPropertyConstants;
import org.kuali.kfs.module.purap.SingleConfirmationQuestion;
import org.kuali.kfs.module.purap.PurapConstants.PODocumentsStrings;
import org.kuali.kfs.module.purap.PurapConstants.PurchaseOrderDocTypes;
import org.kuali.kfs.module.purap.PurapConstants.PurchaseOrderStatuses;
import org.kuali.kfs.module.purap.businessobject.PurchaseOrderItem;
import org.kuali.kfs.module.purap.businessobject.PurchaseOrderQuoteList;
import org.kuali.kfs.module.purap.businessobject.PurchaseOrderQuoteListVendor;
import org.kuali.kfs.module.purap.businessobject.PurchaseOrderSensitiveData;
import org.kuali.kfs.module.purap.businessobject.PurchaseOrderVendorQuote;
import org.kuali.kfs.module.purap.businessobject.PurchaseOrderVendorStipulation;
import org.kuali.kfs.module.purap.businessobject.SensitiveData;
import org.kuali.kfs.module.purap.businessobject.SensitiveDataAssignment;
import org.kuali.kfs.module.purap.document.PurchaseOrderDocument;
import org.kuali.kfs.module.purap.document.PurchaseOrderRetransmitDocument;
import org.kuali.kfs.module.purap.document.PurchaseOrderSplitDocument;
import org.kuali.kfs.module.purap.document.service.FaxService;
import org.kuali.kfs.module.purap.document.service.PurapService;
import org.kuali.kfs.module.purap.document.service.PurchaseOrderService;
import org.kuali.kfs.module.purap.document.validation.event.AttributedAddVendorToQuoteEvent;
import org.kuali.kfs.module.purap.document.validation.event.AttributedAssignSensitiveDataEvent;
import org.kuali.kfs.module.purap.document.validation.event.AttributedSplitPurchaseOrderEvent;
import org.kuali.kfs.module.purap.service.SensitiveDataService;
import org.kuali.kfs.sys.KFSConstants;
import org.kuali.kfs.sys.KFSPropertyConstants;
import org.kuali.kfs.sys.context.SpringContext;
import org.kuali.kfs.vnd.VendorConstants.AddressTypes;
import org.kuali.kfs.vnd.businessobject.VendorAddress;
import org.kuali.kfs.vnd.businessobject.VendorDetail;
import org.kuali.kfs.vnd.document.service.VendorService;
import org.kuali.rice.kew.exception.WorkflowException;
import org.kuali.rice.kns.bo.Note;
import org.kuali.rice.kns.document.authorization.DocumentAuthorizer;
import org.kuali.rice.kns.exception.ValidationException;
import org.kuali.rice.kns.question.ConfirmationQuestion;
import org.kuali.rice.kns.service.BusinessObjectService;
import org.kuali.rice.kns.service.DataDictionaryService;
import org.kuali.rice.kns.service.DateTimeService;
import org.kuali.rice.kns.service.DictionaryValidationService;
import org.kuali.rice.kns.service.DocumentHelperService;
import org.kuali.rice.kns.service.DocumentService;
import org.kuali.rice.kns.service.KualiConfigurationService;
import org.kuali.rice.kns.service.KualiRuleService;
import org.kuali.rice.kns.util.GlobalVariables;
import org.kuali.rice.kns.util.ObjectUtils;
import org.kuali.rice.kns.util.UrlFactory;
import org.kuali.rice.kns.util.WebUtils;
import org.kuali.rice.kns.web.struts.form.BlankFormFile;
import org.kuali.rice.kns.web.struts.form.KualiDocumentFormBase;
import org.kuali.rice.kns.workflow.service.KualiWorkflowDocument;
/**
* Struts Action for Purchase Order document.
*/
public class PurchaseOrderAction extends PurchasingActionBase {
private static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(PurchaseOrderAction.class);
/**
* @see org.kuali.rice.kns.web.struts.action.KualiAction#refresh(org.apache.struts.action.ActionMapping,
* org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
@Override
public ActionForward refresh(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
PurchaseOrderForm poForm = (PurchaseOrderForm) form;
// retain error messages after a lookup
WebUtils.reuseErrorMapFromPreviousRequest(poForm);
PurchaseOrderDocument document = (PurchaseOrderDocument) poForm.getDocument();
BusinessObjectService businessObjectService = SpringContext.getBean(BusinessObjectService.class);
// Handling lookups for alternate vendor for non-primary vendor payment that are only specific to Purchase Order.
if (request.getParameter("document.alternateVendorHeaderGeneratedIdentifier") != null && request.getParameter("document.alternateVendorDetailAssignedIdentifier") != null) {
Integer alternateVendorDetailAssignedId = document.getAlternateVendorDetailAssignedIdentifier();
Integer alternateVendorHeaderGeneratedId = document.getAlternateVendorHeaderGeneratedIdentifier();
VendorDetail refreshVendorDetail = new VendorDetail();
refreshVendorDetail.setVendorDetailAssignedIdentifier(alternateVendorDetailAssignedId);
refreshVendorDetail.setVendorHeaderGeneratedIdentifier(alternateVendorHeaderGeneratedId);
refreshVendorDetail = (VendorDetail) businessObjectService.retrieve(refreshVendorDetail);
document.templateAlternateVendor(refreshVendorDetail);
}
// Handling lookups for quote list that is specific to Purchase Order.
if (request.getParameter("document.purchaseOrderQuoteListIdentifier") != null) {
// do a lookup and add all the vendors!
Integer poQuoteListIdentifier = document.getPurchaseOrderQuoteListIdentifier();
PurchaseOrderQuoteList poQuoteList = new PurchaseOrderQuoteList();
poQuoteList.setPurchaseOrderQuoteListIdentifier(poQuoteListIdentifier);
poQuoteList = (PurchaseOrderQuoteList) businessObjectService.retrieve(poQuoteList);
if (poQuoteList.isActiveIndicator()) {
for (PurchaseOrderQuoteListVendor poQuoteListVendor : poQuoteList.getQuoteListVendors()) {
VendorDetail newVendor = poQuoteListVendor.getVendorDetail();
if (newVendor.isActiveIndicator() && !newVendor.isVendorDebarred()) {
PurchaseOrderVendorQuote newPOVendorQuote = SpringContext.getBean(PurchaseOrderService.class).populateQuoteWithVendor(newVendor.getVendorHeaderGeneratedIdentifier(), newVendor.getVendorDetailAssignedIdentifier(), document.getDocumentNumber());
document.getPurchaseOrderVendorQuotes().add(newPOVendorQuote);
}
}
}
}
// Handling lookups for quote vendor search that is specific to Purchase Order.
String newVendorHeaderGeneratedIdentifier = request.getParameter("newPurchaseOrderVendorQuote.vendorHeaderGeneratedIdentifier");
String newVendorDetailAssignedIdentifier = request.getParameter("newPurchaseOrderVendorQuote.vendorDetailAssignedIdentifier");
if (newVendorHeaderGeneratedIdentifier != null && newVendorDetailAssignedIdentifier != null) {
PurchaseOrderVendorQuote newPOVendorQuote = SpringContext.getBean(PurchaseOrderService.class).populateQuoteWithVendor(new Integer(newVendorHeaderGeneratedIdentifier), new Integer(newVendorDetailAssignedIdentifier), document.getDocumentNumber());
poForm.setNewPurchaseOrderVendorQuote(newPOVendorQuote);
}
String newStipulation = request.getParameter(KFSPropertyConstants.DOCUMENT + "." + PurapPropertyConstants.VENDOR_STIPULATION_DESCRIPTION);
if (StringUtils.isNotEmpty(newStipulation)) {
poForm.getNewPurchaseOrderVendorStipulationLine().setVendorStipulationDescription(newStipulation);
}
return super.refresh(mapping, form, request, response);
}
/**
* Inactivate an item from the purchase order document.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @throws Exception
* @return An ActionForward
*/
public ActionForward inactivateItem(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
PurchasingAccountsPayableFormBase purchasingForm = (PurchasingAccountsPayableFormBase) form;
PurchaseOrderDocument purDocument = (PurchaseOrderDocument) purchasingForm.getDocument();
PurchaseOrderItem item = (PurchaseOrderItem) purDocument.getItem(getSelectedLine(request));
item.setItemActiveIndicator(false);
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
/**
* For use with a specific set of methods of this class that create new purchase order-derived document types in response to
* user actions, including <code>closePo</code>, <code>reopenPo</code>, <code>paymentHoldPo</code>, <code>removeHoldPo</code>,
* <code>splitPo</code>, <code>amendPo</code>, and <code>voidPo</code>. It employs the question framework to ask
* the user for a response before creating and routing the new document. The response should consist of a note detailing a
* reason, and either yes or no. This method can be better understood if it is noted that it will be gone through twice (via the
* question framework); when each question is originally asked, and again when the yes/no response is processed, for
* confirmation.
*
* @param mapping These are boiler-plate.
* @param form "
* @param request "
* @param response "
* @param questionType A string identifying the type of question being asked.
* @param confirmType A string identifying which type of question is being confirmed.
* @param documentType A string, the type of document to create
* @param notePrefix A string to appear before the note in the BO Notes tab
* @param messageType A string to appear on the PO once the question framework is done, describing the action taken
* @param operation A string, the verb to insert in the original question describing the action to be taken
* @return An ActionForward
* @throws Exception
*/
private ActionForward askQuestionsAndPerformDocumentAction(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response, String questionType, String confirmType, String documentType, String notePrefix, String messageType, String operation) throws Exception {
LOG.debug("askQuestionsAndPerformDocumentAction started.");
KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
PurchaseOrderDocument po = (PurchaseOrderDocument) kualiDocumentFormBase.getDocument();
Object question = request.getParameter(KFSConstants.QUESTION_INST_ATTRIBUTE_NAME);
String reason = request.getParameter(KFSConstants.QUESTION_REASON_ATTRIBUTE_NAME);
String noteText = "";
try {
KualiConfigurationService kualiConfiguration = SpringContext.getBean(KualiConfigurationService.class);
// Start in logic for confirming the proposed operation.
if (ObjectUtils.isNull(question)) {
String message = "";
if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_SPLIT_DOCUMENT)) {
message = kualiConfiguration.getPropertyString(PurapKeyConstants.PURCHASE_ORDER_SPLIT_QUESTION_TEXT);
}
else {
String key = kualiConfiguration.getPropertyString(PurapKeyConstants.PURCHASE_ORDER_QUESTION_DOCUMENT);
message = StringUtils.replace(key, "{0}", operation);
}
// Ask question if not already asked.
return this.performQuestionWithInput(mapping, form, request, response, questionType, message, KFSConstants.CONFIRMATION_QUESTION, questionType, "");
}
else {
Object buttonClicked = request.getParameter(KFSConstants.QUESTION_CLICKED_BUTTON);
if (question.equals(questionType) && buttonClicked.equals(ConfirmationQuestion.NO)) {
// If 'No' is the button clicked, just reload the doc
return returnToPreviousPage(mapping, kualiDocumentFormBase);
}
else if (question.equals(confirmType) && buttonClicked.equals(SingleConfirmationQuestion.OK)) {
// This is the case when the user clicks on "OK" in the end.
// After we inform the user that the close has been rerouted, we'll redirect to the portal page.
return mapping.findForward(KFSConstants.MAPPING_PORTAL);
}
else {
// Have to check length on value entered.
String introNoteMessage = notePrefix + KFSConstants.BLANK_SPACE;
// Build out full message.
noteText = introNoteMessage + reason;
int noteTextLength = noteText.length();
// Get note text max length from DD.
int noteTextMaxLength = SpringContext.getBean(DataDictionaryService.class).getAttributeMaxLength(Note.class, KFSConstants.NOTE_TEXT_PROPERTY_NAME).intValue();
if (StringUtils.isBlank(reason) || (noteTextLength > noteTextMaxLength)) {
// Figure out exact number of characters that the user can enter.
int reasonLimit = noteTextMaxLength - noteTextLength;
if (ObjectUtils.isNull(reason)) {
// Prevent a NPE by setting the reason to a blank string.
reason = "";
}
return this.performQuestionWithInputAgainBecauseOfErrors(mapping, form, request, response, questionType, kualiConfiguration.getPropertyString(PurapKeyConstants.PURCHASE_ORDER_QUESTION_DOCUMENT), KFSConstants.CONFIRMATION_QUESTION, questionType, "", reason, PurapKeyConstants.ERROR_PURCHASE_ORDER_REASON_REQUIRED, KFSConstants.QUESTION_REASON_ATTRIBUTE_NAME, new Integer(reasonLimit).toString());
}
}
}
// Below used as a place holder to allow code to specify actionForward to return if not a 'success question'
ActionForward returnActionForward = null;
if (!po.isPendingActionIndicator()) {
/*
* Below if-else code block calls PurchaseOrderService methods that will throw ValidationException objects if errors
* occur during any process in the attempt to perform its actions. Assume, if these return successfully, that the
* PurchaseOrderDocument object returned from each is the newly created document and that all actions in the method
* were run correctly. NOTE: IF BELOW IF-ELSE IS EDITED THE NEW METHODS CALLED MUST THROW ValidationException OBJECT
* IF AN ERROR IS ADDED TO THE GlobalVariables
*/
if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_SPLIT_DOCUMENT)) {
po.setPendingSplit(true);
// Save adding the note for after the items are picked.
((PurchaseOrderForm)kualiDocumentFormBase).setSplitNoteText(noteText);
returnActionForward = mapping.findForward(KFSConstants.MAPPING_BASIC);
}
else {
String newStatus = null;
if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_AMENDMENT_DOCUMENT)) {
newStatus = PurchaseOrderStatuses.AMENDMENT;
po = SpringContext.getBean(PurchaseOrderService.class).createAndSavePotentialChangeDocument(kualiDocumentFormBase.getDocument().getDocumentNumber(), documentType, newStatus);
returnActionForward = mapping.findForward(KFSConstants.MAPPING_BASIC);
}
else {
if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_CLOSE_DOCUMENT)) {
newStatus = PurchaseOrderStatuses.PENDING_CLOSE;
}
else if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_REOPEN_DOCUMENT)) {
newStatus = PurchaseOrderStatuses.PENDING_REOPEN;
}
else if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_VOID_DOCUMENT)) {
newStatus = PurchaseOrderStatuses.PENDING_VOID;
}
else if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_PAYMENT_HOLD_DOCUMENT)) {
newStatus = PurchaseOrderStatuses.PENDING_PAYMENT_HOLD;
}
else if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_REMOVE_HOLD_DOCUMENT)) {
newStatus = PurchaseOrderStatuses.PENDING_REMOVE_HOLD;
}
else if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_RETRANSMIT_DOCUMENT)) {
newStatus = PurchaseOrderStatuses.PENDING_RETRANSMIT;
}
po = SpringContext.getBean(PurchaseOrderService.class).createAndRoutePotentialChangeDocument(kualiDocumentFormBase.getDocument().getDocumentNumber(), documentType, kualiDocumentFormBase.getAnnotation(), combineAdHocRecipients(kualiDocumentFormBase), newStatus);
}
if (!GlobalVariables.getErrorMap().isEmpty()) {
throw new ValidationException("errors occurred during new PO creation");
}
String previousDocumentId = kualiDocumentFormBase.getDocId();
// Assume at this point document was created properly and 'po' variable is new PurchaseOrderDocument created
kualiDocumentFormBase.setDocument(po);
kualiDocumentFormBase.setDocId(po.getDocumentNumber());
kualiDocumentFormBase.setDocTypeName(po.getDocumentHeader().getWorkflowDocument().getDocumentType());
Note newNote = new Note();
if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_AMENDMENT_DOCUMENT)) {
noteText = noteText + " (Previous Document Id is " + previousDocumentId + ")";
}
newNote.setNoteText(noteText);
newNote.setNoteTypeCode(KFSConstants.NoteTypeEnum.BUSINESS_OBJECT_NOTE_TYPE.getCode());
kualiDocumentFormBase.setNewNote(newNote);
// see KULPURAP-1984 for an explanation of why this is required and another way to do it.
kualiDocumentFormBase.setAttachmentFile(new BlankFormFile());
insertBONote(mapping, kualiDocumentFormBase, request, response);
}
if (StringUtils.isNotEmpty(messageType)) {
GlobalVariables.getMessageList().add(messageType);
}
}
if (ObjectUtils.isNotNull(returnActionForward)) {
return returnActionForward;
}
else {
return this.performQuestionWithoutInput(mapping, form, request, response, confirmType, kualiConfiguration.getPropertyString(messageType), PODocumentsStrings.SINGLE_CONFIRMATION_QUESTION, questionType, "");
}
}
catch (ValidationException ve) {
throw ve;
}
}
/**
* Invoked when the user pressed on the Close Order button on a Purchase Order page to Close the PO. It will
* display the question page to the user to ask whether the user really wants to close the PO and ask the user to enter a reason
* in the text area. If the user has entered the reason, it will invoke a service method to do the processing for closing a PO,
* then display a Single Confirmation page to inform the user that the PO Close Document has been routed.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @throws Exception
* @return An ActionForward
*/
public ActionForward closePo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
LOG.debug("ClosePO started.");
String operation = "Close ";
PurchaseOrderDocument po = ((PurchaseOrderForm)form).getPurchaseOrderDocument();
if (po.canClosePOForTradeIn()) {
return askQuestionsAndPerformDocumentAction(mapping, form, request, response, PODocumentsStrings.CLOSE_QUESTION, PODocumentsStrings.CLOSE_CONFIRM, PurchaseOrderDocTypes.PURCHASE_ORDER_CLOSE_DOCUMENT, PODocumentsStrings.CLOSE_NOTE_PREFIX, PurapKeyConstants.PURCHASE_ORDER_MESSAGE_CLOSE_DOCUMENT, operation);
}
else {
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
}
/**
* Is invoked when the user pressed on the Payment Hold button on a Purchase Order page to put the PO on hold. It
* will display the question page to the user to ask whether the user really wants to put the PO on hold and ask the user to
* enter a reason in the text area. If the user has entered the reason, it will invoke a service method to do the processing for
* putting a PO on hold, then display a Single Confirmation page to inform the user that the PO Payment Hold Document has been
* routed.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @throws Exception
* @return An ActionForward
*/
public ActionForward paymentHoldPo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
LOG.debug("PaymentHoldPO started.");
String operation = "Hold Payment ";
return askQuestionsAndPerformDocumentAction(mapping, form, request, response, PODocumentsStrings.PAYMENT_HOLD_QUESTION, PODocumentsStrings.PAYMENT_HOLD_CONFIRM, PurchaseOrderDocTypes.PURCHASE_ORDER_PAYMENT_HOLD_DOCUMENT, PODocumentsStrings.PAYMENT_HOLD_NOTE_PREFIX, PurapKeyConstants.PURCHASE_ORDER_MESSAGE_PAYMENT_HOLD, operation);
}
/**
* Is invoked when the user pressed on the Remove Hold button on a Payment Hold PO page to remove the PO from hold.
* It will display the question page to the user to ask whether the user really wants to remove the PO from hold and ask the
* user to enter a reason in the text area. If the user has entered the reason, it will invoke a service method to do the
* processing for removing a PO from hold, then display a Single Confirmation page to inform the user that the PO Remove Hold
* Document has been routed.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @throws Exception
* @return An ActionForward
*/
public ActionForward removeHoldPo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
LOG.debug("RemoveHoldPO started.");
String operation = "Remove Payment Hold ";
ActionForward forward = askQuestionsAndPerformDocumentAction(mapping, form, request, response, PODocumentsStrings.REMOVE_HOLD_QUESTION, PODocumentsStrings.REMOVE_HOLD_CONFIRM, PurchaseOrderDocTypes.PURCHASE_ORDER_REMOVE_HOLD_DOCUMENT, PODocumentsStrings.REMOVE_HOLD_NOTE_PREFIX, PurapKeyConstants.PURCHASE_ORDER_MESSAGE_REMOVE_HOLD, operation);
return forward;
}
/**
* Is invoked when the user pressed on the Open Order button on a Purchase Order page that has status "Close" to
* reopen the PO. It will display the question page to the user to ask whether the user really wants to reopen the PO and ask
* the user to enter a reason in the text area. If the user has entered the reason, it will invoke the a service method to do
* the processing for reopening a PO, then display a Single Confirmation page to inform the user that the
* <code>PurchaseOrderReopenDocument</code> has been routed.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @throws Exception
* @return An ActionForward
* @see org.kuali.kfs.module.purap.document.PurchaseOrderReopenDocument
*/
public ActionForward reopenPo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
LOG.debug("Reopen PO started");
String operation = "Reopen ";
return askQuestionsAndPerformDocumentAction(mapping, form, request, response, PODocumentsStrings.REOPEN_PO_QUESTION, PODocumentsStrings.CONFIRM_REOPEN_QUESTION, PurchaseOrderDocTypes.PURCHASE_ORDER_REOPEN_DOCUMENT, PODocumentsStrings.REOPEN_NOTE_PREFIX, PurapKeyConstants.PURCHASE_ORDER_MESSAGE_REOPEN_DOCUMENT, operation);
}
/**
* Is invoked when the user pressed on the Amend button on a Purchase Order page to amend the PO. It will display
* the question page to the user to ask whether the user really wants to amend the PO and ask the user to enter a reason in the
* text area. If the user has entered the reason, it will invoke a service method to do the processing for amending the PO, then
* display a Single Confirmation page to inform the user that the <code>PurchaseOrderAmendmentDocument</code> has been routed.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @throws Exception
* @return An ActionForward
* @see org.kuali.kfs.module.purap.document.PurchaseOrderAmendmentDocument
*/
public ActionForward amendPo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
LOG.debug("Amend PO started");
String operation = "Amend ";
return askQuestionsAndPerformDocumentAction(mapping, form, request, response, PODocumentsStrings.AMENDMENT_PO_QUESTION, PODocumentsStrings.CONFIRM_AMENDMENT_QUESTION, PurchaseOrderDocTypes.PURCHASE_ORDER_AMENDMENT_DOCUMENT, PODocumentsStrings.AMENDMENT_NOTE_PREFIX, null, operation);
}
/**
* Is invoked when the user pressed on the Void button on a Purchase Order page to void the PO. It will display the
* question page to the user to ask whether the user really wants to void the PO and ask the user to enter a reason in the text
* area. If the user has entered the reason, it will invoke a service method to do the processing for voiding the PO, then
* display a Single Confirmation page to inform the user that the <code>PurchaseOrderVoidDocument</code> has been routed.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @throws Exception
* @return An ActionForward
* @see org.kuali.kfs.module.purap.document.PurchaseOrderVoidDocument
*/
public ActionForward voidPo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
LOG.debug("Void PO started");
String operation = "Void ";
return askQuestionsAndPerformDocumentAction(mapping, form, request, response, PODocumentsStrings.VOID_QUESTION, PODocumentsStrings.VOID_CONFIRM, PurchaseOrderDocTypes.PURCHASE_ORDER_VOID_DOCUMENT, PODocumentsStrings.VOID_NOTE_PREFIX, PurapKeyConstants.PURCHASE_ORDER_MESSAGE_VOID_DOCUMENT, operation);
}
/**
* Invoked to initiate the splitting of a Purchase Order. Displays a question page to ask for a reason and confirmation
* of the user's desire to split the Purchase Order, and, if confirmed, a page on which the Split PO tab only is showing,
* and the items to move to the new PO are chosen. If that is done, and the user continues, a new Split Purchase Order document
* will be created, with the chosen items. That same set of items will be deleted from the original Purchase Order.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServeletRequest
* @param response The HttpServeletResponse
* @return An ActionForward
* @throws Exception
* @see org.kuali.kfs.module.purap.document.PurchaseOrderSplitDocument
*/
public ActionForward splitPo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
LOG.debug("Split PO started");
String operation = "Split ";
return askQuestionsAndPerformDocumentAction(mapping, form, request, response, PODocumentsStrings.SPLIT_QUESTION, PODocumentsStrings.SPLIT_CONFIRM, PurchaseOrderDocTypes.PURCHASE_ORDER_SPLIT_DOCUMENT,PODocumentsStrings.SPLIT_NOTE_PREFIX_OLD_DOC,PurapKeyConstants.PURCHASE_ORDER_MESSAGE_SPLIT_DOCUMENT,operation);
}
/**
* Invoked when only the Split Purchase Order tab is showing to continue the process of splitting the PO, once items are chosen
* to be moved to the new PO.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServeletRequest
* @param response The HttpServeletResponse
* @return An ActionForward
* @throws Exception
*/
public ActionForward continuePurchaseOrderSplit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
LOG.debug("Continue Purchase Order Split started");
PurchaseOrderForm purchaseOrderForm = (PurchaseOrderForm) form;
// This PO does not contain all data, but enough for our purposes; it has been reloaded with only the Split PO tab showing.
PurchaseOrderDocument poToSplit = (PurchaseOrderDocument)purchaseOrderForm.getDocument();
boolean copyNotes = poToSplit.isCopyingNotesWhenSplitting();
// Check business rules before splitting.
boolean rulePassed = SpringContext.getBean(KualiRuleService.class).applyRules(new AttributedSplitPurchaseOrderEvent(poToSplit));
if (!rulePassed) {
poToSplit.setPendingSplit(true);
}
else {
HashMap<String, List<PurchaseOrderItem>> categorizedItems = SpringContext.getBean(PurchaseOrderService.class).categorizeItemsForSplit((List<PurchaseOrderItem>)poToSplit.getItems());
List<PurchaseOrderItem> movingPOItems = categorizedItems.get(PODocumentsStrings.ITEMS_MOVING_TO_SPLIT);
List<PurchaseOrderItem> remainingPOItems = categorizedItems.get(PODocumentsStrings.ITEMS_REMAINING);
// Fetch the whole PO from the database, and reset and renumber the items on it.
poToSplit = (PurchaseOrderDocument)SpringContext.getBean(PurchaseOrderService.class).getCurrentPurchaseOrder(poToSplit.getPurapDocumentIdentifier());
poToSplit.setItems(remainingPOItems);
poToSplit.renumberItems(0);
// Add the note that would normally have gone in after the confirmation page.
String noteText = purchaseOrderForm.getSplitNoteText();
try {
Note splitNote = SpringContext.getBean(DocumentService.class).createNoteFromDocument(poToSplit, noteText);
poToSplit.addNote(splitNote);
} catch ( Exception e ) {
throw new RuntimeException(e);
}
SpringContext.getBean(PurapService.class).saveDocumentNoValidation(poToSplit);
PurchaseOrderSplitDocument splitPO = SpringContext.getBean(PurchaseOrderService.class).createAndSavePurchaseOrderSplitDocument(movingPOItems, poToSplit, copyNotes, noteText);
purchaseOrderForm.setDocument(splitPO);
purchaseOrderForm.setDocId(splitPO.getDocumentNumber());
purchaseOrderForm.setDocTypeName(splitPO.getDocumentHeader().getWorkflowDocument().getDocumentType());
try {
loadDocument(purchaseOrderForm);
}
catch (WorkflowException we) {
throw new RuntimeException(we);
}
}
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
/**
* Invoked from the page on which the Split PO tab is showing to cancel the splitting of the PO and return it to its original state.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServeletRequest
* @param response The HttpServeletResponse
* @return An ActionForward
* @throws Exception
*/
public ActionForward cancelPurchaseOrderSplit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
LOG.debug("Cancel Purchase Order Split started");
PurchaseOrderForm purchaseOrderForm = (PurchaseOrderForm)form;
PurchaseOrderDocument po = (PurchaseOrderDocument)purchaseOrderForm.getDocument();
po = SpringContext.getBean(PurchaseOrderService.class).getPurchaseOrderByDocumentNumber(po.getDocumentNumber());
po.setPendingSplit(false);
po.setCopyingNotesWhenSplitting(false);
purchaseOrderForm.setDocument(po);
reload(mapping, purchaseOrderForm, request, response);
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
/**
* Invoked when an authorized user presses "Sensitive Data" button on the purchase order page.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServeletRequest
* @param response The HttpServeletResponse
* @return An ActionForward
* @throws Exception
*/
public ActionForward assignSensitiveData(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
LOG.debug("Assign Sensitive Data started");
PurchaseOrderForm poForm = (PurchaseOrderForm)form;
PurchaseOrderDocument po = (PurchaseOrderDocument)poForm.getDocument();
Integer poId = po.getPurapDocumentIdentifier();
SensitiveDataService sdService = SpringContext.getBean(SensitiveDataService.class);
// set the assignment flag and reset input fields
poForm.setAssigningSensitiveData(true);
poForm.setSensitiveDataAssignmentReason("");
poForm.setNewSensitiveDataLine(new SensitiveData());
// load previous assignment info
SensitiveDataAssignment sda = sdService.getLastSensitiveDataAssignment(poId);
poForm.setLastSensitiveDataAssignment(sda);
// even though at this point, the sensitive data entries should have been loaded into the form already,
// we still load them again in case that someone else has changed that during the time period
List<SensitiveData> posds = sdService.getSensitiveDatasAssignedByPoId(poId);
poForm.setSensitiveDatasAssigned(posds);
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
/**
* Invoked when an authorized user presses "Submit" button on the "Assign Sensitive Data" page.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServeletRequest
* @param response The HttpServeletResponse
* @return An ActionForward
* @throws Exception
*/
public ActionForward submitSensitiveData(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
LOG.debug("Submit Sensitive Data started");
PurchaseOrderForm poForm = (PurchaseOrderForm)form;
PurchaseOrderDocument po = (PurchaseOrderDocument)poForm.getDocument();
Integer poId = po.getPurapDocumentIdentifier();
List<SensitiveData> sds = poForm.getSensitiveDatasAssigned();
SensitiveDataService sdService = SpringContext.getBean(SensitiveDataService.class);
// check business rules
boolean rulePassed = SpringContext.getBean(KualiRuleService.class).applyRules(new AttributedAssignSensitiveDataEvent("", po, sds));
if (!rulePassed) {
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
// update table SensitiveDataAssignment
SensitiveDataAssignment sda = new SensitiveDataAssignment(poId, poForm.getSensitiveDataAssignmentReason(), GlobalVariables.getUserSession().getPerson().getPrincipalId(), poForm.getSensitiveDatasAssigned());
SpringContext.getBean(BusinessObjectService.class).save(sda);
// update table PurchaseOrderSensitiveData
sdService.deletePurchaseOrderSensitiveDatas(poId);
List<PurchaseOrderSensitiveData> posds = new ArrayList();
for (SensitiveData sd : sds) {
posds.add(new PurchaseOrderSensitiveData(poId, po.getRequisitionIdentifier(), sd.getSensitiveDataCode()));
}
SpringContext.getBean(BusinessObjectService.class).save(posds);
// need this to update workflow doc for searching restrictions on sensitive data
SpringContext.getBean(PurapService.class).saveRoutingDataForRelatedDocuments(po.getAccountsPayablePurchasingDocumentLinkIdentifier());
// reset the sensitive data related fields in the po form
poForm.setAssigningSensitiveData(false);
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
/**
* Invoked when an authorized user presses "Cancel" button on the "Assign Sensitive Data" page.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServeletRequest
* @param response The HttpServeletResponse
* @return An ActionForward
* @throws Exception
*/
public ActionForward cancelSensitiveData(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
LOG.debug("Cancel Sensitive Data started");
// reset the sensitive data flag in the po form, reload sensitive data from database to undo the canceled changes
PurchaseOrderForm poForm = (PurchaseOrderForm)form;
PurchaseOrderDocument po = (PurchaseOrderDocument)poForm.getDocument();
poForm.setAssigningSensitiveData(false);
List<SensitiveData> sds = SpringContext.getBean(SensitiveDataService.class).getSensitiveDatasAssignedByPoId(po.getPurapDocumentIdentifier());
poForm.setSensitiveDatasAssigned(sds);
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
/**
* Invoked when an authorized user presses "Add" button on the "Assign Sensitive Data" page.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServeletRequest
* @param response The HttpServeletResponse
* @return An ActionForward
* @throws Exception
*/
public ActionForward addSensitiveData(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
LOG.debug("Add Sensitive Data started");
PurchaseOrderForm poForm = (PurchaseOrderForm)form;
SensitiveDataService sdService = SpringContext.getBean(SensitiveDataService.class);
// retrieve new sensitive data by code, add the new line
SensitiveData newsd = poForm.getNewSensitiveDataLine();
newsd = sdService.getSensitiveDataByCode(newsd.getSensitiveDataCode());
List<SensitiveData> sds = poForm.getSensitiveDatasAssigned();
sds.add(newsd);
// reset new line
poForm.setNewSensitiveDataLine(new SensitiveData());
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
/**
* Invoked when an authorized user presses "Delete" button on the "Assign Sensitive Data" page.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServeletRequest
* @param response The HttpServeletResponse
* @return An ActionForward
* @throws Exception
*/
public ActionForward deleteSensitiveData(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
LOG.debug("Delete Sensitive Data started");
// remove the selected sensitive data line
PurchaseOrderForm poForm = (PurchaseOrderForm)form;
List<SensitiveData> sds = poForm.getSensitiveDatasAssigned();
sds.remove(getSelectedLine(request));
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
/**
* This is a utility method used to prepare to and to return to a previous page, making sure that the buttons will be restored
* in the process.
*
* @param kualiDocumentFormBase The Form, considered as a KualiDocumentFormBase, as it typically is here.
* @return An actionForward mapping back to the original page.
*/
protected ActionForward returnToPreviousPage(ActionMapping mapping, KualiDocumentFormBase kualiDocumentFormBase) {
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
/**
* Is executed when the user clicks on the "print" button on a Purchase Order Print Document page. On a non
* javascript enabled browser, it will display a page with 2 buttons. One is to display the PDF, the other is to view the PO
* tabbed page where the PO document statuses, buttons, etc have already been updated (the updates of those occurred while the
* <code>performPurchaseOrderFirstTransmitViaPrinting</code> method is invoked. On a javascript enabled browser, it will
* display both the PO tabbed page containing the updated PO document info and the pdf on the next window/tab of the browser.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @throws Exception
* @return An ActionForward
*/
public ActionForward firstTransmitPrintPo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
String poDocId = ((PurchaseOrderForm)form).getDocId();
ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
try {
SpringContext.getBean(PurchaseOrderService.class).performPurchaseOrderFirstTransmitViaPrinting(poDocId, baosPDF);
}
finally {
if (baosPDF != null) {
baosPDF.reset();
}
}
String basePath = getBasePath(request);
String docId = ((PurchaseOrderForm) form).getDocId();
String methodToCallPrintPurchaseOrderPDF = "printPurchaseOrderPDFOnly";
String methodToCallDocHandler = "docHandler";
String printPOPDFUrl = getUrlForPrintPO(basePath, docId, methodToCallPrintPurchaseOrderPDF);
String displayPOTabbedPageUrl = getUrlForPrintPO(basePath, docId, methodToCallDocHandler);
request.setAttribute("printPOPDFUrl", printPOPDFUrl);
request.setAttribute("displayPOTabbedPageUrl", displayPOTabbedPageUrl);
String label = SpringContext.getBean(DataDictionaryService.class).getDocumentLabelByClass(PurchaseOrderDocument.class);
request.setAttribute("purchaseOrderLabel", label);
return mapping.findForward("printPurchaseOrderPDF");
}
/**
* Creates a URL to be used in printing the purchase order.
*
* @param basePath String: The base path of the current URL
* @param docId String: The document ID of the document to be printed
* @param methodToCall String: The name of the method that will be invoked to do this particular print
* @return The URL
*/
private String getUrlForPrintPO(String basePath, String docId, String methodToCall) {
StringBuffer result = new StringBuffer(basePath);
result.append("/purapPurchaseOrder.do?methodToCall=");
result.append(methodToCall);
result.append("&docId=");
result.append(docId);
result.append("&command=displayDocSearchView");
return result.toString();
}
/**
* Prints the PDF only, as opposed to <code>firstTransmitPrintPo</code>, which calls this method (indirectly) to print the
* PDF, and calls the doc handler to display the PO tabbed page.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @throws Exception
* @return An ActionForward
*/
public ActionForward printPurchaseOrderPDFOnly(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
String poDocId = request.getParameter("docId");
ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
try {
// will throw validation exception if errors occur
SpringContext.getBean(PurchaseOrderService.class).performPrintPurchaseOrderPDFOnly(poDocId, baosPDF);
response.setHeader("Cache-Control", "max-age=30");
response.setContentType("application/pdf");
StringBuffer sbContentDispValue = new StringBuffer();
String useJavascript = request.getParameter("useJavascript");
if (useJavascript == null || useJavascript.equalsIgnoreCase("false")) {
sbContentDispValue.append("attachment");
}
else {
sbContentDispValue.append("inline");
}
StringBuffer sbFilename = new StringBuffer();
sbFilename.append("PURAP_PO_");
sbFilename.append(poDocId);
sbFilename.append("_");
sbFilename.append(System.currentTimeMillis());
sbFilename.append(".pdf");
sbContentDispValue.append("; filename=");
sbContentDispValue.append(sbFilename);
response.setHeader("Content-disposition", sbContentDispValue.toString());
response.setContentLength(baosPDF.size());
ServletOutputStream sos;
sos = response.getOutputStream();
baosPDF.writeTo(sos);
sos.flush();
}
finally {
if (baosPDF != null) {
baosPDF.reset();
}
}
return null;
}
/**
* Print a particular selected PO Quote as a PDF.
*
* @param mapping An ActionMapping
* @param form An ActionForm -- The PO Quote must be selected here.
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @throws Exception
* @return An ActionForward
*/
public ActionForward printPoQuote(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
// String poDocId = request.getParameter("docId");
// PurchaseOrderDocument po = (PurchaseOrderDocument)
// SpringContext.getBean(DocumentService.class).getByDocumentHeaderId(poDocId);
// Integer poSelectedVendorId = new Integer(request.getParameter("quoteVendorId"));
KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
PurchaseOrderDocument po = (PurchaseOrderDocument) kualiDocumentFormBase.getDocument();
PurchaseOrderVendorQuote poVendorQuote = po.getPurchaseOrderVendorQuotes().get(getSelectedLine(request));
ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
poVendorQuote.setTransmitPrintDisplayed(false);
try {
StringBuffer sbFilename = new StringBuffer();
sbFilename.append("PURAP_PO_QUOTE_");
sbFilename.append(po.getPurapDocumentIdentifier());
sbFilename.append("_");
sbFilename.append(System.currentTimeMillis());
sbFilename.append(".pdf");
boolean success = SpringContext.getBean(PurchaseOrderService.class).printPurchaseOrderQuotePDF(po, poVendorQuote, baosPDF);
if (!success) {
poVendorQuote.setTransmitPrintDisplayed(true);
if (baosPDF != null) {
baosPDF.reset();
}
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
response.setHeader("Cache-Control", "max-age=30");
response.setContentType("application/pdf");
StringBuffer sbContentDispValue = new StringBuffer();
// sbContentDispValue.append("inline");
sbContentDispValue.append("attachment");
sbContentDispValue.append("; filename=");
sbContentDispValue.append(sbFilename);
response.setHeader("Content-disposition", sbContentDispValue.toString());
response.setContentLength(baosPDF.size());
ServletOutputStream sos;
sos = response.getOutputStream();
baosPDF.writeTo(sos);
sos.flush();
}
finally {
if (baosPDF != null) {
baosPDF.reset();
}
}
return null;
}
/**
* Print the list of PO Quote requests.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @throws Exception
* @return An ActionForward
*/
public ActionForward printPoQuoteList(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
PurchaseOrderDocument po = (PurchaseOrderDocument) kualiDocumentFormBase.getDocument();
ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
try {
StringBuffer sbFilename = new StringBuffer();
sbFilename.append("PURAP_PO_QUOTE_LIST_");
sbFilename.append(po.getPurapDocumentIdentifier());
sbFilename.append("_");
sbFilename.append(System.currentTimeMillis());
sbFilename.append(".pdf");
boolean success = SpringContext.getBean(PurchaseOrderService.class).printPurchaseOrderQuoteRequestsListPDF(po, baosPDF);
if (!success) {
if (baosPDF != null) {
baosPDF.reset();
}
return mapping.findForward(KFSConstants.MAPPING_PORTAL);
}
response.setHeader("Cache-Control", "max-age=30");
response.setContentType("application/pdf");
StringBuffer sbContentDispValue = new StringBuffer();
// sbContentDispValue.append("inline");
sbContentDispValue.append("attachment");
sbContentDispValue.append("; filename=");
sbContentDispValue.append(sbFilename);
response.setHeader("Content-disposition", sbContentDispValue.toString());
response.setContentLength(baosPDF.size());
ServletOutputStream sos;
sos = response.getOutputStream();
baosPDF.writeTo(sos);
sos.flush();
}
finally {
if (baosPDF != null) {
baosPDF.reset();
}
}
return null;
}
/**
* Initiates transmission of a PO Quote request.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @throws Exception
* @return An ActionForward
*/
public ActionForward transmitPurchaseOrderQuote(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
PurchaseOrderDocument po = (PurchaseOrderDocument) kualiDocumentFormBase.getDocument();
PurchaseOrderVendorQuote vendorQuote = (PurchaseOrderVendorQuote) po.getPurchaseOrderVendorQuotes().get(getSelectedLine(request));
if (PurapConstants.QuoteTransmitTypes.PRINT.equals(vendorQuote.getPurchaseOrderQuoteTransmitTypeCode())) {
vendorQuote.setPurchaseOrderQuoteTransmitTimestamp(SpringContext.getBean(DateTimeService.class).getCurrentTimestamp());
vendorQuote.setTransmitPrintDisplayed(true);
SpringContext.getBean(PurapService.class).saveDocumentNoValidation(po);
}
else if (PurapConstants.QuoteTransmitTypes.FAX.equals(vendorQuote.getPurchaseOrderQuoteTransmitTypeCode())) {
// call fax service
GlobalVariables.getErrorMap().clear();
FaxService faxService = SpringContext.getBean(FaxService.class);
faxService.faxPurchaseOrderPdf(po, false);
if (GlobalVariables.getErrorMap().size() == 0) {
vendorQuote.setPurchaseOrderQuoteTransmitTimestamp(SpringContext.getBean(DateTimeService.class).getCurrentTimestamp());
SpringContext.getBean(PurapService.class).saveDocumentNoValidation(po);
}
}
else {
GlobalVariables.getErrorMap().putError(PurapPropertyConstants.VENDOR_QUOTES, PurapKeyConstants.ERROR_PURCHASE_ORDER_QUOTE_TRANSMIT_TYPE_NOT_SELECTED);
}
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
/**
* Is invoked when the user clicks on the Select All button on a Purchase Order Retransmit document. It will select
* the checkboxes of all the items to be included in the retransmission of the PO.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @throws Exception
* @return An ActionForward
*/
public ActionForward selectAllForRetransmit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
PurchaseOrderDocument po = (PurchaseOrderDocument) kualiDocumentFormBase.getDocument();
List<PurchaseOrderItem> items = po.getItems();
for (PurchaseOrderItem item : items) {
item.setItemSelectedForRetransmitIndicator(true);
}
return returnToPreviousPage(mapping, kualiDocumentFormBase);
}
/**
* Is invoked when the user clicks on the Deselect All button on a Purchase Order Retransmit document. It will
* uncheck the checkboxes of all the items to be excluded from the retransmission of the PO.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @throws Exception
* @return An ActionForward
*/
public ActionForward deselectAllForRetransmit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
PurchaseOrderDocument po = (PurchaseOrderDocument) kualiDocumentFormBase.getDocument();
List<PurchaseOrderItem> items = po.getItems();
for (PurchaseOrderItem item : items) {
item.setItemSelectedForRetransmitIndicator(false);
}
return returnToPreviousPage(mapping, kualiDocumentFormBase);
}
/**
* Is invoked when the user clicks on the Retransmit button on both the PO tabbed page and on the Purchase Order
* Retransmit Document page, which is essentially a PO tabbed page with the other irrelevant tabs being hidden. If it was
* invoked from the PO tabbed page, if the PO's pending indicator is false, this method will invoke a method in the
* PurchaseOrderService to update the flags, create the PurchaseOrderRetransmitDocument and route it. If the routing was
* successful, we'll display the Purchase Order Retransmit Document page to the user, containing the newly created and routed
* PurchaseOrderRetransmitDocument and a retransmit button as well as a list of items that the user can select to be
* retransmitted. If it was invoked from the Purchase Order Retransmit Document page, we'll invoke the
* retransmitPurchaseOrderPDF method to create a PDF document based on the PO information and the items that were selected by
* the user on the Purchase Order Retransmit Document page to be retransmitted, then display the PDF to the browser.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @throws Exception
* @return An ActionForward
*/
public ActionForward retransmitPo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
PurchaseOrderDocument po = (PurchaseOrderDocument) kualiDocumentFormBase.getDocument();
boolean success;
if (po.isPendingActionIndicator()) {
success = false;
GlobalVariables.getErrorMap().putError(PurapPropertyConstants.PURCHASE_ORDER_IDENTIFIER, PurapKeyConstants.ERROR_PURCHASE_ORDER_IS_PENDING);
}
else {
po = SpringContext.getBean(PurchaseOrderService.class).createAndRoutePotentialChangeDocument(kualiDocumentFormBase.getDocument().getDocumentNumber(), PurchaseOrderDocTypes.PURCHASE_ORDER_RETRANSMIT_DOCUMENT, kualiDocumentFormBase.getAnnotation(), combineAdHocRecipients(kualiDocumentFormBase), PurchaseOrderStatuses.PENDING_RETRANSMIT);
((PurchaseOrderRetransmitDocument)po).setShouldDisplayRetransmitTab(true);
}
kualiDocumentFormBase.setDocument(po);
// we only need to set the editing mode to displayRetransmitTab if it's not yet
// in the editingMode.
if (!kualiDocumentFormBase.getEditingMode().containsKey(PurapAuthorizationConstants.PurchaseOrderEditMode.DISPLAY_RETRANSMIT_TAB)) {
DocumentAuthorizer documentAuthorizer = SpringContext.getBean(DocumentHelperService.class).getDocumentAuthorizer(po);
// TODO this method is gone, fix for kim
// kualiDocumentFormBase.populateAuthorizationFields(documentAuthorizer);
}
return returnToPreviousPage(mapping, kualiDocumentFormBase);
}
/**
* Is invoked when the user clicks on the Retransmit button on both the PO tabbed page and on the Purchase Order
* Retransmit Document page, which is essentially a PO tabbed page with the other irrelevant tabs being hidden. If it was
* invoked from the PO tabbed page, if the PO's pending indicator is false, this method will invoke a method in the
* PurchaseOrderService to update the flags, create the PurchaseOrderRetransmitDocument and route it. If the routing was
* successful, we'll display the Purchase Order Retransmit Document page to the user, containing the newly created and routed
* PurchaseOrderRetransmitDocument and a retransmit button as well as a list of items that the user can select to be
* retransmitted. If it was invoked from the Purchase Order Retransmit Document page, we'll invoke the
* retransmitPurchaseOrderPDF method to create a PDF document based on the PO information and the items that were selected by
* the user on the Purchase Order Retransmit Document page to be retransmitted, then display the PDF to the browser.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @throws Exception
* @return An ActionForward
*/
public ActionForward printingPreviewPo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
String poDocId = ((PurchaseOrderForm)form).getDocId();
ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
try {
SpringContext.getBean(PurchaseOrderService.class).performPurchaseOrderPreviewPrinting(poDocId, baosPDF);
}
finally {
if (baosPDF != null) {
baosPDF.reset();
}
}
String basePath = getBasePath(request);
String docId = ((PurchaseOrderForm) form).getDocId();
String methodToCallPrintPurchaseOrderPDF = "printPurchaseOrderPDFOnly";
String methodToCallDocHandler = "docHandler";
String printPOPDFUrl = getUrlForPrintPO(basePath, docId, methodToCallPrintPurchaseOrderPDF);
String displayPOTabbedPageUrl = getUrlForPrintPO(basePath, docId, methodToCallDocHandler);
request.setAttribute("printPOPDFUrl", printPOPDFUrl);
request.setAttribute("displayPOTabbedPageUrl", displayPOTabbedPageUrl);
String label = SpringContext.getBean(DataDictionaryService.class).getDocumentLabelByClass(PurchaseOrderDocument.class);
request.setAttribute("purchaseOrderLabel", label);
GlobalVariables.getUserSession().addObject("isPreview", new Boolean(true));
return mapping.findForward("printPurchaseOrderPDF");
}
/**
* Forwards to the RetransmitForward.jsp page so that we could open 2 windows for retransmit,
* one is to display the PO tabbed page and the other one display the pdf document.
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward printingRetransmitPo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
String basePath = getBasePath(request);
String docId = ((PurchaseOrderForm) form).getPurchaseOrderDocument().getDocumentNumber();
String methodToCallPrintRetransmitPurchaseOrderPDF = "printingRetransmitPoOnly";
String methodToCallDocHandler = "docHandler";
String printPOPDFUrl = getUrlForPrintPO(basePath, docId, methodToCallPrintRetransmitPurchaseOrderPDF);
String displayPOTabbedPageUrl = getUrlForPrintPO(basePath, docId, methodToCallDocHandler);
KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
PurchaseOrderDocument po = (PurchaseOrderDocument) kualiDocumentFormBase.getDocument();
StringBuffer itemIndexesBuffer = createSelectedItemIndexes(po.getItems());
if (itemIndexesBuffer.length() > 0) {
itemIndexesBuffer.deleteCharAt(itemIndexesBuffer.lastIndexOf(","));
request.setAttribute("selectedItemIndexes", itemIndexesBuffer.toString());
}
request.setAttribute("printPOPDFUrl", printPOPDFUrl);
request.setAttribute("displayPOTabbedPageUrl", displayPOTabbedPageUrl);
request.setAttribute("docId", docId);
String label = SpringContext.getBean(DataDictionaryService.class).getDocumentLabelByClass(PurchaseOrderDocument.class);
request.setAttribute("purchaseOrderLabel", label);
return mapping.findForward("retransmitPurchaseOrderPDF");
}
/**
* Helper method to create a StringBuffer of the indexes of items that the user
* has selected for retransmit to be passed in as an attribute to the RetransmitForward
* page so that we could add these items later on to the pdf page.
*
* @param items The List of items on the PurchaseOrderDocument.
* @return
*/
private StringBuffer createSelectedItemIndexes(List<PurchaseOrderItem>items) {
StringBuffer itemIndexesBuffer = new StringBuffer();
int i = 0;
for (PurchaseOrderItem item : items) {
if (item.isItemSelectedForRetransmitIndicator()) {
itemIndexesBuffer.append(i);
itemIndexesBuffer.append(',');
}
i++;
}
return itemIndexesBuffer;
}
/**
* Creates a PDF document based on the PO information and the items that were selected by the user on the Purchase Order
* Retransmit Document page to be retransmitted, then display the PDF to the browser.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @throws Exception
* @return An ActionForward
*/
public ActionForward printingRetransmitPoOnly(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
String selectedItemIndexes = (String)request.getParameter("selectedItemIndexes");
String documentNumber = (String)request.getParameter("poDocumentNumberForRetransmit");
PurchaseOrderDocument po = SpringContext.getBean(PurchaseOrderService.class).getPurchaseOrderByDocumentNumber(documentNumber);
String retransmitHeader = (String)request.getParameter("retransmitHeader");
// setting the isItemSelectedForRetransmitIndicator items of the PO obtained from the database based on its value from
// the po from the form
setItemSelectedForRetransmitIndicatorFromPOInForm(selectedItemIndexes, po.getItems());
po.setRetransmitHeader(retransmitHeader);
ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
try {
StringBuffer sbFilename = new StringBuffer();
sbFilename.append("PURAP_PO_");
sbFilename.append(po.getPurapDocumentIdentifier());
sbFilename.append("_");
sbFilename.append(System.currentTimeMillis());
sbFilename.append(".pdf");
// below method will throw ValidationException if errors are found
SpringContext.getBean(PurchaseOrderService.class).retransmitPurchaseOrderPDF(po, baosPDF);
response.setHeader("Cache-Control", "max-age=30");
response.setContentType("application/pdf");
StringBuffer sbContentDispValue = new StringBuffer();
sbContentDispValue.append("inline");
sbContentDispValue.append("; filename=");
sbContentDispValue.append(sbFilename);
response.setHeader("Content-disposition", sbContentDispValue.toString());
response.setContentLength(baosPDF.size());
ServletOutputStream sos;
sos = response.getOutputStream();
baosPDF.writeTo(sos);
sos.flush();
}
catch (ValidationException e) {
LOG.warn("Caught ValidationException while trying to retransmit PO with doc id " + po.getDocumentNumber());
return mapping.findForward(KFSConstants.MAPPING_ERROR);
}
finally {
if (baosPDF != null) {
baosPDF.reset();
}
}
return null;
}
/**
* Sets the itemSelectedForRetransmitIndicator to true to the items that the
* user has selected for retransmit.
*
* @param selectedItemIndexes The String containing the indexes of items selected to be retransmitted, separated by comma.
* @param itemsFromDB The List of items of the PurchaseOrderDocument obtained from the database.
*/
private void setItemSelectedForRetransmitIndicatorFromPOInForm(String selectedItemIndexes, List itemsFromDB) {
int i = 0;
StringTokenizer tok = new StringTokenizer(selectedItemIndexes, ",");
while (tok.hasMoreTokens()) {
i = Integer.parseInt(tok.nextToken());
((PurchaseOrderItem) (itemsFromDB.get(i))).setItemSelectedForRetransmitIndicator(true);
}
}
/**
* Checks on a few conditions that would cause a warning message to be displayed on top of the Purchase Order page.
*
* @param po the PurchaseOrderDocument whose status and indicators are to be checked in the conditions
* @return boolean true if the Purchase Order doesn't have any warnings and false otherwise.
*/
private void checkForPOWarnings(PurchaseOrderDocument po, ActionMessages messages) {
// "This is not the current version of this Purchase Order." (curr_ind = N and doc status is not enroute)
if (!po.isPurchaseOrderCurrentIndicator() && !po.getDocumentHeader().getWorkflowDocument().stateIsEnroute()) {
GlobalVariables.getMessageList().add(PurapKeyConstants.WARNING_PURCHASE_ORDER_NOT_CURRENT);
}
// "This document is a pending action. This is not the current version of this Purchase Order" (curr_ind = N and doc status
// is enroute)
if (!po.isPurchaseOrderCurrentIndicator() && po.getDocumentHeader().getWorkflowDocument().stateIsEnroute()) {
GlobalVariables.getMessageList().add(PurapKeyConstants.WARNING_PURCHASE_ORDER_PENDING_ACTION_NOT_CURRENT);
}
// "There is a pending action on this Purchase Order." (pend_action = Y)
if (po.isPendingActionIndicator()) {
GlobalVariables.getMessageList().add(PurapKeyConstants.WARNING_PURCHASE_ORDER_PENDING_ACTION);
}
if (!po.isPurchaseOrderCurrentIndicator()) {
ActionMessage noteMessage = new ActionMessage(PurapKeyConstants.WARNING_PURCHASE_ORDER_ALL_NOTES);
messages.add(PurapConstants.NOTE_TAB_WARNING, noteMessage);
}
}
/**
* Add a stipulation to the document.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @throws Exception
* @return An ActionForward
*/
public ActionForward addStipulation(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
PurchaseOrderForm poForm = (PurchaseOrderForm) form;
PurchaseOrderDocument document = (PurchaseOrderDocument) poForm.getDocument();
if (StringUtils.isBlank(poForm.getNewPurchaseOrderVendorStipulationLine().getVendorStipulationDescription())) {
GlobalVariables.getErrorMap().putError(KFSConstants.DOCUMENT_PROPERTY_NAME + "." + PurapPropertyConstants.VENDOR_STIPULATION, PurapKeyConstants.ERROR_STIPULATION_DESCRIPTION);
}
else {
PurchaseOrderVendorStipulation newStipulation = poForm.getAndResetNewPurchaseOrderVendorStipulationLine();
document.getPurchaseOrderVendorStipulations().add(newStipulation);
}
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
/**
* Delete a stipulation from the document.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @throws Exception
* @return An ActionForward
*/
public ActionForward deleteStipulation(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
PurchaseOrderForm poForm = (PurchaseOrderForm) form;
PurchaseOrderDocument document = (PurchaseOrderDocument) poForm.getDocument();
document.getPurchaseOrderVendorStipulations().remove(getSelectedLine(request));
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
/**
* Overrides the docHandler method in the superclass. In addition to doing the normal process in the superclass and returning
* its action forward from the superclass, it also invokes the <code>checkForPOWarnings</code> method to check on a few
* conditions that could have caused warning messages to be displayed on top of Purchase Order page.
*
* @see org.kuali.rice.kns.web.struts.action.KualiDocumentActionBase#docHandler(org.apache.struts.action.ActionMapping,
* org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
@Override
public ActionForward docHandler(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
ActionForward forward = super.docHandler(mapping, form, request, response);
PurchaseOrderForm poForm = (PurchaseOrderForm) form;
PurchaseOrderDocument po = (PurchaseOrderDocument) poForm.getDocument();
ActionMessages messages = new ActionMessages();
checkForPOWarnings(po, messages);
saveMessages(request, messages);
return forward;
}
/**
* Sets up the PO document for Quote processing.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @throws Exception
* @return An ActionForward
*/
public ActionForward initiateQuote(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
PurchaseOrderForm poForm = (PurchaseOrderForm) form;
PurchaseOrderDocument document = (PurchaseOrderDocument) poForm.getDocument();
if (!PurapConstants.PurchaseOrderStatuses.IN_PROCESS.equals(document.getStatusCode())) {
// PO must be "in process" in order to initiate a quote
GlobalVariables.getErrorMap().putError(PurapPropertyConstants.VENDOR_QUOTES, PurapKeyConstants.ERROR_PURCHASE_ORDER_QUOTE_NOT_IN_PROCESS);
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
Date currentSqlDate = SpringContext.getBean(DateTimeService.class).getCurrentSqlDate();
document.setPurchaseOrderQuoteInitializationDate(currentSqlDate);
document.setStatusCode(PurapConstants.PurchaseOrderStatuses.QUOTE);
Date expDate = new Date(currentSqlDate.getTime() + (10 * 24 * 60 * 60 * 1000)); // add 10 days - TODO: make this a parameter!!!
document.setPurchaseOrderQuoteDueDate(expDate);
document.getPurchaseOrderVendorQuotes().clear();
SpringContext.getBean(PurapService.class).saveDocumentNoValidation(document);
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
/**
* Add to the Quotes a line to contain a Vendor.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @throws Exception
* @return An ActionForward
*/
public ActionForward addVendor(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
PurchaseOrderForm poForm = (PurchaseOrderForm) form;
PurchaseOrderDocument document = (PurchaseOrderDocument) poForm.getDocument();
PurchaseOrderVendorQuote vendorQuote = poForm.getNewPurchaseOrderVendorQuote();
boolean rulePassed = SpringContext.getBean(KualiRuleService.class).applyRules(new AttributedAddVendorToQuoteEvent("", document, vendorQuote));
if (rulePassed) {
poForm.getNewPurchaseOrderVendorQuote().setDocumentNumber(document.getDocumentNumber());
document.getPurchaseOrderVendorQuotes().add(vendorQuote);
poForm.setNewPurchaseOrderVendorQuote(new PurchaseOrderVendorQuote());
}
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
/**
* Deletes a Vendor from the list of those from which a Quote should be obtained.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @throws Exception
* @return An ActionForward
*/
public ActionForward deleteVendor(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
PurchaseOrderForm poForm = (PurchaseOrderForm) form;
PurchaseOrderDocument document = (PurchaseOrderDocument) poForm.getDocument();
document.getPurchaseOrderVendorQuotes().remove(getSelectedLine(request));
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
/**
* Once an awarded Vendor number is present on the PO, verifies the fact, asks the user for confirmation to complete the quoting
* process with the awarded Vendor, and sets the Vendor information on the purchase order, if confirmation is obtained.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @throws Exception
* @return An ActionForward
*/
public ActionForward completeQuote(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
PurchaseOrderForm poForm = (PurchaseOrderForm) form;
PurchaseOrderDocument document = (PurchaseOrderDocument) poForm.getDocument();
PurchaseOrderVendorQuote awardedQuote = new PurchaseOrderVendorQuote();
// verify that all vendors have a quote status
// also run dictionary validations to validate against the DD.
boolean dictionaryValid = true;
for (PurchaseOrderVendorQuote poQuote : document.getPurchaseOrderVendorQuotes()) {
if (poQuote.getPurchaseOrderQuoteStatusCode() == null) {
GlobalVariables.getErrorMap().putError(PurapPropertyConstants.VENDOR_QUOTES, PurapKeyConstants.ERROR_PURCHASE_ORDER_QUOTE_STATUS_NOT_SELECTED);
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
else {
dictionaryValid &= SpringContext.getBean(DictionaryValidationService.class).isBusinessObjectValid(poQuote, PurapPropertyConstants.VENDOR_QUOTES);
}
}
if (!dictionaryValid) {
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
// verify quote status fields
if (poForm.getAwardedVendorNumber() == null) {
GlobalVariables.getErrorMap().putError(PurapPropertyConstants.VENDOR_QUOTES, PurapKeyConstants.ERROR_PURCHASE_ORDER_QUOTE_NO_VENDOR_AWARDED);
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
else {
awardedQuote = document.getPurchaseOrderVendorQuote(poForm.getAwardedVendorNumber().intValue());
if (awardedQuote.getPurchaseOrderQuoteStatusCode() == null) {
GlobalVariables.getErrorMap().putError(PurapPropertyConstants.VENDOR_QUOTES, PurapKeyConstants.ERROR_PURCHASE_ORDER_QUOTE_NOT_TRANSMITTED);
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
else {
VendorDetail awardedVendor = SpringContext.getBean(VendorService.class).getVendorDetail(awardedQuote.getVendorHeaderGeneratedIdentifier(), awardedQuote.getVendorDetailAssignedIdentifier());
if (!awardedVendor.getVendorHeader().getVendorTypeCode().equals("PO")) {
GlobalVariables.getErrorMap().putError(PurapPropertyConstants.VENDOR_QUOTES, PurapKeyConstants.ERROR_PURCHASE_ORDER_QUOTE_AWARD_NON_PO);
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
}
}
// use question framework to make sure they REALLY want to complete the quote...
String message = SpringContext.getBean(KualiConfigurationService.class).getPropertyString(PurapKeyConstants.PURCHASE_ORDER_QUESTION_CONFIRM_AWARD);
String vendorRow = SpringContext.getBean(KualiConfigurationService.class).getPropertyString(PurapKeyConstants.PURCHASE_ORDER_QUESTION_CONFIRM_AWARD_ROW);
String tempRows = "";
for (PurchaseOrderVendorQuote poQuote : document.getPurchaseOrderVendorQuotes()) {
String tempRow = vendorRow;
tempRow = StringUtils.replace(tempRow, "{0}", poQuote.getVendorName());
if (poQuote.getPurchaseOrderQuoteAwardTimestamp() == null) {
if (awardedQuote.getVendorNumber().equals(poQuote.getVendorNumber())) {
tempRow = StringUtils.replace(tempRow, "{1}", SpringContext.getBean(DateTimeService.class).getCurrentSqlDate().toString());
}
else {
tempRow = StringUtils.replace(tempRow, "{1}", "");
}
}
else {
tempRow = StringUtils.replace(tempRow, "{1}", poQuote.getPurchaseOrderQuoteAwardTimestamp().toString());
}
if (poQuote.getPurchaseOrderQuoteStatusCode() != null) {
poQuote.refreshReferenceObject(PurapPropertyConstants.PURCHASE_ORDER_QUOTE_STATUS);
tempRow = StringUtils.replace(tempRow, "{2}", poQuote.getPurchaseOrderQuoteStatus().getStatusDescription());
}
else {
tempRow = StringUtils.replace(tempRow, "{2}", "N/A");
}
if (poQuote.getPurchaseOrderQuoteRankNumber() != null) {
tempRow = StringUtils.replace(tempRow, "{3}", poQuote.getPurchaseOrderQuoteRankNumber());
}
else {
tempRow = StringUtils.replace(tempRow, "{3}", "N/A");
}
tempRows += tempRow;
}
message = StringUtils.replace(message, "{0}", tempRows);
Object question = request.getParameter(KFSConstants.QUESTION_INST_ATTRIBUTE_NAME);
if (question == null) {
// ask question if not already asked
return performQuestionWithoutInput(mapping, form, request, response, PODocumentsStrings.CONFIRM_AWARD_QUESTION, message, KFSConstants.CONFIRMATION_QUESTION, PODocumentsStrings.CONFIRM_AWARD_RETURN, "");
}
else {
Object buttonClicked = request.getParameter(KFSConstants.QUESTION_CLICKED_BUTTON);
if ((PODocumentsStrings.CONFIRM_AWARD_QUESTION.equals(question)) && ConfirmationQuestion.YES.equals(buttonClicked)) {
// set awarded date
awardedQuote.setPurchaseOrderQuoteAwardTimestamp(SpringContext.getBean(DateTimeService.class).getCurrentTimestamp());
Date currentSqlDate = SpringContext.getBean(DateTimeService.class).getCurrentSqlDate();
document.setPurchaseOrderQuoteAwardedDate(currentSqlDate);
// PO vendor information updated with awarded vendor
document.setVendorName(awardedQuote.getVendorName());
document.setVendorNumber(awardedQuote.getVendorNumber());
Integer headID = awardedQuote.getVendorHeaderGeneratedIdentifier();
Integer detailID = awardedQuote.getVendorDetailAssignedIdentifier();
document.setVendorHeaderGeneratedIdentifier(headID);
document.setVendorDetailAssignedIdentifier(detailID);
// use PO type address to fill in vendor address
String campusCode = GlobalVariables.getUserSession().getPerson().getCampusCode();
VendorAddress pova = SpringContext.getBean(VendorService.class).getVendorDefaultAddress(headID, detailID, AddressTypes.PURCHASE_ORDER, campusCode);
document.setVendorLine1Address(pova.getVendorLine1Address());
document.setVendorLine2Address(pova.getVendorLine2Address());
document.setVendorCityName(pova.getVendorCityName());
document.setVendorStateCode(pova.getVendorStateCode());
document.setVendorPostalCode(pova.getVendorZipCode());
document.setVendorCountryCode(pova.getVendorCountryCode());
document.setVendorFaxNumber(pova.getVendorFaxNumber());
document.setStatusCode(PurapConstants.PurchaseOrderStatuses.IN_PROCESS);
SpringContext.getBean(PurapService.class).saveDocumentNoValidation(document);
}
}
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
/**
* Cancels the process of obtaining quotes. Checks whether any of the quote requests have been transmitted. If none have, tries
* to obtain confirmation from the user for the cancellation. If confirmation is obtained, clears out the list of Vendors from
* which to obtain quotes and writes the given reason to a note on the PO.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @throws Exception
* @return An ActionForward
*/
public ActionForward cancelQuote(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
PurchaseOrderForm poForm = (PurchaseOrderForm) form;
PurchaseOrderDocument document = (PurchaseOrderDocument) poForm.getDocument();
for (PurchaseOrderVendorQuote quotedVendors : document.getPurchaseOrderVendorQuotes()) {
if (quotedVendors.getPurchaseOrderQuoteTransmitTimestamp() != null) {
GlobalVariables.getErrorMap().putError(PurapPropertyConstants.VENDOR_QUOTES, PurapKeyConstants.ERROR_PURCHASE_ORDER_QUOTE_ALREADY_TRASNMITTED);
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
}
String message = SpringContext.getBean(KualiConfigurationService.class).getPropertyString(PurapKeyConstants.PURCHASE_ORDER_QUESTION_CONFIRM_CANCEL_QUOTE);
Object question = request.getParameter(KFSConstants.QUESTION_INST_ATTRIBUTE_NAME);
if (question == null) {
// ask question if not already asked
return performQuestionWithInput(mapping, form, request, response, PODocumentsStrings.CONFIRM_CANCEL_QUESTION, message, KFSConstants.CONFIRMATION_QUESTION, PODocumentsStrings.CONFIRM_CANCEL_RETURN, "");
}
else {
Object buttonClicked = request.getParameter(KFSConstants.QUESTION_CLICKED_BUTTON);
if ((PODocumentsStrings.CONFIRM_CANCEL_QUESTION.equals(question)) && ConfirmationQuestion.YES.equals(buttonClicked)) {
String reason = request.getParameter(KFSConstants.QUESTION_REASON_ATTRIBUTE_NAME);
if (StringUtils.isEmpty(reason)) {
return performQuestionWithInputAgainBecauseOfErrors(mapping, form, request, response, PODocumentsStrings.CONFIRM_CANCEL_QUESTION, message, KFSConstants.CONFIRMATION_QUESTION, PODocumentsStrings.CONFIRM_CANCEL_RETURN, "", "", PurapKeyConstants.ERROR_PURCHASE_ORDER_REASON_REQUIRED, KFSConstants.QUESTION_REASON_ATTRIBUTE_NAME, "250");
}
document.getPurchaseOrderVendorQuotes().clear();
Note cancelNote = new Note();
cancelNote.setAuthorUniversalIdentifier(GlobalVariables.getUserSession().getPerson().getPrincipalId());
String reasonPrefix = SpringContext.getBean(KualiConfigurationService.class).getPropertyString(PurapKeyConstants.PURCHASE_ORDER_CANCEL_QUOTE_NOTE_TEXT);
cancelNote.setNoteText(reasonPrefix + reason);
document.addNote(cancelNote);
document.setStatusCode(PurapConstants.PurchaseOrderStatuses.IN_PROCESS);
SpringContext.getBean(PurapService.class).saveDocumentNoValidation(document);
}
}
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
/**
* @see org.kuali.rice.kns.web.struts.action.KualiDocumentActionBase#cancel(org.apache.struts.action.ActionMapping,
* org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
@Override
public ActionForward cancel(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
Object question = request.getParameter(KFSConstants.QUESTION_INST_ATTRIBUTE_NAME);
// this should probably be moved into a private instance variable
KualiConfigurationService kualiConfiguration = SpringContext.getBean(KualiConfigurationService.class);
// logic for cancel question
if (question == null) {
// ask question if not already asked
return this.performQuestionWithoutInput(mapping, form, request, response, KFSConstants.DOCUMENT_CANCEL_QUESTION, kualiConfiguration.getPropertyString("document.question.cancel.text"), KFSConstants.CONFIRMATION_QUESTION, KFSConstants.MAPPING_CANCEL, "");
}
else {
Object buttonClicked = request.getParameter(KFSConstants.QUESTION_CLICKED_BUTTON);
if ((KFSConstants.DOCUMENT_CANCEL_QUESTION.equals(question)) && ConfirmationQuestion.NO.equals(buttonClicked)) {
// if no button clicked just reload the doc
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
// else go to cancel logic below
}
KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
SpringContext.getBean(DocumentService.class).cancelDocument(kualiDocumentFormBase.getDocument(), kualiDocumentFormBase.getAnnotation());
return returnToSender(mapping, kualiDocumentFormBase);
}
/**
* @see org.kuali.rice.kns.web.struts.action.KualiDocumentActionBase#save(org.apache.struts.action.ActionMapping,
* org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
@Override
public ActionForward save(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
PurchaseOrderForm poForm = (PurchaseOrderForm) form;
PurchaseOrderDocument po = poForm.getPurchaseOrderDocument();
if (StringUtils.isNotBlank(po.getStatusCode()) && StringUtils.isNotBlank(po.getStatusChange()) && (!StringUtils.equals(po.getStatusCode(), po.getStatusChange()))) {
KualiWorkflowDocument workflowDocument = po.getDocumentHeader().getWorkflowDocument();
if (ObjectUtils.isNull(workflowDocument) || workflowDocument.stateIsInitiated() || workflowDocument.stateIsSaved()) {
return this.askSaveQuestions(mapping, form, request, response, PODocumentsStrings.MANUAL_STATUS_CHANGE_QUESTION);
}
}
return super.save(mapping, form, request, response);
}
/**
* Obtains confirmation and records reasons for the manual status changes which can take place before the purchase order has
* been routed. If confirmation is given, changes the status, saves, and records the given reason in an note on the purchase
* order.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @return An ActionForward
*/
private ActionForward askSaveQuestions(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response, String questionType) {
KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
PurchaseOrderDocument po = (PurchaseOrderDocument) kualiDocumentFormBase.getDocument();
Object question = request.getParameter(KFSConstants.QUESTION_INST_ATTRIBUTE_NAME);
String reason = request.getParameter(KFSConstants.QUESTION_REASON_ATTRIBUTE_NAME);
KualiConfigurationService kualiConfiguration = SpringContext.getBean(KualiConfigurationService.class);
ActionForward forward = mapping.findForward(KFSConstants.MAPPING_BASIC);
String notePrefix = "";
if (StringUtils.equals(questionType, PODocumentsStrings.MANUAL_STATUS_CHANGE_QUESTION) && ObjectUtils.isNull(question)) {
String message = kualiConfiguration.getPropertyString(PurapKeyConstants.PURCHASE_ORDER_QUESTION_MANUAL_STATUS_CHANGE);
try {
return this.performQuestionWithInput(mapping, form, request, response, questionType, message, KFSConstants.CONFIRMATION_QUESTION, questionType, "");
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
else {
Object buttonClicked = request.getParameter(KFSConstants.QUESTION_CLICKED_BUTTON);
if (question.equals(questionType) && buttonClicked.equals(ConfirmationQuestion.NO)) {
// If 'No' is the button clicked, just reload the doc
return forward;
}
// Build out full message.
if (StringUtils.equals(questionType, PODocumentsStrings.MANUAL_STATUS_CHANGE_QUESTION)) {
Map<String, String> manuallyChangeableStatuses = new HashMap<String, String>();
manuallyChangeableStatuses.put(PurchaseOrderStatuses.IN_PROCESS, "In Process");
manuallyChangeableStatuses.put(PurchaseOrderStatuses.WAITING_FOR_VENDOR, "Waiting for Vendor");
manuallyChangeableStatuses.put(PurchaseOrderStatuses.WAITING_FOR_DEPARTMENT, "Waiting for Department");
String key = kualiConfiguration.getPropertyString(PurapKeyConstants.PURCHASE_ORDER_MANUAL_STATUS_CHANGE_NOTE_PREFIX);
String oldStatus = manuallyChangeableStatuses.get(po.getStatusCode());
String newStatus = manuallyChangeableStatuses.get(po.getStatusChange());
key = StringUtils.replace(key, "{0}", (StringUtils.isBlank(oldStatus) ? " " : oldStatus));
notePrefix = StringUtils.replace(key, "{1}", (StringUtils.isBlank(newStatus) ? " " : newStatus));
}
String noteText = notePrefix + KFSConstants.BLANK_SPACE + reason;
int noteTextLength = noteText.length();
// Get note text max length from DD.
int noteTextMaxLength = SpringContext.getBean(DataDictionaryService.class).getAttributeMaxLength(Note.class, KFSConstants.NOTE_TEXT_PROPERTY_NAME).intValue();
if (StringUtils.isBlank(reason) || (noteTextLength > noteTextMaxLength)) {
// Figure out exact number of characters that the user can enter.
int reasonLimit = noteTextMaxLength - noteTextLength;
if (ObjectUtils.isNull(reason)) {
// Prevent a NPE by setting the reason to a blank string.
reason = "";
}
try {
if (StringUtils.equals(questionType, PODocumentsStrings.MANUAL_STATUS_CHANGE_QUESTION)) {
return this.performQuestionWithInputAgainBecauseOfErrors(mapping, form, request, response, questionType, kualiConfiguration.getPropertyString(PurapKeyConstants.PURCHASE_ORDER_QUESTION_MANUAL_STATUS_CHANGE), KFSConstants.CONFIRMATION_QUESTION, questionType, "", reason, PurapKeyConstants.ERROR_PURCHASE_ORDER_REASON_REQUIRED, KFSConstants.QUESTION_REASON_ATTRIBUTE_NAME, new Integer(reasonLimit).toString());
}
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
else if (StringUtils.equals(questionType, PODocumentsStrings.MANUAL_STATUS_CHANGE_QUESTION)) {
executeManualStatusChange(po);
try {
forward = super.save(mapping, form, request, response);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
Note newNote = new Note();
newNote.setNoteText(noteText);
newNote.setNoteTypeCode(KFSConstants.NoteTypeEnum.BUSINESS_OBJECT_NOTE_TYPE.getCode());
kualiDocumentFormBase.setNewNote(newNote);
try {
insertBONote(mapping, kualiDocumentFormBase, request, response);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
return forward;
}
/**
* Applies a manual change of status to the given purchase order document.
*
* @param po A PurchaseOrderDocument
*/
private void executeManualStatusChange(PurchaseOrderDocument po) {
try {
SpringContext.getBean(PurapService.class).updateStatus(po, po.getStatusChange());
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* @see org.kuali.kfs.module.purap.document.web.struts.PurchasingAccountsPayableActionBase#loadDocument(org.kuali.rice.kns.web.struts.form.KualiDocumentFormBase)
*/
@Override
protected void loadDocument(KualiDocumentFormBase kualiDocumentFormBase) throws WorkflowException {
super.loadDocument(kualiDocumentFormBase);
PurchaseOrderForm poForm = (PurchaseOrderForm) kualiDocumentFormBase;
PurchaseOrderDocument po = (PurchaseOrderDocument) poForm.getDocument();
po.setInternalPurchasingLimit(SpringContext.getBean(PurchaseOrderService.class).getInternalPurchasingDollarLimit(po));
}
/**
* Adds a PurchasingItemCapitalAsset (a container for the Capital Asset Number) to the selected
* item's list.
*
* @param mapping An ActionMapping
* @param form The Form
* @param request An HttpServletRequest
* @param response The HttpServletResponse
* @return An ActionForward
* @throws Exception
*/
public ActionForward addAsset(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
PurchaseOrderForm poForm = (PurchaseOrderForm)form;
PurchaseOrderDocument document = (PurchaseOrderDocument)poForm.getDocument();
PurchaseOrderItem item = (PurchaseOrderItem)document.getItemByLineNumber(getSelectedLine(request) + 1);
//TODO: Add a new way to add assets to the system.
//item.addAsset();
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
public ActionForward removeAlternateVendor(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
PurchaseOrderForm poForm = (PurchaseOrderForm) form;
PurchaseOrderDocument document = (PurchaseOrderDocument) poForm.getDocument();
document.setAlternateVendorDetailAssignedIdentifier(null);
document.setAlternateVendorHeaderGeneratedIdentifier(null);
document.setAlternateVendorName(null);
document.setAlternateVendorNumber(null);
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
public ActionForward createReceivingLine(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
PurchaseOrderForm poForm = (PurchaseOrderForm) form;
PurchaseOrderDocument document = (PurchaseOrderDocument) poForm.getDocument();
String basePath = getBasePath(request);
String methodToCallDocHandler = "docHandler";
String methodToCallReceivingLine = "initiate";
//set parameters
Properties parameters = new Properties();
parameters.put(KFSConstants.DISPATCH_REQUEST_PARAMETER, methodToCallDocHandler);
parameters.put(KFSConstants.PARAMETER_COMMAND, methodToCallReceivingLine);
parameters.put(KFSConstants.DOCUMENT_TYPE_NAME, "RCVL");
parameters.put("purchaseOrderId", document.getPurapDocumentIdentifier().toString() );
//create url
String receivingUrl = UrlFactory.parameterizeUrl(basePath + "/" + "purapLineItemReceiving.do", parameters);
//create forward
ActionForward forward = new ActionForward(receivingUrl, true);
return forward;
}
public ActionForward resendPoCxml(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
PurchaseOrderDocument po = (PurchaseOrderDocument) ((PurchaseOrderForm) form).getDocument();
SpringContext.getBean(PurchaseOrderService.class).retransmitB2BPurchaseOrder(po);
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
}
| work/src/org/kuali/kfs/module/purap/document/web/struts/PurchaseOrderAction.java | /*
* Copyright 2006-2007 The Kuali Foundation.
*
* Licensed under the Educational Community License, Version 1.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/ecl1.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.purap.document.web.struts;
import java.io.ByteArrayOutputStream;
import java.sql.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.StringTokenizer;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.kuali.kfs.module.purap.PurapAuthorizationConstants;
import org.kuali.kfs.module.purap.PurapConstants;
import org.kuali.kfs.module.purap.PurapKeyConstants;
import org.kuali.kfs.module.purap.PurapPropertyConstants;
import org.kuali.kfs.module.purap.SingleConfirmationQuestion;
import org.kuali.kfs.module.purap.PurapConstants.PODocumentsStrings;
import org.kuali.kfs.module.purap.PurapConstants.PurchaseOrderDocTypes;
import org.kuali.kfs.module.purap.PurapConstants.PurchaseOrderStatuses;
import org.kuali.kfs.module.purap.businessobject.PurchaseOrderItem;
import org.kuali.kfs.module.purap.businessobject.PurchaseOrderQuoteList;
import org.kuali.kfs.module.purap.businessobject.PurchaseOrderQuoteListVendor;
import org.kuali.kfs.module.purap.businessobject.PurchaseOrderSensitiveData;
import org.kuali.kfs.module.purap.businessobject.PurchaseOrderVendorQuote;
import org.kuali.kfs.module.purap.businessobject.PurchaseOrderVendorStipulation;
import org.kuali.kfs.module.purap.businessobject.SensitiveData;
import org.kuali.kfs.module.purap.businessobject.SensitiveDataAssignment;
import org.kuali.kfs.module.purap.document.PurchaseOrderDocument;
import org.kuali.kfs.module.purap.document.PurchaseOrderRetransmitDocument;
import org.kuali.kfs.module.purap.document.PurchaseOrderSplitDocument;
import org.kuali.kfs.module.purap.document.service.FaxService;
import org.kuali.kfs.module.purap.document.service.PurapService;
import org.kuali.kfs.module.purap.document.service.PurchaseOrderService;
import org.kuali.kfs.module.purap.document.validation.event.AttributedAddVendorToQuoteEvent;
import org.kuali.kfs.module.purap.document.validation.event.AttributedAssignSensitiveDataEvent;
import org.kuali.kfs.module.purap.document.validation.event.AttributedSplitPurchaseOrderEvent;
import org.kuali.kfs.module.purap.service.SensitiveDataService;
import org.kuali.kfs.sys.KFSConstants;
import org.kuali.kfs.sys.KFSPropertyConstants;
import org.kuali.kfs.sys.context.SpringContext;
import org.kuali.kfs.vnd.businessobject.VendorDetail;
import org.kuali.kfs.vnd.document.service.VendorService;
import org.kuali.rice.kew.exception.WorkflowException;
import org.kuali.rice.kns.bo.Note;
import org.kuali.rice.kns.document.authorization.DocumentAuthorizer;
import org.kuali.rice.kns.exception.ValidationException;
import org.kuali.rice.kns.question.ConfirmationQuestion;
import org.kuali.rice.kns.service.BusinessObjectService;
import org.kuali.rice.kns.service.DataDictionaryService;
import org.kuali.rice.kns.service.DateTimeService;
import org.kuali.rice.kns.service.DictionaryValidationService;
import org.kuali.rice.kns.service.DocumentHelperService;
import org.kuali.rice.kns.service.DocumentService;
import org.kuali.rice.kns.service.KualiConfigurationService;
import org.kuali.rice.kns.service.KualiRuleService;
import org.kuali.rice.kns.util.GlobalVariables;
import org.kuali.rice.kns.util.ObjectUtils;
import org.kuali.rice.kns.util.UrlFactory;
import org.kuali.rice.kns.util.WebUtils;
import org.kuali.rice.kns.web.struts.form.BlankFormFile;
import org.kuali.rice.kns.web.struts.form.KualiDocumentFormBase;
import org.kuali.rice.kns.workflow.service.KualiWorkflowDocument;
/**
* Struts Action for Purchase Order document.
*/
public class PurchaseOrderAction extends PurchasingActionBase {
private static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(PurchaseOrderAction.class);
/**
* @see org.kuali.rice.kns.web.struts.action.KualiAction#refresh(org.apache.struts.action.ActionMapping,
* org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
@Override
public ActionForward refresh(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
PurchaseOrderForm poForm = (PurchaseOrderForm) form;
// retain error messages after a lookup
WebUtils.reuseErrorMapFromPreviousRequest(poForm);
PurchaseOrderDocument document = (PurchaseOrderDocument) poForm.getDocument();
BusinessObjectService businessObjectService = SpringContext.getBean(BusinessObjectService.class);
// Handling lookups for alternate vendor for non-primary vendor payment that are only specific to Purchase Order.
if (request.getParameter("document.alternateVendorHeaderGeneratedIdentifier") != null && request.getParameter("document.alternateVendorDetailAssignedIdentifier") != null) {
Integer alternateVendorDetailAssignedId = document.getAlternateVendorDetailAssignedIdentifier();
Integer alternateVendorHeaderGeneratedId = document.getAlternateVendorHeaderGeneratedIdentifier();
VendorDetail refreshVendorDetail = new VendorDetail();
refreshVendorDetail.setVendorDetailAssignedIdentifier(alternateVendorDetailAssignedId);
refreshVendorDetail.setVendorHeaderGeneratedIdentifier(alternateVendorHeaderGeneratedId);
refreshVendorDetail = (VendorDetail) businessObjectService.retrieve(refreshVendorDetail);
document.templateAlternateVendor(refreshVendorDetail);
}
// Handling lookups for quote list that is specific to Purchase Order.
if (request.getParameter("document.purchaseOrderQuoteListIdentifier") != null) {
// do a lookup and add all the vendors!
Integer poQuoteListIdentifier = document.getPurchaseOrderQuoteListIdentifier();
PurchaseOrderQuoteList poQuoteList = new PurchaseOrderQuoteList();
poQuoteList.setPurchaseOrderQuoteListIdentifier(poQuoteListIdentifier);
poQuoteList = (PurchaseOrderQuoteList) businessObjectService.retrieve(poQuoteList);
if (poQuoteList.isActiveIndicator()) {
for (PurchaseOrderQuoteListVendor poQuoteListVendor : poQuoteList.getQuoteListVendors()) {
VendorDetail newVendor = poQuoteListVendor.getVendorDetail();
if (newVendor.isActiveIndicator() && !newVendor.isVendorDebarred()) {
PurchaseOrderVendorQuote newPOVendorQuote = SpringContext.getBean(PurchaseOrderService.class).populateQuoteWithVendor(newVendor.getVendorHeaderGeneratedIdentifier(), newVendor.getVendorDetailAssignedIdentifier(), document.getDocumentNumber());
document.getPurchaseOrderVendorQuotes().add(newPOVendorQuote);
}
}
}
}
// Handling lookups for quote vendor search that is specific to Purchase Order.
String newVendorHeaderGeneratedIdentifier = request.getParameter("newPurchaseOrderVendorQuote.vendorHeaderGeneratedIdentifier");
String newVendorDetailAssignedIdentifier = request.getParameter("newPurchaseOrderVendorQuote.vendorDetailAssignedIdentifier");
if (newVendorHeaderGeneratedIdentifier != null && newVendorDetailAssignedIdentifier != null) {
PurchaseOrderVendorQuote newPOVendorQuote = SpringContext.getBean(PurchaseOrderService.class).populateQuoteWithVendor(new Integer(newVendorHeaderGeneratedIdentifier), new Integer(newVendorDetailAssignedIdentifier), document.getDocumentNumber());
poForm.setNewPurchaseOrderVendorQuote(newPOVendorQuote);
}
String newStipulation = request.getParameter(KFSPropertyConstants.DOCUMENT + "." + PurapPropertyConstants.VENDOR_STIPULATION_DESCRIPTION);
if (StringUtils.isNotEmpty(newStipulation)) {
poForm.getNewPurchaseOrderVendorStipulationLine().setVendorStipulationDescription(newStipulation);
}
return super.refresh(mapping, form, request, response);
}
/**
* Inactivate an item from the purchase order document.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @throws Exception
* @return An ActionForward
*/
public ActionForward inactivateItem(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
PurchasingAccountsPayableFormBase purchasingForm = (PurchasingAccountsPayableFormBase) form;
PurchaseOrderDocument purDocument = (PurchaseOrderDocument) purchasingForm.getDocument();
PurchaseOrderItem item = (PurchaseOrderItem) purDocument.getItem(getSelectedLine(request));
item.setItemActiveIndicator(false);
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
/**
* For use with a specific set of methods of this class that create new purchase order-derived document types in response to
* user actions, including <code>closePo</code>, <code>reopenPo</code>, <code>paymentHoldPo</code>, <code>removeHoldPo</code>,
* <code>splitPo</code>, <code>amendPo</code>, and <code>voidPo</code>. It employs the question framework to ask
* the user for a response before creating and routing the new document. The response should consist of a note detailing a
* reason, and either yes or no. This method can be better understood if it is noted that it will be gone through twice (via the
* question framework); when each question is originally asked, and again when the yes/no response is processed, for
* confirmation.
*
* @param mapping These are boiler-plate.
* @param form "
* @param request "
* @param response "
* @param questionType A string identifying the type of question being asked.
* @param confirmType A string identifying which type of question is being confirmed.
* @param documentType A string, the type of document to create
* @param notePrefix A string to appear before the note in the BO Notes tab
* @param messageType A string to appear on the PO once the question framework is done, describing the action taken
* @param operation A string, the verb to insert in the original question describing the action to be taken
* @return An ActionForward
* @throws Exception
*/
private ActionForward askQuestionsAndPerformDocumentAction(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response, String questionType, String confirmType, String documentType, String notePrefix, String messageType, String operation) throws Exception {
LOG.debug("askQuestionsAndPerformDocumentAction started.");
KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
PurchaseOrderDocument po = (PurchaseOrderDocument) kualiDocumentFormBase.getDocument();
Object question = request.getParameter(KFSConstants.QUESTION_INST_ATTRIBUTE_NAME);
String reason = request.getParameter(KFSConstants.QUESTION_REASON_ATTRIBUTE_NAME);
String noteText = "";
try {
KualiConfigurationService kualiConfiguration = SpringContext.getBean(KualiConfigurationService.class);
// Start in logic for confirming the proposed operation.
if (ObjectUtils.isNull(question)) {
String message = "";
if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_SPLIT_DOCUMENT)) {
message = kualiConfiguration.getPropertyString(PurapKeyConstants.PURCHASE_ORDER_SPLIT_QUESTION_TEXT);
}
else {
String key = kualiConfiguration.getPropertyString(PurapKeyConstants.PURCHASE_ORDER_QUESTION_DOCUMENT);
message = StringUtils.replace(key, "{0}", operation);
}
// Ask question if not already asked.
return this.performQuestionWithInput(mapping, form, request, response, questionType, message, KFSConstants.CONFIRMATION_QUESTION, questionType, "");
}
else {
Object buttonClicked = request.getParameter(KFSConstants.QUESTION_CLICKED_BUTTON);
if (question.equals(questionType) && buttonClicked.equals(ConfirmationQuestion.NO)) {
// If 'No' is the button clicked, just reload the doc
return returnToPreviousPage(mapping, kualiDocumentFormBase);
}
else if (question.equals(confirmType) && buttonClicked.equals(SingleConfirmationQuestion.OK)) {
// This is the case when the user clicks on "OK" in the end.
// After we inform the user that the close has been rerouted, we'll redirect to the portal page.
return mapping.findForward(KFSConstants.MAPPING_PORTAL);
}
else {
// Have to check length on value entered.
String introNoteMessage = notePrefix + KFSConstants.BLANK_SPACE;
// Build out full message.
noteText = introNoteMessage + reason;
int noteTextLength = noteText.length();
// Get note text max length from DD.
int noteTextMaxLength = SpringContext.getBean(DataDictionaryService.class).getAttributeMaxLength(Note.class, KFSConstants.NOTE_TEXT_PROPERTY_NAME).intValue();
if (StringUtils.isBlank(reason) || (noteTextLength > noteTextMaxLength)) {
// Figure out exact number of characters that the user can enter.
int reasonLimit = noteTextMaxLength - noteTextLength;
if (ObjectUtils.isNull(reason)) {
// Prevent a NPE by setting the reason to a blank string.
reason = "";
}
return this.performQuestionWithInputAgainBecauseOfErrors(mapping, form, request, response, questionType, kualiConfiguration.getPropertyString(PurapKeyConstants.PURCHASE_ORDER_QUESTION_DOCUMENT), KFSConstants.CONFIRMATION_QUESTION, questionType, "", reason, PurapKeyConstants.ERROR_PURCHASE_ORDER_REASON_REQUIRED, KFSConstants.QUESTION_REASON_ATTRIBUTE_NAME, new Integer(reasonLimit).toString());
}
}
}
// Below used as a place holder to allow code to specify actionForward to return if not a 'success question'
ActionForward returnActionForward = null;
if (!po.isPendingActionIndicator()) {
/*
* Below if-else code block calls PurchaseOrderService methods that will throw ValidationException objects if errors
* occur during any process in the attempt to perform its actions. Assume, if these return successfully, that the
* PurchaseOrderDocument object returned from each is the newly created document and that all actions in the method
* were run correctly. NOTE: IF BELOW IF-ELSE IS EDITED THE NEW METHODS CALLED MUST THROW ValidationException OBJECT
* IF AN ERROR IS ADDED TO THE GlobalVariables
*/
if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_SPLIT_DOCUMENT)) {
po.setPendingSplit(true);
// Save adding the note for after the items are picked.
((PurchaseOrderForm)kualiDocumentFormBase).setSplitNoteText(noteText);
returnActionForward = mapping.findForward(KFSConstants.MAPPING_BASIC);
}
else {
String newStatus = null;
if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_AMENDMENT_DOCUMENT)) {
newStatus = PurchaseOrderStatuses.AMENDMENT;
po = SpringContext.getBean(PurchaseOrderService.class).createAndSavePotentialChangeDocument(kualiDocumentFormBase.getDocument().getDocumentNumber(), documentType, newStatus);
returnActionForward = mapping.findForward(KFSConstants.MAPPING_BASIC);
}
else {
if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_CLOSE_DOCUMENT)) {
newStatus = PurchaseOrderStatuses.PENDING_CLOSE;
}
else if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_REOPEN_DOCUMENT)) {
newStatus = PurchaseOrderStatuses.PENDING_REOPEN;
}
else if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_VOID_DOCUMENT)) {
newStatus = PurchaseOrderStatuses.PENDING_VOID;
}
else if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_PAYMENT_HOLD_DOCUMENT)) {
newStatus = PurchaseOrderStatuses.PENDING_PAYMENT_HOLD;
}
else if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_REMOVE_HOLD_DOCUMENT)) {
newStatus = PurchaseOrderStatuses.PENDING_REMOVE_HOLD;
}
else if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_RETRANSMIT_DOCUMENT)) {
newStatus = PurchaseOrderStatuses.PENDING_RETRANSMIT;
}
po = SpringContext.getBean(PurchaseOrderService.class).createAndRoutePotentialChangeDocument(kualiDocumentFormBase.getDocument().getDocumentNumber(), documentType, kualiDocumentFormBase.getAnnotation(), combineAdHocRecipients(kualiDocumentFormBase), newStatus);
}
if (!GlobalVariables.getErrorMap().isEmpty()) {
throw new ValidationException("errors occurred during new PO creation");
}
String previousDocumentId = kualiDocumentFormBase.getDocId();
// Assume at this point document was created properly and 'po' variable is new PurchaseOrderDocument created
kualiDocumentFormBase.setDocument(po);
kualiDocumentFormBase.setDocId(po.getDocumentNumber());
kualiDocumentFormBase.setDocTypeName(po.getDocumentHeader().getWorkflowDocument().getDocumentType());
Note newNote = new Note();
if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_AMENDMENT_DOCUMENT)) {
noteText = noteText + " (Previous Document Id is " + previousDocumentId + ")";
}
newNote.setNoteText(noteText);
newNote.setNoteTypeCode(KFSConstants.NoteTypeEnum.BUSINESS_OBJECT_NOTE_TYPE.getCode());
kualiDocumentFormBase.setNewNote(newNote);
// see KULPURAP-1984 for an explanation of why this is required and another way to do it.
kualiDocumentFormBase.setAttachmentFile(new BlankFormFile());
insertBONote(mapping, kualiDocumentFormBase, request, response);
}
if (StringUtils.isNotEmpty(messageType)) {
GlobalVariables.getMessageList().add(messageType);
}
}
if (ObjectUtils.isNotNull(returnActionForward)) {
return returnActionForward;
}
else {
return this.performQuestionWithoutInput(mapping, form, request, response, confirmType, kualiConfiguration.getPropertyString(messageType), PODocumentsStrings.SINGLE_CONFIRMATION_QUESTION, questionType, "");
}
}
catch (ValidationException ve) {
throw ve;
}
}
/**
* Invoked when the user pressed on the Close Order button on a Purchase Order page to Close the PO. It will
* display the question page to the user to ask whether the user really wants to close the PO and ask the user to enter a reason
* in the text area. If the user has entered the reason, it will invoke a service method to do the processing for closing a PO,
* then display a Single Confirmation page to inform the user that the PO Close Document has been routed.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @throws Exception
* @return An ActionForward
*/
public ActionForward closePo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
LOG.debug("ClosePO started.");
String operation = "Close ";
PurchaseOrderDocument po = ((PurchaseOrderForm)form).getPurchaseOrderDocument();
if (po.canClosePOForTradeIn()) {
return askQuestionsAndPerformDocumentAction(mapping, form, request, response, PODocumentsStrings.CLOSE_QUESTION, PODocumentsStrings.CLOSE_CONFIRM, PurchaseOrderDocTypes.PURCHASE_ORDER_CLOSE_DOCUMENT, PODocumentsStrings.CLOSE_NOTE_PREFIX, PurapKeyConstants.PURCHASE_ORDER_MESSAGE_CLOSE_DOCUMENT, operation);
}
else {
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
}
/**
* Is invoked when the user pressed on the Payment Hold button on a Purchase Order page to put the PO on hold. It
* will display the question page to the user to ask whether the user really wants to put the PO on hold and ask the user to
* enter a reason in the text area. If the user has entered the reason, it will invoke a service method to do the processing for
* putting a PO on hold, then display a Single Confirmation page to inform the user that the PO Payment Hold Document has been
* routed.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @throws Exception
* @return An ActionForward
*/
public ActionForward paymentHoldPo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
LOG.debug("PaymentHoldPO started.");
String operation = "Hold Payment ";
return askQuestionsAndPerformDocumentAction(mapping, form, request, response, PODocumentsStrings.PAYMENT_HOLD_QUESTION, PODocumentsStrings.PAYMENT_HOLD_CONFIRM, PurchaseOrderDocTypes.PURCHASE_ORDER_PAYMENT_HOLD_DOCUMENT, PODocumentsStrings.PAYMENT_HOLD_NOTE_PREFIX, PurapKeyConstants.PURCHASE_ORDER_MESSAGE_PAYMENT_HOLD, operation);
}
/**
* Is invoked when the user pressed on the Remove Hold button on a Payment Hold PO page to remove the PO from hold.
* It will display the question page to the user to ask whether the user really wants to remove the PO from hold and ask the
* user to enter a reason in the text area. If the user has entered the reason, it will invoke a service method to do the
* processing for removing a PO from hold, then display a Single Confirmation page to inform the user that the PO Remove Hold
* Document has been routed.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @throws Exception
* @return An ActionForward
*/
public ActionForward removeHoldPo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
LOG.debug("RemoveHoldPO started.");
String operation = "Remove Payment Hold ";
ActionForward forward = askQuestionsAndPerformDocumentAction(mapping, form, request, response, PODocumentsStrings.REMOVE_HOLD_QUESTION, PODocumentsStrings.REMOVE_HOLD_CONFIRM, PurchaseOrderDocTypes.PURCHASE_ORDER_REMOVE_HOLD_DOCUMENT, PODocumentsStrings.REMOVE_HOLD_NOTE_PREFIX, PurapKeyConstants.PURCHASE_ORDER_MESSAGE_REMOVE_HOLD, operation);
return forward;
}
/**
* Is invoked when the user pressed on the Open Order button on a Purchase Order page that has status "Close" to
* reopen the PO. It will display the question page to the user to ask whether the user really wants to reopen the PO and ask
* the user to enter a reason in the text area. If the user has entered the reason, it will invoke the a service method to do
* the processing for reopening a PO, then display a Single Confirmation page to inform the user that the
* <code>PurchaseOrderReopenDocument</code> has been routed.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @throws Exception
* @return An ActionForward
* @see org.kuali.kfs.module.purap.document.PurchaseOrderReopenDocument
*/
public ActionForward reopenPo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
LOG.debug("Reopen PO started");
String operation = "Reopen ";
return askQuestionsAndPerformDocumentAction(mapping, form, request, response, PODocumentsStrings.REOPEN_PO_QUESTION, PODocumentsStrings.CONFIRM_REOPEN_QUESTION, PurchaseOrderDocTypes.PURCHASE_ORDER_REOPEN_DOCUMENT, PODocumentsStrings.REOPEN_NOTE_PREFIX, PurapKeyConstants.PURCHASE_ORDER_MESSAGE_REOPEN_DOCUMENT, operation);
}
/**
* Is invoked when the user pressed on the Amend button on a Purchase Order page to amend the PO. It will display
* the question page to the user to ask whether the user really wants to amend the PO and ask the user to enter a reason in the
* text area. If the user has entered the reason, it will invoke a service method to do the processing for amending the PO, then
* display a Single Confirmation page to inform the user that the <code>PurchaseOrderAmendmentDocument</code> has been routed.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @throws Exception
* @return An ActionForward
* @see org.kuali.kfs.module.purap.document.PurchaseOrderAmendmentDocument
*/
public ActionForward amendPo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
LOG.debug("Amend PO started");
String operation = "Amend ";
return askQuestionsAndPerformDocumentAction(mapping, form, request, response, PODocumentsStrings.AMENDMENT_PO_QUESTION, PODocumentsStrings.CONFIRM_AMENDMENT_QUESTION, PurchaseOrderDocTypes.PURCHASE_ORDER_AMENDMENT_DOCUMENT, PODocumentsStrings.AMENDMENT_NOTE_PREFIX, null, operation);
}
/**
* Is invoked when the user pressed on the Void button on a Purchase Order page to void the PO. It will display the
* question page to the user to ask whether the user really wants to void the PO and ask the user to enter a reason in the text
* area. If the user has entered the reason, it will invoke a service method to do the processing for voiding the PO, then
* display a Single Confirmation page to inform the user that the <code>PurchaseOrderVoidDocument</code> has been routed.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @throws Exception
* @return An ActionForward
* @see org.kuali.kfs.module.purap.document.PurchaseOrderVoidDocument
*/
public ActionForward voidPo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
LOG.debug("Void PO started");
String operation = "Void ";
return askQuestionsAndPerformDocumentAction(mapping, form, request, response, PODocumentsStrings.VOID_QUESTION, PODocumentsStrings.VOID_CONFIRM, PurchaseOrderDocTypes.PURCHASE_ORDER_VOID_DOCUMENT, PODocumentsStrings.VOID_NOTE_PREFIX, PurapKeyConstants.PURCHASE_ORDER_MESSAGE_VOID_DOCUMENT, operation);
}
/**
* Invoked to initiate the splitting of a Purchase Order. Displays a question page to ask for a reason and confirmation
* of the user's desire to split the Purchase Order, and, if confirmed, a page on which the Split PO tab only is showing,
* and the items to move to the new PO are chosen. If that is done, and the user continues, a new Split Purchase Order document
* will be created, with the chosen items. That same set of items will be deleted from the original Purchase Order.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServeletRequest
* @param response The HttpServeletResponse
* @return An ActionForward
* @throws Exception
* @see org.kuali.kfs.module.purap.document.PurchaseOrderSplitDocument
*/
public ActionForward splitPo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
LOG.debug("Split PO started");
String operation = "Split ";
return askQuestionsAndPerformDocumentAction(mapping, form, request, response, PODocumentsStrings.SPLIT_QUESTION, PODocumentsStrings.SPLIT_CONFIRM, PurchaseOrderDocTypes.PURCHASE_ORDER_SPLIT_DOCUMENT,PODocumentsStrings.SPLIT_NOTE_PREFIX_OLD_DOC,PurapKeyConstants.PURCHASE_ORDER_MESSAGE_SPLIT_DOCUMENT,operation);
}
/**
* Invoked when only the Split Purchase Order tab is showing to continue the process of splitting the PO, once items are chosen
* to be moved to the new PO.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServeletRequest
* @param response The HttpServeletResponse
* @return An ActionForward
* @throws Exception
*/
public ActionForward continuePurchaseOrderSplit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
LOG.debug("Continue Purchase Order Split started");
PurchaseOrderForm purchaseOrderForm = (PurchaseOrderForm) form;
// This PO does not contain all data, but enough for our purposes; it has been reloaded with only the Split PO tab showing.
PurchaseOrderDocument poToSplit = (PurchaseOrderDocument)purchaseOrderForm.getDocument();
boolean copyNotes = poToSplit.isCopyingNotesWhenSplitting();
// Check business rules before splitting.
boolean rulePassed = SpringContext.getBean(KualiRuleService.class).applyRules(new AttributedSplitPurchaseOrderEvent(poToSplit));
if (!rulePassed) {
poToSplit.setPendingSplit(true);
}
else {
HashMap<String, List<PurchaseOrderItem>> categorizedItems = SpringContext.getBean(PurchaseOrderService.class).categorizeItemsForSplit((List<PurchaseOrderItem>)poToSplit.getItems());
List<PurchaseOrderItem> movingPOItems = categorizedItems.get(PODocumentsStrings.ITEMS_MOVING_TO_SPLIT);
List<PurchaseOrderItem> remainingPOItems = categorizedItems.get(PODocumentsStrings.ITEMS_REMAINING);
// Fetch the whole PO from the database, and reset and renumber the items on it.
poToSplit = (PurchaseOrderDocument)SpringContext.getBean(PurchaseOrderService.class).getCurrentPurchaseOrder(poToSplit.getPurapDocumentIdentifier());
poToSplit.setItems(remainingPOItems);
poToSplit.renumberItems(0);
// Add the note that would normally have gone in after the confirmation page.
String noteText = purchaseOrderForm.getSplitNoteText();
try {
Note splitNote = SpringContext.getBean(DocumentService.class).createNoteFromDocument(poToSplit, noteText);
poToSplit.addNote(splitNote);
} catch ( Exception e ) {
throw new RuntimeException(e);
}
SpringContext.getBean(PurapService.class).saveDocumentNoValidation(poToSplit);
PurchaseOrderSplitDocument splitPO = SpringContext.getBean(PurchaseOrderService.class).createAndSavePurchaseOrderSplitDocument(movingPOItems, poToSplit, copyNotes, noteText);
purchaseOrderForm.setDocument(splitPO);
purchaseOrderForm.setDocId(splitPO.getDocumentNumber());
purchaseOrderForm.setDocTypeName(splitPO.getDocumentHeader().getWorkflowDocument().getDocumentType());
try {
loadDocument(purchaseOrderForm);
}
catch (WorkflowException we) {
throw new RuntimeException(we);
}
}
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
/**
* Invoked from the page on which the Split PO tab is showing to cancel the splitting of the PO and return it to its original state.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServeletRequest
* @param response The HttpServeletResponse
* @return An ActionForward
* @throws Exception
*/
public ActionForward cancelPurchaseOrderSplit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
LOG.debug("Cancel Purchase Order Split started");
PurchaseOrderForm purchaseOrderForm = (PurchaseOrderForm)form;
PurchaseOrderDocument po = (PurchaseOrderDocument)purchaseOrderForm.getDocument();
po = SpringContext.getBean(PurchaseOrderService.class).getPurchaseOrderByDocumentNumber(po.getDocumentNumber());
po.setPendingSplit(false);
po.setCopyingNotesWhenSplitting(false);
purchaseOrderForm.setDocument(po);
reload(mapping, purchaseOrderForm, request, response);
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
/**
* Invoked when an authorized user presses "Sensitive Data" button on the purchase order page.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServeletRequest
* @param response The HttpServeletResponse
* @return An ActionForward
* @throws Exception
*/
public ActionForward assignSensitiveData(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
LOG.debug("Assign Sensitive Data started");
PurchaseOrderForm poForm = (PurchaseOrderForm)form;
PurchaseOrderDocument po = (PurchaseOrderDocument)poForm.getDocument();
Integer poId = po.getPurapDocumentIdentifier();
SensitiveDataService sdService = SpringContext.getBean(SensitiveDataService.class);
// set the assignment flag and reset input fields
poForm.setAssigningSensitiveData(true);
poForm.setSensitiveDataAssignmentReason("");
poForm.setNewSensitiveDataLine(new SensitiveData());
// load previous assignment info
SensitiveDataAssignment sda = sdService.getLastSensitiveDataAssignment(poId);
poForm.setLastSensitiveDataAssignment(sda);
// even though at this point, the sensitive data entries should have been loaded into the form already,
// we still load them again in case that someone else has changed that during the time period
List<SensitiveData> posds = sdService.getSensitiveDatasAssignedByPoId(poId);
poForm.setSensitiveDatasAssigned(posds);
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
/**
* Invoked when an authorized user presses "Submit" button on the "Assign Sensitive Data" page.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServeletRequest
* @param response The HttpServeletResponse
* @return An ActionForward
* @throws Exception
*/
public ActionForward submitSensitiveData(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
LOG.debug("Submit Sensitive Data started");
PurchaseOrderForm poForm = (PurchaseOrderForm)form;
PurchaseOrderDocument po = (PurchaseOrderDocument)poForm.getDocument();
Integer poId = po.getPurapDocumentIdentifier();
List<SensitiveData> sds = poForm.getSensitiveDatasAssigned();
SensitiveDataService sdService = SpringContext.getBean(SensitiveDataService.class);
//FIXME this is broken KULPURAP-3297
// check business rules
boolean rulePassed = SpringContext.getBean(KualiRuleService.class).applyRules(new AttributedAssignSensitiveDataEvent("", po, sds));
if (!rulePassed) {
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
// update table SensitiveDataAssignment
SensitiveDataAssignment sda = new SensitiveDataAssignment(poId, poForm.getSensitiveDataAssignmentReason(), GlobalVariables.getUserSession().getPerson().getPrincipalId(), poForm.getSensitiveDatasAssigned());
SpringContext.getBean(BusinessObjectService.class).save(sda);
// update table PurchaseOrderSensitiveData
sdService.deletePurchaseOrderSensitiveDatas(poId);
List<PurchaseOrderSensitiveData> posds = new ArrayList();
for (SensitiveData sd : sds) {
posds.add(new PurchaseOrderSensitiveData(poId, po.getRequisitionIdentifier(), sd.getSensitiveDataCode()));
}
SpringContext.getBean(BusinessObjectService.class).save(posds);
// need this to update workflow doc for searching restrictions on sensitive data
SpringContext.getBean(PurapService.class).saveRoutingDataForRelatedDocuments(po.getAccountsPayablePurchasingDocumentLinkIdentifier());
// reset the sensitive data related fields in the po form
poForm.setAssigningSensitiveData(false);
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
/**
* Invoked when an authorized user presses "Cancel" button on the "Assign Sensitive Data" page.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServeletRequest
* @param response The HttpServeletResponse
* @return An ActionForward
* @throws Exception
*/
public ActionForward cancelSensitiveData(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
LOG.debug("Cancel Sensitive Data started");
// reset the sensitive data flag in the po form, reload sensitive data from database to undo the canceled changes
PurchaseOrderForm poForm = (PurchaseOrderForm)form;
PurchaseOrderDocument po = (PurchaseOrderDocument)poForm.getDocument();
poForm.setAssigningSensitiveData(false);
List<SensitiveData> sds = SpringContext.getBean(SensitiveDataService.class).getSensitiveDatasAssignedByPoId(po.getPurapDocumentIdentifier());
poForm.setSensitiveDatasAssigned(sds);
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
/**
* Invoked when an authorized user presses "Add" button on the "Assign Sensitive Data" page.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServeletRequest
* @param response The HttpServeletResponse
* @return An ActionForward
* @throws Exception
*/
public ActionForward addSensitiveData(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
LOG.debug("Add Sensitive Data started");
PurchaseOrderForm poForm = (PurchaseOrderForm)form;
SensitiveDataService sdService = SpringContext.getBean(SensitiveDataService.class);
// retrieve new sensitive data by code, add the new line
SensitiveData newsd = poForm.getNewSensitiveDataLine();
newsd = sdService.getSensitiveDataByCode(newsd.getSensitiveDataCode());
List<SensitiveData> sds = poForm.getSensitiveDatasAssigned();
sds.add(newsd);
// reset new line
poForm.setNewSensitiveDataLine(new SensitiveData());
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
/**
* Invoked when an authorized user presses "Delete" button on the "Assign Sensitive Data" page.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServeletRequest
* @param response The HttpServeletResponse
* @return An ActionForward
* @throws Exception
*/
public ActionForward deleteSensitiveData(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
LOG.debug("Delete Sensitive Data started");
// remove the selected sensitive data line
PurchaseOrderForm poForm = (PurchaseOrderForm)form;
List<SensitiveData> sds = poForm.getSensitiveDatasAssigned();
sds.remove(getSelectedLine(request));
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
/**
* This is a utility method used to prepare to and to return to a previous page, making sure that the buttons will be restored
* in the process.
*
* @param kualiDocumentFormBase The Form, considered as a KualiDocumentFormBase, as it typically is here.
* @return An actionForward mapping back to the original page.
*/
protected ActionForward returnToPreviousPage(ActionMapping mapping, KualiDocumentFormBase kualiDocumentFormBase) {
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
/**
* Is executed when the user clicks on the "print" button on a Purchase Order Print Document page. On a non
* javascript enabled browser, it will display a page with 2 buttons. One is to display the PDF, the other is to view the PO
* tabbed page where the PO document statuses, buttons, etc have already been updated (the updates of those occurred while the
* <code>performPurchaseOrderFirstTransmitViaPrinting</code> method is invoked. On a javascript enabled browser, it will
* display both the PO tabbed page containing the updated PO document info and the pdf on the next window/tab of the browser.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @throws Exception
* @return An ActionForward
*/
public ActionForward firstTransmitPrintPo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
String poDocId = ((PurchaseOrderForm)form).getDocId();
ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
try {
SpringContext.getBean(PurchaseOrderService.class).performPurchaseOrderFirstTransmitViaPrinting(poDocId, baosPDF);
}
finally {
if (baosPDF != null) {
baosPDF.reset();
}
}
String basePath = getBasePath(request);
String docId = ((PurchaseOrderForm) form).getDocId();
String methodToCallPrintPurchaseOrderPDF = "printPurchaseOrderPDFOnly";
String methodToCallDocHandler = "docHandler";
String printPOPDFUrl = getUrlForPrintPO(basePath, docId, methodToCallPrintPurchaseOrderPDF);
String displayPOTabbedPageUrl = getUrlForPrintPO(basePath, docId, methodToCallDocHandler);
request.setAttribute("printPOPDFUrl", printPOPDFUrl);
request.setAttribute("displayPOTabbedPageUrl", displayPOTabbedPageUrl);
String label = SpringContext.getBean(DataDictionaryService.class).getDocumentLabelByClass(PurchaseOrderDocument.class);
request.setAttribute("purchaseOrderLabel", label);
return mapping.findForward("printPurchaseOrderPDF");
}
/**
* Creates a URL to be used in printing the purchase order.
*
* @param basePath String: The base path of the current URL
* @param docId String: The document ID of the document to be printed
* @param methodToCall String: The name of the method that will be invoked to do this particular print
* @return The URL
*/
private String getUrlForPrintPO(String basePath, String docId, String methodToCall) {
StringBuffer result = new StringBuffer(basePath);
result.append("/purapPurchaseOrder.do?methodToCall=");
result.append(methodToCall);
result.append("&docId=");
result.append(docId);
result.append("&command=displayDocSearchView");
return result.toString();
}
/**
* Prints the PDF only, as opposed to <code>firstTransmitPrintPo</code>, which calls this method (indirectly) to print the
* PDF, and calls the doc handler to display the PO tabbed page.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @throws Exception
* @return An ActionForward
*/
public ActionForward printPurchaseOrderPDFOnly(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
String poDocId = request.getParameter("docId");
ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
try {
// will throw validation exception if errors occur
SpringContext.getBean(PurchaseOrderService.class).performPrintPurchaseOrderPDFOnly(poDocId, baosPDF);
response.setHeader("Cache-Control", "max-age=30");
response.setContentType("application/pdf");
StringBuffer sbContentDispValue = new StringBuffer();
String useJavascript = request.getParameter("useJavascript");
if (useJavascript == null || useJavascript.equalsIgnoreCase("false")) {
sbContentDispValue.append("attachment");
}
else {
sbContentDispValue.append("inline");
}
StringBuffer sbFilename = new StringBuffer();
sbFilename.append("PURAP_PO_");
sbFilename.append(poDocId);
sbFilename.append("_");
sbFilename.append(System.currentTimeMillis());
sbFilename.append(".pdf");
sbContentDispValue.append("; filename=");
sbContentDispValue.append(sbFilename);
response.setHeader("Content-disposition", sbContentDispValue.toString());
response.setContentLength(baosPDF.size());
ServletOutputStream sos;
sos = response.getOutputStream();
baosPDF.writeTo(sos);
sos.flush();
}
finally {
if (baosPDF != null) {
baosPDF.reset();
}
}
return null;
}
/**
* Print a particular selected PO Quote as a PDF.
*
* @param mapping An ActionMapping
* @param form An ActionForm -- The PO Quote must be selected here.
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @throws Exception
* @return An ActionForward
*/
public ActionForward printPoQuote(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
// String poDocId = request.getParameter("docId");
// PurchaseOrderDocument po = (PurchaseOrderDocument)
// SpringContext.getBean(DocumentService.class).getByDocumentHeaderId(poDocId);
// Integer poSelectedVendorId = new Integer(request.getParameter("quoteVendorId"));
KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
PurchaseOrderDocument po = (PurchaseOrderDocument) kualiDocumentFormBase.getDocument();
PurchaseOrderVendorQuote poVendorQuote = po.getPurchaseOrderVendorQuotes().get(getSelectedLine(request));
ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
poVendorQuote.setTransmitPrintDisplayed(false);
try {
StringBuffer sbFilename = new StringBuffer();
sbFilename.append("PURAP_PO_QUOTE_");
sbFilename.append(po.getPurapDocumentIdentifier());
sbFilename.append("_");
sbFilename.append(System.currentTimeMillis());
sbFilename.append(".pdf");
boolean success = SpringContext.getBean(PurchaseOrderService.class).printPurchaseOrderQuotePDF(po, poVendorQuote, baosPDF);
if (!success) {
poVendorQuote.setTransmitPrintDisplayed(true);
if (baosPDF != null) {
baosPDF.reset();
}
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
response.setHeader("Cache-Control", "max-age=30");
response.setContentType("application/pdf");
StringBuffer sbContentDispValue = new StringBuffer();
// sbContentDispValue.append("inline");
sbContentDispValue.append("attachment");
sbContentDispValue.append("; filename=");
sbContentDispValue.append(sbFilename);
response.setHeader("Content-disposition", sbContentDispValue.toString());
response.setContentLength(baosPDF.size());
ServletOutputStream sos;
sos = response.getOutputStream();
baosPDF.writeTo(sos);
sos.flush();
}
finally {
if (baosPDF != null) {
baosPDF.reset();
}
}
return null;
}
/**
* Print the list of PO Quote requests.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @throws Exception
* @return An ActionForward
*/
public ActionForward printPoQuoteList(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
PurchaseOrderDocument po = (PurchaseOrderDocument) kualiDocumentFormBase.getDocument();
ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
try {
StringBuffer sbFilename = new StringBuffer();
sbFilename.append("PURAP_PO_QUOTE_LIST_");
sbFilename.append(po.getPurapDocumentIdentifier());
sbFilename.append("_");
sbFilename.append(System.currentTimeMillis());
sbFilename.append(".pdf");
boolean success = SpringContext.getBean(PurchaseOrderService.class).printPurchaseOrderQuoteRequestsListPDF(po, baosPDF);
if (!success) {
if (baosPDF != null) {
baosPDF.reset();
}
return mapping.findForward(KFSConstants.MAPPING_PORTAL);
}
response.setHeader("Cache-Control", "max-age=30");
response.setContentType("application/pdf");
StringBuffer sbContentDispValue = new StringBuffer();
// sbContentDispValue.append("inline");
sbContentDispValue.append("attachment");
sbContentDispValue.append("; filename=");
sbContentDispValue.append(sbFilename);
response.setHeader("Content-disposition", sbContentDispValue.toString());
response.setContentLength(baosPDF.size());
ServletOutputStream sos;
sos = response.getOutputStream();
baosPDF.writeTo(sos);
sos.flush();
}
finally {
if (baosPDF != null) {
baosPDF.reset();
}
}
return null;
}
/**
* Initiates transmission of a PO Quote request.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @throws Exception
* @return An ActionForward
*/
public ActionForward transmitPurchaseOrderQuote(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
PurchaseOrderDocument po = (PurchaseOrderDocument) kualiDocumentFormBase.getDocument();
PurchaseOrderVendorQuote vendorQuote = (PurchaseOrderVendorQuote) po.getPurchaseOrderVendorQuotes().get(getSelectedLine(request));
if (PurapConstants.QuoteTransmitTypes.PRINT.equals(vendorQuote.getPurchaseOrderQuoteTransmitTypeCode())) {
vendorQuote.setPurchaseOrderQuoteTransmitTimestamp(SpringContext.getBean(DateTimeService.class).getCurrentTimestamp());
vendorQuote.setTransmitPrintDisplayed(true);
SpringContext.getBean(PurapService.class).saveDocumentNoValidation(po);
}
else if (PurapConstants.QuoteTransmitTypes.FAX.equals(vendorQuote.getPurchaseOrderQuoteTransmitTypeCode())) {
// call fax service
GlobalVariables.getErrorMap().clear();
FaxService faxService = SpringContext.getBean(FaxService.class);
faxService.faxPurchaseOrderPdf(po, false);
if (GlobalVariables.getErrorMap().size() == 0) {
vendorQuote.setPurchaseOrderQuoteTransmitTimestamp(SpringContext.getBean(DateTimeService.class).getCurrentTimestamp());
SpringContext.getBean(PurapService.class).saveDocumentNoValidation(po);
}
}
else {
GlobalVariables.getErrorMap().putError(PurapPropertyConstants.VENDOR_QUOTES, PurapKeyConstants.ERROR_PURCHASE_ORDER_QUOTE_TRANSMIT_TYPE_NOT_SELECTED);
}
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
/**
* Is invoked when the user clicks on the Select All button on a Purchase Order Retransmit document. It will select
* the checkboxes of all the items to be included in the retransmission of the PO.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @throws Exception
* @return An ActionForward
*/
public ActionForward selectAllForRetransmit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
PurchaseOrderDocument po = (PurchaseOrderDocument) kualiDocumentFormBase.getDocument();
List<PurchaseOrderItem> items = po.getItems();
for (PurchaseOrderItem item : items) {
item.setItemSelectedForRetransmitIndicator(true);
}
return returnToPreviousPage(mapping, kualiDocumentFormBase);
}
/**
* Is invoked when the user clicks on the Deselect All button on a Purchase Order Retransmit document. It will
* uncheck the checkboxes of all the items to be excluded from the retransmission of the PO.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @throws Exception
* @return An ActionForward
*/
public ActionForward deselectAllForRetransmit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
PurchaseOrderDocument po = (PurchaseOrderDocument) kualiDocumentFormBase.getDocument();
List<PurchaseOrderItem> items = po.getItems();
for (PurchaseOrderItem item : items) {
item.setItemSelectedForRetransmitIndicator(false);
}
return returnToPreviousPage(mapping, kualiDocumentFormBase);
}
/**
* Is invoked when the user clicks on the Retransmit button on both the PO tabbed page and on the Purchase Order
* Retransmit Document page, which is essentially a PO tabbed page with the other irrelevant tabs being hidden. If it was
* invoked from the PO tabbed page, if the PO's pending indicator is false, this method will invoke a method in the
* PurchaseOrderService to update the flags, create the PurchaseOrderRetransmitDocument and route it. If the routing was
* successful, we'll display the Purchase Order Retransmit Document page to the user, containing the newly created and routed
* PurchaseOrderRetransmitDocument and a retransmit button as well as a list of items that the user can select to be
* retransmitted. If it was invoked from the Purchase Order Retransmit Document page, we'll invoke the
* retransmitPurchaseOrderPDF method to create a PDF document based on the PO information and the items that were selected by
* the user on the Purchase Order Retransmit Document page to be retransmitted, then display the PDF to the browser.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @throws Exception
* @return An ActionForward
*/
public ActionForward retransmitPo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
PurchaseOrderDocument po = (PurchaseOrderDocument) kualiDocumentFormBase.getDocument();
boolean success;
if (po.isPendingActionIndicator()) {
success = false;
GlobalVariables.getErrorMap().putError(PurapPropertyConstants.PURCHASE_ORDER_IDENTIFIER, PurapKeyConstants.ERROR_PURCHASE_ORDER_IS_PENDING);
}
else {
po = SpringContext.getBean(PurchaseOrderService.class).createAndRoutePotentialChangeDocument(kualiDocumentFormBase.getDocument().getDocumentNumber(), PurchaseOrderDocTypes.PURCHASE_ORDER_RETRANSMIT_DOCUMENT, kualiDocumentFormBase.getAnnotation(), combineAdHocRecipients(kualiDocumentFormBase), PurchaseOrderStatuses.PENDING_RETRANSMIT);
((PurchaseOrderRetransmitDocument)po).setShouldDisplayRetransmitTab(true);
}
kualiDocumentFormBase.setDocument(po);
// we only need to set the editing mode to displayRetransmitTab if it's not yet
// in the editingMode.
if (!kualiDocumentFormBase.getEditingMode().containsKey(PurapAuthorizationConstants.PurchaseOrderEditMode.DISPLAY_RETRANSMIT_TAB)) {
DocumentAuthorizer documentAuthorizer = SpringContext.getBean(DocumentHelperService.class).getDocumentAuthorizer(po);
// TODO this method is gone, fix for kim
// kualiDocumentFormBase.populateAuthorizationFields(documentAuthorizer);
}
return returnToPreviousPage(mapping, kualiDocumentFormBase);
}
/**
* Is invoked when the user clicks on the Retransmit button on both the PO tabbed page and on the Purchase Order
* Retransmit Document page, which is essentially a PO tabbed page with the other irrelevant tabs being hidden. If it was
* invoked from the PO tabbed page, if the PO's pending indicator is false, this method will invoke a method in the
* PurchaseOrderService to update the flags, create the PurchaseOrderRetransmitDocument and route it. If the routing was
* successful, we'll display the Purchase Order Retransmit Document page to the user, containing the newly created and routed
* PurchaseOrderRetransmitDocument and a retransmit button as well as a list of items that the user can select to be
* retransmitted. If it was invoked from the Purchase Order Retransmit Document page, we'll invoke the
* retransmitPurchaseOrderPDF method to create a PDF document based on the PO information and the items that were selected by
* the user on the Purchase Order Retransmit Document page to be retransmitted, then display the PDF to the browser.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @throws Exception
* @return An ActionForward
*/
public ActionForward printingPreviewPo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
String poDocId = ((PurchaseOrderForm)form).getDocId();
ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
try {
SpringContext.getBean(PurchaseOrderService.class).performPurchaseOrderPreviewPrinting(poDocId, baosPDF);
}
finally {
if (baosPDF != null) {
baosPDF.reset();
}
}
String basePath = getBasePath(request);
String docId = ((PurchaseOrderForm) form).getDocId();
String methodToCallPrintPurchaseOrderPDF = "printPurchaseOrderPDFOnly";
String methodToCallDocHandler = "docHandler";
String printPOPDFUrl = getUrlForPrintPO(basePath, docId, methodToCallPrintPurchaseOrderPDF);
String displayPOTabbedPageUrl = getUrlForPrintPO(basePath, docId, methodToCallDocHandler);
request.setAttribute("printPOPDFUrl", printPOPDFUrl);
request.setAttribute("displayPOTabbedPageUrl", displayPOTabbedPageUrl);
String label = SpringContext.getBean(DataDictionaryService.class).getDocumentLabelByClass(PurchaseOrderDocument.class);
request.setAttribute("purchaseOrderLabel", label);
GlobalVariables.getUserSession().addObject("isPreview", new Boolean(true));
return mapping.findForward("printPurchaseOrderPDF");
}
/**
* Forwards to the RetransmitForward.jsp page so that we could open 2 windows for retransmit,
* one is to display the PO tabbed page and the other one display the pdf document.
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward printingRetransmitPo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
String basePath = getBasePath(request);
String docId = ((PurchaseOrderForm) form).getPurchaseOrderDocument().getDocumentNumber();
String methodToCallPrintRetransmitPurchaseOrderPDF = "printingRetransmitPoOnly";
String methodToCallDocHandler = "docHandler";
String printPOPDFUrl = getUrlForPrintPO(basePath, docId, methodToCallPrintRetransmitPurchaseOrderPDF);
String displayPOTabbedPageUrl = getUrlForPrintPO(basePath, docId, methodToCallDocHandler);
KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
PurchaseOrderDocument po = (PurchaseOrderDocument) kualiDocumentFormBase.getDocument();
StringBuffer itemIndexesBuffer = createSelectedItemIndexes(po.getItems());
if (itemIndexesBuffer.length() > 0) {
itemIndexesBuffer.deleteCharAt(itemIndexesBuffer.lastIndexOf(","));
request.setAttribute("selectedItemIndexes", itemIndexesBuffer.toString());
}
request.setAttribute("printPOPDFUrl", printPOPDFUrl);
request.setAttribute("displayPOTabbedPageUrl", displayPOTabbedPageUrl);
request.setAttribute("docId", docId);
String label = SpringContext.getBean(DataDictionaryService.class).getDocumentLabelByClass(PurchaseOrderDocument.class);
request.setAttribute("purchaseOrderLabel", label);
return mapping.findForward("retransmitPurchaseOrderPDF");
}
/**
* Helper method to create a StringBuffer of the indexes of items that the user
* has selected for retransmit to be passed in as an attribute to the RetransmitForward
* page so that we could add these items later on to the pdf page.
*
* @param items The List of items on the PurchaseOrderDocument.
* @return
*/
private StringBuffer createSelectedItemIndexes(List<PurchaseOrderItem>items) {
StringBuffer itemIndexesBuffer = new StringBuffer();
int i = 0;
for (PurchaseOrderItem item : items) {
if (item.isItemSelectedForRetransmitIndicator()) {
itemIndexesBuffer.append(i);
itemIndexesBuffer.append(',');
}
i++;
}
return itemIndexesBuffer;
}
/**
* Creates a PDF document based on the PO information and the items that were selected by the user on the Purchase Order
* Retransmit Document page to be retransmitted, then display the PDF to the browser.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @throws Exception
* @return An ActionForward
*/
public ActionForward printingRetransmitPoOnly(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
String selectedItemIndexes = (String)request.getParameter("selectedItemIndexes");
String documentNumber = (String)request.getParameter("poDocumentNumberForRetransmit");
PurchaseOrderDocument po = SpringContext.getBean(PurchaseOrderService.class).getPurchaseOrderByDocumentNumber(documentNumber);
String retransmitHeader = (String)request.getParameter("retransmitHeader");
// setting the isItemSelectedForRetransmitIndicator items of the PO obtained from the database based on its value from
// the po from the form
setItemSelectedForRetransmitIndicatorFromPOInForm(selectedItemIndexes, po.getItems());
po.setRetransmitHeader(retransmitHeader);
ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
try {
StringBuffer sbFilename = new StringBuffer();
sbFilename.append("PURAP_PO_");
sbFilename.append(po.getPurapDocumentIdentifier());
sbFilename.append("_");
sbFilename.append(System.currentTimeMillis());
sbFilename.append(".pdf");
// below method will throw ValidationException if errors are found
SpringContext.getBean(PurchaseOrderService.class).retransmitPurchaseOrderPDF(po, baosPDF);
response.setHeader("Cache-Control", "max-age=30");
response.setContentType("application/pdf");
StringBuffer sbContentDispValue = new StringBuffer();
sbContentDispValue.append("inline");
sbContentDispValue.append("; filename=");
sbContentDispValue.append(sbFilename);
response.setHeader("Content-disposition", sbContentDispValue.toString());
response.setContentLength(baosPDF.size());
ServletOutputStream sos;
sos = response.getOutputStream();
baosPDF.writeTo(sos);
sos.flush();
}
catch (ValidationException e) {
LOG.warn("Caught ValidationException while trying to retransmit PO with doc id " + po.getDocumentNumber());
return mapping.findForward(KFSConstants.MAPPING_ERROR);
}
finally {
if (baosPDF != null) {
baosPDF.reset();
}
}
return null;
}
/**
* Sets the itemSelectedForRetransmitIndicator to true to the items that the
* user has selected for retransmit.
*
* @param selectedItemIndexes The String containing the indexes of items selected to be retransmitted, separated by comma.
* @param itemsFromDB The List of items of the PurchaseOrderDocument obtained from the database.
*/
private void setItemSelectedForRetransmitIndicatorFromPOInForm(String selectedItemIndexes, List itemsFromDB) {
int i = 0;
StringTokenizer tok = new StringTokenizer(selectedItemIndexes, ",");
while (tok.hasMoreTokens()) {
i = Integer.parseInt(tok.nextToken());
((PurchaseOrderItem) (itemsFromDB.get(i))).setItemSelectedForRetransmitIndicator(true);
}
}
/**
* Checks on a few conditions that would cause a warning message to be displayed on top of the Purchase Order page.
*
* @param po the PurchaseOrderDocument whose status and indicators are to be checked in the conditions
* @return boolean true if the Purchase Order doesn't have any warnings and false otherwise.
*/
private void checkForPOWarnings(PurchaseOrderDocument po, ActionMessages messages) {
// "This is not the current version of this Purchase Order." (curr_ind = N and doc status is not enroute)
if (!po.isPurchaseOrderCurrentIndicator() && !po.getDocumentHeader().getWorkflowDocument().stateIsEnroute()) {
GlobalVariables.getMessageList().add(PurapKeyConstants.WARNING_PURCHASE_ORDER_NOT_CURRENT);
}
// "This document is a pending action. This is not the current version of this Purchase Order" (curr_ind = N and doc status
// is enroute)
if (!po.isPurchaseOrderCurrentIndicator() && po.getDocumentHeader().getWorkflowDocument().stateIsEnroute()) {
GlobalVariables.getMessageList().add(PurapKeyConstants.WARNING_PURCHASE_ORDER_PENDING_ACTION_NOT_CURRENT);
}
// "There is a pending action on this Purchase Order." (pend_action = Y)
if (po.isPendingActionIndicator()) {
GlobalVariables.getMessageList().add(PurapKeyConstants.WARNING_PURCHASE_ORDER_PENDING_ACTION);
}
if (!po.isPurchaseOrderCurrentIndicator()) {
ActionMessage noteMessage = new ActionMessage(PurapKeyConstants.WARNING_PURCHASE_ORDER_ALL_NOTES);
messages.add(PurapConstants.NOTE_TAB_WARNING, noteMessage);
}
}
/**
* Add a stipulation to the document.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @throws Exception
* @return An ActionForward
*/
public ActionForward addStipulation(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
PurchaseOrderForm poForm = (PurchaseOrderForm) form;
PurchaseOrderDocument document = (PurchaseOrderDocument) poForm.getDocument();
if (StringUtils.isBlank(poForm.getNewPurchaseOrderVendorStipulationLine().getVendorStipulationDescription())) {
GlobalVariables.getErrorMap().putError(KFSConstants.DOCUMENT_PROPERTY_NAME + "." + PurapPropertyConstants.VENDOR_STIPULATION, PurapKeyConstants.ERROR_STIPULATION_DESCRIPTION);
}
else {
PurchaseOrderVendorStipulation newStipulation = poForm.getAndResetNewPurchaseOrderVendorStipulationLine();
document.getPurchaseOrderVendorStipulations().add(newStipulation);
}
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
/**
* Delete a stipulation from the document.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @throws Exception
* @return An ActionForward
*/
public ActionForward deleteStipulation(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
PurchaseOrderForm poForm = (PurchaseOrderForm) form;
PurchaseOrderDocument document = (PurchaseOrderDocument) poForm.getDocument();
document.getPurchaseOrderVendorStipulations().remove(getSelectedLine(request));
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
/**
* Overrides the docHandler method in the superclass. In addition to doing the normal process in the superclass and returning
* its action forward from the superclass, it also invokes the <code>checkForPOWarnings</code> method to check on a few
* conditions that could have caused warning messages to be displayed on top of Purchase Order page.
*
* @see org.kuali.rice.kns.web.struts.action.KualiDocumentActionBase#docHandler(org.apache.struts.action.ActionMapping,
* org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
@Override
public ActionForward docHandler(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
ActionForward forward = super.docHandler(mapping, form, request, response);
PurchaseOrderForm poForm = (PurchaseOrderForm) form;
PurchaseOrderDocument po = (PurchaseOrderDocument) poForm.getDocument();
ActionMessages messages = new ActionMessages();
checkForPOWarnings(po, messages);
saveMessages(request, messages);
return forward;
}
/**
* Sets up the PO document for Quote processing.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @throws Exception
* @return An ActionForward
*/
public ActionForward initiateQuote(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
PurchaseOrderForm poForm = (PurchaseOrderForm) form;
PurchaseOrderDocument document = (PurchaseOrderDocument) poForm.getDocument();
if (!PurapConstants.PurchaseOrderStatuses.IN_PROCESS.equals(document.getStatusCode())) {
// PO must be "in process" in order to initiate a quote
GlobalVariables.getErrorMap().putError(PurapPropertyConstants.VENDOR_QUOTES, PurapKeyConstants.ERROR_PURCHASE_ORDER_QUOTE_NOT_IN_PROCESS);
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
Date currentSqlDate = SpringContext.getBean(DateTimeService.class).getCurrentSqlDate();
document.setPurchaseOrderQuoteInitializationDate(currentSqlDate);
document.setStatusCode(PurapConstants.PurchaseOrderStatuses.QUOTE);
Date expDate = new Date(currentSqlDate.getTime() + (10 * 24 * 60 * 60 * 1000)); // add 10 days - TODO: make this a parameter!!!
document.setPurchaseOrderQuoteDueDate(expDate);
document.getPurchaseOrderVendorQuotes().clear();
SpringContext.getBean(PurapService.class).saveDocumentNoValidation(document);
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
/**
* Add to the Quotes a line to contain a Vendor.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @throws Exception
* @return An ActionForward
*/
public ActionForward addVendor(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
PurchaseOrderForm poForm = (PurchaseOrderForm) form;
PurchaseOrderDocument document = (PurchaseOrderDocument) poForm.getDocument();
PurchaseOrderVendorQuote vendorQuote = poForm.getNewPurchaseOrderVendorQuote();
boolean rulePassed = SpringContext.getBean(KualiRuleService.class).applyRules(new AttributedAddVendorToQuoteEvent("", document, vendorQuote));
if (rulePassed) {
poForm.getNewPurchaseOrderVendorQuote().setDocumentNumber(document.getDocumentNumber());
document.getPurchaseOrderVendorQuotes().add(vendorQuote);
poForm.setNewPurchaseOrderVendorQuote(new PurchaseOrderVendorQuote());
}
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
/**
* Deletes a Vendor from the list of those from which a Quote should be obtained.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @throws Exception
* @return An ActionForward
*/
public ActionForward deleteVendor(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
PurchaseOrderForm poForm = (PurchaseOrderForm) form;
PurchaseOrderDocument document = (PurchaseOrderDocument) poForm.getDocument();
document.getPurchaseOrderVendorQuotes().remove(getSelectedLine(request));
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
/**
* Once an awarded Vendor number is present on the PO, verifies the fact, asks the user for confirmation to complete the quoting
* process with the awarded Vendor, and sets the Vendor information on the purchase order, if confirmation is obtained.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @throws Exception
* @return An ActionForward
*/
public ActionForward completeQuote(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
PurchaseOrderForm poForm = (PurchaseOrderForm) form;
PurchaseOrderDocument document = (PurchaseOrderDocument) poForm.getDocument();
PurchaseOrderVendorQuote awardedQuote = new PurchaseOrderVendorQuote();
// verify that all vendors have a quote status
// also run dictionary validations to validate against the DD.
boolean dictionaryValid = true;
for (PurchaseOrderVendorQuote poQuote : document.getPurchaseOrderVendorQuotes()) {
if (poQuote.getPurchaseOrderQuoteStatusCode() == null) {
GlobalVariables.getErrorMap().putError(PurapPropertyConstants.VENDOR_QUOTES, PurapKeyConstants.ERROR_PURCHASE_ORDER_QUOTE_STATUS_NOT_SELECTED);
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
else {
dictionaryValid &= SpringContext.getBean(DictionaryValidationService.class).isBusinessObjectValid(poQuote, PurapPropertyConstants.VENDOR_QUOTES);
}
}
if (!dictionaryValid) {
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
// verify quote status fields
if (poForm.getAwardedVendorNumber() == null) {
GlobalVariables.getErrorMap().putError(PurapPropertyConstants.VENDOR_QUOTES, PurapKeyConstants.ERROR_PURCHASE_ORDER_QUOTE_NO_VENDOR_AWARDED);
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
else {
awardedQuote = document.getPurchaseOrderVendorQuote(poForm.getAwardedVendorNumber().intValue());
if (awardedQuote.getPurchaseOrderQuoteStatusCode() == null) {
GlobalVariables.getErrorMap().putError(PurapPropertyConstants.VENDOR_QUOTES, PurapKeyConstants.ERROR_PURCHASE_ORDER_QUOTE_NOT_TRANSMITTED);
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
else {
VendorDetail awardedVendor = SpringContext.getBean(VendorService.class).getVendorDetail(awardedQuote.getVendorHeaderGeneratedIdentifier(), awardedQuote.getVendorDetailAssignedIdentifier());
if (!awardedVendor.getVendorHeader().getVendorTypeCode().equals("PO")) {
GlobalVariables.getErrorMap().putError(PurapPropertyConstants.VENDOR_QUOTES, PurapKeyConstants.ERROR_PURCHASE_ORDER_QUOTE_AWARD_NON_PO);
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
}
}
// use question framework to make sure they REALLY want to complete the quote...
String message = SpringContext.getBean(KualiConfigurationService.class).getPropertyString(PurapKeyConstants.PURCHASE_ORDER_QUESTION_CONFIRM_AWARD);
String vendorRow = SpringContext.getBean(KualiConfigurationService.class).getPropertyString(PurapKeyConstants.PURCHASE_ORDER_QUESTION_CONFIRM_AWARD_ROW);
String tempRows = "";
for (PurchaseOrderVendorQuote poQuote : document.getPurchaseOrderVendorQuotes()) {
String tempRow = vendorRow;
tempRow = StringUtils.replace(tempRow, "{0}", poQuote.getVendorName());
if (poQuote.getPurchaseOrderQuoteAwardTimestamp() == null) {
if (awardedQuote.getVendorNumber().equals(poQuote.getVendorNumber())) {
tempRow = StringUtils.replace(tempRow, "{1}", SpringContext.getBean(DateTimeService.class).getCurrentSqlDate().toString());
}
else {
tempRow = StringUtils.replace(tempRow, "{1}", "");
}
}
else {
tempRow = StringUtils.replace(tempRow, "{1}", poQuote.getPurchaseOrderQuoteAwardTimestamp().toString());
}
if (poQuote.getPurchaseOrderQuoteStatusCode() != null) {
poQuote.refreshReferenceObject(PurapPropertyConstants.PURCHASE_ORDER_QUOTE_STATUS);
tempRow = StringUtils.replace(tempRow, "{2}", poQuote.getPurchaseOrderQuoteStatus().getStatusDescription());
}
else {
tempRow = StringUtils.replace(tempRow, "{2}", "N/A");
}
if (poQuote.getPurchaseOrderQuoteRankNumber() != null) {
tempRow = StringUtils.replace(tempRow, "{3}", poQuote.getPurchaseOrderQuoteRankNumber());
}
else {
tempRow = StringUtils.replace(tempRow, "{3}", "N/A");
}
tempRows += tempRow;
}
message = StringUtils.replace(message, "{0}", tempRows);
Object question = request.getParameter(KFSConstants.QUESTION_INST_ATTRIBUTE_NAME);
if (question == null) {
// ask question if not already asked
return performQuestionWithoutInput(mapping, form, request, response, PODocumentsStrings.CONFIRM_AWARD_QUESTION, message, KFSConstants.CONFIRMATION_QUESTION, PODocumentsStrings.CONFIRM_AWARD_RETURN, "");
}
else {
Object buttonClicked = request.getParameter(KFSConstants.QUESTION_CLICKED_BUTTON);
if ((PODocumentsStrings.CONFIRM_AWARD_QUESTION.equals(question)) && ConfirmationQuestion.YES.equals(buttonClicked)) {
// set awarded date
awardedQuote.setPurchaseOrderQuoteAwardTimestamp(SpringContext.getBean(DateTimeService.class).getCurrentTimestamp());
Date currentSqlDate = SpringContext.getBean(DateTimeService.class).getCurrentSqlDate();
document.setPurchaseOrderQuoteAwardedDate(currentSqlDate);
// PO vendor information updated with awarded vendor
document.setVendorName(awardedQuote.getVendorName());
document.setVendorNumber(awardedQuote.getVendorNumber());
document.setVendorHeaderGeneratedIdentifier(awardedQuote.getVendorHeaderGeneratedIdentifier());
document.setVendorDetailAssignedIdentifier(awardedQuote.getVendorDetailAssignedIdentifier());
document.setVendorLine1Address(awardedQuote.getVendorLine1Address());
document.setVendorLine2Address(awardedQuote.getVendorLine2Address());
document.setVendorCityName(awardedQuote.getVendorCityName());
document.setVendorStateCode(awardedQuote.getVendorStateCode());
document.setVendorPostalCode(awardedQuote.getVendorPostalCode());
document.setVendorCountryCode(awardedQuote.getVendorCountryCode());
document.setVendorPhoneNumber(awardedQuote.getVendorPhoneNumber());
document.setVendorFaxNumber(awardedQuote.getVendorFaxNumber());
document.setStatusCode(PurapConstants.PurchaseOrderStatuses.IN_PROCESS);
SpringContext.getBean(PurapService.class).saveDocumentNoValidation(document);
}
}
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
/**
* Cancels the process of obtaining quotes. Checks whether any of the quote requests have been transmitted. If none have, tries
* to obtain confirmation from the user for the cancellation. If confirmation is obtained, clears out the list of Vendors from
* which to obtain quotes and writes the given reason to a note on the PO.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @throws Exception
* @return An ActionForward
*/
public ActionForward cancelQuote(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
PurchaseOrderForm poForm = (PurchaseOrderForm) form;
PurchaseOrderDocument document = (PurchaseOrderDocument) poForm.getDocument();
for (PurchaseOrderVendorQuote quotedVendors : document.getPurchaseOrderVendorQuotes()) {
if (quotedVendors.getPurchaseOrderQuoteTransmitTimestamp() != null) {
GlobalVariables.getErrorMap().putError(PurapPropertyConstants.VENDOR_QUOTES, PurapKeyConstants.ERROR_PURCHASE_ORDER_QUOTE_ALREADY_TRASNMITTED);
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
}
String message = SpringContext.getBean(KualiConfigurationService.class).getPropertyString(PurapKeyConstants.PURCHASE_ORDER_QUESTION_CONFIRM_CANCEL_QUOTE);
Object question = request.getParameter(KFSConstants.QUESTION_INST_ATTRIBUTE_NAME);
if (question == null) {
// ask question if not already asked
return performQuestionWithInput(mapping, form, request, response, PODocumentsStrings.CONFIRM_CANCEL_QUESTION, message, KFSConstants.CONFIRMATION_QUESTION, PODocumentsStrings.CONFIRM_CANCEL_RETURN, "");
}
else {
Object buttonClicked = request.getParameter(KFSConstants.QUESTION_CLICKED_BUTTON);
if ((PODocumentsStrings.CONFIRM_CANCEL_QUESTION.equals(question)) && ConfirmationQuestion.YES.equals(buttonClicked)) {
String reason = request.getParameter(KFSConstants.QUESTION_REASON_ATTRIBUTE_NAME);
if (StringUtils.isEmpty(reason)) {
return performQuestionWithInputAgainBecauseOfErrors(mapping, form, request, response, PODocumentsStrings.CONFIRM_CANCEL_QUESTION, message, KFSConstants.CONFIRMATION_QUESTION, PODocumentsStrings.CONFIRM_CANCEL_RETURN, "", "", PurapKeyConstants.ERROR_PURCHASE_ORDER_REASON_REQUIRED, KFSConstants.QUESTION_REASON_ATTRIBUTE_NAME, "250");
}
document.getPurchaseOrderVendorQuotes().clear();
Note cancelNote = new Note();
cancelNote.setAuthorUniversalIdentifier(GlobalVariables.getUserSession().getPerson().getPrincipalId());
String reasonPrefix = SpringContext.getBean(KualiConfigurationService.class).getPropertyString(PurapKeyConstants.PURCHASE_ORDER_CANCEL_QUOTE_NOTE_TEXT);
cancelNote.setNoteText(reasonPrefix + reason);
document.addNote(cancelNote);
document.setStatusCode(PurapConstants.PurchaseOrderStatuses.IN_PROCESS);
SpringContext.getBean(PurapService.class).saveDocumentNoValidation(document);
}
}
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
/**
* @see org.kuali.rice.kns.web.struts.action.KualiDocumentActionBase#cancel(org.apache.struts.action.ActionMapping,
* org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
@Override
public ActionForward cancel(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
Object question = request.getParameter(KFSConstants.QUESTION_INST_ATTRIBUTE_NAME);
// this should probably be moved into a private instance variable
KualiConfigurationService kualiConfiguration = SpringContext.getBean(KualiConfigurationService.class);
// logic for cancel question
if (question == null) {
// ask question if not already asked
return this.performQuestionWithoutInput(mapping, form, request, response, KFSConstants.DOCUMENT_CANCEL_QUESTION, kualiConfiguration.getPropertyString("document.question.cancel.text"), KFSConstants.CONFIRMATION_QUESTION, KFSConstants.MAPPING_CANCEL, "");
}
else {
Object buttonClicked = request.getParameter(KFSConstants.QUESTION_CLICKED_BUTTON);
if ((KFSConstants.DOCUMENT_CANCEL_QUESTION.equals(question)) && ConfirmationQuestion.NO.equals(buttonClicked)) {
// if no button clicked just reload the doc
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
// else go to cancel logic below
}
KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
SpringContext.getBean(DocumentService.class).cancelDocument(kualiDocumentFormBase.getDocument(), kualiDocumentFormBase.getAnnotation());
return returnToSender(mapping, kualiDocumentFormBase);
}
/**
* @see org.kuali.rice.kns.web.struts.action.KualiDocumentActionBase#save(org.apache.struts.action.ActionMapping,
* org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
@Override
public ActionForward save(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
PurchaseOrderForm poForm = (PurchaseOrderForm) form;
PurchaseOrderDocument po = poForm.getPurchaseOrderDocument();
if (StringUtils.isNotBlank(po.getStatusCode()) && StringUtils.isNotBlank(po.getStatusChange()) && (!StringUtils.equals(po.getStatusCode(), po.getStatusChange()))) {
KualiWorkflowDocument workflowDocument = po.getDocumentHeader().getWorkflowDocument();
if (ObjectUtils.isNull(workflowDocument) || workflowDocument.stateIsInitiated() || workflowDocument.stateIsSaved()) {
return this.askSaveQuestions(mapping, form, request, response, PODocumentsStrings.MANUAL_STATUS_CHANGE_QUESTION);
}
}
return super.save(mapping, form, request, response);
}
/**
* Obtains confirmation and records reasons for the manual status changes which can take place before the purchase order has
* been routed. If confirmation is given, changes the status, saves, and records the given reason in an note on the purchase
* order.
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request The HttpServletRequest
* @param response The HttpServletResponse
* @return An ActionForward
*/
private ActionForward askSaveQuestions(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response, String questionType) {
KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
PurchaseOrderDocument po = (PurchaseOrderDocument) kualiDocumentFormBase.getDocument();
Object question = request.getParameter(KFSConstants.QUESTION_INST_ATTRIBUTE_NAME);
String reason = request.getParameter(KFSConstants.QUESTION_REASON_ATTRIBUTE_NAME);
KualiConfigurationService kualiConfiguration = SpringContext.getBean(KualiConfigurationService.class);
ActionForward forward = mapping.findForward(KFSConstants.MAPPING_BASIC);
String notePrefix = "";
if (StringUtils.equals(questionType, PODocumentsStrings.MANUAL_STATUS_CHANGE_QUESTION) && ObjectUtils.isNull(question)) {
String message = kualiConfiguration.getPropertyString(PurapKeyConstants.PURCHASE_ORDER_QUESTION_MANUAL_STATUS_CHANGE);
try {
return this.performQuestionWithInput(mapping, form, request, response, questionType, message, KFSConstants.CONFIRMATION_QUESTION, questionType, "");
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
else {
Object buttonClicked = request.getParameter(KFSConstants.QUESTION_CLICKED_BUTTON);
if (question.equals(questionType) && buttonClicked.equals(ConfirmationQuestion.NO)) {
// If 'No' is the button clicked, just reload the doc
return forward;
}
// Build out full message.
if (StringUtils.equals(questionType, PODocumentsStrings.MANUAL_STATUS_CHANGE_QUESTION)) {
Map<String, String> manuallyChangeableStatuses = new HashMap<String, String>();
manuallyChangeableStatuses.put(PurchaseOrderStatuses.IN_PROCESS, "In Process");
manuallyChangeableStatuses.put(PurchaseOrderStatuses.WAITING_FOR_VENDOR, "Waiting for Vendor");
manuallyChangeableStatuses.put(PurchaseOrderStatuses.WAITING_FOR_DEPARTMENT, "Waiting for Department");
String key = kualiConfiguration.getPropertyString(PurapKeyConstants.PURCHASE_ORDER_MANUAL_STATUS_CHANGE_NOTE_PREFIX);
String oldStatus = manuallyChangeableStatuses.get(po.getStatusCode());
String newStatus = manuallyChangeableStatuses.get(po.getStatusChange());
key = StringUtils.replace(key, "{0}", (StringUtils.isBlank(oldStatus) ? " " : oldStatus));
notePrefix = StringUtils.replace(key, "{1}", (StringUtils.isBlank(newStatus) ? " " : newStatus));
}
String noteText = notePrefix + KFSConstants.BLANK_SPACE + reason;
int noteTextLength = noteText.length();
// Get note text max length from DD.
int noteTextMaxLength = SpringContext.getBean(DataDictionaryService.class).getAttributeMaxLength(Note.class, KFSConstants.NOTE_TEXT_PROPERTY_NAME).intValue();
if (StringUtils.isBlank(reason) || (noteTextLength > noteTextMaxLength)) {
// Figure out exact number of characters that the user can enter.
int reasonLimit = noteTextMaxLength - noteTextLength;
if (ObjectUtils.isNull(reason)) {
// Prevent a NPE by setting the reason to a blank string.
reason = "";
}
try {
if (StringUtils.equals(questionType, PODocumentsStrings.MANUAL_STATUS_CHANGE_QUESTION)) {
return this.performQuestionWithInputAgainBecauseOfErrors(mapping, form, request, response, questionType, kualiConfiguration.getPropertyString(PurapKeyConstants.PURCHASE_ORDER_QUESTION_MANUAL_STATUS_CHANGE), KFSConstants.CONFIRMATION_QUESTION, questionType, "", reason, PurapKeyConstants.ERROR_PURCHASE_ORDER_REASON_REQUIRED, KFSConstants.QUESTION_REASON_ATTRIBUTE_NAME, new Integer(reasonLimit).toString());
}
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
else if (StringUtils.equals(questionType, PODocumentsStrings.MANUAL_STATUS_CHANGE_QUESTION)) {
executeManualStatusChange(po);
try {
forward = super.save(mapping, form, request, response);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
Note newNote = new Note();
newNote.setNoteText(noteText);
newNote.setNoteTypeCode(KFSConstants.NoteTypeEnum.BUSINESS_OBJECT_NOTE_TYPE.getCode());
kualiDocumentFormBase.setNewNote(newNote);
try {
insertBONote(mapping, kualiDocumentFormBase, request, response);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
return forward;
}
/**
* Applies a manual change of status to the given purchase order document.
*
* @param po A PurchaseOrderDocument
*/
private void executeManualStatusChange(PurchaseOrderDocument po) {
try {
SpringContext.getBean(PurapService.class).updateStatus(po, po.getStatusChange());
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* @see org.kuali.kfs.module.purap.document.web.struts.PurchasingAccountsPayableActionBase#loadDocument(org.kuali.rice.kns.web.struts.form.KualiDocumentFormBase)
*/
@Override
protected void loadDocument(KualiDocumentFormBase kualiDocumentFormBase) throws WorkflowException {
super.loadDocument(kualiDocumentFormBase);
PurchaseOrderForm poForm = (PurchaseOrderForm) kualiDocumentFormBase;
PurchaseOrderDocument po = (PurchaseOrderDocument) poForm.getDocument();
po.setInternalPurchasingLimit(SpringContext.getBean(PurchaseOrderService.class).getInternalPurchasingDollarLimit(po));
}
/**
* Adds a PurchasingItemCapitalAsset (a container for the Capital Asset Number) to the selected
* item's list.
*
* @param mapping An ActionMapping
* @param form The Form
* @param request An HttpServletRequest
* @param response The HttpServletResponse
* @return An ActionForward
* @throws Exception
*/
public ActionForward addAsset(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
PurchaseOrderForm poForm = (PurchaseOrderForm)form;
PurchaseOrderDocument document = (PurchaseOrderDocument)poForm.getDocument();
PurchaseOrderItem item = (PurchaseOrderItem)document.getItemByLineNumber(getSelectedLine(request) + 1);
//TODO: Add a new way to add assets to the system.
//item.addAsset();
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
public ActionForward removeAlternateVendor(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
PurchaseOrderForm poForm = (PurchaseOrderForm) form;
PurchaseOrderDocument document = (PurchaseOrderDocument) poForm.getDocument();
document.setAlternateVendorDetailAssignedIdentifier(null);
document.setAlternateVendorHeaderGeneratedIdentifier(null);
document.setAlternateVendorName(null);
document.setAlternateVendorNumber(null);
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
public ActionForward createReceivingLine(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
PurchaseOrderForm poForm = (PurchaseOrderForm) form;
PurchaseOrderDocument document = (PurchaseOrderDocument) poForm.getDocument();
String basePath = getBasePath(request);
String methodToCallDocHandler = "docHandler";
String methodToCallReceivingLine = "initiate";
//set parameters
Properties parameters = new Properties();
parameters.put(KFSConstants.DISPATCH_REQUEST_PARAMETER, methodToCallDocHandler);
parameters.put(KFSConstants.PARAMETER_COMMAND, methodToCallReceivingLine);
parameters.put(KFSConstants.DOCUMENT_TYPE_NAME, "RCVL");
parameters.put("purchaseOrderId", document.getPurapDocumentIdentifier().toString() );
//create url
String receivingUrl = UrlFactory.parameterizeUrl(basePath + "/" + "purapLineItemReceiving.do", parameters);
//create forward
ActionForward forward = new ActionForward(receivingUrl, true);
return forward;
}
public ActionForward resendPoCxml(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
PurchaseOrderDocument po = (PurchaseOrderDocument) ((PurchaseOrderForm) form).getDocument();
SpringContext.getBean(PurchaseOrderService.class).retransmitB2BPurchaseOrder(po);
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
}
| KULPURAP-3282
| work/src/org/kuali/kfs/module/purap/document/web/struts/PurchaseOrderAction.java | KULPURAP-3282 | <ide><path>ork/src/org/kuali/kfs/module/purap/document/web/struts/PurchaseOrderAction.java
<ide> import org.kuali.kfs.sys.KFSConstants;
<ide> import org.kuali.kfs.sys.KFSPropertyConstants;
<ide> import org.kuali.kfs.sys.context.SpringContext;
<add>import org.kuali.kfs.vnd.VendorConstants.AddressTypes;
<add>import org.kuali.kfs.vnd.businessobject.VendorAddress;
<ide> import org.kuali.kfs.vnd.businessobject.VendorDetail;
<ide> import org.kuali.kfs.vnd.document.service.VendorService;
<ide> import org.kuali.rice.kew.exception.WorkflowException;
<ide> List<SensitiveData> sds = poForm.getSensitiveDatasAssigned();
<ide> SensitiveDataService sdService = SpringContext.getBean(SensitiveDataService.class);
<ide>
<del> //FIXME this is broken KULPURAP-3297
<ide> // check business rules
<ide> boolean rulePassed = SpringContext.getBean(KualiRuleService.class).applyRules(new AttributedAssignSensitiveDataEvent("", po, sds));
<ide> if (!rulePassed) {
<ide> message = StringUtils.replace(message, "{0}", tempRows);
<ide>
<ide> Object question = request.getParameter(KFSConstants.QUESTION_INST_ATTRIBUTE_NAME);
<del>
<ide> if (question == null) {
<del>
<ide> // ask question if not already asked
<ide> return performQuestionWithoutInput(mapping, form, request, response, PODocumentsStrings.CONFIRM_AWARD_QUESTION, message, KFSConstants.CONFIRMATION_QUESTION, PODocumentsStrings.CONFIRM_AWARD_RETURN, "");
<ide> }
<ide> // PO vendor information updated with awarded vendor
<ide> document.setVendorName(awardedQuote.getVendorName());
<ide> document.setVendorNumber(awardedQuote.getVendorNumber());
<del> document.setVendorHeaderGeneratedIdentifier(awardedQuote.getVendorHeaderGeneratedIdentifier());
<del> document.setVendorDetailAssignedIdentifier(awardedQuote.getVendorDetailAssignedIdentifier());
<del> document.setVendorLine1Address(awardedQuote.getVendorLine1Address());
<del> document.setVendorLine2Address(awardedQuote.getVendorLine2Address());
<del> document.setVendorCityName(awardedQuote.getVendorCityName());
<del> document.setVendorStateCode(awardedQuote.getVendorStateCode());
<del> document.setVendorPostalCode(awardedQuote.getVendorPostalCode());
<del> document.setVendorCountryCode(awardedQuote.getVendorCountryCode());
<del> document.setVendorPhoneNumber(awardedQuote.getVendorPhoneNumber());
<del> document.setVendorFaxNumber(awardedQuote.getVendorFaxNumber());
<add> Integer headID = awardedQuote.getVendorHeaderGeneratedIdentifier();
<add> Integer detailID = awardedQuote.getVendorDetailAssignedIdentifier();
<add> document.setVendorHeaderGeneratedIdentifier(headID);
<add> document.setVendorDetailAssignedIdentifier(detailID);
<add>
<add> // use PO type address to fill in vendor address
<add> String campusCode = GlobalVariables.getUserSession().getPerson().getCampusCode();
<add> VendorAddress pova = SpringContext.getBean(VendorService.class).getVendorDefaultAddress(headID, detailID, AddressTypes.PURCHASE_ORDER, campusCode);
<add> document.setVendorLine1Address(pova.getVendorLine1Address());
<add> document.setVendorLine2Address(pova.getVendorLine2Address());
<add> document.setVendorCityName(pova.getVendorCityName());
<add> document.setVendorStateCode(pova.getVendorStateCode());
<add> document.setVendorPostalCode(pova.getVendorZipCode());
<add> document.setVendorCountryCode(pova.getVendorCountryCode());
<add> document.setVendorFaxNumber(pova.getVendorFaxNumber());
<ide>
<ide> document.setStatusCode(PurapConstants.PurchaseOrderStatuses.IN_PROCESS);
<ide> SpringContext.getBean(PurapService.class).saveDocumentNoValidation(document); |
|
Java | apache-2.0 | e6d3a7462cb21041f57bdd09713ceeadb233b0c3 | 0 | rzel/kanzi,sharkkid/kanzi,rukistar/kanzi,rzel/kanzi,rukistar/kanzi,sharkkid/kanzi,Sputuks3/kanzi,rzel/kanzi,Sputuks3/kanzi,rukistar/kanzi,sharkkid/kanzi,Sputuks3/kanzi | /*
Copyright 2011-2013 Frederic Langlet
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 kanzi.filter.seam;
import java.util.concurrent.ExecutorService;
import kanzi.IndexedIntArray;
import kanzi.IntSorter;
import kanzi.IntFilter;
import kanzi.filter.ParallelFilter;
import kanzi.filter.SobelFilter;
import kanzi.util.sort.BucketSort;
import kanzi.util.sort.RadixSort;
// Based on algorithm by Shai Avidan, Ariel Shamir
// Described in [Seam Carving for Content-Aware Image Resizing]
//
// This implementation is focused on speed and is indeed very fast (but it does
// only calculate an approximation of the energy minimizing paths because finding
// the absolute best paths takes too much time)
// It is also possible to calculate the seams on a subset of the image which is
// useful to iterate over the same (shrinking) image.
//
// Note: the name seam carving is a bit unfortunate, what the algo achieves
// is detection and removal of the paths of least resistance (energy wise) in
// the image. These paths really are geodesics.
public class ContextResizer implements IntFilter
{
// Possible directions
public static final int HORIZONTAL = 1;
public static final int VERTICAL = 2;
// Possible actions
public static final int SHRINK = 1;
public static final int EXPAND = 2;
private static final int USED_MASK = 0x80000000;
private static final int VALUE_MASK = USED_MASK - 1;
private static final int DEFAULT_BEST_COST = 0x0FFFFFFF;
private static final int DEFAULT_MAX_COST_PER_PIXEL = 256;
private static final int RED_COLOR = 0xFFFF0000;
private static final int BLUE_COLOR = 0xFF0000FF;
private int width;
private int height;
private final int stride;
private final int direction;
private final int maxSearches;
private final int maxAvgGeoPixCost;
private final int[] costs;
private final int nbGeodesics;
private int action;
private boolean debug;
private final IntSorter sorter;
private IndexedIntArray buffer;
private final boolean fastMode;
private final ExecutorService pool;
public ContextResizer(int width, int height, int direction, int action)
{
this(width, height, width, direction, action, 1, false, false, null);
}
public ContextResizer(int width, int height, int stride, int direction,
int action, int nbGeodesics)
{
this(width, height, stride, direction, action, nbGeodesics, false, false, null);
}
// width, height, offset and stride allow to apply the filter on a subset of an image
// For packed RGB images, use 3 channels mode for more accurate results (fastMode=false)
// and one channel mode (fastMode=true) for faster results.
// For unpacked images, use one channel mode (fastMode=true).
public ContextResizer(int width, int height, int stride,
int direction, int action, int nbGeodesics,
boolean fastMode, boolean debug, ExecutorService pool)
{
this(width, height, stride, direction, action, nbGeodesics,
Math.max(width, height), fastMode, debug, pool, DEFAULT_MAX_COST_PER_PIXEL);
}
// width, height, offset and stride allow to apply the filter on a subset of an image
// maxAvgGeoPixCost allows to limit the cost of geodesics: only those with an
// average cost per pixel less than maxAvgGeoPixCost are allowed (it may be
// less than nbGeodesics).
// For packed RGB images, use 3 channels mode for more accurate results (fastMode=false)
// and one channel mode (fastMode=true) for faster results.
// For unpacked images, use one channel mode (fastMode=true).
public ContextResizer(int width, int height, int stride,
int direction, int action, int nbGeodesics, int maxSearches,
boolean fastMode, boolean debug, ExecutorService pool, int maxAvgGeoPixCost)
{
if (height < 8)
throw new IllegalArgumentException("The height must be at least 8");
if (width < 8)
throw new IllegalArgumentException("The width must be at least 8");
if (stride < 8)
throw new IllegalArgumentException("The stride must be at least 8");
if (maxAvgGeoPixCost < 1)
throw new IllegalArgumentException("The max average pixel cost in a geodesic must be at least 1");
if (nbGeodesics < 1)
throw new IllegalArgumentException("The number of geodesics must be at least 1");
if (((direction & HORIZONTAL) == 0) && ((direction & VERTICAL) == 0))
throw new IllegalArgumentException("Invalid direction parameter (must be VERTICAL or HORIZONTAL)");
if ((action != SHRINK) && (action != EXPAND))
throw new IllegalArgumentException("Invalid action parameter (must be SHRINK or EXPAND)");
if ((direction & HORIZONTAL) == 0)
{
if (nbGeodesics > width)
throw new IllegalArgumentException("The number of geodesics must be at most "+width);
}
else
{
if (nbGeodesics > height)
throw new IllegalArgumentException("The number of geodesics must be at most "+height);
}
this.height = height;
this.width = width;
this.stride = stride;
this.direction = direction;
this.maxSearches = maxSearches;
this.costs = new int[stride*height];
this.nbGeodesics = nbGeodesics;
this.maxAvgGeoPixCost = maxAvgGeoPixCost;
this.action = action;
this.buffer = new IndexedIntArray(new int[0], 0);
this.fastMode = fastMode;
this.debug = debug;
this.pool = pool;
int dim = (height >= width) ? height : width;
int log = 0;
for (long val=dim+1; val>1; val>>=1)
log++;
if ((dim & (dim-1)) != 0)
log++;
// Used to sort coordinates of geodesics
this.sorter = (log < 12) ? new BucketSort(log) : new RadixSort(8, log);
}
public int getWidth()
{
return this.width;
}
public int getHeight()
{
return this.height;
}
public boolean getDebug()
{
return this.debug;
}
// Not thread safe
public boolean setDebug(boolean debug)
{
this.debug = debug;
return true;
}
public int getAction()
{
return this.action;
}
// Not thread safe
public boolean setAction(int action)
{
if ((action != SHRINK) && (action != EXPAND))
return false;
this.action = action;
return true;
}
public boolean shrink(IndexedIntArray src, IndexedIntArray dst)
{
this.setAction(SHRINK);
return this.shrink_(src, dst);
}
public boolean expand(IndexedIntArray src, IndexedIntArray dst)
{
this.setAction(EXPAND);
return this.expand_(src, dst);
}
// Will modify the width and/or height attributes
// The src image is modified if both directions are selected
@Override
public boolean apply(IndexedIntArray src, IndexedIntArray dst)
{
return (this.action == SHRINK) ? this.shrink_(src, dst) :
this.expand_(src, dst);
}
// Will increase the width and/or height attributes. Result must fit in width*height
private boolean expand_(IndexedIntArray src, IndexedIntArray dst)
{
int processed = 0;
IndexedIntArray input = src;
IndexedIntArray output = dst;
if ((this.direction & VERTICAL) != 0)
{
if ((this.direction & HORIZONTAL) != 0)
{
// Lazy dynamic memory allocation
if (this.buffer.array.length < this.stride * this.height)
this.buffer.array = new int[this.stride*this.height];
output = this.buffer;
}
Geodesic[] geodesics = this.computeGeodesics(input, VERTICAL);
if (geodesics.length > 0)
{
processed += geodesics.length;
this.addGeodesics(geodesics, input, output, VERTICAL);
}
if ((this.direction & HORIZONTAL) != 0)
{
input = this.buffer;
output = dst;
}
}
if ((this.direction & HORIZONTAL) != 0)
{
Geodesic[] geodesics = this.computeGeodesics(input, HORIZONTAL);
if (geodesics.length > 0)
{
processed += geodesics.length;
this.addGeodesics(geodesics, input, output, HORIZONTAL);
}
}
if ((processed == 0) && (src.array != dst.array))
{
System.arraycopy(src.array, src.index, dst.array, dst.index, this.height*this.stride);
}
return true;
}
// Will decrease the width and/or height attributes
private boolean shrink_(IndexedIntArray src, IndexedIntArray dst)
{
int processed = 0;
IndexedIntArray input = src;
IndexedIntArray output = dst;
if ((this.direction & VERTICAL) != 0)
{
if ((this.direction & HORIZONTAL) != 0)
{
// Lazy dynamic memory allocation
if (this.buffer.array.length < this.stride * this.height)
this.buffer.array = new int[this.stride*this.height];
output = this.buffer;
}
Geodesic[] geodesics = this.computeGeodesics(input, VERTICAL);
if (geodesics.length > 0)
{
processed += geodesics.length;
this.removeGeodesics(geodesics, input, output, VERTICAL);
}
if ((this.direction & HORIZONTAL) != 0)
{
input = this.buffer;
output = dst;
}
}
if ((this.direction & HORIZONTAL) != 0)
{
Geodesic[] geodesics = this.computeGeodesics(input, HORIZONTAL);
if (geodesics.length > 0)
{
processed += geodesics.length;
this.removeGeodesics(geodesics, input, output, HORIZONTAL);
}
}
if ((processed == 0) && (src.array != dst.array))
{
System.arraycopy(src.array, src.index, dst.array, dst.index, this.height*this.stride);
}
return true;
}
// dir must be either VERTICAL or HORIZONTAL
public boolean addGeodesics(Geodesic[] geodesics, IndexedIntArray source,
IndexedIntArray destination, int dir)
{
if (((dir & VERTICAL) == 0) && ((dir & HORIZONTAL) == 0))
return false;
if (((dir & VERTICAL) != 0) && ((dir & HORIZONTAL) != 0))
return false;
if (geodesics.length == 0)
return true ;
final int[] src = source.array;
final int[] dst = destination.array;
int srcStart = source.index;
int dstStart = destination.index;
final int[] linePositions = new int[geodesics.length];
final int endj;
final int endi;
final int incStart;
final int incIdx;
final int color;
if (dir == HORIZONTAL)
{
endj = this.width;
endi = this.height;
incStart = 1;
incIdx = this.stride;
color = BLUE_COLOR;
}
else
{
endj = this.height;
endi = this.width;
incStart = this.stride;
incIdx = 1;
color = RED_COLOR;
}
for (int j=endj-1; j>=0; j--)
{
// Find all the pixels belonging to geodesics in this line
for (int k=0; k<linePositions.length; k++)
linePositions[k] = geodesics[k].positions[j];
// Sort the pixels by increasing position
if (linePositions.length > 1)
this.sorter.sort(linePositions, 0, linePositions.length);
int posIdx = 0;
int srcIdx = srcStart;
int dstIdx = dstStart;
final int endPosIdx = linePositions.length;
int pos = 0;
while (posIdx < endPosIdx)
{
int newPos = linePositions[posIdx];
final int len = newPos - pos;
if (len > 0)
{
if ((dir == VERTICAL) && (len >= 32))
{
// Speed up copy
System.arraycopy(src, srcIdx, dst, dstIdx, len);
srcIdx += len;
dstIdx += len;
}
else
{
copy(src, srcIdx, dst, dstIdx, len, incIdx);
srcIdx += (len * incIdx);
dstIdx += (len * incIdx);
}
pos = newPos;
}
// Insert new pixel into the destination
if (this.debug == true)
{
dst[dstIdx] = color;
}
else
{
final int pix = src[srcIdx];
final int r = (pix >> 16) & 0xFF;
final int g = (pix >> 8) & 0xFF;
final int b = pix & 0xFF;
dst[dstIdx] = (r << 16) | (g << 8) | b;
}
pos++;
dstIdx += incIdx;
posIdx++;
}
final int len = endi - pos;
// Finish the line, no more test for geodesic pixels required
if ((dir == VERTICAL) && (len >= 32))
{
// Speed up copy
System.arraycopy(src, srcIdx, dst, dstIdx, len);
srcIdx += len;
dstIdx += len;
}
else
{
// Either incIdx != 1 or not enough pixels for arraycopy to be worth it
copy(src, srcIdx, dst, dstIdx, len, incIdx);
srcIdx += (len * incIdx);
dstIdx += (len * incIdx);
}
srcStart += incStart;
dstStart += incStart;
}
return true;
}
// dir must be either VERTICAL or HORIZONTAL
public boolean removeGeodesics(Geodesic[] geodesics, IndexedIntArray source,
IndexedIntArray destination, int dir)
{
if (((dir & VERTICAL) == 0) && ((dir & HORIZONTAL) == 0))
return false;
if (((dir & VERTICAL) != 0) && ((dir & HORIZONTAL) != 0))
return false;
if (geodesics.length == 0)
return true ;
final int[] src = source.array;
final int[] dst = destination.array;
int srcStart = source.index;
int dstStart = destination.index;
final int[] linePositions = new int[geodesics.length];
final int endj;
final int endLine;
final int incIdx;
final int incStart;
final int color;
if (dir == HORIZONTAL)
{
endj = this.width;
endLine = this.height;
incIdx = this.stride;
incStart = 1;
color = BLUE_COLOR;
}
else
{
endj = this.height;
endLine = this.width;
incIdx = 1;
incStart = this.stride;
color = RED_COLOR;
}
for (int j=0; j<endj; j++)
{
// Find all the pixels belonging to geodesics in this line
for (int k=0; k<linePositions.length; k++)
linePositions[k] = geodesics[k].positions[j];
// Sort the pixels by increasing position
if (linePositions.length > 1)
this.sorter.sort(linePositions, 0, linePositions.length);
int srcIdx = srcStart;
int dstIdx = dstStart;
int posIdx = 0;
final int endPosIdx = linePositions.length;
int pos = 0;
while (posIdx < endPosIdx)
{
final int nextPos = linePositions[posIdx];
final int len = nextPos - pos;
// Copy pixels not belonging to a geodesic
if (len > 0)
{
if ((dir == VERTICAL) && (len >= 32))
{
// Speed up copy
System.arraycopy(src, srcIdx, dst, dstIdx, len);
srcIdx += len;
dstIdx += len;
}
else
{
// Either incIdx != 1 or not enough pixels for arraycopy to be worth it
copy(src, srcIdx, dst, dstIdx, len, incIdx);
srcIdx += (len * incIdx);
dstIdx += (len * incIdx);
}
pos = nextPos;
}
// Mark or remove pixel belonging to a geodesic
if (this.debug == true)
{
dst[dstIdx] = color;
dstIdx += incIdx;
}
pos++;
srcIdx += incIdx;
posIdx++;
}
final int len = endLine - pos;
// Finish the line, no more test for geodesic pixels required
if ((dir == VERTICAL) && (len >= 32))
{
// Speed up copy
System.arraycopy(src, srcIdx, dst, dstIdx, len);
srcIdx += len;
dstIdx += len;
}
else
{
// Either incIdx != 1 or not enough pixels for arraycopy to be worth it
copy(src, srcIdx, dst, dstIdx, len, incIdx);
srcIdx += (len * incIdx);
dstIdx += (len * incIdx);
}
srcStart += incStart;
dstStart += incStart;
}
return true;
}
// dir must be either VERTICAL or HORIZONTAL
public Geodesic[] computeGeodesics(IndexedIntArray source, int dir)
{
if (((dir & VERTICAL) == 0) && ((dir & HORIZONTAL) == 0))
return new Geodesic[0];
if (((dir & VERTICAL) != 0) && ((dir & HORIZONTAL) != 0))
return new Geodesic[0];
final int dim = (dir == HORIZONTAL) ? this.height : this.width;
final int searches = Math.min(dim, this.maxSearches);
int[] firstPositions = new int[searches];
int n = 0;
// Spread the first position along 'direction' for better uniformity
// Should improve speed by detecting faster low cost paths and reduce
// geodesic crossing management.
// It will improve quality by spreading the search over the whole image
// if maxSearches is small.
for (int i=0; ((n<searches) && (i<24)); i+=3)
{
// i & 7 shuffles the start position : 0, 3, 6, 1, 4, 7, 2, 5
for (int j=(i & 7); ((n<searches) && (j<dim)); j+=8)
firstPositions[n++] = j;
}
return this.computeGeodesics_(source, dir, firstPositions, searches);
}
// Compute the geodesics but give a constraint on where to start from
// All first position values must be different
// dir must be either VERTICAL or HORIZONTAL
public Geodesic[] computeGeodesics(IndexedIntArray source, int dir, int[] firstPositions)
{
if (((dir & VERTICAL) == 0) && ((dir & HORIZONTAL) == 0))
return new Geodesic[0];
if (((dir & VERTICAL) != 0) && ((dir & HORIZONTAL) != 0))
return new Geodesic[0];
final int dim = (dir == HORIZONTAL) ? this.height : this.width;
final int searches = Math.min(dim, this.maxSearches);
return this.computeGeodesics_(source, dir, firstPositions, searches);
}
private Geodesic[] computeGeodesics_(IndexedIntArray source, int dir, int[] firstPositions, int searches)
{
if ((searches == 0) || (source == null) || (source.array == null) || (firstPositions == null))
return new Geodesic[0];
// Limit searches if there are not enough starting positions
if (searches > firstPositions.length)
searches = firstPositions.length;
final int geoLength;
final int inc;
final int incLine;
final int lineLength;
if (dir == HORIZONTAL)
{
geoLength = this.width;
lineLength = this.height;
inc = this.stride;
incLine = 1;
}
else
{
geoLength = this.height;
lineLength = this.width;
inc = 1;
incLine = this.stride;
}
// Calculate cost at each pixel
this.calculateCosts(source, this.costs);
final int maxGeo = (this.nbGeodesics > searches) ? searches : this.nbGeodesics;
// Queue of geodesics sorted by cost
// The queue size could be less than firstPositions.length
final GeodesicSortedQueue queue = new GeodesicSortedQueue(maxGeo);
boolean consumed = true;
Geodesic geodesic = null;
Geodesic last = null; // last in queue
int maxCost = geoLength * this.maxAvgGeoPixCost;
final int[] costs_ = this.costs; // aliasing
// Calculate path and cost for each geodesic
for (int i=0; i<searches; i++)
{
if (consumed == true)
geodesic = new Geodesic(dir, geoLength);
consumed = false;
int bestLinePos = firstPositions[i];
int costIdx = inc * bestLinePos;
geodesic.positions[0] = bestLinePos;
geodesic.cost = costs_[costIdx];
// Process each row/column
for (int pos=1; pos<geoLength; pos++)
{
costIdx += incLine;
final int startCostIdx = costIdx;
int startBestLinePos = bestLinePos;
int bestCost = ((costs_[startCostIdx] & USED_MASK) == 0) ? costs_[startCostIdx]
: DEFAULT_BEST_COST;
if (bestCost > 0)
{
// Check left/upper pixel, skip already used pixels
int idx = startCostIdx - inc;
for (int linePos=startBestLinePos-1; linePos>=0; idx-=inc, linePos--)
{
final int cost = costs_[idx];
// Skip pixels in use
if ((cost & USED_MASK) != 0)
continue;
if (cost < bestCost)
{
bestCost = cost;
bestLinePos = linePos;
costIdx = idx;
}
break;
}
}
if (bestCost > 0)
{
// Check right/lower pixel, skip already used pixels
int idx = startCostIdx + inc;
for (int linePos=startBestLinePos+1; linePos<lineLength; idx+=inc, linePos++)
{
final int cost = costs_[idx];
if ((cost & USED_MASK) != 0)
continue;
if (cost < bestCost)
{
bestCost = cost;
bestLinePos = linePos;
costIdx = idx;
}
break;
}
geodesic.cost += bestCost;
// Skip, this path is already too expensive
if (geodesic.cost >= maxCost)
break;
}
geodesic.positions[pos] = bestLinePos;
}
if (geodesic.cost < maxCost)
{
final int geoLength4 = geoLength & -4;
// Add geodesic (in increasing cost order). It is sure to succeed
// (it may evict the current tail) because geodesic.cos < maxCost
// and maxCost is adjusted to tail.value
Geodesic newLast = queue.add(geodesic);
// Prevent geodesics from sharing pixels by marking the used pixels
// Only the pixels of the geodesics in the queue are marked as used
if (this.nbGeodesics > 1)
{
// If the previous last element has been expelled from the queue,
// the corresponding pixels can be reused by other geodesics
int startLine = 0;
final int[] gp = geodesic.positions;
if (last != null)
{
final int[] lp = last.positions;
// Tag old pixels as 'free' and new pixels as 'used'
for (int k=0; k<geoLength4; k+=4)
{
costs_[startLine+(inc*gp[k])] |= USED_MASK;
costs_[startLine+(inc*lp[k])] &= VALUE_MASK;
startLine += incLine;
costs_[startLine+(inc*gp[k+1])] |= USED_MASK;
costs_[startLine+(inc*lp[k+1])] &= VALUE_MASK;
startLine += incLine;
costs_[startLine+(inc*gp[k+2])] |= USED_MASK;
costs_[startLine+(inc*lp[k+2])] &= VALUE_MASK;
startLine += incLine;
costs_[startLine+(inc*gp[k+3])] |= USED_MASK;
costs_[startLine+(inc*lp[k+3])] &= VALUE_MASK;
startLine += incLine;
}
for (int k=geoLength4; k<geoLength; k++)
{
costs_[startLine+(inc*gp[k])] |= USED_MASK;
costs_[startLine+(inc*lp[k])] &= VALUE_MASK;
startLine += incLine;
}
}
else
{
for (int k=0; k<geoLength4; k+=4)
{
costs_[startLine+(inc*gp[k])] |= USED_MASK;
startLine += incLine;
costs_[startLine+(inc*gp[k+1])] |= USED_MASK;
startLine += incLine;
costs_[startLine+(inc*gp[k+2])] |= USED_MASK;
startLine += incLine;
costs_[startLine+(inc*gp[k+3])] |= USED_MASK;
startLine += incLine;
}
for (int k=geoLength4; k<geoLength; k++)
{
costs_[startLine+(inc*gp[k])] |= USED_MASK;
startLine += incLine;
}
}
}
// Be green, recycle
if (last == null)
consumed = true;
else
geodesic = last;
// Update maxCost
if (queue.isFull())
{
last = newLast;
maxCost = newLast.cost;
}
}
// All requested geodesics have been found with a cost of 0 => done !
if ((maxCost == 0) && (queue.isFull() == true))
break;
}
return queue.toArray(new Geodesic[queue.size()]);
}
private static void copy(int[] src, int srcIdx, int[] dst, int dstIdx, int len, int inc1)
{
final int len4 = len & -4;
final int inc2 = inc1 + inc1;
final int inc3 = inc2 + inc1;
final int inc4 = inc3 + inc1;
for (int i=0; i<len4; i+=4)
{
dst[dstIdx] = src[srcIdx];
dst[dstIdx+inc1] = src[srcIdx+inc1];
dst[dstIdx+inc2] = src[srcIdx+inc2];
dst[dstIdx+inc3] = src[srcIdx+inc3];
dstIdx += inc4;
srcIdx += inc4;
}
for (int i=len4; i<len; i++)
{
dst[dstIdx] = src[srcIdx];
dstIdx += inc1;
srcIdx += inc1;
}
}
private int[] calculateCosts(IndexedIntArray source, int[] costs_)
{
// For packed RGB images, use 3 channels mode for more accurate results and
// one channel mode (blue) for faster results.
// For unpacked images, use one channel mode (Y for YUV or any for RGB).
int sobelMode = (this.fastMode == true) ? SobelFilter.ONE_CHANNEL : SobelFilter.THREE_CHANNELS;
if (this.pool != null)
{
// Use 4 threads
SobelFilter[] gradientFilters = new SobelFilter[4];
for (int i=0; i<gradientFilters.length; i++)
{
// Do not process the boundaries and overlap the filters (dim + 2)
// to avoid boundary artefacts.
gradientFilters[i] = new SobelFilter(this.width+2, this.height/gradientFilters.length+2,
this.stride, SobelFilter.HORIZONTAL | SobelFilter.VERTICAL,
sobelMode, SobelFilter.COST, false);
}
// Apply the parallel filter
IntFilter pf = new ParallelFilter(this.width, this.height, this.stride,
this.pool, gradientFilters, ParallelFilter.HORIZONTAL);
pf.apply(source, new IndexedIntArray(costs_, 0));
// Fix missing first and last rows of costs (due to non boundary processing filters)
System.arraycopy(costs_, this.width, costs_, 0, this.width);
System.arraycopy(costs_, (this.height-2)*this.stride,
costs_, (this.height-1)*this.stride, this.width);
// Fix missing first column of costs
final int area = this.stride * this.height;
for (int j=0; j<area; j+=this.stride)
costs_[j] = costs_[j+1];
}
else
{
// Mono threaded
SobelFilter gradientFilter = new SobelFilter(this.width, this.height,
this.stride, SobelFilter.HORIZONTAL | SobelFilter.VERTICAL,
sobelMode, SobelFilter.COST, true);
gradientFilter.apply(source, new IndexedIntArray(costs_, 0));
}
// Add a quadratic contribution to the cost
// Favor straight lines if costs of neighbors are all low
for (int i=0; i<costs_.length; i++)
{
final int c = costs_[i];
costs_[i] = (c < 5) ? 0 : c + ((c * c) >> 8);
}
return costs_;
}
}
| java/src/kanzi/filter/seam/ContextResizer.java | /*
Copyright 2011-2013 Frederic Langlet
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 kanzi.filter.seam;
import java.util.concurrent.ExecutorService;
import kanzi.IndexedIntArray;
import kanzi.IntSorter;
import kanzi.IntFilter;
import kanzi.filter.ParallelFilter;
import kanzi.filter.SobelFilter;
import kanzi.util.sort.BucketSort;
import kanzi.util.sort.RadixSort;
// Based on algorithm by Shai Avidan, Ariel Shamir
// Described in [Seam Carving for Content-Aware Image Resizing]
//
// This implementation is focused on speed and is indeed very fast (but it does
// only calculate an approximation of the energy minimizing paths because finding
// the absolute best paths takes too much time)
// It is also possible to calculate the seams on a subset of the image which is
// useful to iterate over the same (shrinking) image.
//
// Note: the name seam carving is a bit unfortunate, what the algo achieves
// is detection and removal of the paths of least resistance (energy wise) in
// the image. These paths really are geodesics.
public class ContextResizer implements IntFilter
{
// Possible directions
public static final int HORIZONTAL = 1;
public static final int VERTICAL = 2;
// Possible actions
public static final int SHRINK = 1;
public static final int EXPAND = 2;
private static final int USED_MASK = 0x80000000;
private static final int VALUE_MASK = USED_MASK - 1;
private static final int DEFAULT_BEST_COST = 0x0FFFFFFF;
private static final int DEFAULT_MAX_COST_PER_PIXEL = 256;
private static final int RED_COLOR = 0xFFFF0000;
private static final int BLUE_COLOR = 0xFF0000FF;
private int width;
private int height;
private final int stride;
private final int direction;
private final int maxSearches;
private final int maxAvgGeoPixCost;
private final int[] costs;
private final int nbGeodesics;
private int action;
private boolean debug;
private final IntSorter sorter;
private IndexedIntArray buffer;
private final boolean fastMode;
private final ExecutorService pool;
public ContextResizer(int width, int height, int direction, int action)
{
this(width, height, width, direction, action, 1, false, false, null);
}
public ContextResizer(int width, int height, int stride, int direction, int action)
{
this(width, height, stride, direction, action, 1, false, false, null);
}
// width, height, offset and stride allow to apply the filter on a subset of an image
// For packed RGB images, use 3 channels mode for more accurate results (fastMode=false)
// and one channel mode (fastMode=true) for faster results.
// For unpacked images, use one channel mode (fastMode=true).
public ContextResizer(int width, int height, int stride,
int direction, int action, int nbGeodesics,
boolean fastMode, boolean debug, ExecutorService pool)
{
this(width, height, stride, direction, action, nbGeodesics,
Math.max(width, height), fastMode, debug, pool, DEFAULT_MAX_COST_PER_PIXEL);
}
// width, height, offset and stride allow to apply the filter on a subset of an image
// maxAvgGeoPixCost allows to limit the cost of geodesics: only those with an
// average cost per pixel less than maxAvgGeoPixCost are allowed (it may be
// less than nbGeodesics).
// For packed RGB images, use 3 channels mode for more accurate results (fastMode=false)
// and one channel mode (fastMode=true) for faster results.
// For unpacked images, use one channel mode (fastMode=true).
public ContextResizer(int width, int height, int stride,
int direction, int action, int nbGeodesics, int maxSearches,
boolean fastMode, boolean debug, ExecutorService pool, int maxAvgGeoPixCost)
{
if (height < 8)
throw new IllegalArgumentException("The height must be at least 8");
if (width < 8)
throw new IllegalArgumentException("The width must be at least 8");
if (stride < 8)
throw new IllegalArgumentException("The stride must be at least 8");
if (maxAvgGeoPixCost < 1)
throw new IllegalArgumentException("The max average pixel cost in a geodesic must be at least 1");
if (nbGeodesics < 1)
throw new IllegalArgumentException("The number of geodesics must be at least 1");
if (((direction & HORIZONTAL) == 0) && ((direction & VERTICAL) == 0))
throw new IllegalArgumentException("Invalid direction parameter (must be VERTICAL or HORIZONTAL)");
if ((action != SHRINK) && (action != EXPAND))
throw new IllegalArgumentException("Invalid action parameter (must be SHRINK or EXPAND)");
if ((direction & HORIZONTAL) == 0)
{
if (nbGeodesics > width)
throw new IllegalArgumentException("The number of geodesics must be at most "+width);
}
else
{
if (nbGeodesics > height)
throw new IllegalArgumentException("The number of geodesics must be at most "+height);
}
this.height = height;
this.width = width;
this.stride = stride;
this.direction = direction;
this.maxSearches = maxSearches;
this.costs = new int[stride*height];
this.nbGeodesics = nbGeodesics;
this.maxAvgGeoPixCost = maxAvgGeoPixCost;
this.action = action;
this.buffer = new IndexedIntArray(new int[0], 0);
this.fastMode = fastMode;
this.debug = debug;
this.pool = pool;
int dim = (height >= width) ? height : width;
int log = 0;
for (long val=dim+1; val>1; val>>=1)
log++;
if ((dim & (dim-1)) != 0)
log++;
// Used to sort coordinates of geodesics
this.sorter = (log < 12) ? new BucketSort(log) : new RadixSort(8, log);
}
public int getWidth()
{
return this.width;
}
public int getHeight()
{
return this.height;
}
public boolean getDebug()
{
return this.debug;
}
// Not thread safe
public boolean setDebug(boolean debug)
{
this.debug = debug;
return true;
}
public int getAction()
{
return this.action;
}
// Not thread safe
public boolean setAction(int action)
{
if ((action != SHRINK) && (action != EXPAND))
return false;
this.action = action;
return true;
}
public boolean shrink(IndexedIntArray src, IndexedIntArray dst)
{
this.setAction(SHRINK);
return this.shrink_(src, dst);
}
public boolean expand(IndexedIntArray src, IndexedIntArray dst)
{
this.setAction(EXPAND);
return this.expand_(src, dst);
}
// Will modify the width and/or height attributes
// The src image is modified if both directions are selected
@Override
public boolean apply(IndexedIntArray src, IndexedIntArray dst)
{
return (this.action == SHRINK) ? this.shrink_(src, dst) :
this.expand_(src, dst);
}
// Will increase the width and/or height attributes. Result must fit in width*height
private boolean expand_(IndexedIntArray src, IndexedIntArray dst)
{
int processed = 0;
IndexedIntArray input = src;
IndexedIntArray output = dst;
if ((this.direction & VERTICAL) != 0)
{
if ((this.direction & HORIZONTAL) != 0)
{
// Lazy dynamic memory allocation
if (this.buffer.array.length < this.stride * this.height)
this.buffer.array = new int[this.stride*this.height];
output = this.buffer;
}
Geodesic[] geodesics = this.computeGeodesics(input, VERTICAL);
if (geodesics.length > 0)
{
processed += geodesics.length;
this.addGeodesics(geodesics, input, output, VERTICAL);
}
if ((this.direction & HORIZONTAL) != 0)
{
input = this.buffer;
output = dst;
}
}
if ((this.direction & HORIZONTAL) != 0)
{
Geodesic[] geodesics = this.computeGeodesics(input, HORIZONTAL);
if (geodesics.length > 0)
{
processed += geodesics.length;
this.addGeodesics(geodesics, input, output, HORIZONTAL);
}
}
if ((processed == 0) && (src.array != dst.array))
{
System.arraycopy(src.array, src.index, dst.array, dst.index, this.height*this.stride);
}
return true;
}
// Will decrease the width and/or height attributes
private boolean shrink_(IndexedIntArray src, IndexedIntArray dst)
{
int processed = 0;
IndexedIntArray input = src;
IndexedIntArray output = dst;
if ((this.direction & VERTICAL) != 0)
{
if ((this.direction & HORIZONTAL) != 0)
{
// Lazy dynamic memory allocation
if (this.buffer.array.length < this.stride * this.height)
this.buffer.array = new int[this.stride*this.height];
output = this.buffer;
}
Geodesic[] geodesics = this.computeGeodesics(input, VERTICAL);
if (geodesics.length > 0)
{
processed += geodesics.length;
this.removeGeodesics(geodesics, input, output, VERTICAL);
}
if ((this.direction & HORIZONTAL) != 0)
{
input = this.buffer;
output = dst;
}
}
if ((this.direction & HORIZONTAL) != 0)
{
Geodesic[] geodesics = this.computeGeodesics(input, HORIZONTAL);
if (geodesics.length > 0)
{
processed += geodesics.length;
this.removeGeodesics(geodesics, input, output, HORIZONTAL);
}
}
if ((processed == 0) && (src.array != dst.array))
{
System.arraycopy(src.array, src.index, dst.array, dst.index, this.height*this.stride);
}
return true;
}
// dir must be either VERTICAL or HORIZONTAL
public boolean addGeodesics(Geodesic[] geodesics, IndexedIntArray source,
IndexedIntArray destination, int dir)
{
if (((dir & VERTICAL) == 0) && ((dir & HORIZONTAL) == 0))
return false;
if (((dir & VERTICAL) != 0) && ((dir & HORIZONTAL) != 0))
return false;
if (geodesics.length == 0)
return true ;
final int[] src = source.array;
final int[] dst = destination.array;
int srcStart = source.index;
int dstStart = destination.index;
final int[] linePositions = new int[geodesics.length];
final int endj;
final int endi;
final int incStart;
final int incIdx;
final int color;
if (dir == HORIZONTAL)
{
endj = this.width;
endi = this.height;
incStart = 1;
incIdx = this.stride;
color = BLUE_COLOR;
}
else
{
endj = this.height;
endi = this.width;
incStart = this.stride;
incIdx = 1;
color = RED_COLOR;
}
for (int j=endj-1; j>=0; j--)
{
// Find all the pixels belonging to geodesics in this line
for (int k=0; k<linePositions.length; k++)
linePositions[k] = geodesics[k].positions[j];
// Sort the pixels by increasing position
if (linePositions.length > 1)
this.sorter.sort(linePositions, 0, linePositions.length);
int posIdx = 0;
int srcIdx = srcStart;
int dstIdx = dstStart;
final int endPosIdx = linePositions.length;
int pos = 0;
while (posIdx < endPosIdx)
{
int newPos = linePositions[posIdx];
final int len = newPos - pos;
if (len > 0)
{
if ((dir == VERTICAL) && (len >= 32))
{
// Speed up copy
System.arraycopy(src, srcIdx, dst, dstIdx, len);
srcIdx += len;
dstIdx += len;
}
else
{
copy(src, srcIdx, dst, dstIdx, len, incIdx);
srcIdx += (len * incIdx);
dstIdx += (len * incIdx);
}
pos = newPos;
}
// Insert new pixel into the destination
if (this.debug == true)
{
dst[dstIdx] = color;
}
else
{
final int pix = src[srcIdx];
final int r = (pix >> 16) & 0xFF;
final int g = (pix >> 8) & 0xFF;
final int b = pix & 0xFF;
dst[dstIdx] = (r << 16) | (g << 8) | b;
}
pos++;
dstIdx += incIdx;
posIdx++;
}
final int len = endi - pos;
// Finish the line, no more test for geodesic pixels required
if ((dir == VERTICAL) && (len >= 32))
{
// Speed up copy
System.arraycopy(src, srcIdx, dst, dstIdx, len);
srcIdx += len;
dstIdx += len;
}
else
{
// Either incIdx != 1 or not enough pixels for arraycopy to be worth it
copy(src, srcIdx, dst, dstIdx, len, incIdx);
srcIdx += (len * incIdx);
dstIdx += (len * incIdx);
}
srcStart += incStart;
dstStart += incStart;
}
return true;
}
// dir must be either VERTICAL or HORIZONTAL
public boolean removeGeodesics(Geodesic[] geodesics, IndexedIntArray source,
IndexedIntArray destination, int dir)
{
if (((dir & VERTICAL) == 0) && ((dir & HORIZONTAL) == 0))
return false;
if (((dir & VERTICAL) != 0) && ((dir & HORIZONTAL) != 0))
return false;
if (geodesics.length == 0)
return true ;
final int[] src = source.array;
final int[] dst = destination.array;
int srcStart = source.index;
int dstStart = destination.index;
final int[] linePositions = new int[geodesics.length];
final int endj;
final int endLine;
final int incIdx;
final int incStart;
final int color;
if (dir == HORIZONTAL)
{
endj = this.width;
endLine = this.height;
incIdx = this.stride;
incStart = 1;
color = BLUE_COLOR;
}
else
{
endj = this.height;
endLine = this.width;
incIdx = 1;
incStart = this.stride;
color = RED_COLOR;
}
for (int j=0; j<endj; j++)
{
// Find all the pixels belonging to geodesics in this line
for (int k=0; k<linePositions.length; k++)
linePositions[k] = geodesics[k].positions[j];
// Sort the pixels by increasing position
if (linePositions.length > 1)
this.sorter.sort(linePositions, 0, linePositions.length);
int srcIdx = srcStart;
int dstIdx = dstStart;
int posIdx = 0;
final int endPosIdx = linePositions.length;
int pos = 0;
while (posIdx < endPosIdx)
{
final int nextPos = linePositions[posIdx];
final int len = nextPos - pos;
// Copy pixels not belonging to a geodesic
if (len > 0)
{
if ((dir == VERTICAL) && (len >= 32))
{
// Speed up copy
System.arraycopy(src, srcIdx, dst, dstIdx, len);
srcIdx += len;
dstIdx += len;
}
else
{
// Either incIdx != 1 or not enough pixels for arraycopy to be worth it
copy(src, srcIdx, dst, dstIdx, len, incIdx);
srcIdx += (len * incIdx);
dstIdx += (len * incIdx);
}
pos = nextPos;
}
// Mark or remove pixel belonging to a geodesic
if (this.debug == true)
{
dst[dstIdx] = color;
dstIdx += incIdx;
}
pos++;
srcIdx += incIdx;
posIdx++;
}
final int len = endLine - pos;
// Finish the line, no more test for geodesic pixels required
if ((dir == VERTICAL) && (len >= 32))
{
// Speed up copy
System.arraycopy(src, srcIdx, dst, dstIdx, len);
srcIdx += len;
dstIdx += len;
}
else
{
// Either incIdx != 1 or not enough pixels for arraycopy to be worth it
copy(src, srcIdx, dst, dstIdx, len, incIdx);
srcIdx += (len * incIdx);
dstIdx += (len * incIdx);
}
srcStart += incStart;
dstStart += incStart;
}
return true;
}
// dir must be either VERTICAL or HORIZONTAL
public Geodesic[] computeGeodesics(IndexedIntArray source, int dir)
{
if (((dir & VERTICAL) == 0) && ((dir & HORIZONTAL) == 0))
return new Geodesic[0];
if (((dir & VERTICAL) != 0) && ((dir & HORIZONTAL) != 0))
return new Geodesic[0];
final int dim = (dir == HORIZONTAL) ? this.height : this.width;
final int searches = Math.min(dim, this.maxSearches);
int[] firstPositions = new int[searches];
int n = 0;
// Spread the first position along 'direction' for better uniformity
// Should improve speed by detecting faster low cost paths and reduce
// geodesic crossing management.
// It will improve quality by spreading the search over the whole image
// if maxSearches is small.
for (int i=0; ((n<searches) && (i<24)); i+=3)
{
// i & 7 shuffles the start position : 0, 3, 6, 1, 4, 7, 2, 5
for (int j=(i & 7); ((n<searches) && (j<dim)); j+=8)
firstPositions[n++] = j;
}
return this.computeGeodesics_(source, dir, firstPositions, searches);
}
// Compute the geodesics but give a constraint on where to start from
// All first position values must be different
// dir must be either VERTICAL or HORIZONTAL
public Geodesic[] computeGeodesics(IndexedIntArray source, int dir, int[] firstPositions)
{
if (((dir & VERTICAL) == 0) && ((dir & HORIZONTAL) == 0))
return new Geodesic[0];
if (((dir & VERTICAL) != 0) && ((dir & HORIZONTAL) != 0))
return new Geodesic[0];
final int dim = (dir == HORIZONTAL) ? this.height : this.width;
final int searches = Math.min(dim, this.maxSearches);
return this.computeGeodesics_(source, dir, firstPositions, searches);
}
private Geodesic[] computeGeodesics_(IndexedIntArray source, int dir, int[] firstPositions, int searches)
{
if ((searches == 0) || (source == null) || (source.array == null) || (firstPositions == null))
return new Geodesic[0];
// Limit searches if there are not enough starting positions
if (searches > firstPositions.length)
searches = firstPositions.length;
final int geoLength;
final int inc;
final int incLine;
final int lineLength;
if (dir == HORIZONTAL)
{
geoLength = this.width;
lineLength = this.height;
inc = this.stride;
incLine = 1;
}
else
{
geoLength = this.height;
lineLength = this.width;
inc = 1;
incLine = this.stride;
}
// Calculate cost at each pixel
this.calculateCosts(source, this.costs);
final int maxGeo = (this.nbGeodesics > searches) ? searches : this.nbGeodesics;
// Queue of geodesics sorted by cost
// The queue size could be less than firstPositions.length
final GeodesicSortedQueue queue = new GeodesicSortedQueue(maxGeo);
boolean consumed = true;
Geodesic geodesic = null;
Geodesic last = null; // last in queue
int maxCost = geoLength * this.maxAvgGeoPixCost;
final int[] costs_ = this.costs; // aliasing
// Calculate path and cost for each geodesic
for (int i=0; i<searches; i++)
{
if (consumed == true)
geodesic = new Geodesic(dir, geoLength);
consumed = false;
int bestLinePos = firstPositions[i];
int costIdx = inc * bestLinePos;
geodesic.positions[0] = bestLinePos;
geodesic.cost = costs_[costIdx];
// Process each row/column
for (int pos=1; pos<geoLength; pos++)
{
costIdx += incLine;
final int startCostIdx = costIdx;
int startBestLinePos = bestLinePos;
int bestCost = ((costs_[startCostIdx] & USED_MASK) == 0) ? costs_[startCostIdx]
: DEFAULT_BEST_COST;
if (bestCost > 0)
{
// Check left/upper pixel, skip already used pixels
int idx = startCostIdx - inc;
for (int linePos=startBestLinePos-1; linePos>=0; idx-=inc, linePos--)
{
final int cost = costs_[idx];
// Skip pixels in use
if ((cost & USED_MASK) != 0)
continue;
if (cost < bestCost)
{
bestCost = cost;
bestLinePos = linePos;
costIdx = idx;
}
break;
}
}
if (bestCost > 0)
{
// Check right/lower pixel, skip already used pixels
int idx = startCostIdx + inc;
for (int linePos=startBestLinePos+1; linePos<lineLength; idx+=inc, linePos++)
{
final int cost = costs_[idx];
if ((cost & USED_MASK) != 0)
continue;
if (cost < bestCost)
{
bestCost = cost;
bestLinePos = linePos;
costIdx = idx;
}
break;
}
geodesic.cost += bestCost;
// Skip, this path is already too expensive
if (geodesic.cost >= maxCost)
break;
}
geodesic.positions[pos] = bestLinePos;
}
if (geodesic.cost < maxCost)
{
final int geoLength4 = geoLength & -4;
// Add geodesic (in increasing cost order). It is sure to succeed
// (it may evict the current tail) because geodesic.cos < maxCost
// and maxCost is adjusted to tail.value
Geodesic newLast = queue.add(geodesic);
// Prevent geodesics from sharing pixels by marking the used pixels
// Only the pixels of the geodesics in the queue are marked as used
if (this.nbGeodesics > 1)
{
// If the previous last element has been expelled from the queue,
// the corresponding pixels can be reused by other geodesics
int startLine = 0;
final int[] gp = geodesic.positions;
if (last != null)
{
final int[] lp = last.positions;
// Tag old pixels as 'free' and new pixels as 'used'
for (int k=0; k<geoLength4; k+=4)
{
costs_[startLine+(inc*gp[k])] |= USED_MASK;
costs_[startLine+(inc*lp[k])] &= VALUE_MASK;
startLine += incLine;
costs_[startLine+(inc*gp[k+1])] |= USED_MASK;
costs_[startLine+(inc*lp[k+1])] &= VALUE_MASK;
startLine += incLine;
costs_[startLine+(inc*gp[k+2])] |= USED_MASK;
costs_[startLine+(inc*lp[k+2])] &= VALUE_MASK;
startLine += incLine;
costs_[startLine+(inc*gp[k+3])] |= USED_MASK;
costs_[startLine+(inc*lp[k+3])] &= VALUE_MASK;
startLine += incLine;
}
for (int k=geoLength4; k<geoLength; k++)
{
costs_[startLine+(inc*gp[k])] |= USED_MASK;
costs_[startLine+(inc*lp[k])] &= VALUE_MASK;
startLine += incLine;
}
}
else
{
for (int k=0; k<geoLength4; k+=4)
{
costs_[startLine+(inc*gp[k])] |= USED_MASK;
startLine += incLine;
costs_[startLine+(inc*gp[k+1])] |= USED_MASK;
startLine += incLine;
costs_[startLine+(inc*gp[k+2])] |= USED_MASK;
startLine += incLine;
costs_[startLine+(inc*gp[k+3])] |= USED_MASK;
startLine += incLine;
}
for (int k=geoLength4; k<geoLength; k++)
{
costs_[startLine+(inc*gp[k])] |= USED_MASK;
startLine += incLine;
}
}
}
// Be green, recycle
if (last == null)
consumed = true;
else
geodesic = last;
// Update maxCost
if (queue.isFull())
{
last = newLast;
maxCost = newLast.cost;
}
}
// All requested geodesics have been found with a cost of 0 => done !
if ((maxCost == 0) && (queue.isFull() == true))
break;
}
return queue.toArray(new Geodesic[queue.size()]);
}
private static void copy(int[] src, int srcIdx, int[] dst, int dstIdx, int len, int inc1)
{
final int len4 = len & -4;
final int inc2 = inc1 + inc1;
final int inc3 = inc2 + inc1;
final int inc4 = inc3 + inc1;
for (int i=0; i<len4; i+=4)
{
dst[dstIdx] = src[srcIdx];
dst[dstIdx+inc1] = src[srcIdx+inc1];
dst[dstIdx+inc2] = src[srcIdx+inc2];
dst[dstIdx+inc3] = src[srcIdx+inc3];
dstIdx += inc4;
srcIdx += inc4;
}
for (int i=len4; i<len; i++)
{
dst[dstIdx] = src[srcIdx];
dstIdx += inc1;
srcIdx += inc1;
}
}
private int[] calculateCosts(IndexedIntArray source, int[] costs_)
{
// For packed RGB images, use 3 channels mode for more accurate results and
// one channel mode (blue) for faster results.
// For unpacked images, use one channel mode (Y for YUV or any for RGB).
int sobelMode = (this.fastMode == true) ? SobelFilter.ONE_CHANNEL : SobelFilter.THREE_CHANNELS;
if (this.pool != null)
{
// Use 4 threads
SobelFilter[] gradientFilters = new SobelFilter[4];
for (int i=0; i<gradientFilters.length; i++)
{
// Do not process the boundaries and overlap the filters (dim + 2)
// to avoid boundary artefacts.
gradientFilters[i] = new SobelFilter(this.width+2, this.height/gradientFilters.length+2,
this.stride, SobelFilter.HORIZONTAL | SobelFilter.VERTICAL,
sobelMode, SobelFilter.COST, false);
}
// Apply the parallel filter
IntFilter pf = new ParallelFilter(this.width, this.height, this.stride,
this.pool, gradientFilters, ParallelFilter.HORIZONTAL);
pf.apply(source, new IndexedIntArray(costs_, 0));
// Fix missing first and last rows of costs (due to non boundary processing filters)
System.arraycopy(costs_, this.width, costs_, 0, this.width);
System.arraycopy(costs_, (this.height-2)*this.stride,
costs_, (this.height-1)*this.stride, this.width);
// Fix missing first column of costs
final int area = this.stride * this.height;
for (int j=0; j<area; j+=this.stride)
costs_[j] = costs_[j+1];
}
else
{
// Mono threaded
SobelFilter gradientFilter = new SobelFilter(this.width, this.height,
this.stride, SobelFilter.HORIZONTAL | SobelFilter.VERTICAL,
sobelMode, SobelFilter.COST, true);
gradientFilter.apply(source, new IndexedIntArray(costs_, 0));
}
// Add a quadratic contribution to the cost
// Favor straight lines if costs of neighbors are all low
for (int i=0; i<costs_.length; i++)
{
final int c = costs_[i];
costs_[i] = (c < 5) ? 0 : c + ((c * c) >> 8);
}
return costs_;
}
}
| Minor change: add a parameter to one of the constructors
| java/src/kanzi/filter/seam/ContextResizer.java | Minor change: add a parameter to one of the constructors | <ide><path>ava/src/kanzi/filter/seam/ContextResizer.java
<ide> }
<ide>
<ide>
<del> public ContextResizer(int width, int height, int stride, int direction, int action)
<del> {
<del> this(width, height, stride, direction, action, 1, false, false, null);
<add> public ContextResizer(int width, int height, int stride, int direction,
<add> int action, int nbGeodesics)
<add> {
<add> this(width, height, stride, direction, action, nbGeodesics, false, false, null);
<ide> }
<ide>
<ide> |
|
JavaScript | apache-2.0 | ecbf783b5a5698537f851e046f7b6caba702495e | 0 | codeaudit/dig,NextCenturyCorporation/dig,codeaudit/dig,NextCenturyCorporation/dig,codeaudit/dig,codeaudit/dig,NextCenturyCorporation/dig,NextCenturyCorporation/dig,codeaudit/dig,NextCenturyCorporation/dig | 'use strict';
angular.module('digApp')
.service('imageSearchService', ['$http', 'simHost', function ($http, simHost) {
var service = {};
var imageSearchResults = [];
var activeImageSearch = null;
service.imageSearch = function(imgUrl) {
imageSearchResults[imgUrl] = {
url: imgUrl,
status: 'searching'
};
// TODO: remove this if we switch to async image searches.
activeImageSearch = imageSearchResults[imgUrl];
$http.get(simHost + '/imagesim?uri' + encodeURIComponent(imgUrl)).
success(function(data, status, headers, config) {
console.log("it completed with " + status);
imageSearchResults[imgUrl].status = 'success';
}).
error(function(data, status, headers, config) {
imageSearchResults[imgUrl].status = 'error';
imageSearchResults[imgUrl].error = data;
});
};
service.getActiveImageSearch = function() {
return activeImageSearch;
};
service.clearActiveImageSearch = function() {
activeImageSearch = null;
};
service.getImageSearchStatus = function(imageUrl) {
(imageSearchResults[imageUrl]) ? imageSearchResults[imageUrl].status : 'no search available' ;
};
service.clearImageSearches = function() {
activeImageSearch = null;
imageSearchResults = [];
}
return service;
}]);
| client/app/imageSearchService/imageSearchService.service.js | 'use strict';
angular.module('digApp')
.service('imageSearchService', ['$http', 'isiHost', function ($http, simHost) {
var service = {};
var imageSearchResults = [];
var activeImageSearch = null;
service.imageSearch = function(imgUrl) {
imageSearchResults[imgUrl] = {
url: imgUrl,
status: 'searching'
};
// TODO: remove this if we switch to async image searches.
activeImageSearch = imageSearchResults[imgUrl];
$http.get(simHost + '/imagesim?uri' + encodeURIComponent(imgUrl)).
success(function(data, status, headers, config) {
console.log("it completed with " + status);
imageSearchResults[imgUrl].status = 'success';
}).
error(function(data, status, headers, config) {
imageSearchResults[imgUrl].status = 'error';
imageSearchResults[imgUrl].error = data;
});
};
service.getActiveImageSearch = function() {
return activeImageSearch;
};
service.clearActiveImageSearch = function() {
activeImageSearch = null;
};
service.getImageSearchStatus = function(imageUrl) {
(imageSearchResults[imageUrl]) ? imageSearchResults[imageUrl].status : 'no search available' ;
};
service.clearImageSearches = function() {
activeImageSearch = null;
imageSearchResults = [];
}
return service;
}]);
| Correcting a typo in an injected constant.
| client/app/imageSearchService/imageSearchService.service.js | Correcting a typo in an injected constant. | <ide><path>lient/app/imageSearchService/imageSearchService.service.js
<ide> 'use strict';
<ide>
<ide> angular.module('digApp')
<del> .service('imageSearchService', ['$http', 'isiHost', function ($http, simHost) {
<add> .service('imageSearchService', ['$http', 'simHost', function ($http, simHost) {
<ide> var service = {};
<ide> var imageSearchResults = [];
<ide> var activeImageSearch = null; |
|
Java | apache-2.0 | ebfba0b6fade315820992e771dbdc95f495a5e8e | 0 | apache/hadoop,apache/hadoop,JingchengDu/hadoop,wwjiang007/hadoop,apache/hadoop,apurtell/hadoop,JingchengDu/hadoop,nandakumar131/hadoop,mapr/hadoop-common,JingchengDu/hadoop,mapr/hadoop-common,JingchengDu/hadoop,mapr/hadoop-common,apurtell/hadoop,wwjiang007/hadoop,wwjiang007/hadoop,apurtell/hadoop,nandakumar131/hadoop,nandakumar131/hadoop,wwjiang007/hadoop,nandakumar131/hadoop,apache/hadoop,mapr/hadoop-common,nandakumar131/hadoop,apurtell/hadoop,apache/hadoop,nandakumar131/hadoop,apurtell/hadoop,apache/hadoop,mapr/hadoop-common,apache/hadoop,wwjiang007/hadoop,wwjiang007/hadoop,apurtell/hadoop,wwjiang007/hadoop,mapr/hadoop-common,JingchengDu/hadoop,JingchengDu/hadoop,apurtell/hadoop,mapr/hadoop-common,JingchengDu/hadoop,nandakumar131/hadoop | /*
* 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.fs.s3a.commit.magic;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.amazonaws.services.s3.model.PartETag;
import com.amazonaws.services.s3.model.PutObjectRequest;
import org.apache.hadoop.thirdparty.com.google.common.base.Preconditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.s3a.WriteOperationHelper;
import org.apache.hadoop.fs.s3a.commit.PutTracker;
import org.apache.hadoop.fs.s3a.commit.files.SinglePendingCommit;
import org.apache.hadoop.fs.statistics.IOStatistics;
import org.apache.hadoop.fs.statistics.IOStatisticsSnapshot;
import static org.apache.hadoop.fs.s3a.commit.CommitConstants.X_HEADER_MAGIC_MARKER;
/**
* Put tracker for Magic commits.
* <p>Important</p>: must not directly or indirectly import a class which
* uses any datatype in hadoop-mapreduce.
*/
@InterfaceAudience.Private
public class MagicCommitTracker extends PutTracker {
public static final Logger LOG = LoggerFactory.getLogger(
MagicCommitTracker.class);
private final String originalDestKey;
private final String pendingPartKey;
private final Path path;
private final WriteOperationHelper writer;
private final String bucket;
private static final byte[] EMPTY = new byte[0];
/**
* Magic commit tracker.
* @param path path nominally being written to
* @param bucket dest bucket
* @param originalDestKey the original key, in the magic directory.
* @param destKey key for the destination
* @param pendingsetKey key of the pendingset file
* @param writer writer instance to use for operations
*/
public MagicCommitTracker(Path path,
String bucket,
String originalDestKey,
String destKey,
String pendingsetKey,
WriteOperationHelper writer) {
super(destKey);
this.bucket = bucket;
this.path = path;
this.originalDestKey = originalDestKey;
this.pendingPartKey = pendingsetKey;
this.writer = writer;
LOG.info("File {} is written as magic file to path {}",
path, destKey);
}
/**
* Initialize the tracker.
* @return true, indicating that the multipart commit must start.
* @throws IOException any IO problem.
*/
@Override
public boolean initialize() throws IOException {
return true;
}
/**
* Flag to indicate that output is not visible after the stream
* is closed.
* @return true
*/
@Override
public boolean outputImmediatelyVisible() {
return false;
}
/**
* Complete operation: generate the final commit data, put it.
* @param uploadId Upload ID
* @param parts list of parts
* @param bytesWritten bytes written
* @param iostatistics nullable IO statistics
* @return false, indicating that the commit must fail.
* @throws IOException any IO problem.
* @throws IllegalArgumentException bad argument
*/
@Override
public boolean aboutToComplete(String uploadId,
List<PartETag> parts,
long bytesWritten,
final IOStatistics iostatistics)
throws IOException {
Preconditions.checkArgument(StringUtils.isNotEmpty(uploadId),
"empty/null upload ID: "+ uploadId);
Preconditions.checkArgument(parts != null,
"No uploaded parts list");
Preconditions.checkArgument(!parts.isEmpty(),
"No uploaded parts to save");
// build the commit summary
SinglePendingCommit commitData = new SinglePendingCommit();
commitData.touch(System.currentTimeMillis());
commitData.setDestinationKey(getDestKey());
commitData.setBucket(bucket);
commitData.setUri(path.toUri().toString());
commitData.setUploadId(uploadId);
commitData.setText("");
commitData.setLength(bytesWritten);
commitData.bindCommitData(parts);
commitData.setIOStatistics(
new IOStatisticsSnapshot(iostatistics));
byte[] bytes = commitData.toBytes();
LOG.info("Uncommitted data pending to file {};"
+ " commit metadata for {} parts in {}. size: {} byte(s)",
path.toUri(), parts.size(), pendingPartKey, bytesWritten);
LOG.debug("Closed MPU to {}, saved commit information to {}; data=:\n{}",
path, pendingPartKey, commitData);
PutObjectRequest put = writer.createPutObjectRequest(
pendingPartKey,
new ByteArrayInputStream(bytes),
bytes.length, null);
writer.uploadObject(put);
// Add the final file length as a header
Map<String, String> headers = new HashMap<>();
headers.put(X_HEADER_MAGIC_MARKER, Long.toString(bytesWritten));
// now put a 0-byte file with the name of the original under-magic path
PutObjectRequest originalDestPut = writer.createPutObjectRequest(
originalDestKey,
new ByteArrayInputStream(EMPTY),
0,
headers);
writer.uploadObject(originalDestPut);
return false;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder(
"MagicCommitTracker{");
sb.append(", destKey=").append(getDestKey());
sb.append(", pendingPartKey='").append(pendingPartKey).append('\'');
sb.append(", path=").append(path);
sb.append(", writer=").append(writer);
sb.append('}');
return sb.toString();
}
}
| hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/commit/magic/MagicCommitTracker.java | /*
* 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.fs.s3a.commit.magic;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.amazonaws.services.s3.model.PartETag;
import com.amazonaws.services.s3.model.PutObjectRequest;
import org.apache.hadoop.thirdparty.com.google.common.base.Preconditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.s3a.WriteOperationHelper;
import org.apache.hadoop.fs.s3a.commit.PutTracker;
import org.apache.hadoop.fs.s3a.commit.files.SinglePendingCommit;
import org.apache.hadoop.fs.statistics.IOStatistics;
import org.apache.hadoop.fs.statistics.IOStatisticsSnapshot;
import static org.apache.hadoop.fs.s3a.commit.CommitConstants.X_HEADER_MAGIC_MARKER;
/**
* Put tracker for Magic commits.
* <p>Important</p>: must not directly or indirectly import a class which
* uses any datatype in hadoop-mapreduce.
*/
@InterfaceAudience.Private
public class MagicCommitTracker extends PutTracker {
public static final Logger LOG = LoggerFactory.getLogger(
MagicCommitTracker.class);
private final String originalDestKey;
private final String pendingPartKey;
private final Path path;
private final WriteOperationHelper writer;
private final String bucket;
private static final byte[] EMPTY = new byte[0];
/**
* Magic commit tracker.
* @param path path nominally being written to
* @param bucket dest bucket
* @param originalDestKey the original key, in the magic directory.
* @param destKey key for the destination
* @param pendingsetKey key of the pendingset file
* @param writer writer instance to use for operations
*/
public MagicCommitTracker(Path path,
String bucket,
String originalDestKey,
String destKey,
String pendingsetKey,
WriteOperationHelper writer) {
super(destKey);
this.bucket = bucket;
this.path = path;
this.originalDestKey = originalDestKey;
this.pendingPartKey = pendingsetKey;
this.writer = writer;
LOG.info("File {} is written as magic file to path {}",
path, destKey);
}
/**
* Initialize the tracker.
* @return true, indicating that the multipart commit must start.
* @throws IOException any IO problem.
*/
@Override
public boolean initialize() throws IOException {
return true;
}
/**
* Flag to indicate that output is not visible after the stream
* is closed.
* @return true
*/
@Override
public boolean outputImmediatelyVisible() {
return false;
}
/**
* Complete operation: generate the final commit data, put it.
* @param uploadId Upload ID
* @param parts list of parts
* @param bytesWritten bytes written
* @param iostatistics nullable IO statistics
* @return false, indicating that the commit must fail.
* @throws IOException any IO problem.
* @throws IllegalArgumentException bad argument
*/
@Override
public boolean aboutToComplete(String uploadId,
List<PartETag> parts,
long bytesWritten,
final IOStatistics iostatistics)
throws IOException {
Preconditions.checkArgument(StringUtils.isNotEmpty(uploadId),
"empty/null upload ID: "+ uploadId);
Preconditions.checkArgument(parts != null,
"No uploaded parts list");
Preconditions.checkArgument(!parts.isEmpty(),
"No uploaded parts to save");
// build the commit summary
SinglePendingCommit commitData = new SinglePendingCommit();
commitData.touch(System.currentTimeMillis());
commitData.setDestinationKey(getDestKey());
commitData.setBucket(bucket);
commitData.setUri(path.toUri().toString());
commitData.setUploadId(uploadId);
commitData.setText("");
commitData.setLength(bytesWritten);
commitData.bindCommitData(parts);
commitData.setIOStatistics(
new IOStatisticsSnapshot(iostatistics));
byte[] bytes = commitData.toBytes();
LOG.info("Uncommitted data pending to file {};"
+ " commit metadata for {} parts in {}. sixe: {} byte(s)",
path.toUri(), parts.size(), pendingPartKey, bytesWritten);
LOG.debug("Closed MPU to {}, saved commit information to {}; data=:\n{}",
path, pendingPartKey, commitData);
PutObjectRequest put = writer.createPutObjectRequest(
pendingPartKey,
new ByteArrayInputStream(bytes),
bytes.length, null);
writer.uploadObject(put);
// Add the final file length as a header
Map<String, String> headers = new HashMap<>();
headers.put(X_HEADER_MAGIC_MARKER, Long.toString(bytesWritten));
// now put a 0-byte file with the name of the original under-magic path
PutObjectRequest originalDestPut = writer.createPutObjectRequest(
originalDestKey,
new ByteArrayInputStream(EMPTY),
0,
headers);
writer.uploadObject(originalDestPut);
return false;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder(
"MagicCommitTracker{");
sb.append(", destKey=").append(getDestKey());
sb.append(", pendingPartKey='").append(pendingPartKey).append('\'');
sb.append(", path=").append(path);
sb.append(", writer=").append(writer);
sb.append('}');
return sb.toString();
}
}
| [HADOOP-17567] typo in MagicCommitTracker (#2749)
Contributed by Pierrick Hymbert | hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/commit/magic/MagicCommitTracker.java | [HADOOP-17567] typo in MagicCommitTracker (#2749) | <ide><path>adoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/commit/magic/MagicCommitTracker.java
<ide> new IOStatisticsSnapshot(iostatistics));
<ide> byte[] bytes = commitData.toBytes();
<ide> LOG.info("Uncommitted data pending to file {};"
<del> + " commit metadata for {} parts in {}. sixe: {} byte(s)",
<add> + " commit metadata for {} parts in {}. size: {} byte(s)",
<ide> path.toUri(), parts.size(), pendingPartKey, bytesWritten);
<ide> LOG.debug("Closed MPU to {}, saved commit information to {}; data=:\n{}",
<ide> path, pendingPartKey, commitData); |
|
Java | mit | fa68727f277ca93a216e83328e2359205f379c3f | 0 | isacarnekvist/Tron | package game;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.ejml.simple.SimpleMatrix;
import org.newdawn.slick.opengl.Texture;
import org.newdawn.slick.opengl.TextureLoader;
import static org.lwjgl.opengl.GL11.*;
public class Sprite {
private Texture texture;
private int fileWidth;
private int imgHeight;
private int imgWidth;
private final int X = 0;
private final int Y = 1;
// Drawing coordinates
private int rotX, rotY; // Around which point should the sprite be rotated
// Vectors from rotation point to corners of image
SimpleMatrix ul, ur, ll, lr;
SimpleMatrix rotation;
/**
* Constructor of self-drawing image.
* @param filename Must be of size 2^n*2^n and type *.png
* @param imgHeight Height of image within file, i.e <= height of file
* @param imgWidth Width of image within file, i.e <= width of file
*/
public Sprite(String filename, int imgHeight, int imgWidth) {
texture = loadTexture(filename);
fileWidth = texture.getImageWidth();
this.imgHeight = imgHeight;
this.imgWidth = imgWidth;
rotX = imgWidth/2;
rotY = imgHeight/2;
ul = new SimpleMatrix(1, 2, true, -imgWidth/2, -imgHeight/2); // Upper left
ur = new SimpleMatrix(1, 2, true, imgWidth/2, -imgHeight/2); // Upper right
ll = new SimpleMatrix(1, 2, true, -imgWidth/2, imgHeight/2); // Lower left
lr = new SimpleMatrix(1, 2, true, imgWidth/2, imgHeight/2); // Lower right
}
private Texture loadTexture(String filename) {
try {
return TextureLoader.getTexture("PNG", new FileInputStream(new File(filename)));
} catch (FileNotFoundException e) {
e.printStackTrace();
System.exit(1);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
return null;
}
/**
* Set the coordinates for which the texture is supposed to be rotated around.
* @param x
* @param y
*/
public void setRotationPoint(int x, int y) {
// Change all vectors that are pointing from rotation point to corners
SimpleMatrix diff = new SimpleMatrix(1, 2, true, rotX - x, rotY - y);
ul = ul.plus(diff);
ur = ur.plus(diff);
ll = ll.plus(diff);
lr = lr.plus(diff);
// Change rotation point
rotX = x;
rotY = y;
}
/**
* Rotate texture n radians clockwise (since our axes are inverted)
* @param r radians
*/
public void rotate(double r) {
rotation = new SimpleMatrix(2, 2, true, Math.cos(r), Math.sin(r), Math.sin(-r), Math.cos(r));
ul = ul.mult(rotation);
ur = ur.mult(rotation);
ll = ll.mult(rotation);
lr = lr.mult(rotation);
}
/**
* @param posX x-coordinate of center or turning point (if set)
* @param posY y-coordinate of - || -
*/
public void draw(int posX, int posY) {
texture.bind();
glBegin(GL_QUADS);
{
glTexCoord2d(0, 0); // Upper left
glVertex2d(posX + ul.get(X), posY + ul.get(Y));
glTexCoord2d(0, (double)imgHeight/fileWidth); // Lower left
glVertex2d(posX + ll.get(X), posY + ll.get(Y));
glTexCoord2d((double)imgWidth/fileWidth, (double)imgHeight/fileWidth); // Lower right
glVertex2d(posX + lr.get(X), posY + lr.get(Y));
glTexCoord2d((double)imgWidth/fileWidth, 0); // Upper right
glVertex2d(posX + ur.get(X), posY + ur.get(Y));
}
glEnd();
}
public int getWidth() {
return imgWidth;
}
public int getHeight() {
return imgHeight;
}
public SimpleMatrix getFrontLeft() {
return ur;
}
public SimpleMatrix getFrontRight() {
return lr;
}
public SimpleMatrix getBackLeft() {
return ul;
}
public SimpleMatrix getBackRight() {
return ll;
}
}
| src/game/Sprite.java | package game;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.ejml.simple.SimpleMatrix;
import org.newdawn.slick.opengl.Texture;
import org.newdawn.slick.opengl.TextureLoader;
import static org.lwjgl.opengl.GL11.*;
public class Sprite {
private Texture texture;
private int fileWidth;
private int imgHeight;
private int imgWidth;
private final int X = 0;
private final int Y = 1;
// Drawing coordinates
private int rotX, rotY; // Around which point should the sprite be rotated
// Vectors from rotation point to corners of image
SimpleMatrix ul, ur, ll, lr;
SimpleMatrix rotation;
/**
* Constructor of self-drawing image.
* @param filename Must be of size 2^n*2^n and type *.png
* @param imgHeight Height of image within file, i.e <= height of file
* @param imgWidth Width of image within file, i.e <= width of file
*/
public Sprite(String filename, int imgHeight, int imgWidth) {
texture = loadTexture(filename);
fileWidth = texture.getImageWidth();
this.imgHeight = imgHeight;
this.imgWidth = imgWidth;
rotX = imgWidth/2;
rotY = imgHeight/2;
ul = new SimpleMatrix(1, 2, true, -imgWidth/2, -imgHeight/2); // Upper left
ur = new SimpleMatrix(1, 2, true, imgWidth/2, -imgHeight/2); // Upper right
ll = new SimpleMatrix(1, 2, true, -imgWidth/2, imgHeight/2); // Lower left
lr = new SimpleMatrix(1, 2, true, imgWidth/2, imgHeight/2); // Lower right
}
private Texture loadTexture(String filename) {
try {
return TextureLoader.getTexture("PNG", new FileInputStream(new File(filename)));
} catch (FileNotFoundException e) {
e.printStackTrace();
System.exit(1);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
return null;
}
/**
* Set the coordinates for which the texture is supposed to be rotated around.
* @param x
* @param y
*/
public void setRotationPoint(int x, int y) {
// Change all vectors that are pointing from rotation point to corners
SimpleMatrix diff = new SimpleMatrix(1, 2, true, rotX - x, rotY - y);
ul = ul.plus(diff);
ur = ur.plus(diff);
ll = ll.plus(diff);
lr = lr.plus(diff);
// Change rotation point
rotX = x;
rotY = y;
}
/**
* Rotate texture n radians clockwise (since our axes are inverted)
* @param r radians
*/
public void rotate(double r) {
rotation = new SimpleMatrix(2, 2, true, Math.cos(r), Math.sin(r), Math.sin(-r), Math.cos(r));
ul = ul.mult(rotation);
ur = ur.mult(rotation);
ll = ll.mult(rotation);
lr = lr.mult(rotation);
}
/**
* @param posX x-coordinate of center or turning point (if set)
* @param posY y-coordinate of - || -
*/
public void draw(int posX, int posY) {
texture.bind();
glBegin(GL_QUADS);
{
glTexCoord2d(0, 0); // Upper left
glVertex2d(posX + ul.get(X), posY + ul.get(Y));
glTexCoord2d(0, (double)imgHeight/fileWidth); // Lower left
glVertex2d(posX + ll.get(X), posY + ll.get(Y));
glTexCoord2d((double)imgWidth/fileWidth, (double)imgHeight/fileWidth); // Lower right
glVertex2d(posX + lr.get(X), posY + lr.get(Y));
glTexCoord2d((double)imgWidth/fileWidth, 0); // Upper right
glVertex2d(posX + ur.get(X), posY + ur.get(Y));
}
glEnd();
}
public int getWidth() {
return imgWidth;
}
public int getHeight() {
return imgHeight;
}
public SimpleMatrix getFrontLeft() {
return ur;
}
public SimpleMatrix getFrontRight() {
return lr;
}
}
| some utility methods
| src/game/Sprite.java | some utility methods | <ide><path>rc/game/Sprite.java
<ide> public SimpleMatrix getFrontRight() {
<ide> return lr;
<ide> }
<add>
<add> public SimpleMatrix getBackLeft() {
<add> return ul;
<add> }
<add>
<add> public SimpleMatrix getBackRight() {
<add> return ll;
<add> }
<ide> } |
|
Java | apache-2.0 | 16f22c9b91b8edd11607d166bafdb7a9bda24fb1 | 0 | DamonHD/reutils | /*
Copyright (c) 2008-2021, Damon Hart-Davis
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package localtest;
import org.hd.d.edh.FUELINSTUtils;
import org.hd.d.edh.TrafficLight;
import org.hd.d.edh.TwitterUtils;
import junit.framework.TestCase;
/**Twitter tests.
*/
public final class TestTwitter extends TestCase
{
/**Test that all possible grid status Tweets are legal with the current property set.
* Check that message are not null and not too long.
*/
public static void testTweetValidity()
{
final int max_chars = TwitterUtils.MAX_TWEET_CHARS - 5; // Allow for some traling decoration.
for(final boolean isDataStale : new boolean[]{ true, false } )
{
for(final TrafficLight status : TrafficLight.values())
{
for(final int retailIntensity : new int[]{9, 99, 999})
{
final String message = FUELINSTUtils.generateTweetMessage(
isDataStale, status, retailIntensity);
assertNotNull("Generated Tweet must not be null", message);
System.err.println("LENGTH="+message.length()+": "+message);
assertFalse("Generated Tweet must not be empty", message.trim().isEmpty());
assertTrue("Generated Tweet must not be over-long: was "+message.length()+" vs max "+TwitterUtils.MAX_TWEET_CHARS+" message: "+message,
message.length() <= TwitterUtils.MAX_TWEET_CHARS);
// Ensure that template has been filled in.
assertFalse("Template not applied?", message.contains("{1}"));
}
}
}
}
// /**Test very basic access to our selected Twitter user.
// */
// public static void testBasics()
// throws Exception
// {
// final TwitterDetails td = TwitterUtils.getTwitterHandle(true);
// if(null != td)
// {
// // If we have a Twitter ID then we should be able to
// // print our user's status with no exception.
// System.out.println("Current status of "+td.username+": " + td.handle.getStatus(td.username));
// }
//
//// td.handle.setStatus("After the pip it will be: " + (new Date()));
//// TwitterUtils.setTwitterStatusIfChanged(td, null, "Pip: "+(new Date()));
// }
// /**Test user-mediated extraction of auth token.
// * Also useful for gathering new secrets manually...
// */
// public static void testOOBTokenAccess()
// {
// final OAuthSignpostClient client = new OAuthSignpostClient(OAuthSignpostClient.JTWITTER_OAUTH_KEY, OAuthSignpostClient.JTWITTER_OAUTH_SECRET, "oob");
// final Twitter jtwit = new Twitter("EarthOrgUK", client);
// // open the authorisation page in the user's browser
// // This is a convenience method for directing the user to client.authorizeUrl()
// client.authorizeDesktop();
// // get the pin
// final String v = OAuthSignpostClient.askUser("Please enter the verification PIN from Twitter");
// client.setAuthorizationCode(v);
// // Optional: store the authorisation token details
// final String[] accessToken = client.getAccessToken();
// for(final String s : accessToken) { System.out.println(s); }
// // use the API!
// jtwit.setStatus("Testing auth...");
// }
}
| test/localtest/TestTwitter.java | /*
Copyright (c) 2008-2021, Damon Hart-Davis
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package localtest;
import org.hd.d.edh.FUELINSTUtils;
import org.hd.d.edh.TrafficLight;
import org.hd.d.edh.TwitterUtils;
import junit.framework.TestCase;
/**Twitter tests.
*/
public final class TestTwitter extends TestCase
{
/**Test that all possible grid status Tweets are legal with the current property set.
* Check that message are not null and not too long.
*/
public static void testTweetValidity()
{
final int max_chars = TwitterUtils.MAX_TWEET_CHARS - 5; // Allow for some traling decoration.
for(final boolean isDataStale : new boolean[]{ true, false } )
{
for(final TrafficLight status : TrafficLight.values())
{
for(final int retailIntensity : new int[]{9, 99, 999})
{
final String message = FUELINSTUtils.generateTweetMessage(
isDataStale, status, retailIntensity);
assertNotNull("Generated Tweet must not be null", message);
System.err.println("LENGTH="+message.length()+": "+message);
assertFalse("Generated Tweet must not be empty", message.trim().isEmpty());
assertTrue("Generated Tweet must not be over-long: was "+message.length()+" vs max "+TwitterUtils.MAX_TWEET_CHARS+" message: "+message,
message.length() <= TwitterUtils.MAX_TWEET_CHARS);
}
}
}
}
// /**Test very basic access to our selected Twitter user.
// */
// public static void testBasics()
// throws Exception
// {
// final TwitterDetails td = TwitterUtils.getTwitterHandle(true);
// if(null != td)
// {
// // If we have a Twitter ID then we should be able to
// // print our user's status with no exception.
// System.out.println("Current status of "+td.username+": " + td.handle.getStatus(td.username));
// }
//
//// td.handle.setStatus("After the pip it will be: " + (new Date()));
//// TwitterUtils.setTwitterStatusIfChanged(td, null, "Pip: "+(new Date()));
// }
// /**Test user-mediated extraction of auth token.
// * Also useful for gathering new secrets manually...
// */
// public static void testOOBTokenAccess()
// {
// final OAuthSignpostClient client = new OAuthSignpostClient(OAuthSignpostClient.JTWITTER_OAUTH_KEY, OAuthSignpostClient.JTWITTER_OAUTH_SECRET, "oob");
// final Twitter jtwit = new Twitter("EarthOrgUK", client);
// // open the authorisation page in the user's browser
// // This is a convenience method for directing the user to client.authorizeUrl()
// client.authorizeDesktop();
// // get the pin
// final String v = OAuthSignpostClient.askUser("Please enter the verification PIN from Twitter");
// client.setAuthorizationCode(v);
// // Optional: store the authorisation token details
// final String[] accessToken = client.getAccessToken();
// for(final String s : accessToken) { System.out.println(s); }
// // use the API!
// jtwit.setStatus("Testing auth...");
// }
}
| Checking that template is being applied... | test/localtest/TestTwitter.java | Checking that template is being applied... | <ide><path>est/localtest/TestTwitter.java
<ide> assertFalse("Generated Tweet must not be empty", message.trim().isEmpty());
<ide> assertTrue("Generated Tweet must not be over-long: was "+message.length()+" vs max "+TwitterUtils.MAX_TWEET_CHARS+" message: "+message,
<ide> message.length() <= TwitterUtils.MAX_TWEET_CHARS);
<add> // Ensure that template has been filled in.
<add> assertFalse("Template not applied?", message.contains("{1}"));
<ide> }
<ide> }
<ide> } |
|
JavaScript | mit | 6602bd19a8dc6335a160333913d11af598eaaf25 | 0 | nickm01/packhack,nickm01/packhack | const twilio = require('twilio')
const textProcessor = require('./textprocessor')
const logger = require('winston')
const commandTypes = require('./commandtypes')
const logs = require('../model/logs')
const smsProcessor = require('./smsprocessor')
const config = require('../config')
const route = (request, response) => {
const bodyText = request.query['Body'].toLowerCase()
const fromPhoneNumber = request.query['From']
logger.log('info', '*** Twilio From:' + fromPhoneNumber + ' Message:' + bodyText)
// Get Cached ListName
let cachedListName
if (request.cookies && request.cookies.listName) {
cachedListName = request.cookies.listName
}
// MAIN LOGIC
const data = {
originalText: bodyText,
cachedListName,
fromPhoneNumber,
now: new Date((new Date()).getTime() - 1000 * 60) // 1 minute in the past
}
logs.saveNewPromise(data)
.then(textProcessor.processTextPromise)
.then(logs.saveNewPromise)
.then(result => {
logger.log('info', '*** after processTextpromise', result)
cacheListName(result, response) // TODO: Make sure this isn't the case for delete
sendSMSResponse(result.responseText, response)
})
.then(smsLogging)
}
const sendSMSResponse = (responseText, response) => {
const twilioResponse = new twilio.TwimlResponse()
twilioResponse.message(responseText)
response.send(twilioResponse.toString())
}
const cacheListName = (data, response) => {
// If there's been an error and list name is now different or if delete list command then expire the cookie
if ((data.errorMessage && data.list !== data.cacheListName) ||
data.command === commandTypes.deleteList
) {
logger.log('info', '___twilio.route_cacheListName expire cache')
response.cookie('listName', '', {expires: new Date(0)})
} else {
logger.log('info', '___twilio.route_cacheListName cache:', data.list)
response.cookie('listName', data.list, {maxAge: 1000 * 60 * 60 * 72})
}
}
const smsLogging = (data) => {
logger.log('info', '___twilio.route_smsLoggingNo: ' + config.smsLoggingPhoneNumber)
if (config.smsLoggingPhoneNumber) {
logger.log('info', '___twilio.route_smsLoggingNo2')
console.log('hello1')
console.log(data)
const sendText = 'LOG:' + data.familyId + ',' + data.fromPerson + ': ' + data.originalText + ' > ' + data.responseText
console.log('hello2')
logger.log('info', '___twilio.route_smsLogging: ' + sendText)
console.log(sendText)
return smsProcessor.sendSmsPromise(data, config.smsLoggingPhoneNumber, sendText)
}
}
module.exports = {
route
}
| src/twilio.route.js | const twilio = require('twilio')
const textProcessor = require('./textprocessor')
const logger = require('winston')
const commandTypes = require('./commandtypes')
const logs = require('../model/logs')
const smsProcessor = require('./smsprocessor')
const config = require('../config')
const route = (request, response) => {
const bodyText = request.query['Body'].toLowerCase()
const fromPhoneNumber = request.query['From']
logger.log('info', '*** Twilio From:' + fromPhoneNumber + ' Message:' + bodyText)
// Get Cached ListName
let cachedListName
if (request.cookies && request.cookies.listName) {
cachedListName = request.cookies.listName
}
// MAIN LOGIC
const data = {
originalText: bodyText,
cachedListName,
fromPhoneNumber,
now: new Date((new Date()).getTime() - 1000 * 60) // 1 minute in the past
}
logs.saveNewPromise(data)
.then(textProcessor.processTextPromise)
.then(logs.saveNewPromise)
.then(result => {
logger.log('info', '*** after processTextpromise', result)
cacheListName(result, response) // TODO: Make sure this isn't the case for delete
sendSMSResponse(result.responseText, response)
})
.then(smsLogging)
}
const sendSMSResponse = (responseText, response) => {
const twilioResponse = new twilio.TwimlResponse()
twilioResponse.message(responseText)
response.send(twilioResponse.toString())
}
const cacheListName = (data, response) => {
// If there's been an error and list name is now different or if delete list command then expire the cookie
if ((data.errorMessage && data.list !== data.cacheListName) ||
data.command === commandTypes.deleteList
) {
logger.log('info', '___twilio.route_cacheListName expire cache')
response.cookie('listName', '', {expires: new Date(0)})
} else {
logger.log('info', '___twilio.route_cacheListName cache:', data.list)
response.cookie('listName', data.list, {maxAge: 1000 * 60 * 60 * 72})
}
}
const smsLogging = (data) => {
logger.log('info', '___twilio.route_smsLoggingNo: ' + config.smsLoggingPhoneNumber)
if (config.smsLoggingPhoneNumber) {
logger.log('info', '___twilio.route_smsLoggingNo2')
console.log('hello1')
const sendText = 'LOG:' + data.familyId + ',' + data.fromPerson + ': ' + data.originalText + ' > ' + data.responseText
console.log('hello2')
logger.log('info', '___twilio.route_smsLogging: ' + sendText)
console.log(sendText)
return smsProcessor.sendSmsPromise(data, config.smsLoggingPhoneNumber, sendText)
}
}
module.exports = {
route
}
| additional logging
| src/twilio.route.js | additional logging | <ide><path>rc/twilio.route.js
<ide> if (config.smsLoggingPhoneNumber) {
<ide> logger.log('info', '___twilio.route_smsLoggingNo2')
<ide> console.log('hello1')
<add> console.log(data)
<ide> const sendText = 'LOG:' + data.familyId + ',' + data.fromPerson + ': ' + data.originalText + ' > ' + data.responseText
<ide> console.log('hello2')
<ide> logger.log('info', '___twilio.route_smsLogging: ' + sendText) |
|
JavaScript | mit | 04adf9ba918dcbb3b53d715794c42591cbb9930b | 0 | evansoderberg/react-joyride,evansoderberg/react-joyride | var React = require('react/addons'),
scroll = require('scroll'),
Beacon = require('./Beacon'),
Tooltip = require('./Tooltip');
var joyride = {
browser: undefined,
initialized: false,
mixin: false,
steps: [],
getBrowser: function () {
// Return cached result if avalible, else get result then cache it.
if (this.browser) {
return this.browser;
}
var isOpera = Boolean(window.opera) || navigator.userAgent.indexOf(' OPR/') >= 0;
// Opera 8.0+ (UA detection to detect Blink/v8-powered Opera)
var isFirefox = typeof InstallTrigger !== 'undefined';// Firefox 1.0+
var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
// At least Safari 3+: "[object HTMLElementConstructor]"
var isChrome = Boolean(window.chrome) && !isOpera;// Chrome 1+
var isIE = /*@cc_on!@*/false || Boolean(document.documentMode); // At least IE6
return (this.browser =
isOpera ? 'opera' :
isFirefox ? 'firefox' :
isSafari ? 'safari' :
isChrome ? 'chrome' :
isIE ? 'ie' :
'');
},
getElementDimensions: function (el) {
// Get the DOM Node if you pass in a string
el = (typeof el === 'string') ? document.querySelector(el) : el;
var styles = window.getComputedStyle(el),
height = el.clientHeight + parseInt(styles.marginTop, 10) + parseInt(styles.marginBottom, 10),
width = el.clientWidth + parseInt(styles.marginLeft, 10) + parseInt(styles.marginRight, 10);
return {
height: height,
width: width
};
},
keyboardNavigation: function (e) {
var intKey = (window.Event) ? e.which : e.keyCode,
hasSteps;
if (this.state.joyrideShowTooltip) {
if ([32, 38, 40].indexOf(intKey) > -1) {
e.preventDefault();
}
if (intKey === 27) {
joyride.toggleTooltip(false, this.state.joyrideCurrentIndex + 1);
}
else if ([13, 32].indexOf(intKey) > -1) {
hasSteps = Boolean(joyride.steps[this.state.joyrideCurrentIndex + 1]);
joyride.toggleTooltip(hasSteps, this.state.joyrideCurrentIndex + 1);
}
}
},
preventWindowOverflow: function (value, axis, elWidth, elHeight) {
var winWidth = window.innerWidth,
docHeight = document.body.offsetHeight,
newValue = value;
if (axis === 'x') {
if (value + elWidth >= winWidth) {
newValue = winWidth - elWidth - 15;
}
else if (value < 0) {
newValue = 15;
}
}
else if (axis === 'y') {
if (value + elHeight >= docHeight) {
newValue = docHeight - elHeight - 15;
}
else if (value < 0) {
newValue = 15;
}
}
return newValue;
}
};
var Mixin = {
getInitialState: function () {
return {
joyrideCurrentIndex: 0,
joyrideKeyboardNavigation: true,
joyrideLocale: {
back: 'Back',
close: 'Close',
last: 'Last',
next: 'Next'
},
joyrideOverridePosition: false,
joyridePlay: false,
joyrideScrollToSteps: true,
joyrideScrollOffset: 20,
joyrideShowBackButton: true,
joyrideShowOverlay: true,
joyrideShowStepsProgress: false,
joyrideShowTooltip: false,
joyrideTooltipOffset: 15,
joyrideType: 'guided',
joyrideCompleteCallback: undefined,
joyrideStepCallback: undefined,
joyrideXPos: -1000,
joyrideYPos: -1000
};
},
componentDidMount: function () {
var state = this.state;
this._target = document.createElement('div');
this._target.className = 'joyride';
document.body.appendChild(this._target);
if (state.joyridePlay && joyride.steps[state.joyrideCurrentIndex]) {
this.joyrideRenderLayer();
}
joyride.mixin = this;
window.addEventListener('resize', this.joyrideCalcPlacement);
if (this.state.joyrideKeyboardNavigation) {
document.body.addEventListener('keydown', joyride.keyboardNavigation.bind(this));
}
},
componentWillUnmount: function () {
this.joyrideUnrenderLayer();
document.body.removeChild(this._target);
window.removeEventListener('resize', this.joyrideCalcPlacement);
if (this.state.joyrideKeyboardNavigation) {
document.body.removeEventListener('keydown', joyride.keyboardNavigation.bind(this));
}
},
componentDidUpdate: function (prevProps, prevState) {
var state = this.state,
opt = {
shouldRun: state.joyridePlay && (state.joyridePlay !== prevState.joyridePlay || state.joyrideCurrentIndex !== prevState.joyrideCurrentIndex),
hasStep: Boolean(joyride.steps[state.joyrideCurrentIndex]),
hasSteps: joyride.steps.length > 0,
newX: state.joyrideXPos !== prevState.joyrideXPos,
newY: state.joyrideYPos !== prevState.joyrideYPos,
toggleTooltip: state.joyrideShowTooltip !== prevState.joyrideShowTooltip
};
if ((opt.shouldRun || opt.toggleTooltip || opt.newX || opt.newY) && opt.hasStep) {
this.joyrideRenderLayer();
}
else if (opt.shouldRun && opt.hasSteps && !opt.hasStep) {
if (typeof state.joyrideCompleteCallback === 'function') {
state.joyrideCompleteCallback(joyride.steps);
}
this.joyrideUnrenderLayer();
}
},
/**
* Starts the tour
* @param {boolean} [autorun]- Starts with the first tooltip opened
*/
joyrideStart: function (autorun) {
autorun = autorun || false;
this.setState({
joyrideShowTooltip: autorun,
joyridePlay: true
});
},
/**
* Add Steps
* @param {object|array} steps - Steps to add to the tour
* @param {boolean} [start] - Starts the tour right away
*/
joyrideAddSteps: function (steps, start) {
var tmpSteps = [],
el;
start = start || this.state.joyridePlay;
if (Array.isArray(steps)) {
steps.forEach(function (s) {
if (s instanceof Object) {
tmpSteps.push(s);
}
});
}
else {
tmpSteps = [steps];
}
tmpSteps.forEach(function (s) {
el = document.querySelector(s.selector);
s.position = s.position || 'top';
if (el && el.offsetParent) {
joyride.steps.push(s);
}
});
this.setState(
React.addons.update(this.state, {
joyridePlay: { $set: start }
})
);
},
/**
* Retrieve the current progress of your tour
* @returns {{index: (number|*), percentageComplete: number, step: (object|null)}}
*/
joyrideGetProgress: function () {
return {
index: this.state.joyrideCurrentIndex,
percentageComplete: parseFloat(((this.state.joyrideCurrentIndex / joyride.steps.length) * 100).toFixed(2).replace('.00', '')),
step: joyride.steps[this.state.joyrideCurrentIndex]
};
},
_onClickBeacon: function (e) {
e.preventDefault();
this.setState({
joyrideShowTooltip: true,
joyrideXPos: -1000,
joyrideYPos: -1000
});
},
_onClickTooltip: function (e) {
e.preventDefault();
e.stopPropagation();
var state = this.state,
type = e.currentTarget.getAttribute('data-type'),
newIndex = state.joyrideCurrentIndex + (type === 'back' ? -1 : 1);
if (e.target === e.currentTarget) {
if (typeof state.joyrideStepCallback === 'function') {
state.joyrideStepCallback(joyride.steps[state.joyrideCurrentIndex]);
}
this.setState({
joyrideShowTooltip: state.joyrideType === 'guided' && type !== 'close' && Boolean(joyride.steps[newIndex]),
joyrideCurrentIndex: newIndex,
joyrideXPos: -1000,
joyrideYPos: -1000
});
}
},
joyrideCalcPlacement: function () {
var state = this.state,
step = joyride.steps[state.joyrideCurrentIndex],
component = document.querySelector((state.joyrideShowTooltip ? '.joyride-tooltip' : '.joyride-beacon')),
position,
body,
target,
placement = {
x: -1000,
y: -1000
};
if (step && (!/animate/.test(component.className) || state.joyrideXPos < 0)) {
position = step.position;
body = document.body.getBoundingClientRect();
target = document.querySelector(step.selector).getBoundingClientRect();
component = joyride.getElementDimensions((state.joyrideShowTooltip ? '.joyride-tooltip' : '.joyride-beacon'));
// Change the step position in the tooltip won't fit in the window
if (/^left/.test(position) && target.left - (component.width + state.joyrideTooltipOffset) < 0) {
position = 'top';
}
else if (/^right/.test(position) && target.left + target.width + (component.width + state.joyrideTooltipOffset) > body.width) {
position = 'bottom';
}
// Calculate x position
if (/^left/.test(position)) {
placement.x = target.left - (state.joyrideShowTooltip ? component.width + state.joyrideTooltipOffset : component.width / 2);
}
else if (/^right/.test(position)) {
placement.x = target.left + target.width - (state.joyrideShowTooltip ? -state.joyrideTooltipOffset : component.width / 2);
}
else {
placement.x = target.left + target.width / 2 - component.width / 2;
}
// Calculate y position
if (/^top/.test(position)) {
placement.y = (target.top - body.top) - (state.joyrideShowTooltip ? component.height + state.joyrideTooltipOffset : component.height / 2);
}
else if (/^bottom/.test(position)) {
placement.y = (target.top - body.top) + target.height - (state.joyrideShowTooltip ? -state.joyrideTooltipOffset : component.height / 2);
}
else {
placement.y = (target.top - body.top) + target.height / 2 - component.height / 2 + (state.joyrideShowTooltip ? state.joyrideTooltipOffset : 0);
}
if (/^bottom|^top/.test(position)) {
if (/left/.test(position)) {
placement.x = target.left - (state.joyrideShowTooltip ? state.joyrideTooltipOffset : component.width / 2);
}
else if (/right/.test(position)) {
placement.x = target.left + target.width - (state.joyrideShowTooltip ? component.width - state.joyrideTooltipOffset : component.width / 2);
}
}
this.setState({
joyrideXPos: joyride.preventWindowOverflow(Math.ceil(placement.x), 'x', component.width, component.height),
joyrideYPos: joyride.preventWindowOverflow(Math.ceil(placement.y), 'y', component.width, component.height),
joyrideOverridePosition: step.position !== position ? position : false
});
}
},
_getScrollTop: function () {
var step = joyride.steps[this.state.joyrideCurrentIndex],
position = this.state.joyrideOverridePosition || step.position,
target = document.querySelector(step.selector),
targetTop = target.getBoundingClientRect().top + document.body.scrollTop,
scrollTop = 0;
if (/^top/.test(position)) {
scrollTop = Math.floor(this.state.joyrideYPos - this.state.joyrideScrollOffset);
}
else if (/^bottom|^left|^right/.test(position)) {
scrollTop = Math.floor(targetTop - this.state.joyrideScrollOffset);
}
return scrollTop;
},
_scrollToNextStep: function (cb) {
if (joyride.steps[this.state.joyrideCurrentIndex] && this.state.joyrideScrollToSteps) {
scroll.top(document.body, this._getScrollTop(), cb);
}
},
joyrideRenderLayer: function () {
var component = this.joyrideRenderStep();
if (!joyride.initialized) {
joyride.initialized = true;
React.renderToString(component);
}
React.render(component, this._target, function () {
this._scrollToNextStep();
this.joyrideCalcPlacement();
}.bind(this));
},
joyrideUnrenderLayer: function () {
React.unmountComponentAtNode(this._target);
},
joyrideRenderStep: function () {
var state = this.state,
component,
currentStep = joyride.steps[state.joyrideCurrentIndex],
buttons = {
primary: state.joyrideLocale.close
},
target = currentStep && currentStep.selector ? document.querySelector(currentStep.selector) : null,
cssPosition = target ? target.style.position : null;
if (target) {
if (state.joyrideShowTooltip) {
if (state.joyrideType === 'guided') {
buttons.primary = state.joyrideLocale.last;
if (Boolean(joyride.steps[state.joyrideCurrentIndex + 1])) {
buttons.primary = state.joyrideLocale.next;
if (state.joyrideShowStepsProgress) {
buttons.primary += ' ' + (state.joyrideCurrentIndex + 1) + '/' + joyride.steps.length;
}
}
if (state.joyrideShowBackButton && state.joyrideCurrentIndex > 0) {
buttons.secondary = state.joyrideLocale.back;
}
}
component = React.createElement(Tooltip, {
animate: state.joyrideXPos > -1,
browser: joyride.getBrowser(),
buttons: buttons,
cssPosition: cssPosition,
overridePosition: state.joyrideOverridePosition,
showOverlay: state.joyrideShowOverlay,
step: currentStep,
xPos: state.joyrideXPos,
yPos: state.joyrideYPos,
onClick: this._onClickTooltip
});
}
else {
component = React.createElement(Beacon, {
cssPosition: cssPosition,
xPos: state.joyrideXPos,
yPos: state.joyrideYPos,
handleClick: this._onClickBeacon
});
}
}
return component;
}
};
module.exports = Mixin;
| lib/scripts/Mixin.js | var React = require('react/addons'),
scroll = require('scroll'),
Beacon = require('./Beacon'),
Tooltip = require('./Tooltip');
var joyride = {
browser: undefined,
initialized: false,
mixin: false,
steps: [],
getBrowser: function () {
// Return cached result if avalible, else get result then cache it.
if (this.browser) {
return this.browser;
}
var isOpera = Boolean(window.opera) || navigator.userAgent.indexOf(' OPR/') >= 0;
// Opera 8.0+ (UA detection to detect Blink/v8-powered Opera)
var isFirefox = typeof InstallTrigger !== 'undefined';// Firefox 1.0+
var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
// At least Safari 3+: "[object HTMLElementConstructor]"
var isChrome = Boolean(window.chrome) && !isOpera;// Chrome 1+
var isIE = /*@cc_on!@*/false || Boolean(document.documentMode); // At least IE6
return (this.browser =
isOpera ? 'opera' :
isFirefox ? 'firefox' :
isSafari ? 'safari' :
isChrome ? 'chrome' :
isIE ? 'ie' :
'');
},
getElementDimensions: function (el) {
// Get the DOM Node if you pass in a string
el = (typeof el === 'string') ? document.querySelector(el) : el;
var styles = window.getComputedStyle(el),
height = el.clientHeight + parseInt(styles.marginTop, 10) + parseInt(styles.marginBottom, 10),
width = el.clientWidth + parseInt(styles.marginLeft, 10) + parseInt(styles.marginRight, 10);
return {
height: height,
width: width
};
},
keyboardNavigation: function (e) {
var intKey = (window.Event) ? e.which : e.keyCode,
hasSteps;
if (this.state.joyrideShowTooltip) {
if ([32, 38, 40].indexOf(intKey) > -1) {
e.preventDefault();
}
if (intKey === 27) {
joyride.toggleTooltip(false, this.state.joyrideCurrentIndex + 1);
}
else if ([13, 32].indexOf(intKey) > -1) {
hasSteps = Boolean(joyride.steps[this.state.joyrideCurrentIndex + 1]);
joyride.toggleTooltip(hasSteps, this.state.joyrideCurrentIndex + 1);
}
}
},
preventWindowOverflow: function (value, axis, elWidth, elHeight) {
var winWidth = window.innerWidth,
docHeight = document.body.offsetHeight,
newValue = value;
if (axis === 'x') {
if (value + elWidth >= winWidth) {
newValue = winWidth - elWidth - 15;
}
else if (value < 0) {
newValue = 15;
}
}
else if (axis === 'y') {
if (value + elHeight >= docHeight) {
newValue = docHeight - elHeight - 15;
}
else if (value < 0) {
newValue = 15;
}
}
return newValue;
}
};
var Mixin = {
getInitialState: function () {
return {
joyrideCurrentIndex: 0,
joyrideKeyboardNavigation: true,
joyrideLocale: {
back: 'Back',
close: 'Close',
last: 'Last',
next: 'Next'
},
joyrideOverridePosition: false,
joyridePlay: false,
joyrideScrollToSteps: true,
joyrideScrollOffset: 20,
joyrideShowBackButton: true,
joyrideShowOverlay: true,
joyrideShowStepsProgress: false,
joyrideShowTooltip: false,
joyrideTooltipOffset: 15,
joyrideType: 'guided',
joyrideCompleteCallback: undefined,
joyrideStepCallback: undefined,
joyrideXPos: -1000,
joyrideYPos: -1000
};
},
componentDidMount: function () {
var state = this.state;
this._target = document.createElement('div');
this._target.className = 'joyride';
document.body.appendChild(this._target);
if (state.joyridePlay && joyride.steps[state.joyrideCurrentIndex]) {
this._renderLayer();
}
joyride.mixin = this;
window.addEventListener('resize', this.joyrideCalcPlacement);
if (this.state.joyrideKeyboardNavigation) {
document.body.addEventListener('keydown', joyride.keyboardNavigation.bind(this));
}
},
componentWillUnmount: function () {
this._unrenderLayer();
document.body.removeChild(this._target);
window.removeEventListener('resize', this.joyrideCalcPlacement);
if (this.state.joyrideKeyboardNavigation) {
document.body.removeEventListener('keydown', joyride.keyboardNavigation.bind(this));
}
},
componentDidUpdate: function (prevProps, prevState) {
var state = this.state,
opt = {
shouldRun: state.joyridePlay && (state.joyridePlay !== prevState.joyridePlay || state.joyrideCurrentIndex !== prevState.joyrideCurrentIndex),
hasStep: Boolean(joyride.steps[state.joyrideCurrentIndex]),
hasSteps: joyride.steps.length > 0,
newX: state.joyrideXPos !== prevState.joyrideXPos,
newY: state.joyrideYPos !== prevState.joyrideYPos,
toggleTooltip: state.joyrideShowTooltip !== prevState.joyrideShowTooltip
};
if ((opt.shouldRun || opt.toggleTooltip || opt.newX || opt.newY) && opt.hasStep) {
this._renderLayer();
}
else if (opt.shouldRun && opt.hasSteps && !opt.hasStep) {
if (typeof state.joyrideCompleteCallback === 'function') {
state.joyrideCompleteCallback(joyride.steps);
}
this._unrenderLayer();
}
},
/**
* Starts the tour
* @param {boolean} [autorun]- Starts with the first tooltip opened
*/
joyrideStart: function (autorun) {
autorun = autorun || false;
this.setState({
joyrideShowTooltip: autorun,
joyridePlay: true
});
},
/**
* Add Steps
* @param {object|array} steps - Steps to add to the tour
* @param {boolean} [start] - Starts the tour right away
*/
joyrideAddSteps: function (steps, start) {
var tmpSteps = [],
el;
start = start || this.state.joyridePlay;
if (Array.isArray(steps)) {
steps.forEach(function (s) {
if (s instanceof Object) {
tmpSteps.push(s);
}
});
}
else {
tmpSteps = [steps];
}
tmpSteps.forEach(function (s) {
el = document.querySelector(s.selector);
s.position = s.position || 'top';
if (el && el.offsetParent) {
joyride.steps.push(s);
}
});
this.setState(
React.addons.update(this.state, {
joyridePlay: { $set: start }
})
);
},
/**
* Retrieve the current progress of your tour
* @returns {{index: (number|*), percentageComplete: number, step: (object|null)}}
*/
joyrideGetProgress: function () {
return {
index: this.state.joyrideCurrentIndex,
percentageComplete: parseFloat(((this.state.joyrideCurrentIndex / joyride.steps.length) * 100).toFixed(2).replace('.00', '')),
step: joyride.steps[this.state.joyrideCurrentIndex]
};
},
_onClickBeacon: function (e) {
e.preventDefault();
this.setState({
joyrideShowTooltip: true,
joyrideXPos: -1000,
joyrideYPos: -1000
});
},
_onClickTooltip: function (e) {
e.preventDefault();
e.stopPropagation();
var state = this.state,
type = e.currentTarget.getAttribute('data-type'),
newIndex = state.joyrideCurrentIndex + (type === 'back' ? -1 : 1);
if (e.target === e.currentTarget) {
if (typeof state.joyrideStepCallback === 'function') {
state.joyrideStepCallback(joyride.steps[state.joyrideCurrentIndex]);
}
this.setState({
joyrideShowTooltip: state.joyrideType === 'guided' && type !== 'close' && Boolean(joyride.steps[newIndex]),
joyrideCurrentIndex: newIndex,
joyrideXPos: -1000,
joyrideYPos: -1000
});
}
},
_calculatePlacement: function () {
var state = this.state,
step = joyride.steps[state.joyrideCurrentIndex],
component = document.querySelector((state.joyrideShowTooltip ? '.joyride-tooltip' : '.joyride-beacon')),
position,
body,
target,
placement = {
x: -1000,
y: -1000
};
if (step && (!/animate/.test(component.className) || state.joyrideXPos < 0)) {
position = step.position;
body = document.body.getBoundingClientRect();
target = document.querySelector(step.selector).getBoundingClientRect();
component = joyride.getElementDimensions((state.joyrideShowTooltip ? '.joyride-tooltip' : '.joyride-beacon'));
// Change the step position in the tooltip won't fit in the window
if (/^left/.test(position) && target.left - (component.width + state.joyrideTooltipOffset) < 0) {
position = 'top';
}
else if (/^right/.test(position) && target.left + target.width + (component.width + state.joyrideTooltipOffset) > body.width) {
position = 'bottom';
}
// Calculate x position
if (/^left/.test(position)) {
placement.x = target.left - (state.joyrideShowTooltip ? component.width + state.joyrideTooltipOffset : component.width / 2);
}
else if (/^right/.test(position)) {
placement.x = target.left + target.width - (state.joyrideShowTooltip ? -state.joyrideTooltipOffset : component.width / 2);
}
else {
placement.x = target.left + target.width / 2 - component.width / 2;
}
// Calculate y position
if (/^top/.test(position)) {
placement.y = (target.top - body.top) - (state.joyrideShowTooltip ? component.height + state.joyrideTooltipOffset : component.height / 2);
}
else if (/^bottom/.test(position)) {
placement.y = (target.top - body.top) + target.height - (state.joyrideShowTooltip ? -state.joyrideTooltipOffset : component.height / 2);
}
else {
placement.y = (target.top - body.top) + target.height / 2 - component.height / 2 + (state.joyrideShowTooltip ? state.joyrideTooltipOffset : 0);
}
if (/^bottom|^top/.test(position)) {
if (/left/.test(position)) {
placement.x = target.left - (state.joyrideShowTooltip ? state.joyrideTooltipOffset : component.width / 2);
}
else if (/right/.test(position)) {
placement.x = target.left + target.width - (state.joyrideShowTooltip ? component.width - state.joyrideTooltipOffset : component.width / 2);
}
}
this.setState({
joyrideXPos: joyride.preventWindowOverflow(Math.ceil(placement.x), 'x', component.width, component.height),
joyrideYPos: joyride.preventWindowOverflow(Math.ceil(placement.y), 'y', component.width, component.height),
joyrideOverridePosition: step.position !== position ? position : false
});
}
},
_getScrollTop: function () {
var step = joyride.steps[this.state.joyrideCurrentIndex],
position = this.state.joyrideOverridePosition || step.position,
target = document.querySelector(step.selector),
targetTop = target.getBoundingClientRect().top + document.body.scrollTop,
scrollTop = 0;
if (/^top/.test(position)) {
scrollTop = Math.floor(this.state.joyrideYPos - this.state.joyrideScrollOffset);
}
else if (/^bottom|^left|^right/.test(position)) {
scrollTop = Math.floor(targetTop - this.state.joyrideScrollOffset);
}
return scrollTop;
},
_scrollToNextStep: function (cb) {
if (joyride.steps[this.state.joyrideCurrentIndex] && this.state.joyrideScrollToSteps) {
scroll.top(document.body, this._getScrollTop(), cb);
}
},
_renderLayer: function () {
var component = this._renderCurrentStep();
if (!joyride.initialized) {
joyride.initialized = true;
React.renderToString(component);
}
React.render(component, this._target, function () {
this._calculatePlacement();
this._scrollToNextStep();
}.bind(this));
},
_unrenderLayer: function () {
React.unmountComponentAtNode(this._target);
},
_renderCurrentStep: function () {
var state = this.state,
component,
currentStep = joyride.steps[state.joyrideCurrentIndex],
buttons = {
primary: state.joyrideLocale.close
},
target = currentStep && currentStep.selector ? document.querySelector(currentStep.selector) : null,
cssPosition = target ? target.style.position : null;
if (target) {
if (state.joyrideShowTooltip) {
if (state.joyrideType === 'guided') {
buttons.primary = state.joyrideLocale.last;
if (Boolean(joyride.steps[state.joyrideCurrentIndex + 1])) {
buttons.primary = state.joyrideLocale.next;
if (state.joyrideShowStepsProgress) {
buttons.primary += ' ' + (state.joyrideCurrentIndex + 1) + '/' + joyride.steps.length;
}
}
if (state.joyrideShowBackButton && state.joyrideCurrentIndex > 0) {
buttons.secondary = state.joyrideLocale.back;
}
}
component = React.createElement(Tooltip, {
animate: state.joyrideXPos > -1,
browser: joyride.getBrowser(),
buttons: buttons,
cssPosition: cssPosition,
overridePosition: state.joyrideOverridePosition,
showOverlay: state.joyrideShowOverlay,
step: currentStep,
xPos: state.joyrideXPos,
yPos: state.joyrideYPos,
onClick: this._onClickTooltip
});
}
else {
component = React.createElement(Beacon, {
cssPosition: cssPosition,
xPos: state.joyrideXPos,
yPos: state.joyrideYPos,
handleClick: this._onClickBeacon
});
}
}
return component;
}
};
module.exports = Mixin;
| rename mixin shared functions
| lib/scripts/Mixin.js | rename mixin shared functions | <ide><path>ib/scripts/Mixin.js
<ide> document.body.appendChild(this._target);
<ide>
<ide> if (state.joyridePlay && joyride.steps[state.joyrideCurrentIndex]) {
<del> this._renderLayer();
<add> this.joyrideRenderLayer();
<ide> }
<ide>
<ide> joyride.mixin = this;
<ide> },
<ide>
<ide> componentWillUnmount: function () {
<del> this._unrenderLayer();
<add> this.joyrideUnrenderLayer();
<ide> document.body.removeChild(this._target);
<ide>
<ide> window.removeEventListener('resize', this.joyrideCalcPlacement);
<ide> };
<ide>
<ide> if ((opt.shouldRun || opt.toggleTooltip || opt.newX || opt.newY) && opt.hasStep) {
<del> this._renderLayer();
<add> this.joyrideRenderLayer();
<ide> }
<ide> else if (opt.shouldRun && opt.hasSteps && !opt.hasStep) {
<ide> if (typeof state.joyrideCompleteCallback === 'function') {
<ide> state.joyrideCompleteCallback(joyride.steps);
<ide> }
<del> this._unrenderLayer();
<add> this.joyrideUnrenderLayer();
<ide> }
<ide> },
<ide>
<ide> }
<ide> },
<ide>
<del> _calculatePlacement: function () {
<add> joyrideCalcPlacement: function () {
<ide> var state = this.state,
<ide> step = joyride.steps[state.joyrideCurrentIndex],
<ide> component = document.querySelector((state.joyrideShowTooltip ? '.joyride-tooltip' : '.joyride-beacon')),
<ide> }
<ide> },
<ide>
<del> _renderLayer: function () {
<del> var component = this._renderCurrentStep();
<add> joyrideRenderLayer: function () {
<add> var component = this.joyrideRenderStep();
<ide> if (!joyride.initialized) {
<ide> joyride.initialized = true;
<ide> React.renderToString(component);
<ide> }
<ide>
<ide> React.render(component, this._target, function () {
<del> this._calculatePlacement();
<ide> this._scrollToNextStep();
<add> this.joyrideCalcPlacement();
<ide> }.bind(this));
<ide> },
<ide>
<del> _unrenderLayer: function () {
<add> joyrideUnrenderLayer: function () {
<ide> React.unmountComponentAtNode(this._target);
<ide> },
<ide>
<del> _renderCurrentStep: function () {
<add> joyrideRenderStep: function () {
<ide> var state = this.state,
<ide> component,
<ide> currentStep = joyride.steps[state.joyrideCurrentIndex], |
|
Java | apache-2.0 | 0cab1dba8aa443fef58757ca5bd5ee6943802058 | 0 | petrandreev/arquillian-extension-warp,arquillian/arquillian-extension-warp,arquillian/arquillian-extension-warp,CSchulz/arquillian-extension-warp,CSchulz/arquillian-extension-warp | /**
* JBoss, Home of Professional Open Source
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.arquillian.warp.jsf.ftest.producer;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.arquillian.warp.Activity;
import org.jboss.arquillian.warp.Inspection;
import org.jboss.arquillian.warp.Warp;
import org.jboss.arquillian.warp.WarpTest;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
@RunWith(Arquillian.class)
@WarpTest
@RunAsClient
public class TestJSFResourceNotFound {
@Drone
WebDriver browser;
@ArquillianResource
URL contextPath;
@Deployment
public static WebArchive createDeployment() {
return ShrinkWrap.create(WebArchive.class, "jsf-test.war")
.addAsWebInfResource(new StringAsset("<faces-config></faces-config>"), "faces-config.xml");
}
@Test
public void testNotFound() {
Warp.initiate(new Activity() {
@Override
public void perform() {
try {
URL url = new URL(contextPath, "faces/notExisting.xhtml");
URLConnection connection = url.openConnection();
connection.getInputStream();
} catch (FileNotFoundException e) {
// the FNFE is expected
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
}).inspect(new Inspection() {
private static final long serialVersionUID = 1L;
});
}
}
| extension/jsf-ftest/src/test/java/org/jboss/arquillian/warp/jsf/ftest/producer/TestJSFResourceNotFound.java | /**
* JBoss, Home of Professional Open Source
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.arquillian.warp.jsf.ftest.producer;
import static org.junit.Assert.fail;
import java.io.FileNotFoundException;
import java.net.URL;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.arquillian.test.spi.ArquillianProxyException;
import org.jboss.arquillian.warp.Activity;
import org.jboss.arquillian.warp.Inspection;
import org.jboss.arquillian.warp.Warp;
import org.jboss.arquillian.warp.WarpTest;
import org.jboss.arquillian.warp.exception.ServerWarpExecutionException;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
@RunWith(Arquillian.class)
@WarpTest
@RunAsClient
public class TestJSFResourceNotFound {
@Drone
WebDriver browser;
@ArquillianResource
URL contextPath;
@Deployment
public static WebArchive createDeployment() {
return ShrinkWrap.create(WebArchive.class, "jsf-test.war")
.addAsWebInfResource(EmptyAsset.INSTANCE, "faces-config.xml");
}
@Test
public void testNotFound() {
try {
Warp.initiate(new Activity() {
@Override
public void perform() {
browser.navigate().to(contextPath + "faces/notFound.xhtml");
}
}).inspect(new Inspection() {
private static final long serialVersionUID = 1L;
});
fail("expected server exception");
} catch (ArquillianProxyException e) {
// FileNotFoundException on server
} catch (ServerWarpExecutionException e) {
if (!(e.getCause() instanceof FileNotFoundException)) {
fail("expected FileNotFound on server");
}
}
}
}
| fix TestJSFResourceNotFound test on wildfly
| extension/jsf-ftest/src/test/java/org/jboss/arquillian/warp/jsf/ftest/producer/TestJSFResourceNotFound.java | fix TestJSFResourceNotFound test on wildfly | <ide><path>xtension/jsf-ftest/src/test/java/org/jboss/arquillian/warp/jsf/ftest/producer/TestJSFResourceNotFound.java
<ide> */
<ide> package org.jboss.arquillian.warp.jsf.ftest.producer;
<ide>
<del>import static org.junit.Assert.fail;
<del>
<ide> import java.io.FileNotFoundException;
<add>import java.io.IOException;
<ide> import java.net.URL;
<add>import java.net.URLConnection;
<ide>
<ide> import org.jboss.arquillian.container.test.api.Deployment;
<ide> import org.jboss.arquillian.container.test.api.RunAsClient;
<ide> import org.jboss.arquillian.drone.api.annotation.Drone;
<ide> import org.jboss.arquillian.junit.Arquillian;
<ide> import org.jboss.arquillian.test.api.ArquillianResource;
<del>import org.jboss.arquillian.test.spi.ArquillianProxyException;
<ide> import org.jboss.arquillian.warp.Activity;
<ide> import org.jboss.arquillian.warp.Inspection;
<ide> import org.jboss.arquillian.warp.Warp;
<ide> import org.jboss.arquillian.warp.WarpTest;
<del>import org.jboss.arquillian.warp.exception.ServerWarpExecutionException;
<ide> import org.jboss.shrinkwrap.api.ShrinkWrap;
<del>import org.jboss.shrinkwrap.api.asset.EmptyAsset;
<add>import org.jboss.shrinkwrap.api.asset.StringAsset;
<ide> import org.jboss.shrinkwrap.api.spec.WebArchive;
<ide> import org.junit.Test;
<ide> import org.junit.runner.RunWith;
<ide> @Deployment
<ide> public static WebArchive createDeployment() {
<ide> return ShrinkWrap.create(WebArchive.class, "jsf-test.war")
<del> .addAsWebInfResource(EmptyAsset.INSTANCE, "faces-config.xml");
<add> .addAsWebInfResource(new StringAsset("<faces-config></faces-config>"), "faces-config.xml");
<ide> }
<ide>
<ide> @Test
<ide> public void testNotFound() {
<del> try {
<del> Warp.initiate(new Activity() {
<add> Warp.initiate(new Activity() {
<ide>
<del> @Override
<del> public void perform() {
<del> browser.navigate().to(contextPath + "faces/notFound.xhtml");
<add> @Override
<add> public void perform() {
<add> try {
<add> URL url = new URL(contextPath, "faces/notExisting.xhtml");
<add> URLConnection connection = url.openConnection();
<add> connection.getInputStream();
<add> } catch (FileNotFoundException e) {
<add> // the FNFE is expected
<add> } catch (IOException e) {
<add> throw new IllegalStateException(e);
<ide> }
<add> }
<ide>
<del> }).inspect(new Inspection() {
<del> private static final long serialVersionUID = 1L;
<del> });
<del>
<del> fail("expected server exception");
<del> } catch (ArquillianProxyException e) {
<del> // FileNotFoundException on server
<del> } catch (ServerWarpExecutionException e) {
<del> if (!(e.getCause() instanceof FileNotFoundException)) {
<del> fail("expected FileNotFound on server");
<del> }
<del> }
<add> }).inspect(new Inspection() {
<add> private static final long serialVersionUID = 1L;
<add> });
<ide> }
<ide> } |
|
Java | mit | 1ade3135c8b645da577864937f0dfbac7838cc31 | 0 | unparalleled/kcards | package com.mrkevinthomas.kcards;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.support.v4.view.ViewPager;
import android.view.View;
import com.mrkevinthomas.kcards.models.Deck;
import java.util.Locale;
public class CardViewActivity extends BaseActivity {
private static final int OFFSCREEN_PAGE_LIMIT = 2;
private Deck deck;
private int position;
private ViewPager viewPager;
private CardViewAdapter cardViewAdapter;
private TextToSpeech textToSpeech;
@Override
protected boolean shouldShowUpButton() {
return true;
}
@Override
protected int getViewId() {
return R.layout.view_pager;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
deck = getIntent().getParcelableExtra(ARG_DECK);
position = getIntent().getIntExtra(ARG_POSITION, 0);
getSupportActionBar().setTitle(deck.getName());
getSupportActionBar().setSubtitle(deck.getDescription());
viewPager = (ViewPager) findViewById(R.id.view_pager);
viewPager.setVisibility(View.VISIBLE);
fab.setVisibility(View.GONE);
cardViewAdapter = new CardViewAdapter(deck, this);
viewPager.setAdapter(cardViewAdapter);
viewPager.setCurrentItem(position);
viewPager.setOffscreenPageLimit(OFFSCREEN_PAGE_LIMIT);
textToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
}
});
textToSpeech.setLanguage(Locale.US);
}
@Override
protected void onDestroy() {
super.onDestroy();
textToSpeech.shutdown();
}
public TextToSpeech getTextToSpeech() {
return textToSpeech;
}
}
| app/src/main/java/com/mrkevinthomas/kcards/CardViewActivity.java | package com.mrkevinthomas.kcards;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.support.v4.view.ViewPager;
import android.view.View;
import com.mrkevinthomas.kcards.models.Deck;
import java.util.Locale;
public class CardViewActivity extends BaseActivity {
private static final int OFFSCREEN_PAGE_LIMIT = 2;
private Deck deck;
private int position;
private ViewPager viewPager;
private CardViewAdapter cardViewAdapter;
private TextToSpeech textToSpeech;
@Override
protected boolean shouldShowUpButton() {
return true;
}
@Override
protected int getViewId() {
return R.layout.view_pager;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
deck = getIntent().getParcelableExtra(ARG_DECK);
position = getIntent().getIntExtra(ARG_POSITION, 0);
viewPager = (ViewPager) findViewById(R.id.view_pager);
viewPager.setVisibility(View.VISIBLE);
fab.setVisibility(View.GONE);
cardViewAdapter = new CardViewAdapter(deck, this);
viewPager.setAdapter(cardViewAdapter);
viewPager.setCurrentItem(position);
viewPager.setOffscreenPageLimit(OFFSCREEN_PAGE_LIMIT);
textToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
}
});
textToSpeech.setLanguage(Locale.US);
}
@Override
protected void onDestroy() {
super.onDestroy();
textToSpeech.shutdown();
}
public TextToSpeech getTextToSpeech() {
return textToSpeech;
}
}
| set action bar title and subtitle in card viewer activity
| app/src/main/java/com/mrkevinthomas/kcards/CardViewActivity.java | set action bar title and subtitle in card viewer activity | <ide><path>pp/src/main/java/com/mrkevinthomas/kcards/CardViewActivity.java
<ide> deck = getIntent().getParcelableExtra(ARG_DECK);
<ide> position = getIntent().getIntExtra(ARG_POSITION, 0);
<ide>
<add> getSupportActionBar().setTitle(deck.getName());
<add> getSupportActionBar().setSubtitle(deck.getDescription());
<add>
<ide> viewPager = (ViewPager) findViewById(R.id.view_pager);
<ide> viewPager.setVisibility(View.VISIBLE);
<ide> fab.setVisibility(View.GONE); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.